This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perldelta for 191f8909fa4e
[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 /* this is a chain of data about sub patterns we are processing that
105    need to be handled separately/specially in study_chunk. Its so
106    we can simulate recursion without losing state.  */
107 struct scan_frame;
108 typedef struct scan_frame {
109     regnode *last_regnode;      /* last node to process in this frame */
110     regnode *next_regnode;      /* next node to process when last is reached */
111     U32 prev_recursed_depth;
112     I32 stopparen;              /* what stopparen do we use */
113
114     struct scan_frame *this_prev_frame; /* this previous frame */
115     struct scan_frame *prev_frame;      /* previous frame */
116     struct scan_frame *next_frame;      /* next frame */
117 } scan_frame;
118
119 /* Certain characters are output as a sequence with the first being a
120  * backslash. */
121 #define isBACKSLASHED_PUNCT(c)  strchr("-[]\\^", c)
122
123
124 struct RExC_state_t {
125     U32         flags;                  /* RXf_* are we folding, multilining? */
126     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
127     char        *precomp;               /* uncompiled string. */
128     char        *precomp_end;           /* pointer to end of uncompiled string. */
129     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
130     regexp      *rx;                    /* perl core regexp structure */
131     regexp_internal     *rxi;           /* internal data for regexp object
132                                            pprivate field */
133     char        *start;                 /* Start of input for compile */
134     char        *end;                   /* End of input for compile */
135     char        *parse;                 /* Input-scan pointer. */
136     char        *copy_start;            /* start of copy of input within
137                                            constructed parse string */
138     char        *copy_start_in_input;   /* Position in input string
139                                            corresponding to copy_start */
140     SSize_t     whilem_seen;            /* number of WHILEM in this expr */
141     regnode     *emit_start;            /* Start of emitted-code area */
142     regnode_offset emit;                /* Code-emit pointer */
143     I32         naughty;                /* How bad is this pattern? */
144     I32         sawback;                /* Did we see \1, ...? */
145     U32         seen;
146     SSize_t     size;                   /* Number of regnode equivalents in
147                                            pattern */
148
149     /* position beyond 'precomp' of the warning message furthest away from
150      * 'precomp'.  During the parse, no warnings are raised for any problems
151      * earlier in the parse than this position.  This works if warnings are
152      * raised the first time a given spot is parsed, and if only one
153      * independent warning is raised for any given spot */
154     Size_t      latest_warn_offset;
155
156     I32         npar;                   /* Capture buffer count so far in the
157                                            parse, (OPEN) plus one. ("par" 0 is
158                                            the whole pattern)*/
159     I32         total_par;              /* During initial parse, is either 0,
160                                            or -1; the latter indicating a
161                                            reparse is needed.  After that pass,
162                                            it is what 'npar' became after the
163                                            pass.  Hence, it being > 0 indicates
164                                            we are in a reparse situation */
165     I32         nestroot;               /* root parens we are in - used by
166                                            accept */
167     I32         seen_zerolen;
168     regnode_offset *open_parens;        /* offsets to open parens */
169     regnode_offset *close_parens;       /* offsets to close parens */
170     regnode     *end_op;                /* END node in program */
171     I32         utf8;           /* whether the pattern is utf8 or not */
172     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
173                                 /* XXX use this for future optimisation of case
174                                  * where pattern must be upgraded to utf8. */
175     I32         uni_semantics;  /* If a d charset modifier should use unicode
176                                    rules, even if the pattern is not in
177                                    utf8 */
178     HV          *paren_names;           /* Paren names */
179
180     regnode     **recurse;              /* Recurse regops */
181     I32         recurse_count;          /* Number of recurse regops we have generated */
182     U8          *study_chunk_recursed;  /* bitmap of which subs we have moved
183                                            through */
184     U32         study_chunk_recursed_bytes;  /* bytes in bitmap */
185     I32         in_lookbehind;
186     I32         contains_locale;
187     I32         override_recoding;
188 #ifdef EBCDIC
189     I32         recode_x_to_native;
190 #endif
191     I32         in_multi_char_class;
192     struct reg_code_blocks *code_blocks;/* positions of literal (?{})
193                                             within pattern */
194     int         code_index;             /* next code_blocks[] slot */
195     SSize_t     maxlen;                        /* mininum possible number of chars in string to match */
196     scan_frame *frame_head;
197     scan_frame *frame_last;
198     U32         frame_count;
199     AV         *warn_text;
200 #ifdef ADD_TO_REGEXEC
201     char        *starttry;              /* -Dr: where regtry was called. */
202 #define RExC_starttry   (pRExC_state->starttry)
203 #endif
204     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
205 #ifdef DEBUGGING
206     const char  *lastparse;
207     I32         lastnum;
208     AV          *paren_name_list;       /* idx -> name */
209     U32         study_chunk_recursed_count;
210     SV          *mysv1;
211     SV          *mysv2;
212
213 #define RExC_lastparse  (pRExC_state->lastparse)
214 #define RExC_lastnum    (pRExC_state->lastnum)
215 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
216 #define RExC_study_chunk_recursed_count    (pRExC_state->study_chunk_recursed_count)
217 #define RExC_mysv       (pRExC_state->mysv1)
218 #define RExC_mysv1      (pRExC_state->mysv1)
219 #define RExC_mysv2      (pRExC_state->mysv2)
220
221 #endif
222     bool        seen_d_op;
223     bool        strict;
224     bool        study_started;
225     bool        in_script_run;
226     bool        use_BRANCHJ;
227 };
228
229 #define RExC_flags      (pRExC_state->flags)
230 #define RExC_pm_flags   (pRExC_state->pm_flags)
231 #define RExC_precomp    (pRExC_state->precomp)
232 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
233 #define RExC_copy_start_in_constructed  (pRExC_state->copy_start)
234 #define RExC_precomp_end (pRExC_state->precomp_end)
235 #define RExC_rx_sv      (pRExC_state->rx_sv)
236 #define RExC_rx         (pRExC_state->rx)
237 #define RExC_rxi        (pRExC_state->rxi)
238 #define RExC_start      (pRExC_state->start)
239 #define RExC_end        (pRExC_state->end)
240 #define RExC_parse      (pRExC_state->parse)
241 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
242 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
243 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
244                                                    under /d from /u ? */
245
246
247 #ifdef RE_TRACK_PATTERN_OFFSETS
248 #  define RExC_offsets  (RExC_rxi->u.offsets) /* I am not like the
249                                                          others */
250 #endif
251 #define RExC_emit       (pRExC_state->emit)
252 #define RExC_emit_start (pRExC_state->emit_start)
253 #define RExC_sawback    (pRExC_state->sawback)
254 #define RExC_seen       (pRExC_state->seen)
255 #define RExC_size       (pRExC_state->size)
256 #define RExC_maxlen        (pRExC_state->maxlen)
257 #define RExC_npar       (pRExC_state->npar)
258 #define RExC_total_parens       (pRExC_state->total_par)
259 #define RExC_nestroot   (pRExC_state->nestroot)
260 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
261 #define RExC_utf8       (pRExC_state->utf8)
262 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
263 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
264 #define RExC_open_parens        (pRExC_state->open_parens)
265 #define RExC_close_parens       (pRExC_state->close_parens)
266 #define RExC_end_op     (pRExC_state->end_op)
267 #define RExC_paren_names        (pRExC_state->paren_names)
268 #define RExC_recurse    (pRExC_state->recurse)
269 #define RExC_recurse_count      (pRExC_state->recurse_count)
270 #define RExC_study_chunk_recursed        (pRExC_state->study_chunk_recursed)
271 #define RExC_study_chunk_recursed_bytes  \
272                                    (pRExC_state->study_chunk_recursed_bytes)
273 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
274 #define RExC_contains_locale    (pRExC_state->contains_locale)
275 #ifdef EBCDIC
276 #   define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
277 #endif
278 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
279 #define RExC_frame_head (pRExC_state->frame_head)
280 #define RExC_frame_last (pRExC_state->frame_last)
281 #define RExC_frame_count (pRExC_state->frame_count)
282 #define RExC_strict (pRExC_state->strict)
283 #define RExC_study_started      (pRExC_state->study_started)
284 #define RExC_warn_text (pRExC_state->warn_text)
285 #define RExC_in_script_run      (pRExC_state->in_script_run)
286 #define RExC_use_BRANCHJ        (pRExC_state->use_BRANCHJ)
287
288 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
289  * a flag to disable back-off on the fixed/floating substrings - if it's
290  * a high complexity pattern we assume the benefit of avoiding a full match
291  * is worth the cost of checking for the substrings even if they rarely help.
292  */
293 #define RExC_naughty    (pRExC_state->naughty)
294 #define TOO_NAUGHTY (10)
295 #define MARK_NAUGHTY(add) \
296     if (RExC_naughty < TOO_NAUGHTY) \
297         RExC_naughty += (add)
298 #define MARK_NAUGHTY_EXP(exp, add) \
299     if (RExC_naughty < TOO_NAUGHTY) \
300         RExC_naughty += RExC_naughty / (exp) + (add)
301
302 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
303 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
304         ((*s) == '{' && regcurly(s)))
305
306 /*
307  * Flags to be passed up and down.
308  */
309 #define WORST           0       /* Worst case. */
310 #define HASWIDTH        0x01    /* Known to match non-null strings. */
311
312 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
313  * character.  (There needs to be a case: in the switch statement in regexec.c
314  * for any node marked SIMPLE.)  Note that this is not the same thing as
315  * REGNODE_SIMPLE */
316 #define SIMPLE          0x02
317 #define SPSTART         0x04    /* Starts with * or + */
318 #define POSTPONED       0x08    /* (?1),(?&name), (??{...}) or similar */
319 #define TRYAGAIN        0x10    /* Weeded out a declaration. */
320 #define RESTART_PARSE   0x20    /* Need to redo the parse */
321 #define NEED_UTF8       0x40    /* In conjunction with RESTART_PARSE, need to
322                                    calcuate sizes as UTF-8 */
323
324 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
325
326 /* whether trie related optimizations are enabled */
327 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
328 #define TRIE_STUDY_OPT
329 #define FULL_TRIE_STUDY
330 #define TRIE_STCLASS
331 #endif
332
333
334
335 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
336 #define PBITVAL(paren) (1 << ((paren) & 7))
337 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
338 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
339 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
340
341 #define REQUIRE_UTF8(flagp) STMT_START {                                   \
342                                      if (!UTF) {                           \
343                                          *flagp = RESTART_PARSE|NEED_UTF8; \
344                                          return 0;                         \
345                                      }                                     \
346                              } STMT_END
347
348 /* Change from /d into /u rules, and restart the parse.  RExC_uni_semantics is
349  * a flag that indicates we've changed to /u during the parse.  */
350 #define REQUIRE_UNI_RULES(flagp, restart_retval)                            \
351     STMT_START {                                                            \
352             if (DEPENDS_SEMANTICS) {                                        \
353                 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);      \
354                 RExC_uni_semantics = 1;                                     \
355                 if (RExC_seen_d_op && LIKELY(RExC_total_parens >= 0)) {     \
356                     /* No need to restart the parse if we haven't seen      \
357                      * anything that differs between /u and /d, and no need \
358                      * to restart immediately if we're going to reparse     \
359                      * anyway to count parens */                            \
360                     *flagp |= RESTART_PARSE;                                \
361                     return restart_retval;                                  \
362                 }                                                           \
363             }                                                               \
364     } STMT_END
365
366 #define BRANCH_MAX_OFFSET   U16_MAX
367 #define REQUIRE_BRANCHJ(flagp, restart_retval)                              \
368     STMT_START {                                                            \
369                 RExC_use_BRANCHJ = 1;                                       \
370                 if (LIKELY(RExC_total_parens >= 0)) {                       \
371                     /* No need to restart the parse immediately if we're    \
372                      * going to reparse anyway to count parens */           \
373                     *flagp |= RESTART_PARSE;                                \
374                     return restart_retval;                                  \
375                 }                                                           \
376     } STMT_END
377
378 #define REQUIRE_PARENS_PASS                                                 \
379     STMT_START {                                                            \
380                     if (RExC_total_parens == 0) RExC_total_parens = -1;     \
381     } STMT_END
382
383 /* This is used to return failure (zero) early from the calling function if
384  * various flags in 'flags' are set.  Two flags always cause a return:
385  * 'RESTART_PARSE' and 'NEED_UTF8'.   'extra' can be used to specify any
386  * additional flags that should cause a return; 0 if none.  If the return will
387  * be done, '*flagp' is first set to be all of the flags that caused the
388  * return. */
389 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra)                  \
390     STMT_START {                                                            \
391             if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) {              \
392                 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra));     \
393                 return 0;                                                   \
394             }                                                               \
395     } STMT_END
396
397 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
398
399 #define RETURN_FAIL_ON_RESTART(flags,flagp)                                 \
400                         RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
401 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp)                                 \
402                                     if (MUST_RESTART(*(flagp))) return 0
403
404 /* This converts the named class defined in regcomp.h to its equivalent class
405  * number defined in handy.h. */
406 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
407 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
408
409 #define _invlist_union_complement_2nd(a, b, output) \
410                         _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
411 #define _invlist_intersection_complement_2nd(a, b, output) \
412                  _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
413
414 /* About scan_data_t.
415
416   During optimisation we recurse through the regexp program performing
417   various inplace (keyhole style) optimisations. In addition study_chunk
418   and scan_commit populate this data structure with information about
419   what strings MUST appear in the pattern. We look for the longest
420   string that must appear at a fixed location, and we look for the
421   longest string that may appear at a floating location. So for instance
422   in the pattern:
423
424     /FOO[xX]A.*B[xX]BAR/
425
426   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
427   strings (because they follow a .* construct). study_chunk will identify
428   both FOO and BAR as being the longest fixed and floating strings respectively.
429
430   The strings can be composites, for instance
431
432      /(f)(o)(o)/
433
434   will result in a composite fixed substring 'foo'.
435
436   For each string some basic information is maintained:
437
438   - min_offset
439     This is the position the string must appear at, or not before.
440     It also implicitly (when combined with minlenp) tells us how many
441     characters must match before the string we are searching for.
442     Likewise when combined with minlenp and the length of the string it
443     tells us how many characters must appear after the string we have
444     found.
445
446   - max_offset
447     Only used for floating strings. This is the rightmost point that
448     the string can appear at. If set to SSize_t_MAX it indicates that the
449     string can occur infinitely far to the right.
450     For fixed strings, it is equal to min_offset.
451
452   - minlenp
453     A pointer to the minimum number of characters of the pattern that the
454     string was found inside. This is important as in the case of positive
455     lookahead or positive lookbehind we can have multiple patterns
456     involved. Consider
457
458     /(?=FOO).*F/
459
460     The minimum length of the pattern overall is 3, the minimum length
461     of the lookahead part is 3, but the minimum length of the part that
462     will actually match is 1. So 'FOO's minimum length is 3, but the
463     minimum length for the F is 1. This is important as the minimum length
464     is used to determine offsets in front of and behind the string being
465     looked for.  Since strings can be composites this is the length of the
466     pattern at the time it was committed with a scan_commit. Note that
467     the length is calculated by study_chunk, so that the minimum lengths
468     are not known until the full pattern has been compiled, thus the
469     pointer to the value.
470
471   - lookbehind
472
473     In the case of lookbehind the string being searched for can be
474     offset past the start point of the final matching string.
475     If this value was just blithely removed from the min_offset it would
476     invalidate some of the calculations for how many chars must match
477     before or after (as they are derived from min_offset and minlen and
478     the length of the string being searched for).
479     When the final pattern is compiled and the data is moved from the
480     scan_data_t structure into the regexp structure the information
481     about lookbehind is factored in, with the information that would
482     have been lost precalculated in the end_shift field for the
483     associated string.
484
485   The fields pos_min and pos_delta are used to store the minimum offset
486   and the delta to the maximum offset at the current point in the pattern.
487
488 */
489
490 struct scan_data_substrs {
491     SV      *str;       /* longest substring found in pattern */
492     SSize_t min_offset; /* earliest point in string it can appear */
493     SSize_t max_offset; /* latest point in string it can appear */
494     SSize_t *minlenp;   /* pointer to the minlen relevant to the string */
495     SSize_t lookbehind; /* is the pos of the string modified by LB */
496     I32 flags;          /* per substring SF_* and SCF_* flags */
497 };
498
499 typedef struct scan_data_t {
500     /*I32 len_min;      unused */
501     /*I32 len_delta;    unused */
502     SSize_t pos_min;
503     SSize_t pos_delta;
504     SV *last_found;
505     SSize_t last_end;       /* min value, <0 unless valid. */
506     SSize_t last_start_min;
507     SSize_t last_start_max;
508     U8      cur_is_floating; /* whether the last_* values should be set as
509                               * the next fixed (0) or floating (1)
510                               * substring */
511
512     /* [0] is longest fixed substring so far, [1] is longest float so far */
513     struct scan_data_substrs  substrs[2];
514
515     I32 flags;             /* common SF_* and SCF_* flags */
516     I32 whilem_c;
517     SSize_t *last_closep;
518     regnode_ssc *start_class;
519 } scan_data_t;
520
521 /*
522  * Forward declarations for pregcomp()'s friends.
523  */
524
525 static const scan_data_t zero_scan_data = {
526     0, 0, NULL, 0, 0, 0, 0,
527     {
528         { NULL, 0, 0, 0, 0, 0 },
529         { NULL, 0, 0, 0, 0, 0 },
530     },
531     0, 0, NULL, NULL
532 };
533
534 /* study flags */
535
536 #define SF_BEFORE_SEOL          0x0001
537 #define SF_BEFORE_MEOL          0x0002
538 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
539
540 #define SF_IS_INF               0x0040
541 #define SF_HAS_PAR              0x0080
542 #define SF_IN_PAR               0x0100
543 #define SF_HAS_EVAL             0x0200
544
545
546 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
547  * longest substring in the pattern. When it is not set the optimiser keeps
548  * track of position, but does not keep track of the actual strings seen,
549  *
550  * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
551  * /foo/i will not.
552  *
553  * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
554  * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
555  * turned off because of the alternation (BRANCH). */
556 #define SCF_DO_SUBSTR           0x0400
557
558 #define SCF_DO_STCLASS_AND      0x0800
559 #define SCF_DO_STCLASS_OR       0x1000
560 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
561 #define SCF_WHILEM_VISITED_POS  0x2000
562
563 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
564 #define SCF_SEEN_ACCEPT         0x8000
565 #define SCF_TRIE_DOING_RESTUDY 0x10000
566 #define SCF_IN_DEFINE          0x20000
567
568
569
570
571 #define UTF cBOOL(RExC_utf8)
572
573 /* The enums for all these are ordered so things work out correctly */
574 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
575 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags)                    \
576                                                      == REGEX_DEPENDS_CHARSET)
577 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
578 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags)                \
579                                                      >= REGEX_UNICODE_CHARSET)
580 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags)                      \
581                                             == REGEX_ASCII_RESTRICTED_CHARSET)
582 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags)             \
583                                             >= REGEX_ASCII_RESTRICTED_CHARSET)
584 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags)                 \
585                                         == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
586
587 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
588
589 /* For programs that want to be strictly Unicode compatible by dying if any
590  * attempt is made to match a non-Unicode code point against a Unicode
591  * property.  */
592 #define ALWAYS_WARN_SUPER  ckDEAD(packWARN(WARN_NON_UNICODE))
593
594 #define OOB_NAMEDCLASS          -1
595
596 /* There is no code point that is out-of-bounds, so this is problematic.  But
597  * its only current use is to initialize a variable that is always set before
598  * looked at. */
599 #define OOB_UNICODE             0xDEADBEEF
600
601 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
602
603
604 /* length of regex to show in messages that don't mark a position within */
605 #define RegexLengthToShowInErrorMessages 127
606
607 /*
608  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
609  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
610  * op/pragma/warn/regcomp.
611  */
612 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
613 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
614
615 #define REPORT_LOCATION " in regex; marked by " MARKER1    \
616                         " in m/%" UTF8f MARKER2 "%" UTF8f "/"
617
618 /* The code in this file in places uses one level of recursion with parsing
619  * rebased to an alternate string constructed by us in memory.  This can take
620  * the form of something that is completely different from the input, or
621  * something that uses the input as part of the alternate.  In the first case,
622  * there should be no possibility of an error, as we are in complete control of
623  * the alternate string.  But in the second case we don't completely control
624  * the input portion, so there may be errors in that.  Here's an example:
625  *      /[abc\x{DF}def]/ui
626  * is handled specially because \x{df} folds to a sequence of more than one
627  * character: 'ss'.  What is done is to create and parse an alternate string,
628  * which looks like this:
629  *      /(?:\x{DF}|[abc\x{DF}def])/ui
630  * where it uses the input unchanged in the middle of something it constructs,
631  * which is a branch for the DF outside the character class, and clustering
632  * parens around the whole thing. (It knows enough to skip the DF inside the
633  * class while in this substitute parse.) 'abc' and 'def' may have errors that
634  * need to be reported.  The general situation looks like this:
635  *
636  *                                       |<------- identical ------>|
637  *              sI                       tI               xI       eI
638  * Input:       ---------------------------------------------------------------
639  * Constructed:         ---------------------------------------------------
640  *                      sC               tC               xC       eC     EC
641  *                                       |<------- identical ------>|
642  *
643  * sI..eI   is the portion of the input pattern we are concerned with here.
644  * sC..EC   is the constructed substitute parse string.
645  *  sC..tC  is constructed by us
646  *  tC..eC  is an exact duplicate of the portion of the input pattern tI..eI.
647  *          In the diagram, these are vertically aligned.
648  *  eC..EC  is also constructed by us.
649  * xC       is the position in the substitute parse string where we found a
650  *          problem.
651  * xI       is the position in the original pattern corresponding to xC.
652  *
653  * We want to display a message showing the real input string.  Thus we need to
654  * translate from xC to xI.  We know that xC >= tC, since the portion of the
655  * string sC..tC has been constructed by us, and so shouldn't have errors.  We
656  * get:
657  *      xI = tI + (xC - tC)
658  *
659  * When the substitute parse is constructed, the code needs to set:
660  *      RExC_start (sC)
661  *      RExC_end (eC)
662  *      RExC_copy_start_in_input  (tI)
663  *      RExC_copy_start_in_constructed (tC)
664  * and restore them when done.
665  *
666  * During normal processing of the input pattern, both
667  * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
668  * sI, so that xC equals xI.
669  */
670
671 #define sI              RExC_precomp
672 #define eI              RExC_precomp_end
673 #define sC              RExC_start
674 #define eC              RExC_end
675 #define tI              RExC_copy_start_in_input
676 #define tC              RExC_copy_start_in_constructed
677 #define xI(xC)          (tI + (xC - tC))
678 #define xI_offset(xC)   (xI(xC) - sI)
679
680 #define REPORT_LOCATION_ARGS(xC)                                            \
681     UTF8fARG(UTF,                                                           \
682              (xI(xC) > eI) /* Don't run off end */                          \
683               ? eI - sI   /* Length before the <--HERE */                   \
684               : ((xI_offset(xC) >= 0)                                       \
685                  ? xI_offset(xC)                                            \
686                  : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %"    \
687                                     IVdf " trying to output message for "   \
688                                     " pattern %.*s",                        \
689                                     __FILE__, __LINE__, (IV) xI_offset(xC), \
690                                     ((int) (eC - sC)), sC), 0)),            \
691              sI),         /* The input pattern printed up to the <--HERE */ \
692     UTF8fARG(UTF,                                                           \
693              (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */    \
694              (xI(xC) > eI) ? eI : xI(xC))     /* pattern after <--HERE */
695
696 /* Used to point after bad bytes for an error message, but avoid skipping
697  * past a nul byte. */
698 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
699
700 /* Set up to clean up after our imminent demise */
701 #define PREPARE_TO_DIE                                                      \
702     STMT_START {                                                            \
703         if (RExC_rx_sv)                                                     \
704             SAVEFREESV(RExC_rx_sv);                                         \
705         if (RExC_open_parens)                                               \
706             SAVEFREEPV(RExC_open_parens);                                   \
707         if (RExC_close_parens)                                              \
708             SAVEFREEPV(RExC_close_parens);                                  \
709     } STMT_END
710
711 /*
712  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
713  * arg. Show regex, up to a maximum length. If it's too long, chop and add
714  * "...".
715  */
716 #define _FAIL(code) STMT_START {                                        \
717     const char *ellipses = "";                                          \
718     IV len = RExC_precomp_end - RExC_precomp;                           \
719                                                                         \
720     PREPARE_TO_DIE;                                                     \
721     if (len > RegexLengthToShowInErrorMessages) {                       \
722         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
723         len = RegexLengthToShowInErrorMessages - 10;                    \
724         ellipses = "...";                                               \
725     }                                                                   \
726     code;                                                               \
727 } STMT_END
728
729 #define FAIL(msg) _FAIL(                            \
730     Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/",         \
731             msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
732
733 #define FAIL2(msg,arg) _FAIL(                       \
734     Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/",       \
735             arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
736
737 /*
738  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
739  */
740 #define Simple_vFAIL(m) STMT_START {                                    \
741     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
742             m, REPORT_LOCATION_ARGS(RExC_parse));                       \
743 } STMT_END
744
745 /*
746  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
747  */
748 #define vFAIL(m) STMT_START {                           \
749     PREPARE_TO_DIE;                                     \
750     Simple_vFAIL(m);                                    \
751 } STMT_END
752
753 /*
754  * Like Simple_vFAIL(), but accepts two arguments.
755  */
756 #define Simple_vFAIL2(m,a1) STMT_START {                        \
757     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,              \
758                       REPORT_LOCATION_ARGS(RExC_parse));        \
759 } STMT_END
760
761 /*
762  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
763  */
764 #define vFAIL2(m,a1) STMT_START {                       \
765     PREPARE_TO_DIE;                                     \
766     Simple_vFAIL2(m, a1);                               \
767 } STMT_END
768
769
770 /*
771  * Like Simple_vFAIL(), but accepts three arguments.
772  */
773 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
774     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,          \
775             REPORT_LOCATION_ARGS(RExC_parse));                  \
776 } STMT_END
777
778 /*
779  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
780  */
781 #define vFAIL3(m,a1,a2) STMT_START {                    \
782     PREPARE_TO_DIE;                                     \
783     Simple_vFAIL3(m, a1, a2);                           \
784 } STMT_END
785
786 /*
787  * Like Simple_vFAIL(), but accepts four arguments.
788  */
789 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
790     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3,      \
791             REPORT_LOCATION_ARGS(RExC_parse));                  \
792 } STMT_END
793
794 #define vFAIL4(m,a1,a2,a3) STMT_START {                 \
795     PREPARE_TO_DIE;                                     \
796     Simple_vFAIL4(m, a1, a2, a3);                       \
797 } STMT_END
798
799 /* A specialized version of vFAIL2 that works with UTF8f */
800 #define vFAIL2utf8f(m, a1) STMT_START {             \
801     PREPARE_TO_DIE;                                 \
802     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,  \
803             REPORT_LOCATION_ARGS(RExC_parse));      \
804 } STMT_END
805
806 #define vFAIL3utf8f(m, a1, a2) STMT_START {             \
807     PREPARE_TO_DIE;                                     \
808     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,  \
809             REPORT_LOCATION_ARGS(RExC_parse));          \
810 } STMT_END
811
812 /* Setting this to NULL is a signal to not output warnings */
813 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE RExC_copy_start_in_constructed = NULL
814 #define RESTORE_WARNINGS RExC_copy_start_in_constructed = RExC_precomp
815
816 /* Since a warning can be generated multiple times as the input is reparsed, we
817  * output it the first time we come to that point in the parse, but suppress it
818  * otherwise.  'RExC_copy_start_in_constructed' being NULL is a flag to not
819  * generate any warnings */
820 #define TO_OUTPUT_WARNINGS(loc)                                         \
821   (   RExC_copy_start_in_constructed                                    \
822    && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
823
824 /* After we've emitted a warning, we save the position in the input so we don't
825  * output it again */
826 #define UPDATE_WARNINGS_LOC(loc)                                        \
827     STMT_START {                                                        \
828         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
829             RExC_latest_warn_offset = (xI(loc)) - RExC_precomp;         \
830         }                                                               \
831     } STMT_END
832
833 /* 'warns' is the output of the packWARNx macro used in 'code' */
834 #define _WARN_HELPER(loc, warns, code)                                  \
835     STMT_START {                                                        \
836         if (! RExC_copy_start_in_constructed) {                         \
837             Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none"  \
838                               " expected at '%s'",                      \
839                               __FILE__, __LINE__, loc);                 \
840         }                                                               \
841         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
842             if (ckDEAD(warns))                                          \
843                 PREPARE_TO_DIE;                                         \
844             code;                                                       \
845             UPDATE_WARNINGS_LOC(loc);                                   \
846         }                                                               \
847     } STMT_END
848
849 /* m is not necessarily a "literal string", in this macro */
850 #define reg_warn_non_literal_string(loc, m)                             \
851     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
852                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
853                                        "%s" REPORT_LOCATION,            \
854                                   m, REPORT_LOCATION_ARGS(loc)))
855
856 #define ckWARNreg(loc,m)                                                \
857     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
858                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
859                                           m REPORT_LOCATION,            \
860                                           REPORT_LOCATION_ARGS(loc)))
861
862 #define vWARN(loc, m)                                                   \
863     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
864                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
865                                        m REPORT_LOCATION,               \
866                                        REPORT_LOCATION_ARGS(loc)))      \
867
868 #define vWARN_dep(loc, m)                                               \
869     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
870                       Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),      \
871                                        m REPORT_LOCATION,               \
872                                        REPORT_LOCATION_ARGS(loc)))
873
874 #define ckWARNdep(loc,m)                                                \
875     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
876                       Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
877                                             m REPORT_LOCATION,          \
878                                             REPORT_LOCATION_ARGS(loc)))
879
880 #define ckWARNregdep(loc,m)                                                 \
881     _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP),              \
882                       Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED,     \
883                                                       WARN_REGEXP),         \
884                                              m REPORT_LOCATION,             \
885                                              REPORT_LOCATION_ARGS(loc)))
886
887 #define ckWARN2reg_d(loc,m, a1)                                             \
888     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
889                       Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP),         \
890                                             m REPORT_LOCATION,              \
891                                             a1, REPORT_LOCATION_ARGS(loc)))
892
893 #define ckWARN2reg(loc, m, a1)                                              \
894     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
895                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
896                                           m REPORT_LOCATION,                \
897                                           a1, REPORT_LOCATION_ARGS(loc)))
898
899 #define vWARN3(loc, m, a1, a2)                                              \
900     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
901                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),              \
902                                        m REPORT_LOCATION,                   \
903                                        a1, a2, REPORT_LOCATION_ARGS(loc)))
904
905 #define ckWARN3reg(loc, m, a1, a2)                                          \
906     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
907                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
908                                           m REPORT_LOCATION,                \
909                                           a1, a2,                           \
910                                           REPORT_LOCATION_ARGS(loc)))
911
912 #define vWARN4(loc, m, a1, a2, a3)                                      \
913     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
914                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
915                                        m REPORT_LOCATION,               \
916                                        a1, a2, a3,                      \
917                                        REPORT_LOCATION_ARGS(loc)))
918
919 #define ckWARN4reg(loc, m, a1, a2, a3)                                  \
920     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
921                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
922                                           m REPORT_LOCATION,            \
923                                           a1, a2, a3,                   \
924                                           REPORT_LOCATION_ARGS(loc)))
925
926 #define vWARN5(loc, m, a1, a2, a3, a4)                                  \
927     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
928                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
929                                        m REPORT_LOCATION,               \
930                                        a1, a2, a3, a4,                  \
931                                        REPORT_LOCATION_ARGS(loc)))
932
933 #define ckWARNexperimental(loc, class, m)                               \
934     _WARN_HELPER(loc, packWARN(class),                                  \
935                       Perl_ck_warner_d(aTHX_ packWARN(class),           \
936                                             m REPORT_LOCATION,          \
937                                             REPORT_LOCATION_ARGS(loc)))
938
939 /* Convert between a pointer to a node and its offset from the beginning of the
940  * program */
941 #define REGNODE_p(offset)    (RExC_emit_start + (offset))
942 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
943
944 /* Macros for recording node offsets.   20001227 mjd@plover.com
945  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
946  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
947  * Element 0 holds the number n.
948  * Position is 1 indexed.
949  */
950 #ifndef RE_TRACK_PATTERN_OFFSETS
951 #define Set_Node_Offset_To_R(offset,byte)
952 #define Set_Node_Offset(node,byte)
953 #define Set_Cur_Node_Offset
954 #define Set_Node_Length_To_R(node,len)
955 #define Set_Node_Length(node,len)
956 #define Set_Node_Cur_Length(node,start)
957 #define Node_Offset(n)
958 #define Node_Length(n)
959 #define Set_Node_Offset_Length(node,offset,len)
960 #define ProgLen(ri) ri->u.proglen
961 #define SetProgLen(ri,x) ri->u.proglen = x
962 #define Track_Code(code)
963 #else
964 #define ProgLen(ri) ri->u.offsets[0]
965 #define SetProgLen(ri,x) ri->u.offsets[0] = x
966 #define Set_Node_Offset_To_R(offset,byte) STMT_START {                  \
967         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
968                     __LINE__, (int)(offset), (int)(byte)));             \
969         if((offset) < 0) {                                              \
970             Perl_croak(aTHX_ "value of node is %d in Offset macro",     \
971                                          (int)(offset));                \
972         } else {                                                        \
973             RExC_offsets[2*(offset)-1] = (byte);                        \
974         }                                                               \
975 } STMT_END
976
977 #define Set_Node_Offset(node,byte)                                      \
978     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
979 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
980
981 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
982         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
983                 __LINE__, (int)(node), (int)(len)));                    \
984         if((node) < 0) {                                                \
985             Perl_croak(aTHX_ "value of node is %d in Length macro",     \
986                                          (int)(node));                  \
987         } else {                                                        \
988             RExC_offsets[2*(node)] = (len);                             \
989         }                                                               \
990 } STMT_END
991
992 #define Set_Node_Length(node,len) \
993     Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
994 #define Set_Node_Cur_Length(node, start)                \
995     Set_Node_Length(node, RExC_parse - start)
996
997 /* Get offsets and lengths */
998 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
999 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1000
1001 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
1002     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset));       \
1003     Set_Node_Length_To_R(REGNODE_OFFSET(node), (len));  \
1004 } STMT_END
1005
1006 #define Track_Code(code) STMT_START { code } STMT_END
1007 #endif
1008
1009 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1010 #define EXPERIMENTAL_INPLACESCAN
1011 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1012
1013 #ifdef DEBUGGING
1014 int
1015 Perl_re_printf(pTHX_ const char *fmt, ...)
1016 {
1017     va_list ap;
1018     int result;
1019     PerlIO *f= Perl_debug_log;
1020     PERL_ARGS_ASSERT_RE_PRINTF;
1021     va_start(ap, fmt);
1022     result = PerlIO_vprintf(f, fmt, ap);
1023     va_end(ap);
1024     return result;
1025 }
1026
1027 int
1028 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1029 {
1030     va_list ap;
1031     int result;
1032     PerlIO *f= Perl_debug_log;
1033     PERL_ARGS_ASSERT_RE_INDENTF;
1034     va_start(ap, depth);
1035     PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1036     result = PerlIO_vprintf(f, fmt, ap);
1037     va_end(ap);
1038     return result;
1039 }
1040 #endif /* DEBUGGING */
1041
1042 #define DEBUG_RExC_seen()                                                   \
1043         DEBUG_OPTIMISE_MORE_r({                                             \
1044             Perl_re_printf( aTHX_ "RExC_seen: ");                           \
1045                                                                             \
1046             if (RExC_seen & REG_ZERO_LEN_SEEN)                              \
1047                 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN ");                \
1048                                                                             \
1049             if (RExC_seen & REG_LOOKBEHIND_SEEN)                            \
1050                 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN ");              \
1051                                                                             \
1052             if (RExC_seen & REG_GPOS_SEEN)                                  \
1053                 Perl_re_printf( aTHX_ "REG_GPOS_SEEN ");                    \
1054                                                                             \
1055             if (RExC_seen & REG_RECURSE_SEEN)                               \
1056                 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN ");                 \
1057                                                                             \
1058             if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)                    \
1059                 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN ");      \
1060                                                                             \
1061             if (RExC_seen & REG_VERBARG_SEEN)                               \
1062                 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN ");                 \
1063                                                                             \
1064             if (RExC_seen & REG_CUTGROUP_SEEN)                              \
1065                 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN ");                \
1066                                                                             \
1067             if (RExC_seen & REG_RUN_ON_COMMENT_SEEN)                        \
1068                 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN ");          \
1069                                                                             \
1070             if (RExC_seen & REG_UNFOLDED_MULTI_SEEN)                        \
1071                 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN ");          \
1072                                                                             \
1073             if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)                  \
1074                 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN ");    \
1075                                                                             \
1076             Perl_re_printf( aTHX_ "\n");                                    \
1077         });
1078
1079 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1080   if ((flags) & flag) Perl_re_printf( aTHX_  "%s ", #flag)
1081
1082
1083 #ifdef DEBUGGING
1084 static void
1085 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1086                                     const char *close_str)
1087 {
1088     if (!flags)
1089         return;
1090
1091     Perl_re_printf( aTHX_  "%s", open_str);
1092     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1093     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1094     DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1095     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1096     DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1097     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1098     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1099     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1100     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1101     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1102     DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1103     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1104     DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1105     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1106     DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1107     Perl_re_printf( aTHX_  "%s", close_str);
1108 }
1109
1110
1111 static void
1112 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1113                     U32 depth, int is_inf)
1114 {
1115     GET_RE_DEBUG_FLAGS_DECL;
1116
1117     DEBUG_OPTIMISE_MORE_r({
1118         if (!data)
1119             return;
1120         Perl_re_indentf(aTHX_  "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1121             depth,
1122             where,
1123             (IV)data->pos_min,
1124             (IV)data->pos_delta,
1125             (UV)data->flags
1126         );
1127
1128         S_debug_show_study_flags(aTHX_ data->flags," [","]");
1129
1130         Perl_re_printf( aTHX_
1131             " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1132             (IV)data->whilem_c,
1133             (IV)(data->last_closep ? *((data)->last_closep) : -1),
1134             is_inf ? "INF " : ""
1135         );
1136
1137         if (data->last_found) {
1138             int i;
1139             Perl_re_printf(aTHX_
1140                 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1141                     SvPVX_const(data->last_found),
1142                     (IV)data->last_end,
1143                     (IV)data->last_start_min,
1144                     (IV)data->last_start_max
1145             );
1146
1147             for (i = 0; i < 2; i++) {
1148                 Perl_re_printf(aTHX_
1149                     " %s%s: '%s' @ %" IVdf "/%" IVdf,
1150                     data->cur_is_floating == i ? "*" : "",
1151                     i ? "Float" : "Fixed",
1152                     SvPVX_const(data->substrs[i].str),
1153                     (IV)data->substrs[i].min_offset,
1154                     (IV)data->substrs[i].max_offset
1155                 );
1156                 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1157             }
1158         }
1159
1160         Perl_re_printf( aTHX_ "\n");
1161     });
1162 }
1163
1164
1165 static void
1166 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1167                 regnode *scan, U32 depth, U32 flags)
1168 {
1169     GET_RE_DEBUG_FLAGS_DECL;
1170
1171     DEBUG_OPTIMISE_r({
1172         regnode *Next;
1173
1174         if (!scan)
1175             return;
1176         Next = regnext(scan);
1177         regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1178         Perl_re_indentf( aTHX_   "%s>%3d: %s (%d)",
1179             depth,
1180             str,
1181             REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1182             Next ? (REG_NODE_NUM(Next)) : 0 );
1183         S_debug_show_study_flags(aTHX_ flags," [ ","]");
1184         Perl_re_printf( aTHX_  "\n");
1185    });
1186 }
1187
1188
1189 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1190                     S_debug_studydata(aTHX_ where, data, depth, is_inf)
1191
1192 #  define DEBUG_PEEP(str, scan, depth, flags)   \
1193                     S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1194
1195 #else
1196 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1197 #  define DEBUG_PEEP(str, scan, depth, flags)         NOOP
1198 #endif
1199
1200
1201 /* =========================================================
1202  * BEGIN edit_distance stuff.
1203  *
1204  * This calculates how many single character changes of any type are needed to
1205  * transform a string into another one.  It is taken from version 3.1 of
1206  *
1207  * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1208  */
1209
1210 /* Our unsorted dictionary linked list.   */
1211 /* Note we use UVs, not chars. */
1212
1213 struct dictionary{
1214   UV key;
1215   UV value;
1216   struct dictionary* next;
1217 };
1218 typedef struct dictionary item;
1219
1220
1221 PERL_STATIC_INLINE item*
1222 push(UV key, item* curr)
1223 {
1224     item* head;
1225     Newx(head, 1, item);
1226     head->key = key;
1227     head->value = 0;
1228     head->next = curr;
1229     return head;
1230 }
1231
1232
1233 PERL_STATIC_INLINE item*
1234 find(item* head, UV key)
1235 {
1236     item* iterator = head;
1237     while (iterator){
1238         if (iterator->key == key){
1239             return iterator;
1240         }
1241         iterator = iterator->next;
1242     }
1243
1244     return NULL;
1245 }
1246
1247 PERL_STATIC_INLINE item*
1248 uniquePush(item* head, UV key)
1249 {
1250     item* iterator = head;
1251
1252     while (iterator){
1253         if (iterator->key == key) {
1254             return head;
1255         }
1256         iterator = iterator->next;
1257     }
1258
1259     return push(key, head);
1260 }
1261
1262 PERL_STATIC_INLINE void
1263 dict_free(item* head)
1264 {
1265     item* iterator = head;
1266
1267     while (iterator) {
1268         item* temp = iterator;
1269         iterator = iterator->next;
1270         Safefree(temp);
1271     }
1272
1273     head = NULL;
1274 }
1275
1276 /* End of Dictionary Stuff */
1277
1278 /* All calculations/work are done here */
1279 STATIC int
1280 S_edit_distance(const UV* src,
1281                 const UV* tgt,
1282                 const STRLEN x,             /* length of src[] */
1283                 const STRLEN y,             /* length of tgt[] */
1284                 const SSize_t maxDistance
1285 )
1286 {
1287     item *head = NULL;
1288     UV swapCount, swapScore, targetCharCount, i, j;
1289     UV *scores;
1290     UV score_ceil = x + y;
1291
1292     PERL_ARGS_ASSERT_EDIT_DISTANCE;
1293
1294     /* intialize matrix start values */
1295     Newx(scores, ( (x + 2) * (y + 2)), UV);
1296     scores[0] = score_ceil;
1297     scores[1 * (y + 2) + 0] = score_ceil;
1298     scores[0 * (y + 2) + 1] = score_ceil;
1299     scores[1 * (y + 2) + 1] = 0;
1300     head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1301
1302     /* work loops    */
1303     /* i = src index */
1304     /* j = tgt index */
1305     for (i=1;i<=x;i++) {
1306         if (i < x)
1307             head = uniquePush(head, src[i]);
1308         scores[(i+1) * (y + 2) + 1] = i;
1309         scores[(i+1) * (y + 2) + 0] = score_ceil;
1310         swapCount = 0;
1311
1312         for (j=1;j<=y;j++) {
1313             if (i == 1) {
1314                 if(j < y)
1315                 head = uniquePush(head, tgt[j]);
1316                 scores[1 * (y + 2) + (j + 1)] = j;
1317                 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1318             }
1319
1320             targetCharCount = find(head, tgt[j-1])->value;
1321             swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1322
1323             if (src[i-1] != tgt[j-1]){
1324                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(swapScore,(MIN(scores[i * (y + 2) + j], MIN(scores[(i+1) * (y + 2) + j], scores[i * (y + 2) + (j + 1)])) + 1));
1325             }
1326             else {
1327                 swapCount = j;
1328                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1329             }
1330         }
1331
1332         find(head, src[i-1])->value = i;
1333     }
1334
1335     {
1336         IV score = scores[(x+1) * (y + 2) + (y + 1)];
1337         dict_free(head);
1338         Safefree(scores);
1339         return (maxDistance != 0 && maxDistance < score)?(-1):score;
1340     }
1341 }
1342
1343 /* END of edit_distance() stuff
1344  * ========================================================= */
1345
1346 /* is c a control character for which we have a mnemonic? */
1347 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1348
1349 STATIC const char *
1350 S_cntrl_to_mnemonic(const U8 c)
1351 {
1352     /* Returns the mnemonic string that represents character 'c', if one
1353      * exists; NULL otherwise.  The only ones that exist for the purposes of
1354      * this routine are a few control characters */
1355
1356     switch (c) {
1357         case '\a':       return "\\a";
1358         case '\b':       return "\\b";
1359         case ESC_NATIVE: return "\\e";
1360         case '\f':       return "\\f";
1361         case '\n':       return "\\n";
1362         case '\r':       return "\\r";
1363         case '\t':       return "\\t";
1364     }
1365
1366     return NULL;
1367 }
1368
1369 /* Mark that we cannot extend a found fixed substring at this point.
1370    Update the longest found anchored substring or the longest found
1371    floating substrings if needed. */
1372
1373 STATIC void
1374 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1375                     SSize_t *minlenp, int is_inf)
1376 {
1377     const STRLEN l = CHR_SVLEN(data->last_found);
1378     SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1379     const STRLEN old_l = CHR_SVLEN(longest_sv);
1380     GET_RE_DEBUG_FLAGS_DECL;
1381
1382     PERL_ARGS_ASSERT_SCAN_COMMIT;
1383
1384     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1385         const U8 i = data->cur_is_floating;
1386         SvSetMagicSV(longest_sv, data->last_found);
1387         data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1388
1389         if (!i) /* fixed */
1390             data->substrs[0].max_offset = data->substrs[0].min_offset;
1391         else { /* float */
1392             data->substrs[1].max_offset = (l
1393                           ? data->last_start_max
1394                           : (data->pos_delta > SSize_t_MAX - data->pos_min
1395                                          ? SSize_t_MAX
1396                                          : data->pos_min + data->pos_delta));
1397             if (is_inf
1398                  || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1399                 data->substrs[1].max_offset = SSize_t_MAX;
1400         }
1401
1402         if (data->flags & SF_BEFORE_EOL)
1403             data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1404         else
1405             data->substrs[i].flags &= ~SF_BEFORE_EOL;
1406         data->substrs[i].minlenp = minlenp;
1407         data->substrs[i].lookbehind = 0;
1408     }
1409
1410     SvCUR_set(data->last_found, 0);
1411     {
1412         SV * const sv = data->last_found;
1413         if (SvUTF8(sv) && SvMAGICAL(sv)) {
1414             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1415             if (mg)
1416                 mg->mg_len = 0;
1417         }
1418     }
1419     data->last_end = -1;
1420     data->flags &= ~SF_BEFORE_EOL;
1421     DEBUG_STUDYDATA("commit", data, 0, is_inf);
1422 }
1423
1424 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1425  * list that describes which code points it matches */
1426
1427 STATIC void
1428 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1429 {
1430     /* Set the SSC 'ssc' to match an empty string or any code point */
1431
1432     PERL_ARGS_ASSERT_SSC_ANYTHING;
1433
1434     assert(is_ANYOF_SYNTHETIC(ssc));
1435
1436     /* mortalize so won't leak */
1437     ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1438     ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING;  /* Plus matches empty */
1439 }
1440
1441 STATIC int
1442 S_ssc_is_anything(const regnode_ssc *ssc)
1443 {
1444     /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1445      * point; FALSE otherwise.  Thus, this is used to see if using 'ssc' buys
1446      * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1447      * in any way, so there's no point in using it */
1448
1449     UV start, end;
1450     bool ret;
1451
1452     PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1453
1454     assert(is_ANYOF_SYNTHETIC(ssc));
1455
1456     if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1457         return FALSE;
1458     }
1459
1460     /* See if the list consists solely of the range 0 - Infinity */
1461     invlist_iterinit(ssc->invlist);
1462     ret = invlist_iternext(ssc->invlist, &start, &end)
1463           && start == 0
1464           && end == UV_MAX;
1465
1466     invlist_iterfinish(ssc->invlist);
1467
1468     if (ret) {
1469         return TRUE;
1470     }
1471
1472     /* If e.g., both \w and \W are set, matches everything */
1473     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1474         int i;
1475         for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1476             if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1477                 return TRUE;
1478             }
1479         }
1480     }
1481
1482     return FALSE;
1483 }
1484
1485 STATIC void
1486 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1487 {
1488     /* Initializes the SSC 'ssc'.  This includes setting it to match an empty
1489      * string, any code point, or any posix class under locale */
1490
1491     PERL_ARGS_ASSERT_SSC_INIT;
1492
1493     Zero(ssc, 1, regnode_ssc);
1494     set_ANYOF_SYNTHETIC(ssc);
1495     ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1496     ssc_anything(ssc);
1497
1498     /* If any portion of the regex is to operate under locale rules that aren't
1499      * fully known at compile time, initialization includes it.  The reason
1500      * this isn't done for all regexes is that the optimizer was written under
1501      * the assumption that locale was all-or-nothing.  Given the complexity and
1502      * lack of documentation in the optimizer, and that there are inadequate
1503      * test cases for locale, many parts of it may not work properly, it is
1504      * safest to avoid locale unless necessary. */
1505     if (RExC_contains_locale) {
1506         ANYOF_POSIXL_SETALL(ssc);
1507     }
1508     else {
1509         ANYOF_POSIXL_ZERO(ssc);
1510     }
1511 }
1512
1513 STATIC int
1514 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1515                         const regnode_ssc *ssc)
1516 {
1517     /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1518      * to the list of code points matched, and locale posix classes; hence does
1519      * not check its flags) */
1520
1521     UV start, end;
1522     bool ret;
1523
1524     PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1525
1526     assert(is_ANYOF_SYNTHETIC(ssc));
1527
1528     invlist_iterinit(ssc->invlist);
1529     ret = invlist_iternext(ssc->invlist, &start, &end)
1530           && start == 0
1531           && end == UV_MAX;
1532
1533     invlist_iterfinish(ssc->invlist);
1534
1535     if (! ret) {
1536         return FALSE;
1537     }
1538
1539     if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1540         return FALSE;
1541     }
1542
1543     return TRUE;
1544 }
1545
1546 STATIC SV*
1547 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1548                                const regnode_charclass* const node)
1549 {
1550     /* Returns a mortal inversion list defining which code points are matched
1551      * by 'node', which is of type ANYOF.  Handles complementing the result if
1552      * appropriate.  If some code points aren't knowable at this time, the
1553      * returned list must, and will, contain every code point that is a
1554      * possibility. */
1555
1556     SV* invlist = NULL;
1557     SV* only_utf8_locale_invlist = NULL;
1558     unsigned int i;
1559     const U32 n = ARG(node);
1560     bool new_node_has_latin1 = FALSE;
1561
1562     PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1563
1564     /* Look at the data structure created by S_set_ANYOF_arg() */
1565     if (n != ANYOF_ONLY_HAS_BITMAP) {
1566         SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1567         AV * const av = MUTABLE_AV(SvRV(rv));
1568         SV **const ary = AvARRAY(av);
1569         assert(RExC_rxi->data->what[n] == 's');
1570
1571         if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
1572             invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1]), NULL));
1573         }
1574         else if (ary[0] && ary[0] != &PL_sv_undef) {
1575
1576             /* Here, no compile-time swash, and there are things that won't be
1577              * known until runtime -- we have to assume it could be anything */
1578             invlist = sv_2mortal(_new_invlist(1));
1579             return _add_range_to_invlist(invlist, 0, UV_MAX);
1580         }
1581         else if (ary[3] && ary[3] != &PL_sv_undef) {
1582
1583             /* Here no compile-time swash, and no run-time only data.  Use the
1584              * node's inversion list */
1585             invlist = sv_2mortal(invlist_clone(ary[3], NULL));
1586         }
1587
1588         /* Get the code points valid only under UTF-8 locales */
1589         if ((ANYOF_FLAGS(node) & ANYOFL_FOLD)
1590             && ary[2] && ary[2] != &PL_sv_undef)
1591         {
1592             only_utf8_locale_invlist = ary[2];
1593         }
1594     }
1595
1596     if (! invlist) {
1597         invlist = sv_2mortal(_new_invlist(0));
1598     }
1599
1600     /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1601      * code points, and an inversion list for the others, but if there are code
1602      * points that should match only conditionally on the target string being
1603      * UTF-8, those are placed in the inversion list, and not the bitmap.
1604      * Since there are circumstances under which they could match, they are
1605      * included in the SSC.  But if the ANYOF node is to be inverted, we have
1606      * to exclude them here, so that when we invert below, the end result
1607      * actually does include them.  (Think about "\xe0" =~ /[^\xc0]/di;).  We
1608      * have to do this here before we add the unconditionally matched code
1609      * points */
1610     if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1611         _invlist_intersection_complement_2nd(invlist,
1612                                              PL_UpperLatin1,
1613                                              &invlist);
1614     }
1615
1616     /* Add in the points from the bit map */
1617     for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1618         if (ANYOF_BITMAP_TEST(node, i)) {
1619             unsigned int start = i++;
1620
1621             for (; i < NUM_ANYOF_CODE_POINTS && ANYOF_BITMAP_TEST(node, i); ++i) {
1622                 /* empty */
1623             }
1624             invlist = _add_range_to_invlist(invlist, start, i-1);
1625             new_node_has_latin1 = TRUE;
1626         }
1627     }
1628
1629     /* If this can match all upper Latin1 code points, have to add them
1630      * as well.  But don't add them if inverting, as when that gets done below,
1631      * it would exclude all these characters, including the ones it shouldn't
1632      * that were added just above */
1633     if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
1634         && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1635     {
1636         _invlist_union(invlist, PL_UpperLatin1, &invlist);
1637     }
1638
1639     /* Similarly for these */
1640     if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1641         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1642     }
1643
1644     if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1645         _invlist_invert(invlist);
1646     }
1647     else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1648
1649         /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1650          * locale.  We can skip this if there are no 0-255 at all. */
1651         _invlist_union(invlist, PL_Latin1, &invlist);
1652     }
1653
1654     /* Similarly add the UTF-8 locale possible matches.  These have to be
1655      * deferred until after the non-UTF-8 locale ones are taken care of just
1656      * above, or it leads to wrong results under ANYOF_INVERT */
1657     if (only_utf8_locale_invlist) {
1658         _invlist_union_maybe_complement_2nd(invlist,
1659                                             only_utf8_locale_invlist,
1660                                             ANYOF_FLAGS(node) & ANYOF_INVERT,
1661                                             &invlist);
1662     }
1663
1664     return invlist;
1665 }
1666
1667 /* These two functions currently do the exact same thing */
1668 #define ssc_init_zero           ssc_init
1669
1670 #define ssc_add_cp(ssc, cp)   ssc_add_range((ssc), (cp), (cp))
1671 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1672
1673 /* 'AND' a given class with another one.  Can create false positives.  'ssc'
1674  * should not be inverted.  'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1675  * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1676
1677 STATIC void
1678 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1679                 const regnode_charclass *and_with)
1680 {
1681     /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1682      * another SSC or a regular ANYOF class.  Can create false positives. */
1683
1684     SV* anded_cp_list;
1685     U8  anded_flags;
1686
1687     PERL_ARGS_ASSERT_SSC_AND;
1688
1689     assert(is_ANYOF_SYNTHETIC(ssc));
1690
1691     /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1692      * the code point inversion list and just the relevant flags */
1693     if (is_ANYOF_SYNTHETIC(and_with)) {
1694         anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1695         anded_flags = ANYOF_FLAGS(and_with);
1696
1697         /* XXX This is a kludge around what appears to be deficiencies in the
1698          * optimizer.  If we make S_ssc_anything() add in the WARN_SUPER flag,
1699          * there are paths through the optimizer where it doesn't get weeded
1700          * out when it should.  And if we don't make some extra provision for
1701          * it like the code just below, it doesn't get added when it should.
1702          * This solution is to add it only when AND'ing, which is here, and
1703          * only when what is being AND'ed is the pristine, original node
1704          * matching anything.  Thus it is like adding it to ssc_anything() but
1705          * only when the result is to be AND'ed.  Probably the same solution
1706          * could be adopted for the same problem we have with /l matching,
1707          * which is solved differently in S_ssc_init(), and that would lead to
1708          * fewer false positives than that solution has.  But if this solution
1709          * creates bugs, the consequences are only that a warning isn't raised
1710          * that should be; while the consequences for having /l bugs is
1711          * incorrect matches */
1712         if (ssc_is_anything((regnode_ssc *)and_with)) {
1713             anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1714         }
1715     }
1716     else {
1717         anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1718         if (OP(and_with) == ANYOFD) {
1719             anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1720         }
1721         else {
1722             anded_flags = ANYOF_FLAGS(and_with)
1723             &( ANYOF_COMMON_FLAGS
1724               |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1725               |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1726             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1727                 anded_flags &=
1728                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1729             }
1730         }
1731     }
1732
1733     ANYOF_FLAGS(ssc) &= anded_flags;
1734
1735     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1736      * C2 is the list of code points in 'and-with'; P2, its posix classes.
1737      * 'and_with' may be inverted.  When not inverted, we have the situation of
1738      * computing:
1739      *  (C1 | P1) & (C2 | P2)
1740      *                     =  (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1741      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1742      *                    <=  ((C1 & C2) |       P2)) | ( P1       | (P1 & P2))
1743      *                    <=  ((C1 & C2) | P1 | P2)
1744      * Alternatively, the last few steps could be:
1745      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1746      *                    <=  ((C1 & C2) |  C1      ) | (      C2  | (P1 & P2))
1747      *                    <=  (C1 | C2 | (P1 & P2))
1748      * We favor the second approach if either P1 or P2 is non-empty.  This is
1749      * because these components are a barrier to doing optimizations, as what
1750      * they match cannot be known until the moment of matching as they are
1751      * dependent on the current locale, 'AND"ing them likely will reduce or
1752      * eliminate them.
1753      * But we can do better if we know that C1,P1 are in their initial state (a
1754      * frequent occurrence), each matching everything:
1755      *  (<everything>) & (C2 | P2) =  C2 | P2
1756      * Similarly, if C2,P2 are in their initial state (again a frequent
1757      * occurrence), the result is a no-op
1758      *  (C1 | P1) & (<everything>) =  C1 | P1
1759      *
1760      * Inverted, we have
1761      *  (C1 | P1) & ~(C2 | P2)  =  (C1 | P1) & (~C2 & ~P2)
1762      *                          =  (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1763      *                         <=  (C1 & ~C2) | (P1 & ~P2)
1764      * */
1765
1766     if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1767         && ! is_ANYOF_SYNTHETIC(and_with))
1768     {
1769         unsigned int i;
1770
1771         ssc_intersection(ssc,
1772                          anded_cp_list,
1773                          FALSE /* Has already been inverted */
1774                          );
1775
1776         /* If either P1 or P2 is empty, the intersection will be also; can skip
1777          * the loop */
1778         if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1779             ANYOF_POSIXL_ZERO(ssc);
1780         }
1781         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1782
1783             /* Note that the Posix class component P from 'and_with' actually
1784              * looks like:
1785              *      P = Pa | Pb | ... | Pn
1786              * where each component is one posix class, such as in [\w\s].
1787              * Thus
1788              *      ~P = ~(Pa | Pb | ... | Pn)
1789              *         = ~Pa & ~Pb & ... & ~Pn
1790              *        <= ~Pa | ~Pb | ... | ~Pn
1791              * The last is something we can easily calculate, but unfortunately
1792              * is likely to have many false positives.  We could do better
1793              * in some (but certainly not all) instances if two classes in
1794              * P have known relationships.  For example
1795              *      :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1796              * So
1797              *      :lower: & :print: = :lower:
1798              * And similarly for classes that must be disjoint.  For example,
1799              * since \s and \w can have no elements in common based on rules in
1800              * the POSIX standard,
1801              *      \w & ^\S = nothing
1802              * Unfortunately, some vendor locales do not meet the Posix
1803              * standard, in particular almost everything by Microsoft.
1804              * The loop below just changes e.g., \w into \W and vice versa */
1805
1806             regnode_charclass_posixl temp;
1807             int add = 1;    /* To calculate the index of the complement */
1808
1809             Zero(&temp, 1, regnode_charclass_posixl);
1810             ANYOF_POSIXL_ZERO(&temp);
1811             for (i = 0; i < ANYOF_MAX; i++) {
1812                 assert(i % 2 != 0
1813                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1814                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1815
1816                 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1817                     ANYOF_POSIXL_SET(&temp, i + add);
1818                 }
1819                 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1820             }
1821             ANYOF_POSIXL_AND(&temp, ssc);
1822
1823         } /* else ssc already has no posixes */
1824     } /* else: Not inverted.  This routine is a no-op if 'and_with' is an SSC
1825          in its initial state */
1826     else if (! is_ANYOF_SYNTHETIC(and_with)
1827              || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1828     {
1829         /* But if 'ssc' is in its initial state, the result is just 'and_with';
1830          * copy it over 'ssc' */
1831         if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1832             if (is_ANYOF_SYNTHETIC(and_with)) {
1833                 StructCopy(and_with, ssc, regnode_ssc);
1834             }
1835             else {
1836                 ssc->invlist = anded_cp_list;
1837                 ANYOF_POSIXL_ZERO(ssc);
1838                 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1839                     ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1840                 }
1841             }
1842         }
1843         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1844                  || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1845         {
1846             /* One or the other of P1, P2 is non-empty. */
1847             if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1848                 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1849             }
1850             ssc_union(ssc, anded_cp_list, FALSE);
1851         }
1852         else { /* P1 = P2 = empty */
1853             ssc_intersection(ssc, anded_cp_list, FALSE);
1854         }
1855     }
1856 }
1857
1858 STATIC void
1859 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1860                const regnode_charclass *or_with)
1861 {
1862     /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1863      * another SSC or a regular ANYOF class.  Can create false positives if
1864      * 'or_with' is to be inverted. */
1865
1866     SV* ored_cp_list;
1867     U8 ored_flags;
1868
1869     PERL_ARGS_ASSERT_SSC_OR;
1870
1871     assert(is_ANYOF_SYNTHETIC(ssc));
1872
1873     /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1874      * the code point inversion list and just the relevant flags */
1875     if (is_ANYOF_SYNTHETIC(or_with)) {
1876         ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1877         ored_flags = ANYOF_FLAGS(or_with);
1878     }
1879     else {
1880         ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1881         ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1882         if (OP(or_with) != ANYOFD) {
1883             ored_flags
1884             |= ANYOF_FLAGS(or_with)
1885              & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1886                 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1887             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1888                 ored_flags |=
1889                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1890             }
1891         }
1892     }
1893
1894     ANYOF_FLAGS(ssc) |= ored_flags;
1895
1896     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1897      * C2 is the list of code points in 'or-with'; P2, its posix classes.
1898      * 'or_with' may be inverted.  When not inverted, we have the simple
1899      * situation of computing:
1900      *  (C1 | P1) | (C2 | P2)  =  (C1 | C2) | (P1 | P2)
1901      * If P1|P2 yields a situation with both a class and its complement are
1902      * set, like having both \w and \W, this matches all code points, and we
1903      * can delete these from the P component of the ssc going forward.  XXX We
1904      * might be able to delete all the P components, but I (khw) am not certain
1905      * about this, and it is better to be safe.
1906      *
1907      * Inverted, we have
1908      *  (C1 | P1) | ~(C2 | P2)  =  (C1 | P1) | (~C2 & ~P2)
1909      *                         <=  (C1 | P1) | ~C2
1910      *                         <=  (C1 | ~C2) | P1
1911      * (which results in actually simpler code than the non-inverted case)
1912      * */
1913
1914     if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1915         && ! is_ANYOF_SYNTHETIC(or_with))
1916     {
1917         /* We ignore P2, leaving P1 going forward */
1918     }   /* else  Not inverted */
1919     else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1920         ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1921         if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1922             unsigned int i;
1923             for (i = 0; i < ANYOF_MAX; i += 2) {
1924                 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1925                 {
1926                     ssc_match_all_cp(ssc);
1927                     ANYOF_POSIXL_CLEAR(ssc, i);
1928                     ANYOF_POSIXL_CLEAR(ssc, i+1);
1929                 }
1930             }
1931         }
1932     }
1933
1934     ssc_union(ssc,
1935               ored_cp_list,
1936               FALSE /* Already has been inverted */
1937               );
1938 }
1939
1940 PERL_STATIC_INLINE void
1941 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1942 {
1943     PERL_ARGS_ASSERT_SSC_UNION;
1944
1945     assert(is_ANYOF_SYNTHETIC(ssc));
1946
1947     _invlist_union_maybe_complement_2nd(ssc->invlist,
1948                                         invlist,
1949                                         invert2nd,
1950                                         &ssc->invlist);
1951 }
1952
1953 PERL_STATIC_INLINE void
1954 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1955                          SV* const invlist,
1956                          const bool invert2nd)
1957 {
1958     PERL_ARGS_ASSERT_SSC_INTERSECTION;
1959
1960     assert(is_ANYOF_SYNTHETIC(ssc));
1961
1962     _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1963                                                invlist,
1964                                                invert2nd,
1965                                                &ssc->invlist);
1966 }
1967
1968 PERL_STATIC_INLINE void
1969 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1970 {
1971     PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1972
1973     assert(is_ANYOF_SYNTHETIC(ssc));
1974
1975     ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1976 }
1977
1978 PERL_STATIC_INLINE void
1979 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1980 {
1981     /* AND just the single code point 'cp' into the SSC 'ssc' */
1982
1983     SV* cp_list = _new_invlist(2);
1984
1985     PERL_ARGS_ASSERT_SSC_CP_AND;
1986
1987     assert(is_ANYOF_SYNTHETIC(ssc));
1988
1989     cp_list = add_cp_to_invlist(cp_list, cp);
1990     ssc_intersection(ssc, cp_list,
1991                      FALSE /* Not inverted */
1992                      );
1993     SvREFCNT_dec_NN(cp_list);
1994 }
1995
1996 PERL_STATIC_INLINE void
1997 S_ssc_clear_locale(regnode_ssc *ssc)
1998 {
1999     /* Set the SSC 'ssc' to not match any locale things */
2000     PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2001
2002     assert(is_ANYOF_SYNTHETIC(ssc));
2003
2004     ANYOF_POSIXL_ZERO(ssc);
2005     ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2006 }
2007
2008 #define NON_OTHER_COUNT   NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2009
2010 STATIC bool
2011 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2012 {
2013     /* The synthetic start class is used to hopefully quickly winnow down
2014      * places where a pattern could start a match in the target string.  If it
2015      * doesn't really narrow things down that much, there isn't much point to
2016      * having the overhead of using it.  This function uses some very crude
2017      * heuristics to decide if to use the ssc or not.
2018      *
2019      * It returns TRUE if 'ssc' rules out more than half what it considers to
2020      * be the "likely" possible matches, but of course it doesn't know what the
2021      * actual things being matched are going to be; these are only guesses
2022      *
2023      * For /l matches, it assumes that the only likely matches are going to be
2024      *      in the 0-255 range, uniformly distributed, so half of that is 127
2025      * For /a and /d matches, it assumes that the likely matches will be just
2026      *      the ASCII range, so half of that is 63
2027      * For /u and there isn't anything matching above the Latin1 range, it
2028      *      assumes that that is the only range likely to be matched, and uses
2029      *      half that as the cut-off: 127.  If anything matches above Latin1,
2030      *      it assumes that all of Unicode could match (uniformly), except for
2031      *      non-Unicode code points and things in the General Category "Other"
2032      *      (unassigned, private use, surrogates, controls and formats).  This
2033      *      is a much large number. */
2034
2035     U32 count = 0;      /* Running total of number of code points matched by
2036                            'ssc' */
2037     UV start, end;      /* Start and end points of current range in inversion
2038                            list */
2039     const U32 max_code_points = (LOC)
2040                                 ?  256
2041                                 : ((   ! UNI_SEMANTICS
2042                                      || invlist_highest(ssc->invlist) < 256)
2043                                   ? 128
2044                                   : NON_OTHER_COUNT);
2045     const U32 max_match = max_code_points / 2;
2046
2047     PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2048
2049     invlist_iterinit(ssc->invlist);
2050     while (invlist_iternext(ssc->invlist, &start, &end)) {
2051         if (start >= max_code_points) {
2052             break;
2053         }
2054         end = MIN(end, max_code_points - 1);
2055         count += end - start + 1;
2056         if (count >= max_match) {
2057             invlist_iterfinish(ssc->invlist);
2058             return FALSE;
2059         }
2060     }
2061
2062     return TRUE;
2063 }
2064
2065
2066 STATIC void
2067 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2068 {
2069     /* The inversion list in the SSC is marked mortal; now we need a more
2070      * permanent copy, which is stored the same way that is done in a regular
2071      * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2072      * map */
2073
2074     SV* invlist = invlist_clone(ssc->invlist, NULL);
2075
2076     PERL_ARGS_ASSERT_SSC_FINALIZE;
2077
2078     assert(is_ANYOF_SYNTHETIC(ssc));
2079
2080     /* The code in this file assumes that all but these flags aren't relevant
2081      * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2082      * by the time we reach here */
2083     assert(! (ANYOF_FLAGS(ssc)
2084         & ~( ANYOF_COMMON_FLAGS
2085             |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2086             |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2087
2088     populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2089
2090     set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
2091                                 NULL, NULL, NULL, FALSE);
2092
2093     /* Make sure is clone-safe */
2094     ssc->invlist = NULL;
2095
2096     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2097         ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2098         OP(ssc) = ANYOFPOSIXL;
2099     }
2100     else if (RExC_contains_locale) {
2101         OP(ssc) = ANYOFL;
2102     }
2103
2104     assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2105 }
2106
2107 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2108 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
2109 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2110 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list         \
2111                                ? (TRIE_LIST_CUR( idx ) - 1)           \
2112                                : 0 )
2113
2114
2115 #ifdef DEBUGGING
2116 /*
2117    dump_trie(trie,widecharmap,revcharmap)
2118    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2119    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2120
2121    These routines dump out a trie in a somewhat readable format.
2122    The _interim_ variants are used for debugging the interim
2123    tables that are used to generate the final compressed
2124    representation which is what dump_trie expects.
2125
2126    Part of the reason for their existence is to provide a form
2127    of documentation as to how the different representations function.
2128
2129 */
2130
2131 /*
2132   Dumps the final compressed table form of the trie to Perl_debug_log.
2133   Used for debugging make_trie().
2134 */
2135
2136 STATIC void
2137 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2138             AV *revcharmap, U32 depth)
2139 {
2140     U32 state;
2141     SV *sv=sv_newmortal();
2142     int colwidth= widecharmap ? 6 : 4;
2143     U16 word;
2144     GET_RE_DEBUG_FLAGS_DECL;
2145
2146     PERL_ARGS_ASSERT_DUMP_TRIE;
2147
2148     Perl_re_indentf( aTHX_  "Char : %-6s%-6s%-4s ",
2149         depth+1, "Match","Base","Ofs" );
2150
2151     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2152         SV ** const tmp = av_fetch( revcharmap, state, 0);
2153         if ( tmp ) {
2154             Perl_re_printf( aTHX_  "%*s",
2155                 colwidth,
2156                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2157                             PL_colors[0], PL_colors[1],
2158                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2159                             PERL_PV_ESCAPE_FIRSTCHAR
2160                 )
2161             );
2162         }
2163     }
2164     Perl_re_printf( aTHX_  "\n");
2165     Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2166
2167     for( state = 0 ; state < trie->uniquecharcount ; state++ )
2168         Perl_re_printf( aTHX_  "%.*s", colwidth, "--------");
2169     Perl_re_printf( aTHX_  "\n");
2170
2171     for( state = 1 ; state < trie->statecount ; state++ ) {
2172         const U32 base = trie->states[ state ].trans.base;
2173
2174         Perl_re_indentf( aTHX_  "#%4" UVXf "|", depth+1, (UV)state);
2175
2176         if ( trie->states[ state ].wordnum ) {
2177             Perl_re_printf( aTHX_  " W%4X", trie->states[ state ].wordnum );
2178         } else {
2179             Perl_re_printf( aTHX_  "%6s", "" );
2180         }
2181
2182         Perl_re_printf( aTHX_  " @%4" UVXf " ", (UV)base );
2183
2184         if ( base ) {
2185             U32 ofs = 0;
2186
2187             while( ( base + ofs  < trie->uniquecharcount ) ||
2188                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
2189                      && trie->trans[ base + ofs - trie->uniquecharcount ].check
2190                                                                     != state))
2191                     ofs++;
2192
2193             Perl_re_printf( aTHX_  "+%2" UVXf "[ ", (UV)ofs);
2194
2195             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2196                 if ( ( base + ofs >= trie->uniquecharcount )
2197                         && ( base + ofs - trie->uniquecharcount
2198                                                         < trie->lasttrans )
2199                         && trie->trans[ base + ofs
2200                                     - trie->uniquecharcount ].check == state )
2201                 {
2202                    Perl_re_printf( aTHX_  "%*" UVXf, colwidth,
2203                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2204                    );
2205                 } else {
2206                     Perl_re_printf( aTHX_  "%*s", colwidth,"   ." );
2207                 }
2208             }
2209
2210             Perl_re_printf( aTHX_  "]");
2211
2212         }
2213         Perl_re_printf( aTHX_  "\n" );
2214     }
2215     Perl_re_indentf( aTHX_  "word_info N:(prev,len)=",
2216                                 depth);
2217     for (word=1; word <= trie->wordcount; word++) {
2218         Perl_re_printf( aTHX_  " %d:(%d,%d)",
2219             (int)word, (int)(trie->wordinfo[word].prev),
2220             (int)(trie->wordinfo[word].len));
2221     }
2222     Perl_re_printf( aTHX_  "\n" );
2223 }
2224 /*
2225   Dumps a fully constructed but uncompressed trie in list form.
2226   List tries normally only are used for construction when the number of
2227   possible chars (trie->uniquecharcount) is very high.
2228   Used for debugging make_trie().
2229 */
2230 STATIC void
2231 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2232                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
2233                          U32 depth)
2234 {
2235     U32 state;
2236     SV *sv=sv_newmortal();
2237     int colwidth= widecharmap ? 6 : 4;
2238     GET_RE_DEBUG_FLAGS_DECL;
2239
2240     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2241
2242     /* print out the table precompression.  */
2243     Perl_re_indentf( aTHX_  "State :Word | Transition Data\n",
2244             depth+1 );
2245     Perl_re_indentf( aTHX_  "%s",
2246             depth+1, "------:-----+-----------------\n" );
2247
2248     for( state=1 ; state < next_alloc ; state ++ ) {
2249         U16 charid;
2250
2251         Perl_re_indentf( aTHX_  " %4" UVXf " :",
2252             depth+1, (UV)state  );
2253         if ( ! trie->states[ state ].wordnum ) {
2254             Perl_re_printf( aTHX_  "%5s| ","");
2255         } else {
2256             Perl_re_printf( aTHX_  "W%4x| ",
2257                 trie->states[ state ].wordnum
2258             );
2259         }
2260         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2261             SV ** const tmp = av_fetch( revcharmap,
2262                                         TRIE_LIST_ITEM(state, charid).forid, 0);
2263             if ( tmp ) {
2264                 Perl_re_printf( aTHX_  "%*s:%3X=%4" UVXf " | ",
2265                     colwidth,
2266                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2267                               colwidth,
2268                               PL_colors[0], PL_colors[1],
2269                               (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2270                               | PERL_PV_ESCAPE_FIRSTCHAR
2271                     ) ,
2272                     TRIE_LIST_ITEM(state, charid).forid,
2273                     (UV)TRIE_LIST_ITEM(state, charid).newstate
2274                 );
2275                 if (!(charid % 10))
2276                     Perl_re_printf( aTHX_  "\n%*s| ",
2277                         (int)((depth * 2) + 14), "");
2278             }
2279         }
2280         Perl_re_printf( aTHX_  "\n");
2281     }
2282 }
2283
2284 /*
2285   Dumps a fully constructed but uncompressed trie in table form.
2286   This is the normal DFA style state transition table, with a few
2287   twists to facilitate compression later.
2288   Used for debugging make_trie().
2289 */
2290 STATIC void
2291 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2292                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
2293                           U32 depth)
2294 {
2295     U32 state;
2296     U16 charid;
2297     SV *sv=sv_newmortal();
2298     int colwidth= widecharmap ? 6 : 4;
2299     GET_RE_DEBUG_FLAGS_DECL;
2300
2301     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2302
2303     /*
2304        print out the table precompression so that we can do a visual check
2305        that they are identical.
2306      */
2307
2308     Perl_re_indentf( aTHX_  "Char : ", depth+1 );
2309
2310     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2311         SV ** const tmp = av_fetch( revcharmap, charid, 0);
2312         if ( tmp ) {
2313             Perl_re_printf( aTHX_  "%*s",
2314                 colwidth,
2315                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2316                             PL_colors[0], PL_colors[1],
2317                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2318                             PERL_PV_ESCAPE_FIRSTCHAR
2319                 )
2320             );
2321         }
2322     }
2323
2324     Perl_re_printf( aTHX_ "\n");
2325     Perl_re_indentf( aTHX_  "State+-", depth+1 );
2326
2327     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2328         Perl_re_printf( aTHX_  "%.*s", colwidth,"--------");
2329     }
2330
2331     Perl_re_printf( aTHX_  "\n" );
2332
2333     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2334
2335         Perl_re_indentf( aTHX_  "%4" UVXf " : ",
2336             depth+1,
2337             (UV)TRIE_NODENUM( state ) );
2338
2339         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2340             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2341             if (v)
2342                 Perl_re_printf( aTHX_  "%*" UVXf, colwidth, v );
2343             else
2344                 Perl_re_printf( aTHX_  "%*s", colwidth, "." );
2345         }
2346         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2347             Perl_re_printf( aTHX_  " (%4" UVXf ")\n",
2348                                             (UV)trie->trans[ state ].check );
2349         } else {
2350             Perl_re_printf( aTHX_  " (%4" UVXf ") W%4X\n",
2351                                             (UV)trie->trans[ state ].check,
2352             trie->states[ TRIE_NODENUM( state ) ].wordnum );
2353         }
2354     }
2355 }
2356
2357 #endif
2358
2359
2360 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2361   startbranch: the first branch in the whole branch sequence
2362   first      : start branch of sequence of branch-exact nodes.
2363                May be the same as startbranch
2364   last       : Thing following the last branch.
2365                May be the same as tail.
2366   tail       : item following the branch sequence
2367   count      : words in the sequence
2368   flags      : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2369   depth      : indent depth
2370
2371 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2372
2373 A trie is an N'ary tree where the branches are determined by digital
2374 decomposition of the key. IE, at the root node you look up the 1st character and
2375 follow that branch repeat until you find the end of the branches. Nodes can be
2376 marked as "accepting" meaning they represent a complete word. Eg:
2377
2378   /he|she|his|hers/
2379
2380 would convert into the following structure. Numbers represent states, letters
2381 following numbers represent valid transitions on the letter from that state, if
2382 the number is in square brackets it represents an accepting state, otherwise it
2383 will be in parenthesis.
2384
2385       +-h->+-e->[3]-+-r->(8)-+-s->[9]
2386       |    |
2387       |   (2)
2388       |    |
2389      (1)   +-i->(6)-+-s->[7]
2390       |
2391       +-s->(3)-+-h->(4)-+-e->[5]
2392
2393       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2394
2395 This shows that when matching against the string 'hers' we will begin at state 1
2396 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2397 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2398 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2399 single traverse. We store a mapping from accepting to state to which word was
2400 matched, and then when we have multiple possibilities we try to complete the
2401 rest of the regex in the order in which they occurred in the alternation.
2402
2403 The only prior NFA like behaviour that would be changed by the TRIE support is
2404 the silent ignoring of duplicate alternations which are of the form:
2405
2406  / (DUPE|DUPE) X? (?{ ... }) Y /x
2407
2408 Thus EVAL blocks following a trie may be called a different number of times with
2409 and without the optimisation. With the optimisations dupes will be silently
2410 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2411 the following demonstrates:
2412
2413  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2414
2415 which prints out 'word' three times, but
2416
2417  'words'=~/(word|word|word)(?{ print $1 })S/
2418
2419 which doesnt print it out at all. This is due to other optimisations kicking in.
2420
2421 Example of what happens on a structural level:
2422
2423 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2424
2425    1: CURLYM[1] {1,32767}(18)
2426    5:   BRANCH(8)
2427    6:     EXACT <ac>(16)
2428    8:   BRANCH(11)
2429    9:     EXACT <ad>(16)
2430   11:   BRANCH(14)
2431   12:     EXACT <ab>(16)
2432   16:   SUCCEED(0)
2433   17:   NOTHING(18)
2434   18: END(0)
2435
2436 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2437 and should turn into:
2438
2439    1: CURLYM[1] {1,32767}(18)
2440    5:   TRIE(16)
2441         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2442           <ac>
2443           <ad>
2444           <ab>
2445   16:   SUCCEED(0)
2446   17:   NOTHING(18)
2447   18: END(0)
2448
2449 Cases where tail != last would be like /(?foo|bar)baz/:
2450
2451    1: BRANCH(4)
2452    2:   EXACT <foo>(8)
2453    4: BRANCH(7)
2454    5:   EXACT <bar>(8)
2455    7: TAIL(8)
2456    8: EXACT <baz>(10)
2457   10: END(0)
2458
2459 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2460 and would end up looking like:
2461
2462     1: TRIE(8)
2463       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2464         <foo>
2465         <bar>
2466    7: TAIL(8)
2467    8: EXACT <baz>(10)
2468   10: END(0)
2469
2470     d = uvchr_to_utf8_flags(d, uv, 0);
2471
2472 is the recommended Unicode-aware way of saying
2473
2474     *(d++) = uv;
2475 */
2476
2477 #define TRIE_STORE_REVCHAR(val)                                            \
2478     STMT_START {                                                           \
2479         if (UTF) {                                                         \
2480             SV *zlopp = newSV(UTF8_MAXBYTES);                              \
2481             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
2482             unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2483             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
2484             SvPOK_on(zlopp);                                               \
2485             SvUTF8_on(zlopp);                                              \
2486             av_push(revcharmap, zlopp);                                    \
2487         } else {                                                           \
2488             char ooooff = (char)val;                                           \
2489             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
2490         }                                                                  \
2491         } STMT_END
2492
2493 /* This gets the next character from the input, folding it if not already
2494  * folded. */
2495 #define TRIE_READ_CHAR STMT_START {                                           \
2496     wordlen++;                                                                \
2497     if ( UTF ) {                                                              \
2498         /* if it is UTF then it is either already folded, or does not need    \
2499          * folding */                                                         \
2500         uvc = valid_utf8_to_uvchr( (const U8*) uc, &len);                     \
2501     }                                                                         \
2502     else if (folder == PL_fold_latin1) {                                      \
2503         /* This folder implies Unicode rules, which in the range expressible  \
2504          *  by not UTF is the lower case, with the two exceptions, one of     \
2505          *  which should have been taken care of before calling this */       \
2506         assert(*uc != LATIN_SMALL_LETTER_SHARP_S);                            \
2507         uvc = toLOWER_L1(*uc);                                                \
2508         if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU;         \
2509         len = 1;                                                              \
2510     } else {                                                                  \
2511         /* raw data, will be folded later if needed */                        \
2512         uvc = (U32)*uc;                                                       \
2513         len = 1;                                                              \
2514     }                                                                         \
2515 } STMT_END
2516
2517
2518
2519 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
2520     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
2521         U32 ging = TRIE_LIST_LEN( state ) * 2;                  \
2522         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2523         TRIE_LIST_LEN( state ) = ging;                          \
2524     }                                                           \
2525     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
2526     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
2527     TRIE_LIST_CUR( state )++;                                   \
2528 } STMT_END
2529
2530 #define TRIE_LIST_NEW(state) STMT_START {                       \
2531     Newx( trie->states[ state ].trans.list,                     \
2532         4, reg_trie_trans_le );                                 \
2533      TRIE_LIST_CUR( state ) = 1;                                \
2534      TRIE_LIST_LEN( state ) = 4;                                \
2535 } STMT_END
2536
2537 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
2538     U16 dupe= trie->states[ state ].wordnum;                    \
2539     regnode * const noper_next = regnext( noper );              \
2540                                                                 \
2541     DEBUG_r({                                                   \
2542         /* store the word for dumping */                        \
2543         SV* tmp;                                                \
2544         if (OP(noper) != NOTHING)                               \
2545             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
2546         else                                                    \
2547             tmp = newSVpvn_utf8( "", 0, UTF );                  \
2548         av_push( trie_words, tmp );                             \
2549     });                                                         \
2550                                                                 \
2551     curword++;                                                  \
2552     trie->wordinfo[curword].prev   = 0;                         \
2553     trie->wordinfo[curword].len    = wordlen;                   \
2554     trie->wordinfo[curword].accept = state;                     \
2555                                                                 \
2556     if ( noper_next < tail ) {                                  \
2557         if (!trie->jump)                                        \
2558             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2559                                                  sizeof(U16) ); \
2560         trie->jump[curword] = (U16)(noper_next - convert);      \
2561         if (!jumper)                                            \
2562             jumper = noper_next;                                \
2563         if (!nextbranch)                                        \
2564             nextbranch= regnext(cur);                           \
2565     }                                                           \
2566                                                                 \
2567     if ( dupe ) {                                               \
2568         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
2569         /* chain, so that when the bits of chain are later    */\
2570         /* linked together, the dups appear in the chain      */\
2571         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2572         trie->wordinfo[dupe].prev = curword;                    \
2573     } else {                                                    \
2574         /* we haven't inserted this word yet.                */ \
2575         trie->states[ state ].wordnum = curword;                \
2576     }                                                           \
2577 } STMT_END
2578
2579
2580 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
2581      ( ( base + charid >=  ucharcount                                   \
2582          && base + charid < ubound                                      \
2583          && state == trie->trans[ base - ucharcount + charid ].check    \
2584          && trie->trans[ base - ucharcount + charid ].next )            \
2585            ? trie->trans[ base - ucharcount + charid ].next             \
2586            : ( state==1 ? special : 0 )                                 \
2587       )
2588
2589 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder)           \
2590 STMT_START {                                                \
2591     TRIE_BITMAP_SET(trie, uvc);                             \
2592     /* store the folded codepoint */                        \
2593     if ( folder )                                           \
2594         TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);           \
2595                                                             \
2596     if ( !UTF ) {                                           \
2597         /* store first byte of utf8 representation of */    \
2598         /* variant codepoints */                            \
2599         if (! UVCHR_IS_INVARIANT(uvc)) {                    \
2600             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));   \
2601         }                                                   \
2602     }                                                       \
2603 } STMT_END
2604 #define MADE_TRIE       1
2605 #define MADE_JUMP_TRIE  2
2606 #define MADE_EXACT_TRIE 4
2607
2608 STATIC I32
2609 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2610                   regnode *first, regnode *last, regnode *tail,
2611                   U32 word_count, U32 flags, U32 depth)
2612 {
2613     /* first pass, loop through and scan words */
2614     reg_trie_data *trie;
2615     HV *widecharmap = NULL;
2616     AV *revcharmap = newAV();
2617     regnode *cur;
2618     STRLEN len = 0;
2619     UV uvc = 0;
2620     U16 curword = 0;
2621     U32 next_alloc = 0;
2622     regnode *jumper = NULL;
2623     regnode *nextbranch = NULL;
2624     regnode *convert = NULL;
2625     U32 *prev_states; /* temp array mapping each state to previous one */
2626     /* we just use folder as a flag in utf8 */
2627     const U8 * folder = NULL;
2628
2629     /* in the below add_data call we are storing either 'tu' or 'tuaa'
2630      * which stands for one trie structure, one hash, optionally followed
2631      * by two arrays */
2632 #ifdef DEBUGGING
2633     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2634     AV *trie_words = NULL;
2635     /* along with revcharmap, this only used during construction but both are
2636      * useful during debugging so we store them in the struct when debugging.
2637      */
2638 #else
2639     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2640     STRLEN trie_charcount=0;
2641 #endif
2642     SV *re_trie_maxbuff;
2643     GET_RE_DEBUG_FLAGS_DECL;
2644
2645     PERL_ARGS_ASSERT_MAKE_TRIE;
2646 #ifndef DEBUGGING
2647     PERL_UNUSED_ARG(depth);
2648 #endif
2649
2650     switch (flags) {
2651         case EXACT: case EXACTL: break;
2652         case EXACTFAA:
2653         case EXACTFU_SS:
2654         case EXACTFU:
2655         case EXACTFLU8: folder = PL_fold_latin1; break;
2656         case EXACTF:  folder = PL_fold; break;
2657         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2658     }
2659
2660     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2661     trie->refcount = 1;
2662     trie->startstate = 1;
2663     trie->wordcount = word_count;
2664     RExC_rxi->data->data[ data_slot ] = (void*)trie;
2665     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2666     if (flags == EXACT || flags == EXACTL)
2667         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2668     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2669                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
2670
2671     DEBUG_r({
2672         trie_words = newAV();
2673     });
2674
2675     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2676     assert(re_trie_maxbuff);
2677     if (!SvIOK(re_trie_maxbuff)) {
2678         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2679     }
2680     DEBUG_TRIE_COMPILE_r({
2681         Perl_re_indentf( aTHX_
2682           "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2683           depth+1,
2684           REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2685           REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2686     });
2687
2688    /* Find the node we are going to overwrite */
2689     if ( first == startbranch && OP( last ) != BRANCH ) {
2690         /* whole branch chain */
2691         convert = first;
2692     } else {
2693         /* branch sub-chain */
2694         convert = NEXTOPER( first );
2695     }
2696
2697     /*  -- First loop and Setup --
2698
2699        We first traverse the branches and scan each word to determine if it
2700        contains widechars, and how many unique chars there are, this is
2701        important as we have to build a table with at least as many columns as we
2702        have unique chars.
2703
2704        We use an array of integers to represent the character codes 0..255
2705        (trie->charmap) and we use a an HV* to store Unicode characters. We use
2706        the native representation of the character value as the key and IV's for
2707        the coded index.
2708
2709        *TODO* If we keep track of how many times each character is used we can
2710        remap the columns so that the table compression later on is more
2711        efficient in terms of memory by ensuring the most common value is in the
2712        middle and the least common are on the outside.  IMO this would be better
2713        than a most to least common mapping as theres a decent chance the most
2714        common letter will share a node with the least common, meaning the node
2715        will not be compressible. With a middle is most common approach the worst
2716        case is when we have the least common nodes twice.
2717
2718      */
2719
2720     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2721         regnode *noper = NEXTOPER( cur );
2722         const U8 *uc;
2723         const U8 *e;
2724         int foldlen = 0;
2725         U32 wordlen      = 0;         /* required init */
2726         STRLEN minchars = 0;
2727         STRLEN maxchars = 0;
2728         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2729                                                bitmap?*/
2730
2731         if (OP(noper) == NOTHING) {
2732             /* skip past a NOTHING at the start of an alternation
2733              * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2734              */
2735             regnode *noper_next= regnext(noper);
2736             if (noper_next < tail)
2737                 noper= noper_next;
2738         }
2739
2740         if ( noper < tail &&
2741                 (
2742                     OP(noper) == flags ||
2743                     (
2744                         flags == EXACTFU &&
2745                         OP(noper) == EXACTFU_SS
2746                     )
2747                 )
2748         ) {
2749             uc= (U8*)STRING(noper);
2750             e= uc + STR_LEN(noper);
2751         } else {
2752             trie->minlen= 0;
2753             continue;
2754         }
2755
2756
2757         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2758             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2759                                           regardless of encoding */
2760             if (OP( noper ) == EXACTFU_SS) {
2761                 /* false positives are ok, so just set this */
2762                 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2763             }
2764         }
2765
2766         for ( ; uc < e ; uc += len ) {  /* Look at each char in the current
2767                                            branch */
2768             TRIE_CHARCOUNT(trie)++;
2769             TRIE_READ_CHAR;
2770
2771             /* TRIE_READ_CHAR returns the current character, or its fold if /i
2772              * is in effect.  Under /i, this character can match itself, or
2773              * anything that folds to it.  If not under /i, it can match just
2774              * itself.  Most folds are 1-1, for example k, K, and KELVIN SIGN
2775              * all fold to k, and all are single characters.   But some folds
2776              * expand to more than one character, so for example LATIN SMALL
2777              * LIGATURE FFI folds to the three character sequence 'ffi'.  If
2778              * the string beginning at 'uc' is 'ffi', it could be matched by
2779              * three characters, or just by the one ligature character. (It
2780              * could also be matched by two characters: LATIN SMALL LIGATURE FF
2781              * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2782              * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2783              * match.)  The trie needs to know the minimum and maximum number
2784              * of characters that could match so that it can use size alone to
2785              * quickly reject many match attempts.  The max is simple: it is
2786              * the number of folded characters in this branch (since a fold is
2787              * never shorter than what folds to it. */
2788
2789             maxchars++;
2790
2791             /* And the min is equal to the max if not under /i (indicated by
2792              * 'folder' being NULL), or there are no multi-character folds.  If
2793              * there is a multi-character fold, the min is incremented just
2794              * once, for the character that folds to the sequence.  Each
2795              * character in the sequence needs to be added to the list below of
2796              * characters in the trie, but we count only the first towards the
2797              * min number of characters needed.  This is done through the
2798              * variable 'foldlen', which is returned by the macros that look
2799              * for these sequences as the number of bytes the sequence
2800              * occupies.  Each time through the loop, we decrement 'foldlen' by
2801              * how many bytes the current char occupies.  Only when it reaches
2802              * 0 do we increment 'minchars' or look for another multi-character
2803              * sequence. */
2804             if (folder == NULL) {
2805                 minchars++;
2806             }
2807             else if (foldlen > 0) {
2808                 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2809             }
2810             else {
2811                 minchars++;
2812
2813                 /* See if *uc is the beginning of a multi-character fold.  If
2814                  * so, we decrement the length remaining to look at, to account
2815                  * for the current character this iteration.  (We can use 'uc'
2816                  * instead of the fold returned by TRIE_READ_CHAR because for
2817                  * non-UTF, the latin1_safe macro is smart enough to account
2818                  * for all the unfolded characters, and because for UTF, the
2819                  * string will already have been folded earlier in the
2820                  * compilation process */
2821                 if (UTF) {
2822                     if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2823                         foldlen -= UTF8SKIP(uc);
2824                     }
2825                 }
2826                 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2827                     foldlen--;
2828                 }
2829             }
2830
2831             /* The current character (and any potential folds) should be added
2832              * to the possible matching characters for this position in this
2833              * branch */
2834             if ( uvc < 256 ) {
2835                 if ( folder ) {
2836                     U8 folded= folder[ (U8) uvc ];
2837                     if ( !trie->charmap[ folded ] ) {
2838                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
2839                         TRIE_STORE_REVCHAR( folded );
2840                     }
2841                 }
2842                 if ( !trie->charmap[ uvc ] ) {
2843                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2844                     TRIE_STORE_REVCHAR( uvc );
2845                 }
2846                 if ( set_bit ) {
2847                     /* store the codepoint in the bitmap, and its folded
2848                      * equivalent. */
2849                     TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2850                     set_bit = 0; /* We've done our bit :-) */
2851                 }
2852             } else {
2853
2854                 /* XXX We could come up with the list of code points that fold
2855                  * to this using PL_utf8_foldclosures, except not for
2856                  * multi-char folds, as there may be multiple combinations
2857                  * there that could work, which needs to wait until runtime to
2858                  * resolve (The comment about LIGATURE FFI above is such an
2859                  * example */
2860
2861                 SV** svpp;
2862                 if ( !widecharmap )
2863                     widecharmap = newHV();
2864
2865                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2866
2867                 if ( !svpp )
2868                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2869
2870                 if ( !SvTRUE( *svpp ) ) {
2871                     sv_setiv( *svpp, ++trie->uniquecharcount );
2872                     TRIE_STORE_REVCHAR(uvc);
2873                 }
2874             }
2875         } /* end loop through characters in this branch of the trie */
2876
2877         /* We take the min and max for this branch and combine to find the min
2878          * and max for all branches processed so far */
2879         if( cur == first ) {
2880             trie->minlen = minchars;
2881             trie->maxlen = maxchars;
2882         } else if (minchars < trie->minlen) {
2883             trie->minlen = minchars;
2884         } else if (maxchars > trie->maxlen) {
2885             trie->maxlen = maxchars;
2886         }
2887     } /* end first pass */
2888     DEBUG_TRIE_COMPILE_r(
2889         Perl_re_indentf( aTHX_
2890                 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2891                 depth+1,
2892                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2893                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2894                 (int)trie->minlen, (int)trie->maxlen )
2895     );
2896
2897     /*
2898         We now know what we are dealing with in terms of unique chars and
2899         string sizes so we can calculate how much memory a naive
2900         representation using a flat table  will take. If it's over a reasonable
2901         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2902         conservative but potentially much slower representation using an array
2903         of lists.
2904
2905         At the end we convert both representations into the same compressed
2906         form that will be used in regexec.c for matching with. The latter
2907         is a form that cannot be used to construct with but has memory
2908         properties similar to the list form and access properties similar
2909         to the table form making it both suitable for fast searches and
2910         small enough that its feasable to store for the duration of a program.
2911
2912         See the comment in the code where the compressed table is produced
2913         inplace from the flat tabe representation for an explanation of how
2914         the compression works.
2915
2916     */
2917
2918
2919     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2920     prev_states[1] = 0;
2921
2922     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2923                                                     > SvIV(re_trie_maxbuff) )
2924     {
2925         /*
2926             Second Pass -- Array Of Lists Representation
2927
2928             Each state will be represented by a list of charid:state records
2929             (reg_trie_trans_le) the first such element holds the CUR and LEN
2930             points of the allocated array. (See defines above).
2931
2932             We build the initial structure using the lists, and then convert
2933             it into the compressed table form which allows faster lookups
2934             (but cant be modified once converted).
2935         */
2936
2937         STRLEN transcount = 1;
2938
2939         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using list compiler\n",
2940             depth+1));
2941
2942         trie->states = (reg_trie_state *)
2943             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2944                                   sizeof(reg_trie_state) );
2945         TRIE_LIST_NEW(1);
2946         next_alloc = 2;
2947
2948         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2949
2950             regnode *noper   = NEXTOPER( cur );
2951             U32 state        = 1;         /* required init */
2952             U16 charid       = 0;         /* sanity init */
2953             U32 wordlen      = 0;         /* required init */
2954
2955             if (OP(noper) == NOTHING) {
2956                 regnode *noper_next= regnext(noper);
2957                 if (noper_next < tail)
2958                     noper= noper_next;
2959             }
2960
2961             if ( noper < tail && ( OP(noper) == flags || ( flags == EXACTFU && OP(noper) == EXACTFU_SS ) ) ) {
2962                 const U8 *uc= (U8*)STRING(noper);
2963                 const U8 *e= uc + STR_LEN(noper);
2964
2965                 for ( ; uc < e ; uc += len ) {
2966
2967                     TRIE_READ_CHAR;
2968
2969                     if ( uvc < 256 ) {
2970                         charid = trie->charmap[ uvc ];
2971                     } else {
2972                         SV** const svpp = hv_fetch( widecharmap,
2973                                                     (char*)&uvc,
2974                                                     sizeof( UV ),
2975                                                     0);
2976                         if ( !svpp ) {
2977                             charid = 0;
2978                         } else {
2979                             charid=(U16)SvIV( *svpp );
2980                         }
2981                     }
2982                     /* charid is now 0 if we dont know the char read, or
2983                      * nonzero if we do */
2984                     if ( charid ) {
2985
2986                         U16 check;
2987                         U32 newstate = 0;
2988
2989                         charid--;
2990                         if ( !trie->states[ state ].trans.list ) {
2991                             TRIE_LIST_NEW( state );
2992                         }
2993                         for ( check = 1;
2994                               check <= TRIE_LIST_USED( state );
2995                               check++ )
2996                         {
2997                             if ( TRIE_LIST_ITEM( state, check ).forid
2998                                                                     == charid )
2999                             {
3000                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3001                                 break;
3002                             }
3003                         }
3004                         if ( ! newstate ) {
3005                             newstate = next_alloc++;
3006                             prev_states[newstate] = state;
3007                             TRIE_LIST_PUSH( state, charid, newstate );
3008                             transcount++;
3009                         }
3010                         state = newstate;
3011                     } else {
3012                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3013                     }
3014                 }
3015             }
3016             TRIE_HANDLE_WORD(state);
3017
3018         } /* end second pass */
3019
3020         /* next alloc is the NEXT state to be allocated */
3021         trie->statecount = next_alloc;
3022         trie->states = (reg_trie_state *)
3023             PerlMemShared_realloc( trie->states,
3024                                    next_alloc
3025                                    * sizeof(reg_trie_state) );
3026
3027         /* and now dump it out before we compress it */
3028         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3029                                                          revcharmap, next_alloc,
3030                                                          depth+1)
3031         );
3032
3033         trie->trans = (reg_trie_trans *)
3034             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3035         {
3036             U32 state;
3037             U32 tp = 0;
3038             U32 zp = 0;
3039
3040
3041             for( state=1 ; state < next_alloc ; state ++ ) {
3042                 U32 base=0;
3043
3044                 /*
3045                 DEBUG_TRIE_COMPILE_MORE_r(
3046                     Perl_re_printf( aTHX_  "tp: %d zp: %d ",tp,zp)
3047                 );
3048                 */
3049
3050                 if (trie->states[state].trans.list) {
3051                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3052                     U16 maxid=minid;
3053                     U16 idx;
3054
3055                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3056                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3057                         if ( forid < minid ) {
3058                             minid=forid;
3059                         } else if ( forid > maxid ) {
3060                             maxid=forid;
3061                         }
3062                     }
3063                     if ( transcount < tp + maxid - minid + 1) {
3064                         transcount *= 2;
3065                         trie->trans = (reg_trie_trans *)
3066                             PerlMemShared_realloc( trie->trans,
3067                                                      transcount
3068                                                      * sizeof(reg_trie_trans) );
3069                         Zero( trie->trans + (transcount / 2),
3070                               transcount / 2,
3071                               reg_trie_trans );
3072                     }
3073                     base = trie->uniquecharcount + tp - minid;
3074                     if ( maxid == minid ) {
3075                         U32 set = 0;
3076                         for ( ; zp < tp ; zp++ ) {
3077                             if ( ! trie->trans[ zp ].next ) {
3078                                 base = trie->uniquecharcount + zp - minid;
3079                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3080                                                                    1).newstate;
3081                                 trie->trans[ zp ].check = state;
3082                                 set = 1;
3083                                 break;
3084                             }
3085                         }
3086                         if ( !set ) {
3087                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3088                                                                    1).newstate;
3089                             trie->trans[ tp ].check = state;
3090                             tp++;
3091                             zp = tp;
3092                         }
3093                     } else {
3094                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3095                             const U32 tid = base
3096                                            - trie->uniquecharcount
3097                                            + TRIE_LIST_ITEM( state, idx ).forid;
3098                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3099                                                                 idx ).newstate;
3100                             trie->trans[ tid ].check = state;
3101                         }
3102                         tp += ( maxid - minid + 1 );
3103                     }
3104                     Safefree(trie->states[ state ].trans.list);
3105                 }
3106                 /*
3107                 DEBUG_TRIE_COMPILE_MORE_r(
3108                     Perl_re_printf( aTHX_  " base: %d\n",base);
3109                 );
3110                 */
3111                 trie->states[ state ].trans.base=base;
3112             }
3113             trie->lasttrans = tp + 1;
3114         }
3115     } else {
3116         /*
3117            Second Pass -- Flat Table Representation.
3118
3119            we dont use the 0 slot of either trans[] or states[] so we add 1 to
3120            each.  We know that we will need Charcount+1 trans at most to store
3121            the data (one row per char at worst case) So we preallocate both
3122            structures assuming worst case.
3123
3124            We then construct the trie using only the .next slots of the entry
3125            structs.
3126
3127            We use the .check field of the first entry of the node temporarily
3128            to make compression both faster and easier by keeping track of how
3129            many non zero fields are in the node.
3130
3131            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3132            transition.
3133
3134            There are two terms at use here: state as a TRIE_NODEIDX() which is
3135            a number representing the first entry of the node, and state as a
3136            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3137            and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3138            if there are 2 entrys per node. eg:
3139
3140              A B       A B
3141           1. 2 4    1. 3 7
3142           2. 0 3    3. 0 5
3143           3. 0 0    5. 0 0
3144           4. 0 0    7. 0 0
3145
3146            The table is internally in the right hand, idx form. However as we
3147            also have to deal with the states array which is indexed by nodenum
3148            we have to use TRIE_NODENUM() to convert.
3149
3150         */
3151         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using table compiler\n",
3152             depth+1));
3153
3154         trie->trans = (reg_trie_trans *)
3155             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3156                                   * trie->uniquecharcount + 1,
3157                                   sizeof(reg_trie_trans) );
3158         trie->states = (reg_trie_state *)
3159             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3160                                   sizeof(reg_trie_state) );
3161         next_alloc = trie->uniquecharcount + 1;
3162
3163
3164         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3165
3166             regnode *noper   = NEXTOPER( cur );
3167
3168             U32 state        = 1;         /* required init */
3169
3170             U16 charid       = 0;         /* sanity init */
3171             U32 accept_state = 0;         /* sanity init */
3172
3173             U32 wordlen      = 0;         /* required init */
3174
3175             if (OP(noper) == NOTHING) {
3176                 regnode *noper_next= regnext(noper);
3177                 if (noper_next < tail)
3178                     noper= noper_next;
3179             }
3180
3181             if ( noper < tail && ( OP(noper) == flags || ( flags == EXACTFU && OP(noper) == EXACTFU_SS ) ) ) {
3182                 const U8 *uc= (U8*)STRING(noper);
3183                 const U8 *e= uc + STR_LEN(noper);
3184
3185                 for ( ; uc < e ; uc += len ) {
3186
3187                     TRIE_READ_CHAR;
3188
3189                     if ( uvc < 256 ) {
3190                         charid = trie->charmap[ uvc ];
3191                     } else {
3192                         SV* const * const svpp = hv_fetch( widecharmap,
3193                                                            (char*)&uvc,
3194                                                            sizeof( UV ),
3195                                                            0);
3196                         charid = svpp ? (U16)SvIV(*svpp) : 0;
3197                     }
3198                     if ( charid ) {
3199                         charid--;
3200                         if ( !trie->trans[ state + charid ].next ) {
3201                             trie->trans[ state + charid ].next = next_alloc;
3202                             trie->trans[ state ].check++;
3203                             prev_states[TRIE_NODENUM(next_alloc)]
3204                                     = TRIE_NODENUM(state);
3205                             next_alloc += trie->uniquecharcount;
3206                         }
3207                         state = trie->trans[ state + charid ].next;
3208                     } else {
3209                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3210                     }
3211                     /* charid is now 0 if we dont know the char read, or
3212                      * nonzero if we do */
3213                 }
3214             }
3215             accept_state = TRIE_NODENUM( state );
3216             TRIE_HANDLE_WORD(accept_state);
3217
3218         } /* end second pass */
3219
3220         /* and now dump it out before we compress it */
3221         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3222                                                           revcharmap,
3223                                                           next_alloc, depth+1));
3224
3225         {
3226         /*
3227            * Inplace compress the table.*
3228
3229            For sparse data sets the table constructed by the trie algorithm will
3230            be mostly 0/FAIL transitions or to put it another way mostly empty.
3231            (Note that leaf nodes will not contain any transitions.)
3232
3233            This algorithm compresses the tables by eliminating most such
3234            transitions, at the cost of a modest bit of extra work during lookup:
3235
3236            - Each states[] entry contains a .base field which indicates the
3237            index in the state[] array wheres its transition data is stored.
3238
3239            - If .base is 0 there are no valid transitions from that node.
3240
3241            - If .base is nonzero then charid is added to it to find an entry in
3242            the trans array.
3243
3244            -If trans[states[state].base+charid].check!=state then the
3245            transition is taken to be a 0/Fail transition. Thus if there are fail
3246            transitions at the front of the node then the .base offset will point
3247            somewhere inside the previous nodes data (or maybe even into a node
3248            even earlier), but the .check field determines if the transition is
3249            valid.
3250
3251            XXX - wrong maybe?
3252            The following process inplace converts the table to the compressed
3253            table: We first do not compress the root node 1,and mark all its
3254            .check pointers as 1 and set its .base pointer as 1 as well. This
3255            allows us to do a DFA construction from the compressed table later,
3256            and ensures that any .base pointers we calculate later are greater
3257            than 0.
3258
3259            - We set 'pos' to indicate the first entry of the second node.
3260
3261            - We then iterate over the columns of the node, finding the first and
3262            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3263            and set the .check pointers accordingly, and advance pos
3264            appropriately and repreat for the next node. Note that when we copy
3265            the next pointers we have to convert them from the original
3266            NODEIDX form to NODENUM form as the former is not valid post
3267            compression.
3268
3269            - If a node has no transitions used we mark its base as 0 and do not
3270            advance the pos pointer.
3271
3272            - If a node only has one transition we use a second pointer into the
3273            structure to fill in allocated fail transitions from other states.
3274            This pointer is independent of the main pointer and scans forward
3275            looking for null transitions that are allocated to a state. When it
3276            finds one it writes the single transition into the "hole".  If the
3277            pointer doesnt find one the single transition is appended as normal.
3278
3279            - Once compressed we can Renew/realloc the structures to release the
3280            excess space.
3281
3282            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3283            specifically Fig 3.47 and the associated pseudocode.
3284
3285            demq
3286         */
3287         const U32 laststate = TRIE_NODENUM( next_alloc );
3288         U32 state, charid;
3289         U32 pos = 0, zp=0;
3290         trie->statecount = laststate;
3291
3292         for ( state = 1 ; state < laststate ; state++ ) {
3293             U8 flag = 0;
3294             const U32 stateidx = TRIE_NODEIDX( state );
3295             const U32 o_used = trie->trans[ stateidx ].check;
3296             U32 used = trie->trans[ stateidx ].check;
3297             trie->trans[ stateidx ].check = 0;
3298
3299             for ( charid = 0;
3300                   used && charid < trie->uniquecharcount;
3301                   charid++ )
3302             {
3303                 if ( flag || trie->trans[ stateidx + charid ].next ) {
3304                     if ( trie->trans[ stateidx + charid ].next ) {
3305                         if (o_used == 1) {
3306                             for ( ; zp < pos ; zp++ ) {
3307                                 if ( ! trie->trans[ zp ].next ) {
3308                                     break;
3309                                 }
3310                             }
3311                             trie->states[ state ].trans.base
3312                                                     = zp
3313                                                       + trie->uniquecharcount
3314                                                       - charid ;
3315                             trie->trans[ zp ].next
3316                                 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3317                                                              + charid ].next );
3318                             trie->trans[ zp ].check = state;
3319                             if ( ++zp > pos ) pos = zp;
3320                             break;
3321                         }
3322                         used--;
3323                     }
3324                     if ( !flag ) {
3325                         flag = 1;
3326                         trie->states[ state ].trans.base
3327                                        = pos + trie->uniquecharcount - charid ;
3328                     }
3329                     trie->trans[ pos ].next
3330                         = SAFE_TRIE_NODENUM(
3331                                        trie->trans[ stateidx + charid ].next );
3332                     trie->trans[ pos ].check = state;
3333                     pos++;
3334                 }
3335             }
3336         }
3337         trie->lasttrans = pos + 1;
3338         trie->states = (reg_trie_state *)
3339             PerlMemShared_realloc( trie->states, laststate
3340                                    * sizeof(reg_trie_state) );
3341         DEBUG_TRIE_COMPILE_MORE_r(
3342             Perl_re_indentf( aTHX_  "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3343                 depth+1,
3344                 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3345                        + 1 ),
3346                 (IV)next_alloc,
3347                 (IV)pos,
3348                 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3349             );
3350
3351         } /* end table compress */
3352     }
3353     DEBUG_TRIE_COMPILE_MORE_r(
3354             Perl_re_indentf( aTHX_  "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3355                 depth+1,
3356                 (UV)trie->statecount,
3357                 (UV)trie->lasttrans)
3358     );
3359     /* resize the trans array to remove unused space */
3360     trie->trans = (reg_trie_trans *)
3361         PerlMemShared_realloc( trie->trans, trie->lasttrans
3362                                * sizeof(reg_trie_trans) );
3363
3364     {   /* Modify the program and insert the new TRIE node */
3365         U8 nodetype =(U8)(flags & 0xFF);
3366         char *str=NULL;
3367
3368 #ifdef DEBUGGING
3369         regnode *optimize = NULL;
3370 #ifdef RE_TRACK_PATTERN_OFFSETS
3371
3372         U32 mjd_offset = 0;
3373         U32 mjd_nodelen = 0;
3374 #endif /* RE_TRACK_PATTERN_OFFSETS */
3375 #endif /* DEBUGGING */
3376         /*
3377            This means we convert either the first branch or the first Exact,
3378            depending on whether the thing following (in 'last') is a branch
3379            or not and whther first is the startbranch (ie is it a sub part of
3380            the alternation or is it the whole thing.)
3381            Assuming its a sub part we convert the EXACT otherwise we convert
3382            the whole branch sequence, including the first.
3383          */
3384         /* Find the node we are going to overwrite */
3385         if ( first != startbranch || OP( last ) == BRANCH ) {
3386             /* branch sub-chain */
3387             NEXT_OFF( first ) = (U16)(last - first);
3388 #ifdef RE_TRACK_PATTERN_OFFSETS
3389             DEBUG_r({
3390                 mjd_offset= Node_Offset((convert));
3391                 mjd_nodelen= Node_Length((convert));
3392             });
3393 #endif
3394             /* whole branch chain */
3395         }
3396 #ifdef RE_TRACK_PATTERN_OFFSETS
3397         else {
3398             DEBUG_r({
3399                 const  regnode *nop = NEXTOPER( convert );
3400                 mjd_offset= Node_Offset((nop));
3401                 mjd_nodelen= Node_Length((nop));
3402             });
3403         }
3404         DEBUG_OPTIMISE_r(
3405             Perl_re_indentf( aTHX_  "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3406                 depth+1,
3407                 (UV)mjd_offset, (UV)mjd_nodelen)
3408         );
3409 #endif
3410         /* But first we check to see if there is a common prefix we can
3411            split out as an EXACT and put in front of the TRIE node.  */
3412         trie->startstate= 1;
3413         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
3414             /* we want to find the first state that has more than
3415              * one transition, if that state is not the first state
3416              * then we have a common prefix which we can remove.
3417              */
3418             U32 state;
3419             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3420                 U32 ofs = 0;
3421                 I32 first_ofs = -1; /* keeps track of the ofs of the first
3422                                        transition, -1 means none */
3423                 U32 count = 0;
3424                 const U32 base = trie->states[ state ].trans.base;
3425
3426                 /* does this state terminate an alternation? */
3427                 if ( trie->states[state].wordnum )
3428                         count = 1;
3429
3430                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3431                     if ( ( base + ofs >= trie->uniquecharcount ) &&
3432                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3433                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3434                     {
3435                         if ( ++count > 1 ) {
3436                             /* we have more than one transition */
3437                             SV **tmp;
3438                             U8 *ch;
3439                             /* if this is the first state there is no common prefix
3440                              * to extract, so we can exit */
3441                             if ( state == 1 ) break;
3442                             tmp = av_fetch( revcharmap, ofs, 0);
3443                             ch = (U8*)SvPV_nolen_const( *tmp );
3444
3445                             /* if we are on count 2 then we need to initialize the
3446                              * bitmap, and store the previous char if there was one
3447                              * in it*/
3448                             if ( count == 2 ) {
3449                                 /* clear the bitmap */
3450                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3451                                 DEBUG_OPTIMISE_r(
3452                                     Perl_re_indentf( aTHX_  "New Start State=%" UVuf " Class: [",
3453                                         depth+1,
3454                                         (UV)state));
3455                                 if (first_ofs >= 0) {
3456                                     SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3457                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3458
3459                                     TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3460                                     DEBUG_OPTIMISE_r(
3461                                         Perl_re_printf( aTHX_  "%s", (char*)ch)
3462                                     );
3463                                 }
3464                             }
3465                             /* store the current firstchar in the bitmap */
3466                             TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3467                             DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3468                         }
3469                         first_ofs = ofs;
3470                     }
3471                 }
3472                 if ( count == 1 ) {
3473                     /* This state has only one transition, its transition is part
3474                      * of a common prefix - we need to concatenate the char it
3475                      * represents to what we have so far. */
3476                     SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3477                     STRLEN len;
3478                     char *ch = SvPV( *tmp, len );
3479                     DEBUG_OPTIMISE_r({
3480                         SV *sv=sv_newmortal();
3481                         Perl_re_indentf( aTHX_  "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3482                             depth+1,
3483                             (UV)state, (UV)first_ofs,
3484                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3485                                 PL_colors[0], PL_colors[1],
3486                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3487                                 PERL_PV_ESCAPE_FIRSTCHAR
3488                             )
3489                         );
3490                     });
3491                     if ( state==1 ) {
3492                         OP( convert ) = nodetype;
3493                         str=STRING(convert);
3494                         STR_LEN(convert)=0;
3495                     }
3496                     STR_LEN(convert) += len;
3497                     while (len--)
3498                         *str++ = *ch++;
3499                 } else {
3500 #ifdef DEBUGGING
3501                     if (state>1)
3502                         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3503 #endif
3504                     break;
3505                 }
3506             }
3507             trie->prefixlen = (state-1);
3508             if (str) {
3509                 regnode *n = convert+NODE_SZ_STR(convert);
3510                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3511                 trie->startstate = state;
3512                 trie->minlen -= (state - 1);
3513                 trie->maxlen -= (state - 1);
3514 #ifdef DEBUGGING
3515                /* At least the UNICOS C compiler choked on this
3516                 * being argument to DEBUG_r(), so let's just have
3517                 * it right here. */
3518                if (
3519 #ifdef PERL_EXT_RE_BUILD
3520                    1
3521 #else
3522                    DEBUG_r_TEST
3523 #endif
3524                    ) {
3525                    regnode *fix = convert;
3526                    U32 word = trie->wordcount;
3527 #ifdef RE_TRACK_PATTERN_OFFSETS
3528                    mjd_nodelen++;
3529 #endif
3530                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3531                    while( ++fix < n ) {
3532                        Set_Node_Offset_Length(fix, 0, 0);
3533                    }
3534                    while (word--) {
3535                        SV ** const tmp = av_fetch( trie_words, word, 0 );
3536                        if (tmp) {
3537                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
3538                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3539                            else
3540                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3541                        }
3542                    }
3543                }
3544 #endif
3545                 if (trie->maxlen) {
3546                     convert = n;
3547                 } else {
3548                     NEXT_OFF(convert) = (U16)(tail - convert);
3549                     DEBUG_r(optimize= n);
3550                 }
3551             }
3552         }
3553         if (!jumper)
3554             jumper = last;
3555         if ( trie->maxlen ) {
3556             NEXT_OFF( convert ) = (U16)(tail - convert);
3557             ARG_SET( convert, data_slot );
3558             /* Store the offset to the first unabsorbed branch in
3559                jump[0], which is otherwise unused by the jump logic.
3560                We use this when dumping a trie and during optimisation. */
3561             if (trie->jump)
3562                 trie->jump[0] = (U16)(nextbranch - convert);
3563
3564             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3565              *   and there is a bitmap
3566              *   and the first "jump target" node we found leaves enough room
3567              * then convert the TRIE node into a TRIEC node, with the bitmap
3568              * embedded inline in the opcode - this is hypothetically faster.
3569              */
3570             if ( !trie->states[trie->startstate].wordnum
3571                  && trie->bitmap
3572                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3573             {
3574                 OP( convert ) = TRIEC;
3575                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3576                 PerlMemShared_free(trie->bitmap);
3577                 trie->bitmap= NULL;
3578             } else
3579                 OP( convert ) = TRIE;
3580
3581             /* store the type in the flags */
3582             convert->flags = nodetype;
3583             DEBUG_r({
3584             optimize = convert
3585                       + NODE_STEP_REGNODE
3586                       + regarglen[ OP( convert ) ];
3587             });
3588             /* XXX We really should free up the resource in trie now,
3589                    as we won't use them - (which resources?) dmq */
3590         }
3591         /* needed for dumping*/
3592         DEBUG_r(if (optimize) {
3593             regnode *opt = convert;
3594
3595             while ( ++opt < optimize) {
3596                 Set_Node_Offset_Length(opt, 0, 0);
3597             }
3598             /*
3599                 Try to clean up some of the debris left after the
3600                 optimisation.
3601              */
3602             while( optimize < jumper ) {
3603                 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3604                 OP( optimize ) = OPTIMIZED;
3605                 Set_Node_Offset_Length(optimize, 0, 0);
3606                 optimize++;
3607             }
3608             Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3609         });
3610     } /* end node insert */
3611
3612     /*  Finish populating the prev field of the wordinfo array.  Walk back
3613      *  from each accept state until we find another accept state, and if
3614      *  so, point the first word's .prev field at the second word. If the
3615      *  second already has a .prev field set, stop now. This will be the
3616      *  case either if we've already processed that word's accept state,
3617      *  or that state had multiple words, and the overspill words were
3618      *  already linked up earlier.
3619      */
3620     {
3621         U16 word;
3622         U32 state;
3623         U16 prev;
3624
3625         for (word=1; word <= trie->wordcount; word++) {
3626             prev = 0;
3627             if (trie->wordinfo[word].prev)
3628                 continue;
3629             state = trie->wordinfo[word].accept;
3630             while (state) {
3631                 state = prev_states[state];
3632                 if (!state)
3633                     break;
3634                 prev = trie->states[state].wordnum;
3635                 if (prev)
3636                     break;
3637             }
3638             trie->wordinfo[word].prev = prev;
3639         }
3640         Safefree(prev_states);
3641     }
3642
3643
3644     /* and now dump out the compressed format */
3645     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3646
3647     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3648 #ifdef DEBUGGING
3649     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3650     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3651 #else
3652     SvREFCNT_dec_NN(revcharmap);
3653 #endif
3654     return trie->jump
3655            ? MADE_JUMP_TRIE
3656            : trie->startstate>1
3657              ? MADE_EXACT_TRIE
3658              : MADE_TRIE;
3659 }
3660
3661 STATIC regnode *
3662 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3663 {
3664 /* The Trie is constructed and compressed now so we can build a fail array if
3665  * it's needed
3666
3667    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3668    3.32 in the
3669    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3670    Ullman 1985/88
3671    ISBN 0-201-10088-6
3672
3673    We find the fail state for each state in the trie, this state is the longest
3674    proper suffix of the current state's 'word' that is also a proper prefix of
3675    another word in our trie. State 1 represents the word '' and is thus the
3676    default fail state. This allows the DFA not to have to restart after its
3677    tried and failed a word at a given point, it simply continues as though it
3678    had been matching the other word in the first place.
3679    Consider
3680       'abcdgu'=~/abcdefg|cdgu/
3681    When we get to 'd' we are still matching the first word, we would encounter
3682    'g' which would fail, which would bring us to the state representing 'd' in
3683    the second word where we would try 'g' and succeed, proceeding to match
3684    'cdgu'.
3685  */
3686  /* add a fail transition */
3687     const U32 trie_offset = ARG(source);
3688     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3689     U32 *q;
3690     const U32 ucharcount = trie->uniquecharcount;
3691     const U32 numstates = trie->statecount;
3692     const U32 ubound = trie->lasttrans + ucharcount;
3693     U32 q_read = 0;
3694     U32 q_write = 0;
3695     U32 charid;
3696     U32 base = trie->states[ 1 ].trans.base;
3697     U32 *fail;
3698     reg_ac_data *aho;
3699     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3700     regnode *stclass;
3701     GET_RE_DEBUG_FLAGS_DECL;
3702
3703     PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3704     PERL_UNUSED_CONTEXT;
3705 #ifndef DEBUGGING
3706     PERL_UNUSED_ARG(depth);
3707 #endif
3708
3709     if ( OP(source) == TRIE ) {
3710         struct regnode_1 *op = (struct regnode_1 *)
3711             PerlMemShared_calloc(1, sizeof(struct regnode_1));
3712         StructCopy(source, op, struct regnode_1);
3713         stclass = (regnode *)op;
3714     } else {
3715         struct regnode_charclass *op = (struct regnode_charclass *)
3716             PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3717         StructCopy(source, op, struct regnode_charclass);
3718         stclass = (regnode *)op;
3719     }
3720     OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3721
3722     ARG_SET( stclass, data_slot );
3723     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3724     RExC_rxi->data->data[ data_slot ] = (void*)aho;
3725     aho->trie=trie_offset;
3726     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3727     Copy( trie->states, aho->states, numstates, reg_trie_state );
3728     Newx( q, numstates, U32);
3729     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3730     aho->refcount = 1;
3731     fail = aho->fail;
3732     /* initialize fail[0..1] to be 1 so that we always have
3733        a valid final fail state */
3734     fail[ 0 ] = fail[ 1 ] = 1;
3735
3736     for ( charid = 0; charid < ucharcount ; charid++ ) {
3737         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3738         if ( newstate ) {
3739             q[ q_write ] = newstate;
3740             /* set to point at the root */
3741             fail[ q[ q_write++ ] ]=1;
3742         }
3743     }
3744     while ( q_read < q_write) {
3745         const U32 cur = q[ q_read++ % numstates ];
3746         base = trie->states[ cur ].trans.base;
3747
3748         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3749             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3750             if (ch_state) {
3751                 U32 fail_state = cur;
3752                 U32 fail_base;
3753                 do {
3754                     fail_state = fail[ fail_state ];
3755                     fail_base = aho->states[ fail_state ].trans.base;
3756                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3757
3758                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3759                 fail[ ch_state ] = fail_state;
3760                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3761                 {
3762                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
3763                 }
3764                 q[ q_write++ % numstates] = ch_state;
3765             }
3766         }
3767     }
3768     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3769        when we fail in state 1, this allows us to use the
3770        charclass scan to find a valid start char. This is based on the principle
3771        that theres a good chance the string being searched contains lots of stuff
3772        that cant be a start char.
3773      */
3774     fail[ 0 ] = fail[ 1 ] = 0;
3775     DEBUG_TRIE_COMPILE_r({
3776         Perl_re_indentf( aTHX_  "Stclass Failtable (%" UVuf " states): 0",
3777                       depth, (UV)numstates
3778         );
3779         for( q_read=1; q_read<numstates; q_read++ ) {
3780             Perl_re_printf( aTHX_  ", %" UVuf, (UV)fail[q_read]);
3781         }
3782         Perl_re_printf( aTHX_  "\n");
3783     });
3784     Safefree(q);
3785     /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3786     return stclass;
3787 }
3788
3789
3790 /* The below joins as many adjacent EXACTish nodes as possible into a single
3791  * one.  The regop may be changed if the node(s) contain certain sequences that
3792  * require special handling.  The joining is only done if:
3793  * 1) there is room in the current conglomerated node to entirely contain the
3794  *    next one.
3795  * 2) they are the exact same node type
3796  *
3797  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3798  * these get optimized out
3799  *
3800  * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3801  * as possible, even if that means splitting an existing node so that its first
3802  * part is moved to the preceeding node.  This would maximise the efficiency of
3803  * memEQ during matching.
3804  *
3805  * If a node is to match under /i (folded), the number of characters it matches
3806  * can be different than its character length if it contains a multi-character
3807  * fold.  *min_subtract is set to the total delta number of characters of the
3808  * input nodes.
3809  *
3810  * And *unfolded_multi_char is set to indicate whether or not the node contains
3811  * an unfolded multi-char fold.  This happens when it won't be known until
3812  * runtime whether the fold is valid or not; namely
3813  *  1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3814  *      target string being matched against turns out to be UTF-8 is that fold
3815  *      valid; or
3816  *  2) for EXACTFL nodes whose folding rules depend on the locale in force at
3817  *      runtime.
3818  * (Multi-char folds whose components are all above the Latin1 range are not
3819  * run-time locale dependent, and have already been folded by the time this
3820  * function is called.)
3821  *
3822  * This is as good a place as any to discuss the design of handling these
3823  * multi-character fold sequences.  It's been wrong in Perl for a very long
3824  * time.  There are three code points in Unicode whose multi-character folds
3825  * were long ago discovered to mess things up.  The previous designs for
3826  * dealing with these involved assigning a special node for them.  This
3827  * approach doesn't always work, as evidenced by this example:
3828  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
3829  * Both sides fold to "sss", but if the pattern is parsed to create a node that
3830  * would match just the \xDF, it won't be able to handle the case where a
3831  * successful match would have to cross the node's boundary.  The new approach
3832  * that hopefully generally solves the problem generates an EXACTFU_SS node
3833  * that is "sss" in this case.
3834  *
3835  * It turns out that there are problems with all multi-character folds, and not
3836  * just these three.  Now the code is general, for all such cases.  The
3837  * approach taken is:
3838  * 1)   This routine examines each EXACTFish node that could contain multi-
3839  *      character folded sequences.  Since a single character can fold into
3840  *      such a sequence, the minimum match length for this node is less than
3841  *      the number of characters in the node.  This routine returns in
3842  *      *min_subtract how many characters to subtract from the the actual
3843  *      length of the string to get a real minimum match length; it is 0 if
3844  *      there are no multi-char foldeds.  This delta is used by the caller to
3845  *      adjust the min length of the match, and the delta between min and max,
3846  *      so that the optimizer doesn't reject these possibilities based on size
3847  *      constraints.
3848  * 2)   For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
3849  *      is used for an EXACTFU node that contains at least one "ss" sequence in
3850  *      it.  For non-UTF-8 patterns and strings, this is the only case where
3851  *      there is a possible fold length change.  That means that a regular
3852  *      EXACTFU node without UTF-8 involvement doesn't have to concern itself
3853  *      with length changes, and so can be processed faster.  regexec.c takes
3854  *      advantage of this.  Generally, an EXACTFish node that is in UTF-8 is
3855  *      pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3856  *      known until runtime).  This saves effort in regex matching.  However,
3857  *      the pre-folding isn't done for non-UTF8 patterns because the fold of
3858  *      the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3859  *      forcing the pattern into UTF8 unless necessary.  Also what EXACTF (and,
3860  *      again, EXACTFL) nodes fold to isn't known until runtime.  The fold
3861  *      possibilities for the non-UTF8 patterns are quite simple, except for
3862  *      the sharp s.  All the ones that don't involve a UTF-8 target string are
3863  *      members of a fold-pair, and arrays are set up for all of them so that
3864  *      the other member of the pair can be found quickly.  Code elsewhere in
3865  *      this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3866  *      'ss', even if the pattern isn't UTF-8.  This avoids the issues
3867  *      described in the next item.
3868  * 3)   A problem remains for unfolded multi-char folds. (These occur when the
3869  *      validity of the fold won't be known until runtime, and so must remain
3870  *      unfolded for now.  This happens for the sharp s in EXACTF and EXACTFAA
3871  *      nodes when the pattern isn't in UTF-8.  (Note, BTW, that there cannot
3872  *      be an EXACTF node with a UTF-8 pattern.)  They also occur for various
3873  *      folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3874  *      The reason this is a problem is that the optimizer part of regexec.c
3875  *      (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3876  *      that a character in the pattern corresponds to at most a single
3877  *      character in the target string.  (And I do mean character, and not byte
3878  *      here, unlike other parts of the documentation that have never been
3879  *      updated to account for multibyte Unicode.)  sharp s in EXACTF and
3880  *      EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
3881  *      nodes it can match "\x{17F}\x{17F}".  These, along with other ones in
3882  *      EXACTFL nodes, violate the assumption, and they are the only instances
3883  *      where it is violated.  I'm reluctant to try to change the assumption,
3884  *      as the code involved is impenetrable to me (khw), so instead the code
3885  *      here punts.  This routine examines EXACTFL nodes, and (when the pattern
3886  *      isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
3887  *      boolean indicating whether or not the node contains such a fold.  When
3888  *      it is true, the caller sets a flag that later causes the optimizer in
3889  *      this file to not set values for the floating and fixed string lengths,
3890  *      and thus avoids the optimizer code in regexec.c that makes the invalid
3891  *      assumption.  Thus, there is no optimization based on string lengths for
3892  *      EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3893  *      EXACTF and EXACTFAA nodes that contain the sharp s.  (The reason the
3894  *      assumption is wrong only in these cases is that all other non-UTF-8
3895  *      folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3896  *      their expanded versions.  (Again, we can't prefold sharp s to 'ss' in
3897  *      EXACTF nodes because we don't know at compile time if it actually
3898  *      matches 'ss' or not.  For EXACTF nodes it will match iff the target
3899  *      string is in UTF-8.  This is in contrast to EXACTFU nodes, where it
3900  *      always matches; and EXACTFAA where it never does.  In an EXACTFAA node
3901  *      in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3902  *      problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3903  *      string would require the pattern to be forced into UTF-8, the overhead
3904  *      of which we want to avoid.  Similarly the unfolded multi-char folds in
3905  *      EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3906  *      locale.)
3907  *
3908  *      Similarly, the code that generates tries doesn't currently handle
3909  *      not-already-folded multi-char folds, and it looks like a pain to change
3910  *      that.  Therefore, trie generation of EXACTFAA nodes with the sharp s
3911  *      doesn't work.  Instead, such an EXACTFAA is turned into a new regnode,
3912  *      EXACTFAA_NO_TRIE, which the trie code knows not to handle.  Most people
3913  *      using /iaa matching will be doing so almost entirely with ASCII
3914  *      strings, so this should rarely be encountered in practice */
3915
3916 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3917     if (PL_regkind[OP(scan)] == EXACT) \
3918         join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
3919
3920 STATIC U32
3921 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3922                    UV *min_subtract, bool *unfolded_multi_char,
3923                    U32 flags, regnode *val, U32 depth)
3924 {
3925     /* Merge several consecutive EXACTish nodes into one. */
3926     regnode *n = regnext(scan);
3927     U32 stringok = 1;
3928     regnode *next = scan + NODE_SZ_STR(scan);
3929     U32 merged = 0;
3930     U32 stopnow = 0;
3931 #ifdef DEBUGGING
3932     regnode *stop = scan;
3933     GET_RE_DEBUG_FLAGS_DECL;
3934 #else
3935     PERL_UNUSED_ARG(depth);
3936 #endif
3937
3938     PERL_ARGS_ASSERT_JOIN_EXACT;
3939 #ifndef EXPERIMENTAL_INPLACESCAN
3940     PERL_UNUSED_ARG(flags);
3941     PERL_UNUSED_ARG(val);
3942 #endif
3943     DEBUG_PEEP("join", scan, depth, 0);
3944
3945     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
3946      * EXACT ones that are mergeable to the current one. */
3947     while (n
3948            && (PL_regkind[OP(n)] == NOTHING
3949                || (stringok && OP(n) == OP(scan)))
3950            && NEXT_OFF(n)
3951            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3952     {
3953
3954         if (OP(n) == TAIL || n > next)
3955             stringok = 0;
3956         if (PL_regkind[OP(n)] == NOTHING) {
3957             DEBUG_PEEP("skip:", n, depth, 0);
3958             NEXT_OFF(scan) += NEXT_OFF(n);
3959             next = n + NODE_STEP_REGNODE;
3960 #ifdef DEBUGGING
3961             if (stringok)
3962                 stop = n;
3963 #endif
3964             n = regnext(n);
3965         }
3966         else if (stringok) {
3967             const unsigned int oldl = STR_LEN(scan);
3968             regnode * const nnext = regnext(n);
3969
3970             /* XXX I (khw) kind of doubt that this works on platforms (should
3971              * Perl ever run on one) where U8_MAX is above 255 because of lots
3972              * of other assumptions */
3973             /* Don't join if the sum can't fit into a single node */
3974             if (oldl + STR_LEN(n) > U8_MAX)
3975                 break;
3976
3977             DEBUG_PEEP("merg", n, depth, 0);
3978             merged++;
3979
3980             NEXT_OFF(scan) += NEXT_OFF(n);
3981             STR_LEN(scan) += STR_LEN(n);
3982             next = n + NODE_SZ_STR(n);
3983             /* Now we can overwrite *n : */
3984             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3985 #ifdef DEBUGGING
3986             stop = next - 1;
3987 #endif
3988             n = nnext;
3989             if (stopnow) break;
3990         }
3991
3992 #ifdef EXPERIMENTAL_INPLACESCAN
3993         if (flags && !NEXT_OFF(n)) {
3994             DEBUG_PEEP("atch", val, depth, 0);
3995             if (reg_off_by_arg[OP(n)]) {
3996                 ARG_SET(n, val - n);
3997             }
3998             else {
3999                 NEXT_OFF(n) = val - n;
4000             }
4001             stopnow = 1;
4002         }
4003 #endif
4004     }
4005
4006     *min_subtract = 0;
4007     *unfolded_multi_char = FALSE;
4008
4009     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
4010      * can now analyze for sequences of problematic code points.  (Prior to
4011      * this final joining, sequences could have been split over boundaries, and
4012      * hence missed).  The sequences only happen in folding, hence for any
4013      * non-EXACT EXACTish node */
4014     if (OP(scan) != EXACT && OP(scan) != EXACTL) {
4015         U8* s0 = (U8*) STRING(scan);
4016         U8* s = s0;
4017         U8* s_end = s0 + STR_LEN(scan);
4018
4019         int total_count_delta = 0;  /* Total delta number of characters that
4020                                        multi-char folds expand to */
4021
4022         /* One pass is made over the node's string looking for all the
4023          * possibilities.  To avoid some tests in the loop, there are two main
4024          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4025          * non-UTF-8 */
4026         if (UTF) {
4027             U8* folded = NULL;
4028
4029             if (OP(scan) == EXACTFL) {
4030                 U8 *d;
4031
4032                 /* An EXACTFL node would already have been changed to another
4033                  * node type unless there is at least one character in it that
4034                  * is problematic; likely a character whose fold definition
4035                  * won't be known until runtime, and so has yet to be folded.
4036                  * For all but the UTF-8 locale, folds are 1-1 in length, but
4037                  * to handle the UTF-8 case, we need to create a temporary
4038                  * folded copy using UTF-8 locale rules in order to analyze it.
4039                  * This is because our macros that look to see if a sequence is
4040                  * a multi-char fold assume everything is folded (otherwise the
4041                  * tests in those macros would be too complicated and slow).
4042                  * Note that here, the non-problematic folds will have already
4043                  * been done, so we can just copy such characters.  We actually
4044                  * don't completely fold the EXACTFL string.  We skip the
4045                  * unfolded multi-char folds, as that would just create work
4046                  * below to figure out the size they already are */
4047
4048                 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4049                 d = folded;
4050                 while (s < s_end) {
4051                     STRLEN s_len = UTF8SKIP(s);
4052                     if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4053                         Copy(s, d, s_len, U8);
4054                         d += s_len;
4055                     }
4056                     else if (is_FOLDS_TO_MULTI_utf8(s)) {
4057                         *unfolded_multi_char = TRUE;
4058                         Copy(s, d, s_len, U8);
4059                         d += s_len;
4060                     }
4061                     else if (isASCII(*s)) {
4062                         *(d++) = toFOLD(*s);
4063                     }
4064                     else {
4065                         STRLEN len;
4066                         _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4067                         d += len;
4068                     }
4069                     s += s_len;
4070                 }
4071
4072                 /* Point the remainder of the routine to look at our temporary
4073                  * folded copy */
4074                 s = folded;
4075                 s_end = d;
4076             } /* End of creating folded copy of EXACTFL string */
4077
4078             /* Examine the string for a multi-character fold sequence.  UTF-8
4079              * patterns have all characters pre-folded by the time this code is
4080              * executed */
4081             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4082                                      length sequence we are looking for is 2 */
4083             {
4084                 int count = 0;  /* How many characters in a multi-char fold */
4085                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4086                 if (! len) {    /* Not a multi-char fold: get next char */
4087                     s += UTF8SKIP(s);
4088                     continue;
4089                 }
4090
4091                 /* Nodes with 'ss' require special handling, except for
4092                  * EXACTFAA-ish for which there is no multi-char fold to this */
4093                 if (len == 2 && *s == 's' && *(s+1) == 's'
4094                     && OP(scan) != EXACTFAA
4095                     && OP(scan) != EXACTFAA_NO_TRIE)
4096                 {
4097                     count = 2;
4098                     if (OP(scan) != EXACTFL) {
4099                         OP(scan) = EXACTFU_SS;
4100                     }
4101                     s += 2;
4102                 }
4103                 else { /* Here is a generic multi-char fold. */
4104                     U8* multi_end  = s + len;
4105
4106                     /* Count how many characters are in it.  In the case of
4107                      * /aa, no folds which contain ASCII code points are
4108                      * allowed, so check for those, and skip if found. */
4109                     if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4110                         count = utf8_length(s, multi_end);
4111                         s = multi_end;
4112                     }
4113                     else {
4114                         while (s < multi_end) {
4115                             if (isASCII(*s)) {
4116                                 s++;
4117                                 goto next_iteration;
4118                             }
4119                             else {
4120                                 s += UTF8SKIP(s);
4121                             }
4122                             count++;
4123                         }
4124                     }
4125                 }
4126
4127                 /* The delta is how long the sequence is minus 1 (1 is how long
4128                  * the character that folds to the sequence is) */
4129                 total_count_delta += count - 1;
4130               next_iteration: ;
4131             }
4132
4133             /* We created a temporary folded copy of the string in EXACTFL
4134              * nodes.  Therefore we need to be sure it doesn't go below zero,
4135              * as the real string could be shorter */
4136             if (OP(scan) == EXACTFL) {
4137                 int total_chars = utf8_length((U8*) STRING(scan),
4138                                            (U8*) STRING(scan) + STR_LEN(scan));
4139                 if (total_count_delta > total_chars) {
4140                     total_count_delta = total_chars;
4141                 }
4142             }
4143
4144             *min_subtract += total_count_delta;
4145             Safefree(folded);
4146         }
4147         else if (OP(scan) == EXACTFAA) {
4148
4149             /* Non-UTF-8 pattern, EXACTFAA node.  There can't be a multi-char
4150              * fold to the ASCII range (and there are no existing ones in the
4151              * upper latin1 range).  But, as outlined in the comments preceding
4152              * this function, we need to flag any occurrences of the sharp s.
4153              * This character forbids trie formation (because of added
4154              * complexity) */
4155 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
4156    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
4157                                       || UNICODE_DOT_DOT_VERSION > 0)
4158             while (s < s_end) {
4159                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4160                     OP(scan) = EXACTFAA_NO_TRIE;
4161                     *unfolded_multi_char = TRUE;
4162                     break;
4163                 }
4164                 s++;
4165             }
4166         }
4167         else {
4168
4169             /* Non-UTF-8 pattern, not EXACTFAA node.  Look for the multi-char
4170              * folds that are all Latin1.  As explained in the comments
4171              * preceding this function, we look also for the sharp s in EXACTF
4172              * and EXACTFL nodes; it can be in the final position.  Otherwise
4173              * we can stop looking 1 byte earlier because have to find at least
4174              * two characters for a multi-fold */
4175             const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4176                               ? s_end
4177                               : s_end -1;
4178
4179             while (s < upper) {
4180                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4181                 if (! len) {    /* Not a multi-char fold. */
4182                     if (*s == LATIN_SMALL_LETTER_SHARP_S
4183                         && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4184                     {
4185                         *unfolded_multi_char = TRUE;
4186                     }
4187                     s++;
4188                     continue;
4189                 }
4190
4191                 if (len == 2
4192                     && isALPHA_FOLD_EQ(*s, 's')
4193                     && isALPHA_FOLD_EQ(*(s+1), 's'))
4194                 {
4195
4196                     /* EXACTF nodes need to know that the minimum length
4197                      * changed so that a sharp s in the string can match this
4198                      * ss in the pattern, but they remain EXACTF nodes, as they
4199                      * won't match this unless the target string is is UTF-8,
4200                      * which we don't know until runtime.  EXACTFL nodes can't
4201                      * transform into EXACTFU nodes */
4202                     if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4203                         OP(scan) = EXACTFU_SS;
4204                     }
4205                 }
4206
4207                 *min_subtract += len - 1;
4208                 s += len;
4209             }
4210 #endif
4211         }
4212     }
4213
4214 #ifdef DEBUGGING
4215     /* Allow dumping but overwriting the collection of skipped
4216      * ops and/or strings with fake optimized ops */
4217     n = scan + NODE_SZ_STR(scan);
4218     while (n <= stop) {
4219         OP(n) = OPTIMIZED;
4220         FLAGS(n) = 0;
4221         NEXT_OFF(n) = 0;
4222         n++;
4223     }
4224 #endif
4225     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4226     return stopnow;
4227 }
4228
4229 /* REx optimizer.  Converts nodes into quicker variants "in place".
4230    Finds fixed substrings.  */
4231
4232 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4233    to the position after last scanned or to NULL. */
4234
4235 #define INIT_AND_WITHP \
4236     assert(!and_withp); \
4237     Newx(and_withp, 1, regnode_ssc); \
4238     SAVEFREEPV(and_withp)
4239
4240
4241 static void
4242 S_unwind_scan_frames(pTHX_ const void *p)
4243 {
4244     scan_frame *f= (scan_frame *)p;
4245     do {
4246         scan_frame *n= f->next_frame;
4247         Safefree(f);
4248         f= n;
4249     } while (f);
4250 }
4251
4252 /* the return from this sub is the minimum length that could possibly match */
4253 STATIC SSize_t
4254 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4255                         SSize_t *minlenp, SSize_t *deltap,
4256                         regnode *last,
4257                         scan_data_t *data,
4258                         I32 stopparen,
4259                         U32 recursed_depth,
4260                         regnode_ssc *and_withp,
4261                         U32 flags, U32 depth)
4262                         /* scanp: Start here (read-write). */
4263                         /* deltap: Write maxlen-minlen here. */
4264                         /* last: Stop before this one. */
4265                         /* data: string data about the pattern */
4266                         /* stopparen: treat close N as END */
4267                         /* recursed: which subroutines have we recursed into */
4268                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4269 {
4270     /* There must be at least this number of characters to match */
4271     SSize_t min = 0;
4272     I32 pars = 0, code;
4273     regnode *scan = *scanp, *next;
4274     SSize_t delta = 0;
4275     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4276     int is_inf_internal = 0;            /* The studied chunk is infinite */
4277     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4278     scan_data_t data_fake;
4279     SV *re_trie_maxbuff = NULL;
4280     regnode *first_non_open = scan;
4281     SSize_t stopmin = SSize_t_MAX;
4282     scan_frame *frame = NULL;
4283     GET_RE_DEBUG_FLAGS_DECL;
4284
4285     PERL_ARGS_ASSERT_STUDY_CHUNK;
4286     RExC_study_started= 1;
4287
4288     Zero(&data_fake, 1, scan_data_t);
4289
4290     if ( depth == 0 ) {
4291         while (first_non_open && OP(first_non_open) == OPEN)
4292             first_non_open=regnext(first_non_open);
4293     }
4294
4295
4296   fake_study_recurse:
4297     DEBUG_r(
4298         RExC_study_chunk_recursed_count++;
4299     );
4300     DEBUG_OPTIMISE_MORE_r(
4301     {
4302         Perl_re_indentf( aTHX_  "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4303             depth, (long)stopparen,
4304             (unsigned long)RExC_study_chunk_recursed_count,
4305             (unsigned long)depth, (unsigned long)recursed_depth,
4306             scan,
4307             last);
4308         if (recursed_depth) {
4309             U32 i;
4310             U32 j;
4311             for ( j = 0 ; j < recursed_depth ; j++ ) {
4312                 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4313                     if (
4314                         PAREN_TEST(RExC_study_chunk_recursed +
4315                                    ( j * RExC_study_chunk_recursed_bytes), i )
4316                         && (
4317                             !j ||
4318                             !PAREN_TEST(RExC_study_chunk_recursed +
4319                                    (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
4320                         )
4321                     ) {
4322                         Perl_re_printf( aTHX_ " %d",(int)i);
4323                         break;
4324                     }
4325                 }
4326                 if ( j + 1 < recursed_depth ) {
4327                     Perl_re_printf( aTHX_  ",");
4328                 }
4329             }
4330         }
4331         Perl_re_printf( aTHX_ "\n");
4332     }
4333     );
4334     while ( scan && OP(scan) != END && scan < last ){
4335         UV min_subtract = 0;    /* How mmany chars to subtract from the minimum
4336                                    node length to get a real minimum (because
4337                                    the folded version may be shorter) */
4338         bool unfolded_multi_char = FALSE;
4339         /* Peephole optimizer: */
4340         DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4341         DEBUG_PEEP("Peep", scan, depth, flags);
4342
4343
4344         /* The reason we do this here is that we need to deal with things like
4345          * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4346          * parsing code, as each (?:..) is handled by a different invocation of
4347          * reg() -- Yves
4348          */
4349         JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
4350
4351         /* Follow the next-chain of the current node and optimize
4352            away all the NOTHINGs from it.  */
4353         if (OP(scan) != CURLYX) {
4354             const int max = (reg_off_by_arg[OP(scan)]
4355                        ? I32_MAX
4356                        /* I32 may be smaller than U16 on CRAYs! */
4357                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4358             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4359             int noff;
4360             regnode *n = scan;
4361
4362             /* Skip NOTHING and LONGJMP. */
4363             while ((n = regnext(n))
4364                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4365                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4366                    && off + noff < max)
4367                 off += noff;
4368             if (reg_off_by_arg[OP(scan)])
4369                 ARG(scan) = off;
4370             else
4371                 NEXT_OFF(scan) = off;
4372         }
4373
4374         /* The principal pseudo-switch.  Cannot be a switch, since we
4375            look into several different things.  */
4376         if ( OP(scan) == DEFINEP ) {
4377             SSize_t minlen = 0;
4378             SSize_t deltanext = 0;
4379             SSize_t fake_last_close = 0;
4380             I32 f = SCF_IN_DEFINE;
4381
4382             StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4383             scan = regnext(scan);
4384             assert( OP(scan) == IFTHEN );
4385             DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4386
4387             data_fake.last_closep= &fake_last_close;
4388             minlen = *minlenp;
4389             next = regnext(scan);
4390             scan = NEXTOPER(NEXTOPER(scan));
4391             DEBUG_PEEP("scan", scan, depth, flags);
4392             DEBUG_PEEP("next", next, depth, flags);
4393
4394             /* we suppose the run is continuous, last=next...
4395              * NOTE we dont use the return here! */
4396             /* DEFINEP study_chunk() recursion */
4397             (void)study_chunk(pRExC_state, &scan, &minlen,
4398                               &deltanext, next, &data_fake, stopparen,
4399                               recursed_depth, NULL, f, depth+1);
4400
4401             scan = next;
4402         } else
4403         if (
4404             OP(scan) == BRANCH  ||
4405             OP(scan) == BRANCHJ ||
4406             OP(scan) == IFTHEN
4407         ) {
4408             next = regnext(scan);
4409             code = OP(scan);
4410
4411             /* The op(next)==code check below is to see if we
4412              * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4413              * IFTHEN is special as it might not appear in pairs.
4414              * Not sure whether BRANCH-BRANCHJ is possible, regardless
4415              * we dont handle it cleanly. */
4416             if (OP(next) == code || code == IFTHEN) {
4417                 /* NOTE - There is similar code to this block below for
4418                  * handling TRIE nodes on a re-study.  If you change stuff here
4419                  * check there too. */
4420                 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
4421                 regnode_ssc accum;
4422                 regnode * const startbranch=scan;
4423
4424                 if (flags & SCF_DO_SUBSTR) {
4425                     /* Cannot merge strings after this. */
4426                     scan_commit(pRExC_state, data, minlenp, is_inf);
4427                 }
4428
4429                 if (flags & SCF_DO_STCLASS)
4430                     ssc_init_zero(pRExC_state, &accum);
4431
4432                 while (OP(scan) == code) {
4433                     SSize_t deltanext, minnext, fake;
4434                     I32 f = 0;
4435                     regnode_ssc this_class;
4436
4437                     DEBUG_PEEP("Branch", scan, depth, flags);
4438
4439                     num++;
4440                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4441                     if (data) {
4442                         data_fake.whilem_c = data->whilem_c;
4443                         data_fake.last_closep = data->last_closep;
4444                     }
4445                     else
4446                         data_fake.last_closep = &fake;
4447
4448                     data_fake.pos_delta = delta;
4449                     next = regnext(scan);
4450
4451                     scan = NEXTOPER(scan); /* everything */
4452                     if (code != BRANCH)    /* everything but BRANCH */
4453                         scan = NEXTOPER(scan);
4454
4455                     if (flags & SCF_DO_STCLASS) {
4456                         ssc_init(pRExC_state, &this_class);
4457                         data_fake.start_class = &this_class;
4458                         f = SCF_DO_STCLASS_AND;
4459                     }
4460                     if (flags & SCF_WHILEM_VISITED_POS)
4461                         f |= SCF_WHILEM_VISITED_POS;
4462
4463                     /* we suppose the run is continuous, last=next...*/
4464                     /* recurse study_chunk() for each BRANCH in an alternation */
4465                     minnext = study_chunk(pRExC_state, &scan, minlenp,
4466                                       &deltanext, next, &data_fake, stopparen,
4467                                       recursed_depth, NULL, f, depth+1);
4468
4469                     if (min1 > minnext)
4470                         min1 = minnext;
4471                     if (deltanext == SSize_t_MAX) {
4472                         is_inf = is_inf_internal = 1;
4473                         max1 = SSize_t_MAX;
4474                     } else if (max1 < minnext + deltanext)
4475                         max1 = minnext + deltanext;
4476                     scan = next;
4477                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4478                         pars++;
4479                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4480                         if ( stopmin > minnext)
4481                             stopmin = min + min1;
4482                         flags &= ~SCF_DO_SUBSTR;
4483                         if (data)
4484                             data->flags |= SCF_SEEN_ACCEPT;
4485                     }
4486                     if (data) {
4487                         if (data_fake.flags & SF_HAS_EVAL)
4488                             data->flags |= SF_HAS_EVAL;
4489                         data->whilem_c = data_fake.whilem_c;
4490                     }
4491                     if (flags & SCF_DO_STCLASS)
4492                         ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4493                 }
4494                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4495                     min1 = 0;
4496                 if (flags & SCF_DO_SUBSTR) {
4497                     data->pos_min += min1;
4498                     if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
4499                         data->pos_delta = SSize_t_MAX;
4500                     else
4501                         data->pos_delta += max1 - min1;
4502                     if (max1 != min1 || is_inf)
4503                         data->cur_is_floating = 1;
4504                 }
4505                 min += min1;
4506                 if (delta == SSize_t_MAX
4507                  || SSize_t_MAX - delta - (max1 - min1) < 0)
4508                     delta = SSize_t_MAX;
4509                 else
4510                     delta += max1 - min1;
4511                 if (flags & SCF_DO_STCLASS_OR) {
4512                     ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4513                     if (min1) {
4514                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4515                         flags &= ~SCF_DO_STCLASS;
4516                     }
4517                 }
4518                 else if (flags & SCF_DO_STCLASS_AND) {
4519                     if (min1) {
4520                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4521                         flags &= ~SCF_DO_STCLASS;
4522                     }
4523                     else {
4524                         /* Switch to OR mode: cache the old value of
4525                          * data->start_class */
4526                         INIT_AND_WITHP;
4527                         StructCopy(data->start_class, and_withp, regnode_ssc);
4528                         flags &= ~SCF_DO_STCLASS_AND;
4529                         StructCopy(&accum, data->start_class, regnode_ssc);
4530                         flags |= SCF_DO_STCLASS_OR;
4531                     }
4532                 }
4533
4534                 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4535                         OP( startbranch ) == BRANCH )
4536                 {
4537                 /* demq.
4538
4539                    Assuming this was/is a branch we are dealing with: 'scan'
4540                    now points at the item that follows the branch sequence,
4541                    whatever it is. We now start at the beginning of the
4542                    sequence and look for subsequences of
4543
4544                    BRANCH->EXACT=>x1
4545                    BRANCH->EXACT=>x2
4546                    tail
4547
4548                    which would be constructed from a pattern like
4549                    /A|LIST|OF|WORDS/
4550
4551                    If we can find such a subsequence we need to turn the first
4552                    element into a trie and then add the subsequent branch exact
4553                    strings to the trie.
4554
4555                    We have two cases
4556
4557                      1. patterns where the whole set of branches can be
4558                         converted.
4559
4560                      2. patterns where only a subset can be converted.
4561
4562                    In case 1 we can replace the whole set with a single regop
4563                    for the trie. In case 2 we need to keep the start and end
4564                    branches so
4565
4566                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4567                      becomes BRANCH TRIE; BRANCH X;
4568
4569                   There is an additional case, that being where there is a
4570                   common prefix, which gets split out into an EXACT like node
4571                   preceding the TRIE node.
4572
4573                   If x(1..n)==tail then we can do a simple trie, if not we make
4574                   a "jump" trie, such that when we match the appropriate word
4575                   we "jump" to the appropriate tail node. Essentially we turn
4576                   a nested if into a case structure of sorts.
4577
4578                 */
4579
4580                     int made=0;
4581                     if (!re_trie_maxbuff) {
4582                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4583                         if (!SvIOK(re_trie_maxbuff))
4584                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4585                     }
4586                     if ( SvIV(re_trie_maxbuff)>=0  ) {
4587                         regnode *cur;
4588                         regnode *first = (regnode *)NULL;
4589                         regnode *last = (regnode *)NULL;
4590                         regnode *tail = scan;
4591                         U8 trietype = 0;
4592                         U32 count=0;
4593
4594                         /* var tail is used because there may be a TAIL
4595                            regop in the way. Ie, the exacts will point to the
4596                            thing following the TAIL, but the last branch will
4597                            point at the TAIL. So we advance tail. If we
4598                            have nested (?:) we may have to move through several
4599                            tails.
4600                          */
4601
4602                         while ( OP( tail ) == TAIL ) {
4603                             /* this is the TAIL generated by (?:) */
4604                             tail = regnext( tail );
4605                         }
4606
4607
4608                         DEBUG_TRIE_COMPILE_r({
4609                             regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4610                             Perl_re_indentf( aTHX_  "%s %" UVuf ":%s\n",
4611                               depth+1,
4612                               "Looking for TRIE'able sequences. Tail node is ",
4613                               (UV) REGNODE_OFFSET(tail),
4614                               SvPV_nolen_const( RExC_mysv )
4615                             );
4616                         });
4617
4618                         /*
4619
4620                             Step through the branches
4621                                 cur represents each branch,
4622                                 noper is the first thing to be matched as part
4623                                       of that branch
4624                                 noper_next is the regnext() of that node.
4625
4626                             We normally handle a case like this
4627                             /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4628                             support building with NOJUMPTRIE, which restricts
4629                             the trie logic to structures like /FOO|BAR/.
4630
4631                             If noper is a trieable nodetype then the branch is
4632                             a possible optimization target. If we are building
4633                             under NOJUMPTRIE then we require that noper_next is
4634                             the same as scan (our current position in the regex
4635                             program).
4636
4637                             Once we have two or more consecutive such branches
4638                             we can create a trie of the EXACT's contents and
4639                             stitch it in place into the program.
4640
4641                             If the sequence represents all of the branches in
4642                             the alternation we replace the entire thing with a
4643                             single TRIE node.
4644
4645                             Otherwise when it is a subsequence we need to
4646                             stitch it in place and replace only the relevant
4647                             branches. This means the first branch has to remain
4648                             as it is used by the alternation logic, and its
4649                             next pointer, and needs to be repointed at the item
4650                             on the branch chain following the last branch we
4651                             have optimized away.
4652
4653                             This could be either a BRANCH, in which case the
4654                             subsequence is internal, or it could be the item
4655                             following the branch sequence in which case the
4656                             subsequence is at the end (which does not
4657                             necessarily mean the first node is the start of the
4658                             alternation).
4659
4660                             TRIE_TYPE(X) is a define which maps the optype to a
4661                             trietype.
4662
4663                                 optype          |  trietype
4664                                 ----------------+-----------
4665                                 NOTHING         | NOTHING
4666                                 EXACT           | EXACT
4667                                 EXACTFU         | EXACTFU
4668                                 EXACTFU_SS      | EXACTFU
4669                                 EXACTFAA         | EXACTFAA
4670                                 EXACTL          | EXACTL
4671                                 EXACTFLU8       | EXACTFLU8
4672
4673
4674                         */
4675 #define TRIE_TYPE(X) ( ( NOTHING == (X) )                                   \
4676                        ? NOTHING                                            \
4677                        : ( EXACT == (X) )                                   \
4678                          ? EXACT                                            \
4679                          : ( EXACTFU == (X) || EXACTFU_SS == (X) )          \
4680                            ? EXACTFU                                        \
4681                            : ( EXACTFAA == (X) )                             \
4682                              ? EXACTFAA                                      \
4683                              : ( EXACTL == (X) )                            \
4684                                ? EXACTL                                     \
4685                                : ( EXACTFLU8 == (X) )                        \
4686                                  ? EXACTFLU8                                 \
4687                                  : 0 )
4688
4689                         /* dont use tail as the end marker for this traverse */
4690                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4691                             regnode * const noper = NEXTOPER( cur );
4692                             U8 noper_type = OP( noper );
4693                             U8 noper_trietype = TRIE_TYPE( noper_type );
4694 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4695                             regnode * const noper_next = regnext( noper );
4696                             U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4697                             U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
4698 #endif
4699
4700                             DEBUG_TRIE_COMPILE_r({
4701                                 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4702                                 Perl_re_indentf( aTHX_  "- %d:%s (%d)",
4703                                    depth+1,
4704                                    REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4705
4706                                 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4707                                 Perl_re_printf( aTHX_  " -> %d:%s",
4708                                     REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
4709
4710                                 if ( noper_next ) {
4711                                   regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4712                                   Perl_re_printf( aTHX_ "\t=> %d:%s\t",
4713                                     REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
4714                                 }
4715                                 Perl_re_printf( aTHX_  "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
4716                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4717                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4718                                 );
4719                             });
4720
4721                             /* Is noper a trieable nodetype that can be merged
4722                              * with the current trie (if there is one)? */
4723                             if ( noper_trietype
4724                                   &&
4725                                   (
4726                                         ( noper_trietype == NOTHING )
4727                                         || ( trietype == NOTHING )
4728                                         || ( trietype == noper_trietype )
4729                                   )
4730 #ifdef NOJUMPTRIE
4731                                   && noper_next >= tail
4732 #endif
4733                                   && count < U16_MAX)
4734                             {
4735                                 /* Handle mergable triable node Either we are
4736                                  * the first node in a new trieable sequence,
4737                                  * in which case we do some bookkeeping,
4738                                  * otherwise we update the end pointer. */
4739                                 if ( !first ) {
4740                                     first = cur;
4741                                     if ( noper_trietype == NOTHING ) {
4742 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4743                                         regnode * const noper_next = regnext( noper );
4744                                         U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4745                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4746 #endif
4747
4748                                         if ( noper_next_trietype ) {
4749                                             trietype = noper_next_trietype;
4750                                         } else if (noper_next_type)  {
4751                                             /* a NOTHING regop is 1 regop wide.
4752                                              * We need at least two for a trie
4753                                              * so we can't merge this in */
4754                                             first = NULL;
4755                                         }
4756                                     } else {
4757                                         trietype = noper_trietype;
4758                                     }
4759                                 } else {
4760                                     if ( trietype == NOTHING )
4761                                         trietype = noper_trietype;
4762                                     last = cur;
4763                                 }
4764                                 if (first)
4765                                     count++;
4766                             } /* end handle mergable triable node */
4767                             else {
4768                                 /* handle unmergable node -
4769                                  * noper may either be a triable node which can
4770                                  * not be tried together with the current trie,
4771                                  * or a non triable node */
4772                                 if ( last ) {
4773                                     /* If last is set and trietype is not
4774                                      * NOTHING then we have found at least two
4775                                      * triable branch sequences in a row of a
4776                                      * similar trietype so we can turn them
4777                                      * into a trie. If/when we allow NOTHING to
4778                                      * start a trie sequence this condition
4779                                      * will be required, and it isn't expensive
4780                                      * so we leave it in for now. */
4781                                     if ( trietype && trietype != NOTHING )
4782                                         make_trie( pRExC_state,
4783                                                 startbranch, first, cur, tail,
4784                                                 count, trietype, depth+1 );
4785                                     last = NULL; /* note: we clear/update
4786                                                     first, trietype etc below,
4787                                                     so we dont do it here */
4788                                 }
4789                                 if ( noper_trietype
4790 #ifdef NOJUMPTRIE
4791                                      && noper_next >= tail
4792 #endif
4793                                 ){
4794                                     /* noper is triable, so we can start a new
4795                                      * trie sequence */
4796                                     count = 1;
4797                                     first = cur;
4798                                     trietype = noper_trietype;
4799                                 } else if (first) {
4800                                     /* if we already saw a first but the
4801                                      * current node is not triable then we have
4802                                      * to reset the first information. */
4803                                     count = 0;
4804                                     first = NULL;
4805                                     trietype = 0;
4806                                 }
4807                             } /* end handle unmergable node */
4808                         } /* loop over branches */
4809                         DEBUG_TRIE_COMPILE_r({
4810                             regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4811                             Perl_re_indentf( aTHX_  "- %s (%d) <SCAN FINISHED> ",
4812                               depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
4813                             Perl_re_printf( aTHX_  "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
4814                                REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4815                                PL_reg_name[trietype]
4816                             );
4817
4818                         });
4819                         if ( last && trietype ) {
4820                             if ( trietype != NOTHING ) {
4821                                 /* the last branch of the sequence was part of
4822                                  * a trie, so we have to construct it here
4823                                  * outside of the loop */
4824                                 made= make_trie( pRExC_state, startbranch,
4825                                                  first, scan, tail, count,
4826                                                  trietype, depth+1 );
4827 #ifdef TRIE_STUDY_OPT
4828                                 if ( ((made == MADE_EXACT_TRIE &&
4829                                      startbranch == first)
4830                                      || ( first_non_open == first )) &&
4831                                      depth==0 ) {
4832                                     flags |= SCF_TRIE_RESTUDY;
4833                                     if ( startbranch == first
4834                                          && scan >= tail )
4835                                     {
4836                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
4837                                     }
4838                                 }
4839 #endif
4840                             } else {
4841                                 /* at this point we know whatever we have is a
4842                                  * NOTHING sequence/branch AND if 'startbranch'
4843                                  * is 'first' then we can turn the whole thing
4844                                  * into a NOTHING
4845                                  */
4846                                 if ( startbranch == first ) {
4847                                     regnode *opt;
4848                                     /* the entire thing is a NOTHING sequence,
4849                                      * something like this: (?:|) So we can
4850                                      * turn it into a plain NOTHING op. */
4851                                     DEBUG_TRIE_COMPILE_r({
4852                                         regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4853                                         Perl_re_indentf( aTHX_  "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
4854                                           depth+1,
4855                                           SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
4856
4857                                     });
4858                                     OP(startbranch)= NOTHING;
4859                                     NEXT_OFF(startbranch)= tail - startbranch;
4860                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
4861                                         OP(opt)= OPTIMIZED;
4862                                 }
4863                             }
4864                         } /* end if ( last) */
4865                     } /* TRIE_MAXBUF is non zero */
4866
4867                 } /* do trie */
4868
4869             }
4870             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
4871                 scan = NEXTOPER(NEXTOPER(scan));
4872             } else                      /* single branch is optimized. */
4873                 scan = NEXTOPER(scan);
4874             continue;
4875         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
4876             I32 paren = 0;
4877             regnode *start = NULL;
4878             regnode *end = NULL;
4879             U32 my_recursed_depth= recursed_depth;
4880
4881             if (OP(scan) != SUSPEND) { /* GOSUB */
4882                 /* Do setup, note this code has side effects beyond
4883                  * the rest of this block. Specifically setting
4884                  * RExC_recurse[] must happen at least once during
4885                  * study_chunk(). */
4886                 paren = ARG(scan);
4887                 RExC_recurse[ARG2L(scan)] = scan;
4888                 start = REGNODE_p(RExC_open_parens[paren]);
4889                 end   = REGNODE_p(RExC_close_parens[paren]);
4890
4891                 /* NOTE we MUST always execute the above code, even
4892                  * if we do nothing with a GOSUB */
4893                 if (
4894                     ( flags & SCF_IN_DEFINE )
4895                     ||
4896                     (
4897                         (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
4898                         &&
4899                         ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
4900                     )
4901                 ) {
4902                     /* no need to do anything here if we are in a define. */
4903                     /* or we are after some kind of infinite construct
4904                      * so we can skip recursing into this item.
4905                      * Since it is infinite we will not change the maxlen
4906                      * or delta, and if we miss something that might raise
4907                      * the minlen it will merely pessimise a little.
4908                      *
4909                      * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
4910                      * might result in a minlen of 1 and not of 4,
4911                      * but this doesn't make us mismatch, just try a bit
4912                      * harder than we should.
4913                      * */
4914                     scan= regnext(scan);
4915                     continue;
4916                 }
4917
4918                 if (
4919                     !recursed_depth
4920                     ||
4921                     !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
4922                 ) {
4923                     /* it is quite possible that there are more efficient ways
4924                      * to do this. We maintain a bitmap per level of recursion
4925                      * of which patterns we have entered so we can detect if a
4926                      * pattern creates a possible infinite loop. When we
4927                      * recurse down a level we copy the previous levels bitmap
4928                      * down. When we are at recursion level 0 we zero the top
4929                      * level bitmap. It would be nice to implement a different
4930                      * more efficient way of doing this. In particular the top
4931                      * level bitmap may be unnecessary.
4932                      */
4933                     if (!recursed_depth) {
4934                         Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
4935                     } else {
4936                         Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
4937                              RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
4938                              RExC_study_chunk_recursed_bytes, U8);
4939                     }
4940                     /* we havent recursed into this paren yet, so recurse into it */
4941                     DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
4942                     PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
4943                     my_recursed_depth= recursed_depth + 1;
4944                 } else {
4945                     DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
4946                     /* some form of infinite recursion, assume infinite length
4947                      * */
4948                     if (flags & SCF_DO_SUBSTR) {
4949                         scan_commit(pRExC_state, data, minlenp, is_inf);
4950                         data->cur_is_floating = 1;
4951                     }
4952                     is_inf = is_inf_internal = 1;
4953                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4954                         ssc_anything(data->start_class);
4955                     flags &= ~SCF_DO_STCLASS;
4956
4957                     start= NULL; /* reset start so we dont recurse later on. */
4958                 }
4959             } else {
4960                 paren = stopparen;
4961                 start = scan + 2;
4962                 end = regnext(scan);
4963             }
4964             if (start) {
4965                 scan_frame *newframe;
4966                 assert(end);
4967                 if (!RExC_frame_last) {
4968                     Newxz(newframe, 1, scan_frame);
4969                     SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
4970                     RExC_frame_head= newframe;
4971                     RExC_frame_count++;
4972                 } else if (!RExC_frame_last->next_frame) {
4973                     Newxz(newframe, 1, scan_frame);
4974                     RExC_frame_last->next_frame= newframe;
4975                     newframe->prev_frame= RExC_frame_last;
4976                     RExC_frame_count++;
4977                 } else {
4978                     newframe= RExC_frame_last->next_frame;
4979                 }
4980                 RExC_frame_last= newframe;
4981
4982                 newframe->next_regnode = regnext(scan);
4983                 newframe->last_regnode = last;
4984                 newframe->stopparen = stopparen;
4985                 newframe->prev_recursed_depth = recursed_depth;
4986                 newframe->this_prev_frame= frame;
4987
4988                 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
4989                 DEBUG_PEEP("fnew", scan, depth, flags);
4990
4991                 frame = newframe;
4992                 scan =  start;
4993                 stopparen = paren;
4994                 last = end;
4995                 depth = depth + 1;
4996                 recursed_depth= my_recursed_depth;
4997
4998                 continue;
4999             }
5000         }
5001         else if (OP(scan) == EXACT || OP(scan) == EXACTL) {
5002             SSize_t l = STR_LEN(scan);
5003             UV uc;
5004             assert(l);
5005             if (UTF) {
5006                 const U8 * const s = (U8*)STRING(scan);
5007                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
5008                 l = utf8_length(s, s + l);
5009             } else {
5010                 uc = *((U8*)STRING(scan));
5011             }
5012             min += l;
5013             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5014                 /* The code below prefers earlier match for fixed
5015                    offset, later match for variable offset.  */
5016                 if (data->last_end == -1) { /* Update the start info. */
5017                     data->last_start_min = data->pos_min;
5018                     data->last_start_max = is_inf
5019                         ? SSize_t_MAX : data->pos_min + data->pos_delta;
5020                 }
5021                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
5022                 if (UTF)
5023                     SvUTF8_on(data->last_found);
5024                 {
5025                     SV * const sv = data->last_found;
5026                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5027                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5028                     if (mg && mg->mg_len >= 0)
5029                         mg->mg_len += utf8_length((U8*)STRING(scan),
5030                                               (U8*)STRING(scan)+STR_LEN(scan));
5031                 }
5032                 data->last_end = data->pos_min + l;
5033                 data->pos_min += l; /* As in the first entry. */
5034                 data->flags &= ~SF_BEFORE_EOL;
5035             }
5036
5037             /* ANDing the code point leaves at most it, and not in locale, and
5038              * can't match null string */
5039             if (flags & SCF_DO_STCLASS_AND) {
5040                 ssc_cp_and(data->start_class, uc);
5041                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5042                 ssc_clear_locale(data->start_class);
5043             }
5044             else if (flags & SCF_DO_STCLASS_OR) {
5045                 ssc_add_cp(data->start_class, uc);
5046                 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5047
5048                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5049                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5050             }
5051             flags &= ~SCF_DO_STCLASS;
5052         }
5053         else if (PL_regkind[OP(scan)] == EXACT) {
5054             /* But OP != EXACT!, so is EXACTFish */
5055             SSize_t l = STR_LEN(scan);
5056             const U8 * s = (U8*)STRING(scan);
5057
5058             /* Search for fixed substrings supports EXACT only. */
5059             if (flags & SCF_DO_SUBSTR) {
5060                 assert(data);
5061                 scan_commit(pRExC_state, data, minlenp, is_inf);
5062             }
5063             if (UTF) {
5064                 l = utf8_length(s, s + l);
5065             }
5066             if (unfolded_multi_char) {
5067                 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5068             }
5069             min += l - min_subtract;
5070             assert (min >= 0);
5071             delta += min_subtract;
5072             if (flags & SCF_DO_SUBSTR) {
5073                 data->pos_min += l - min_subtract;
5074                 if (data->pos_min < 0) {
5075                     data->pos_min = 0;
5076                 }
5077                 data->pos_delta += min_subtract;
5078                 if (min_subtract) {
5079                     data->cur_is_floating = 1; /* float */
5080                 }
5081             }
5082
5083             if (flags & SCF_DO_STCLASS) {
5084                 SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);
5085
5086                 assert(EXACTF_invlist);
5087                 if (flags & SCF_DO_STCLASS_AND) {
5088                     if (OP(scan) != EXACTFL)
5089                         ssc_clear_locale(data->start_class);
5090                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5091                     ANYOF_POSIXL_ZERO(data->start_class);
5092                     ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5093                 }
5094                 else {  /* SCF_DO_STCLASS_OR */
5095                     ssc_union(data->start_class, EXACTF_invlist, FALSE);
5096                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5097
5098                     /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5099                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5100                 }
5101                 flags &= ~SCF_DO_STCLASS;
5102                 SvREFCNT_dec(EXACTF_invlist);
5103             }
5104         }
5105         else if (REGNODE_VARIES(OP(scan))) {
5106             SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5107             I32 fl = 0, f = flags;
5108             regnode * const oscan = scan;
5109             regnode_ssc this_class;
5110             regnode_ssc *oclass = NULL;
5111             I32 next_is_eval = 0;
5112
5113             switch (PL_regkind[OP(scan)]) {
5114             case WHILEM:                /* End of (?:...)* . */
5115                 scan = NEXTOPER(scan);
5116                 goto finish;
5117             case PLUS:
5118                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5119                     next = NEXTOPER(scan);
5120                     if (OP(next) == EXACT
5121                         || OP(next) == EXACTL
5122                         || (flags & SCF_DO_STCLASS))
5123                     {
5124                         mincount = 1;
5125                         maxcount = REG_INFTY;
5126                         next = regnext(scan);
5127                         scan = NEXTOPER(scan);
5128                         goto do_curly;
5129                     }
5130                 }
5131                 if (flags & SCF_DO_SUBSTR)
5132                     data->pos_min++;
5133                 min++;
5134                 /* FALLTHROUGH */
5135             case STAR:
5136                 if (flags & SCF_DO_STCLASS) {
5137                     mincount = 0;
5138                     maxcount = REG_INFTY;
5139                     next = regnext(scan);
5140                     scan = NEXTOPER(scan);
5141                     goto do_curly;
5142                 }
5143                 if (flags & SCF_DO_SUBSTR) {
5144                     scan_commit(pRExC_state, data, minlenp, is_inf);
5145                     /* Cannot extend fixed substrings */
5146                     data->cur_is_floating = 1; /* float */
5147                 }
5148                 is_inf = is_inf_internal = 1;
5149                 scan = regnext(scan);
5150                 goto optimize_curly_tail;
5151             case CURLY:
5152                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5153                     && (scan->flags == stopparen))
5154                 {
5155                     mincount = 1;
5156                     maxcount = 1;
5157                 } else {
5158                     mincount = ARG1(scan);
5159                     maxcount = ARG2(scan);
5160                 }
5161                 next = regnext(scan);
5162                 if (OP(scan) == CURLYX) {
5163                     I32 lp = (data ? *(data->last_closep) : 0);
5164                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5165                 }
5166                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5167                 next_is_eval = (OP(scan) == EVAL);
5168               do_curly:
5169                 if (flags & SCF_DO_SUBSTR) {
5170                     if (mincount == 0)
5171                         scan_commit(pRExC_state, data, minlenp, is_inf);
5172                     /* Cannot extend fixed substrings */
5173                     pos_before = data->pos_min;
5174                 }
5175                 if (data) {
5176                     fl = data->flags;
5177                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5178                     if (is_inf)
5179                         data->flags |= SF_IS_INF;
5180                 }
5181                 if (flags & SCF_DO_STCLASS) {
5182                     ssc_init(pRExC_state, &this_class);
5183                     oclass = data->start_class;
5184                     data->start_class = &this_class;
5185                     f |= SCF_DO_STCLASS_AND;
5186                     f &= ~SCF_DO_STCLASS_OR;
5187                 }
5188                 /* Exclude from super-linear cache processing any {n,m}
5189                    regops for which the combination of input pos and regex
5190                    pos is not enough information to determine if a match
5191                    will be possible.
5192
5193                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
5194                    regex pos at the \s*, the prospects for a match depend not
5195                    only on the input position but also on how many (bar\s*)
5196                    repeats into the {4,8} we are. */
5197                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5198                     f &= ~SCF_WHILEM_VISITED_POS;
5199
5200                 /* This will finish on WHILEM, setting scan, or on NULL: */
5201                 /* recurse study_chunk() on loop bodies */
5202                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5203                                   last, data, stopparen, recursed_depth, NULL,
5204                                   (mincount == 0
5205                                    ? (f & ~SCF_DO_SUBSTR)
5206                                    : f)
5207                                   ,depth+1);
5208
5209                 if (flags & SCF_DO_STCLASS)
5210                     data->start_class = oclass;
5211                 if (mincount == 0 || minnext == 0) {
5212                     if (flags & SCF_DO_STCLASS_OR) {
5213                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5214                     }
5215                     else if (flags & SCF_DO_STCLASS_AND) {
5216                         /* Switch to OR mode: cache the old value of
5217                          * data->start_class */
5218                         INIT_AND_WITHP;
5219                         StructCopy(data->start_class, and_withp, regnode_ssc);
5220                         flags &= ~SCF_DO_STCLASS_AND;
5221                         StructCopy(&this_class, data->start_class, regnode_ssc);
5222                         flags |= SCF_DO_STCLASS_OR;
5223                         ANYOF_FLAGS(data->start_class)
5224                                                 |= SSC_MATCHES_EMPTY_STRING;
5225                     }
5226                 } else {                /* Non-zero len */
5227                     if (flags & SCF_DO_STCLASS_OR) {
5228                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5229                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5230                     }
5231                     else if (flags & SCF_DO_STCLASS_AND)
5232                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5233                     flags &= ~SCF_DO_STCLASS;
5234                 }
5235                 if (!scan)              /* It was not CURLYX, but CURLY. */
5236                     scan = next;
5237                 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5238                     /* ? quantifier ok, except for (?{ ... }) */
5239                     && (next_is_eval || !(mincount == 0 && maxcount == 1))
5240                     && (minnext == 0) && (deltanext == 0)
5241                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5242                     && maxcount <= REG_INFTY/3) /* Complement check for big
5243                                                    count */
5244                 {
5245                     _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5246                         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5247                             "Quantifier unexpected on zero-length expression "
5248                             "in regex m/%" UTF8f "/",
5249                              UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5250                                   RExC_precomp)));
5251                 }
5252
5253                 min += minnext * mincount;
5254                 is_inf_internal |= deltanext == SSize_t_MAX
5255                          || (maxcount == REG_INFTY && minnext + deltanext > 0);
5256                 is_inf |= is_inf_internal;
5257                 if (is_inf) {
5258                     delta = SSize_t_MAX;
5259                 } else {
5260                     delta += (minnext + deltanext) * maxcount
5261                              - minnext * mincount;
5262                 }
5263                 /* Try powerful optimization CURLYX => CURLYN. */
5264                 if (  OP(oscan) == CURLYX && data
5265                       && data->flags & SF_IN_PAR
5266                       && !(data->flags & SF_HAS_EVAL)
5267                       && !deltanext && minnext == 1 ) {
5268                     /* Try to optimize to CURLYN.  */
5269                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5270                     regnode * const nxt1 = nxt;
5271 #ifdef DEBUGGING
5272                     regnode *nxt2;
5273 #endif
5274
5275                     /* Skip open. */
5276                     nxt = regnext(nxt);
5277                     if (!REGNODE_SIMPLE(OP(nxt))
5278                         && !(PL_regkind[OP(nxt)] == EXACT
5279                              && STR_LEN(nxt) == 1))
5280                         goto nogo;
5281 #ifdef DEBUGGING
5282                     nxt2 = nxt;
5283 #endif
5284                     nxt = regnext(nxt);
5285                     if (OP(nxt) != CLOSE)
5286                         goto nogo;
5287                     if (RExC_open_parens) {
5288
5289                         /*open->CURLYM*/
5290                         RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5291
5292                         /*close->while*/
5293                         RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5294                     }
5295                     /* Now we know that nxt2 is the only contents: */
5296                     oscan->flags = (U8)ARG(nxt);
5297                     OP(oscan) = CURLYN;
5298                     OP(nxt1) = NOTHING; /* was OPEN. */
5299
5300 #ifdef DEBUGGING
5301                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5302                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5303                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5304                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
5305                     OP(nxt + 1) = OPTIMIZED; /* was count. */
5306                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5307 #endif
5308                 }
5309               nogo:
5310
5311                 /* Try optimization CURLYX => CURLYM. */
5312                 if (  OP(oscan) == CURLYX && data
5313                       && !(data->flags & SF_HAS_PAR)
5314                       && !(data->flags & SF_HAS_EVAL)
5315                       && !deltanext     /* atom is fixed width */
5316                       && minnext != 0   /* CURLYM can't handle zero width */
5317
5318                          /* Nor characters whose fold at run-time may be
5319                           * multi-character */
5320                       && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5321                 ) {
5322                     /* XXXX How to optimize if data == 0? */
5323                     /* Optimize to a simpler form.  */
5324                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5325                     regnode *nxt2;
5326
5327                     OP(oscan) = CURLYM;
5328                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5329                             && (OP(nxt2) != WHILEM))
5330                         nxt = nxt2;
5331                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
5332                     /* Need to optimize away parenths. */
5333                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5334                         /* Set the parenth number.  */
5335                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5336
5337                         oscan->flags = (U8)ARG(nxt);
5338                         if (RExC_open_parens) {
5339                              /*open->CURLYM*/
5340                             RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5341
5342                             /*close->NOTHING*/
5343                             RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5344                                                          + 1;
5345                         }
5346                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
5347                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
5348
5349 #ifdef DEBUGGING
5350                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5351                         OP(nxt + 1) = OPTIMIZED; /* was count. */
5352                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5353                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5354 #endif
5355 #if 0
5356                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
5357                             regnode *nnxt = regnext(nxt1);
5358                             if (nnxt == nxt) {
5359                                 if (reg_off_by_arg[OP(nxt1)])
5360                                     ARG_SET(nxt1, nxt2 - nxt1);
5361                                 else if (nxt2 - nxt1 < U16_MAX)
5362                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
5363                                 else
5364                                     OP(nxt) = NOTHING;  /* Cannot beautify */
5365                             }
5366                             nxt1 = nnxt;
5367                         }
5368 #endif
5369                         /* Optimize again: */
5370                         /* recurse study_chunk() on optimised CURLYX => CURLYM */
5371                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5372                                     NULL, stopparen, recursed_depth, NULL, 0,
5373                                     depth+1);
5374                     }
5375                     else
5376                         oscan->flags = 0;
5377                 }
5378                 else if ((OP(oscan) == CURLYX)
5379                          && (flags & SCF_WHILEM_VISITED_POS)
5380                          /* See the comment on a similar expression above.
5381                             However, this time it's not a subexpression
5382                             we care about, but the expression itself. */
5383                          && (maxcount == REG_INFTY)
5384                          && data) {
5385                     /* This stays as CURLYX, we can put the count/of pair. */
5386                     /* Find WHILEM (as in regexec.c) */
5387                     regnode *nxt = oscan + NEXT_OFF(oscan);
5388
5389                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5390                         nxt += ARG(nxt);
5391                     nxt = PREVOPER(nxt);
5392                     if (nxt->flags & 0xf) {
5393                         /* we've already set whilem count on this node */
5394                     } else if (++data->whilem_c < 16) {
5395                         assert(data->whilem_c <= RExC_whilem_seen);
5396                         nxt->flags = (U8)(data->whilem_c
5397                             | (RExC_whilem_seen << 4)); /* On WHILEM */
5398                     }
5399                 }
5400                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5401                     pars++;
5402                 if (flags & SCF_DO_SUBSTR) {
5403                     SV *last_str = NULL;
5404                     STRLEN last_chrs = 0;
5405                     int counted = mincount != 0;
5406
5407                     if (data->last_end > 0 && mincount != 0) { /* Ends with a
5408                                                                   string. */
5409                         SSize_t b = pos_before >= data->last_start_min
5410                             ? pos_before : data->last_start_min;
5411                         STRLEN l;
5412                         const char * const s = SvPV_const(data->last_found, l);
5413                         SSize_t old = b - data->last_start_min;
5414
5415                         if (UTF)
5416                             old = utf8_hop((U8*)s, old) - (U8*)s;
5417                         l -= old;
5418                         /* Get the added string: */
5419                         last_str = newSVpvn_utf8(s  + old, l, UTF);
5420                         last_chrs = UTF ? utf8_length((U8*)(s + old),
5421                                             (U8*)(s + old + l)) : l;
5422                         if (deltanext == 0 && pos_before == b) {
5423                             /* What was added is a constant string */
5424                             if (mincount > 1) {
5425
5426                                 SvGROW(last_str, (mincount * l) + 1);
5427                                 repeatcpy(SvPVX(last_str) + l,
5428                                           SvPVX_const(last_str), l,
5429                                           mincount - 1);
5430                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5431                                 /* Add additional parts. */
5432                                 SvCUR_set(data->last_found,
5433                                           SvCUR(data->last_found) - l);
5434                                 sv_catsv(data->last_found, last_str);
5435                                 {
5436                                     SV * sv = data->last_found;
5437                                     MAGIC *mg =
5438                                         SvUTF8(sv) && SvMAGICAL(sv) ?
5439                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5440                                     if (mg && mg->mg_len >= 0)
5441                                         mg->mg_len += last_chrs * (mincount-1);
5442                                 }
5443                                 last_chrs *= mincount;
5444                                 data->last_end += l * (mincount - 1);
5445                             }
5446                         } else {
5447                             /* start offset must point into the last copy */
5448                             data->last_start_min += minnext * (mincount - 1);
5449                             data->last_start_max =
5450                               is_inf
5451                                ? SSize_t_MAX
5452                                : data->last_start_max +
5453                                  (maxcount - 1) * (minnext + data->pos_delta);
5454                         }
5455                     }
5456                     /* It is counted once already... */
5457                     data->pos_min += minnext * (mincount - counted);
5458 #if 0
5459 Perl_re_printf( aTHX_  "counted=%" UVuf " deltanext=%" UVuf
5460                               " SSize_t_MAX=%" UVuf " minnext=%" UVuf
5461                               " maxcount=%" UVuf " mincount=%" UVuf "\n",
5462     (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
5463     (UV)mincount);
5464 if (deltanext != SSize_t_MAX)
5465 Perl_re_printf( aTHX_  "LHS=%" UVuf " RHS=%" UVuf "\n",
5466     (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5467           - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
5468 #endif
5469                     if (deltanext == SSize_t_MAX
5470                         || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
5471                         data->pos_delta = SSize_t_MAX;
5472                     else
5473                         data->pos_delta += - counted * deltanext +
5474                         (minnext + deltanext) * maxcount - minnext * mincount;
5475                     if (mincount != maxcount) {
5476                          /* Cannot extend fixed substrings found inside
5477                             the group.  */
5478                         scan_commit(pRExC_state, data, minlenp, is_inf);
5479                         if (mincount && last_str) {
5480                             SV * const sv = data->last_found;
5481                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5482                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5483
5484                             if (mg)
5485                                 mg->mg_len = -1;
5486                             sv_setsv(sv, last_str);
5487                             data->last_end = data->pos_min;
5488                             data->last_start_min = data->pos_min - last_chrs;
5489                             data->last_start_max = is_inf
5490                                 ? SSize_t_MAX
5491                                 : data->pos_min + data->pos_delta - last_chrs;
5492                         }
5493                         data->cur_is_floating = 1; /* float */
5494                     }
5495                     SvREFCNT_dec(last_str);
5496                 }
5497                 if (data && (fl & SF_HAS_EVAL))
5498                     data->flags |= SF_HAS_EVAL;
5499               optimize_curly_tail:
5500                 if (OP(oscan) != CURLYX) {
5501                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5502                            && NEXT_OFF(next))
5503                         NEXT_OFF(oscan) += NEXT_OFF(next);
5504                 }
5505                 continue;
5506
5507             default:
5508 #ifdef DEBUGGING
5509                 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5510                                                                     OP(scan));
5511 #endif
5512             case REF:
5513             case CLUMP:
5514                 if (flags & SCF_DO_SUBSTR) {
5515                     /* Cannot expect anything... */
5516                     scan_commit(pRExC_state, data, minlenp, is_inf);
5517                     data->cur_is_floating = 1; /* float */
5518                 }
5519                 is_inf = is_inf_internal = 1;
5520                 if (flags & SCF_DO_STCLASS_OR) {
5521                     if (OP(scan) == CLUMP) {
5522                         /* Actually is any start char, but very few code points
5523                          * aren't start characters */
5524                         ssc_match_all_cp(data->start_class);
5525                     }
5526                     else {
5527                         ssc_anything(data->start_class);
5528                     }
5529                 }
5530                 flags &= ~SCF_DO_STCLASS;
5531                 break;
5532             }
5533         }
5534         else if (OP(scan) == LNBREAK) {
5535             if (flags & SCF_DO_STCLASS) {
5536                 if (flags & SCF_DO_STCLASS_AND) {
5537                     ssc_intersection(data->start_class,
5538                                     PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5539                     ssc_clear_locale(data->start_class);
5540                     ANYOF_FLAGS(data->start_class)
5541                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5542                 }
5543                 else if (flags & SCF_DO_STCLASS_OR) {
5544                     ssc_union(data->start_class,
5545                               PL_XPosix_ptrs[_CC_VERTSPACE],
5546                               FALSE);
5547                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5548
5549                     /* See commit msg for
5550                      * 749e076fceedeb708a624933726e7989f2302f6a */
5551                     ANYOF_FLAGS(data->start_class)
5552                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5553                 }
5554                 flags &= ~SCF_DO_STCLASS;
5555             }
5556             min++;
5557             if (delta != SSize_t_MAX)
5558                 delta++;    /* Because of the 2 char string cr-lf */
5559             if (flags & SCF_DO_SUBSTR) {
5560                 /* Cannot expect anything... */
5561                 scan_commit(pRExC_state, data, minlenp, is_inf);
5562                 data->pos_min += 1;
5563                 if (data->pos_delta != SSize_t_MAX) {
5564                     data->pos_delta += 1;
5565                 }
5566                 data->cur_is_floating = 1; /* float */
5567             }
5568         }
5569         else if (REGNODE_SIMPLE(OP(scan))) {
5570
5571             if (flags & SCF_DO_SUBSTR) {
5572                 scan_commit(pRExC_state, data, minlenp, is_inf);
5573                 data->pos_min++;
5574             }
5575             min++;
5576             if (flags & SCF_DO_STCLASS) {
5577                 bool invert = 0;
5578                 SV* my_invlist = NULL;
5579                 U8 namedclass;
5580
5581                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5582                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5583
5584                 /* Some of the logic below assumes that switching
5585                    locale on will only add false positives. */
5586                 switch (OP(scan)) {
5587
5588                 default:
5589 #ifdef DEBUGGING
5590                    Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5591                                                                      OP(scan));
5592 #endif
5593                 case SANY:
5594                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5595                         ssc_match_all_cp(data->start_class);
5596                     break;
5597
5598                 case REG_ANY:
5599                     {
5600                         SV* REG_ANY_invlist = _new_invlist(2);
5601                         REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5602                                                             '\n');
5603                         if (flags & SCF_DO_STCLASS_OR) {
5604                             ssc_union(data->start_class,
5605                                       REG_ANY_invlist,
5606                                       TRUE /* TRUE => invert, hence all but \n
5607                                             */
5608                                       );
5609                         }
5610                         else if (flags & SCF_DO_STCLASS_AND) {
5611                             ssc_intersection(data->start_class,
5612                                              REG_ANY_invlist,
5613                                              TRUE  /* TRUE => invert */
5614                                              );
5615                             ssc_clear_locale(data->start_class);
5616                         }
5617                         SvREFCNT_dec_NN(REG_ANY_invlist);
5618                     }
5619                     break;
5620
5621                 case ANYOFD:
5622                 case ANYOFL:
5623                 case ANYOFPOSIXL:
5624                 case ANYOF:
5625                     if (flags & SCF_DO_STCLASS_AND)
5626                         ssc_and(pRExC_state, data->start_class,
5627                                 (regnode_charclass *) scan);
5628                     else
5629                         ssc_or(pRExC_state, data->start_class,
5630                                                           (regnode_charclass *) scan);
5631                     break;
5632
5633                 case NANYOFM:
5634                 case ANYOFM:
5635                   {
5636                     SV* cp_list = get_ANYOFM_contents(scan);
5637
5638                     if (flags & SCF_DO_STCLASS_OR) {
5639                         ssc_union(data->start_class, cp_list, invert);
5640                     }
5641                     else if (flags & SCF_DO_STCLASS_AND) {
5642                         ssc_intersection(data->start_class, cp_list, invert);
5643                     }
5644
5645                     SvREFCNT_dec_NN(cp_list);
5646                     break;
5647                   }
5648
5649                 case NPOSIXL:
5650                     invert = 1;
5651                     /* FALLTHROUGH */
5652
5653                 case POSIXL:
5654                     namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5655                     if (flags & SCF_DO_STCLASS_AND) {
5656                         bool was_there = cBOOL(
5657                                           ANYOF_POSIXL_TEST(data->start_class,
5658                                                                  namedclass));
5659                         ANYOF_POSIXL_ZERO(data->start_class);
5660                         if (was_there) {    /* Do an AND */
5661                             ANYOF_POSIXL_SET(data->start_class, namedclass);
5662                         }
5663                         /* No individual code points can now match */
5664                         data->start_class->invlist
5665                                                 = sv_2mortal(_new_invlist(0));
5666                     }
5667                     else {
5668                         int complement = namedclass + ((invert) ? -1 : 1);
5669
5670                         assert(flags & SCF_DO_STCLASS_OR);
5671
5672                         /* If the complement of this class was already there,
5673                          * the result is that they match all code points,
5674                          * (\d + \D == everything).  Remove the classes from
5675                          * future consideration.  Locale is not relevant in
5676                          * this case */
5677                         if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5678                             ssc_match_all_cp(data->start_class);
5679                             ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5680                             ANYOF_POSIXL_CLEAR(data->start_class, complement);
5681                         }
5682                         else {  /* The usual case; just add this class to the
5683                                    existing set */
5684                             ANYOF_POSIXL_SET(data->start_class, namedclass);
5685                         }
5686                     }
5687                     break;
5688
5689                 case NASCII:
5690                     invert = 1;
5691                     /* FALLTHROUGH */
5692                 case ASCII:
5693                     my_invlist = invlist_clone(PL_Posix_ptrs[_CC_ASCII], NULL);
5694
5695                     /* This can be handled as a Posix class */
5696                     goto join_posix_and_ascii;
5697
5698                 case NPOSIXA:   /* For these, we always know the exact set of
5699                                    what's matched */
5700                     invert = 1;
5701                     /* FALLTHROUGH */
5702                 case POSIXA:
5703                     assert(FLAGS(scan) != _CC_ASCII);
5704                     my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
5705                     goto join_posix_and_ascii;
5706
5707                 case NPOSIXD:
5708                 case NPOSIXU:
5709                     invert = 1;
5710                     /* FALLTHROUGH */
5711                 case POSIXD:
5712                 case POSIXU:
5713                     my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
5714
5715                     /* NPOSIXD matches all upper Latin1 code points unless the
5716                      * target string being matched is UTF-8, which is
5717                      * unknowable until match time.  Since we are going to
5718                      * invert, we want to get rid of all of them so that the
5719                      * inversion will match all */
5720                     if (OP(scan) == NPOSIXD) {
5721                         _invlist_subtract(my_invlist, PL_UpperLatin1,
5722                                           &my_invlist);
5723                     }
5724
5725                   join_posix_and_ascii:
5726
5727                     if (flags & SCF_DO_STCLASS_AND) {
5728                         ssc_intersection(data->start_class, my_invlist, invert);
5729                         ssc_clear_locale(data->start_class);
5730                     }
5731                     else {
5732                         assert(flags & SCF_DO_STCLASS_OR);
5733                         ssc_union(data->start_class, my_invlist, invert);
5734                     }
5735                     SvREFCNT_dec(my_invlist);
5736                 }
5737                 if (flags & SCF_DO_STCLASS_OR)
5738                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5739                 flags &= ~SCF_DO_STCLASS;
5740             }
5741         }
5742         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
5743             data->flags |= (OP(scan) == MEOL
5744                             ? SF_BEFORE_MEOL
5745                             : SF_BEFORE_SEOL);
5746             scan_commit(pRExC_state, data, minlenp, is_inf);
5747
5748         }
5749         else if (  PL_regkind[OP(scan)] == BRANCHJ
5750                  /* Lookbehind, or need to calculate parens/evals/stclass: */
5751                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
5752                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
5753         {
5754             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5755                 || OP(scan) == UNLESSM )
5756             {
5757                 /* Negative Lookahead/lookbehind
5758                    In this case we can't do fixed string optimisation.
5759                 */
5760
5761                 SSize_t deltanext, minnext, fake = 0;
5762                 regnode *nscan;
5763                 regnode_ssc intrnl;
5764                 int f = 0;
5765
5766                 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
5767                 if (data) {
5768                     data_fake.whilem_c = data->whilem_c;
5769                     data_fake.last_closep = data->last_closep;
5770                 }
5771                 else
5772                     data_fake.last_closep = &fake;
5773                 data_fake.pos_delta = delta;
5774                 if ( flags & SCF_DO_STCLASS && !scan->flags
5775                      && OP(scan) == IFMATCH ) { /* Lookahead */
5776                     ssc_init(pRExC_state, &intrnl);
5777                     data_fake.start_class = &intrnl;
5778                     f |= SCF_DO_STCLASS_AND;
5779                 }
5780                 if (flags & SCF_WHILEM_VISITED_POS)
5781                     f |= SCF_WHILEM_VISITED_POS;
5782                 next = regnext(scan);
5783                 nscan = NEXTOPER(NEXTOPER(scan));
5784
5785                 /* recurse study_chunk() for lookahead body */
5786                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
5787                                       last, &data_fake, stopparen,
5788                                       recursed_depth, NULL, f, depth+1);
5789                 if (scan->flags) {
5790                     if (deltanext) {
5791                         FAIL("Variable length lookbehind not implemented");
5792                     }
5793                     else if (minnext > (I32)U8_MAX) {
5794                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
5795                               (UV)U8_MAX);
5796                     }
5797                     scan->flags = (U8)minnext;
5798                 }
5799                 if (data) {
5800                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5801                         pars++;
5802                     if (data_fake.flags & SF_HAS_EVAL)
5803                         data->flags |= SF_HAS_EVAL;
5804                     data->whilem_c = data_fake.whilem_c;
5805                 }
5806                 if (f & SCF_DO_STCLASS_AND) {
5807                     if (flags & SCF_DO_STCLASS_OR) {
5808                         /* OR before, AND after: ideally we would recurse with
5809                          * data_fake to get the AND applied by study of the
5810                          * remainder of the pattern, and then derecurse;
5811                          * *** HACK *** for now just treat as "no information".
5812                          * See [perl #56690].
5813                          */
5814                         ssc_init(pRExC_state, data->start_class);
5815                     }  else {
5816                         /* AND before and after: combine and continue.  These
5817                          * assertions are zero-length, so can match an EMPTY
5818                          * string */
5819                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
5820                         ANYOF_FLAGS(data->start_class)
5821                                                    |= SSC_MATCHES_EMPTY_STRING;
5822                     }
5823                 }
5824             }
5825 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5826             else {
5827                 /* Positive Lookahead/lookbehind
5828                    In this case we can do fixed string optimisation,
5829                    but we must be careful about it. Note in the case of
5830                    lookbehind the positions will be offset by the minimum
5831                    length of the pattern, something we won't know about
5832                    until after the recurse.
5833                 */
5834                 SSize_t deltanext, fake = 0;
5835                 regnode *nscan;
5836                 regnode_ssc intrnl;
5837                 int f = 0;
5838                 /* We use SAVEFREEPV so that when the full compile
5839                     is finished perl will clean up the allocated
5840                     minlens when it's all done. This way we don't
5841                     have to worry about freeing them when we know
5842                     they wont be used, which would be a pain.
5843                  */
5844                 SSize_t *minnextp;
5845                 Newx( minnextp, 1, SSize_t );
5846                 SAVEFREEPV(minnextp);
5847
5848                 if (data) {
5849                     StructCopy(data, &data_fake, scan_data_t);
5850                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
5851                         f |= SCF_DO_SUBSTR;
5852                         if (scan->flags)
5853                             scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
5854                         data_fake.last_found=newSVsv(data->last_found);
5855                     }
5856                 }
5857                 else
5858                     data_fake.last_closep = &fake;
5859                 data_fake.flags = 0;
5860                 data_fake.substrs[0].flags = 0;
5861                 data_fake.substrs[1].flags = 0;
5862                 data_fake.pos_delta = delta;
5863                 if (is_inf)
5864                     data_fake.flags |= SF_IS_INF;
5865                 if ( flags & SCF_DO_STCLASS && !scan->flags
5866                      && OP(scan) == IFMATCH ) { /* Lookahead */
5867                     ssc_init(pRExC_state, &intrnl);
5868                     data_fake.start_class = &intrnl;
5869                     f |= SCF_DO_STCLASS_AND;
5870                 }
5871                 if (flags & SCF_WHILEM_VISITED_POS)
5872                     f |= SCF_WHILEM_VISITED_POS;
5873                 next = regnext(scan);
5874                 nscan = NEXTOPER(NEXTOPER(scan));
5875
5876                 /* positive lookahead study_chunk() recursion */
5877                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
5878                                         &deltanext, last, &data_fake,
5879                                         stopparen, recursed_depth, NULL,
5880                                         f, depth+1);
5881                 if (scan->flags) {
5882                     if (deltanext) {
5883                         FAIL("Variable length lookbehind not implemented");
5884                     }
5885                     else if (*minnextp > (I32)U8_MAX) {
5886                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
5887                               (UV)U8_MAX);
5888                     }
5889                     scan->flags = (U8)*minnextp;
5890                 }
5891
5892                 *minnextp += min;
5893
5894                 if (f & SCF_DO_STCLASS_AND) {
5895                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
5896                     ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
5897                 }
5898                 if (data) {
5899                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5900                         pars++;
5901                     if (data_fake.flags & SF_HAS_EVAL)
5902                         data->flags |= SF_HAS_EVAL;
5903                     data->whilem_c = data_fake.whilem_c;
5904                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
5905                         int i;
5906                         if (RExC_rx->minlen<*minnextp)
5907                             RExC_rx->minlen=*minnextp;
5908                         scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
5909                         SvREFCNT_dec_NN(data_fake.last_found);
5910
5911                         for (i = 0; i < 2; i++) {
5912                             if (data_fake.substrs[i].minlenp != minlenp) {
5913                                 data->substrs[i].min_offset =
5914                                             data_fake.substrs[i].min_offset;
5915                                 data->substrs[i].max_offset =
5916                                             data_fake.substrs[i].max_offset;
5917                                 data->substrs[i].minlenp =
5918                                             data_fake.substrs[i].minlenp;
5919                                 data->substrs[i].lookbehind += scan->flags;
5920                             }
5921                         }
5922                     }
5923                 }
5924             }
5925 #endif
5926         }
5927
5928         else if (OP(scan) == OPEN) {
5929             if (stopparen != (I32)ARG(scan))
5930                 pars++;
5931         }
5932         else if (OP(scan) == CLOSE) {
5933             if (stopparen == (I32)ARG(scan)) {
5934                 break;
5935             }
5936             if ((I32)ARG(scan) == is_par) {
5937                 next = regnext(scan);
5938
5939                 if ( next && (OP(next) != WHILEM) && next < last)
5940                     is_par = 0;         /* Disable optimization */
5941             }
5942             if (data)
5943                 *(data->last_closep) = ARG(scan);
5944         }
5945         else if (OP(scan) == EVAL) {
5946                 if (data)
5947                     data->flags |= SF_HAS_EVAL;
5948         }
5949         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
5950             if (flags & SCF_DO_SUBSTR) {
5951                 scan_commit(pRExC_state, data, minlenp, is_inf);
5952                 flags &= ~SCF_DO_SUBSTR;
5953             }
5954             if (data && OP(scan)==ACCEPT) {
5955                 data->flags |= SCF_SEEN_ACCEPT;
5956                 if (stopmin > min)
5957                     stopmin = min;
5958             }
5959         }
5960         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
5961         {
5962                 if (flags & SCF_DO_SUBSTR) {
5963                     scan_commit(pRExC_state, data, minlenp, is_inf);
5964                     data->cur_is_floating = 1; /* float */
5965                 }
5966                 is_inf = is_inf_internal = 1;
5967                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5968                     ssc_anything(data->start_class);
5969                 flags &= ~SCF_DO_STCLASS;
5970         }
5971         else if (OP(scan) == GPOS) {
5972             if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
5973                 !(delta || is_inf || (data && data->pos_delta)))
5974             {
5975                 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
5976                     RExC_rx->intflags |= PREGf_ANCH_GPOS;
5977                 if (RExC_rx->gofs < (STRLEN)min)
5978                     RExC_rx->gofs = min;
5979             } else {
5980                 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
5981                 RExC_rx->gofs = 0;
5982             }
5983         }
5984 #ifdef TRIE_STUDY_OPT
5985 #ifdef FULL_TRIE_STUDY
5986         else if (PL_regkind[OP(scan)] == TRIE) {
5987             /* NOTE - There is similar code to this block above for handling
5988                BRANCH nodes on the initial study.  If you change stuff here
5989                check there too. */
5990             regnode *trie_node= scan;
5991             regnode *tail= regnext(scan);
5992             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
5993             SSize_t max1 = 0, min1 = SSize_t_MAX;
5994             regnode_ssc accum;
5995
5996             if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
5997                 /* Cannot merge strings after this. */
5998                 scan_commit(pRExC_state, data, minlenp, is_inf);
5999             }
6000             if (flags & SCF_DO_STCLASS)
6001                 ssc_init_zero(pRExC_state, &accum);
6002
6003             if (!trie->jump) {
6004                 min1= trie->minlen;
6005                 max1= trie->maxlen;
6006             } else {
6007                 const regnode *nextbranch= NULL;
6008                 U32 word;
6009
6010                 for ( word=1 ; word <= trie->wordcount ; word++)
6011                 {
6012                     SSize_t deltanext=0, minnext=0, f = 0, fake;
6013                     regnode_ssc this_class;
6014
6015                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6016                     if (data) {
6017                         data_fake.whilem_c = data->whilem_c;
6018                         data_fake.last_closep = data->last_closep;
6019                     }
6020                     else
6021                         data_fake.last_closep = &fake;
6022                     data_fake.pos_delta = delta;
6023                     if (flags & SCF_DO_STCLASS) {
6024                         ssc_init(pRExC_state, &this_class);
6025                         data_fake.start_class = &this_class;
6026                         f = SCF_DO_STCLASS_AND;
6027                     }
6028                     if (flags & SCF_WHILEM_VISITED_POS)
6029                         f |= SCF_WHILEM_VISITED_POS;
6030
6031                     if (trie->jump[word]) {
6032                         if (!nextbranch)
6033                             nextbranch = trie_node + trie->jump[0];
6034                         scan= trie_node + trie->jump[word];
6035                         /* We go from the jump point to the branch that follows
6036                            it. Note this means we need the vestigal unused
6037                            branches even though they arent otherwise used. */
6038                         /* optimise study_chunk() for TRIE */
6039                         minnext = study_chunk(pRExC_state, &scan, minlenp,
6040                             &deltanext, (regnode *)nextbranch, &data_fake,
6041                             stopparen, recursed_depth, NULL, f, depth+1);
6042                     }
6043                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6044                         nextbranch= regnext((regnode*)nextbranch);
6045
6046                     if (min1 > (SSize_t)(minnext + trie->minlen))
6047                         min1 = minnext + trie->minlen;
6048                     if (deltanext == SSize_t_MAX) {
6049                         is_inf = is_inf_internal = 1;
6050                         max1 = SSize_t_MAX;
6051                     } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6052                         max1 = minnext + deltanext + trie->maxlen;
6053
6054                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6055                         pars++;
6056                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
6057                         if ( stopmin > min + min1)
6058                             stopmin = min + min1;
6059                         flags &= ~SCF_DO_SUBSTR;
6060                         if (data)
6061                             data->flags |= SCF_SEEN_ACCEPT;
6062                     }
6063                     if (data) {
6064                         if (data_fake.flags & SF_HAS_EVAL)
6065                             data->flags |= SF_HAS_EVAL;
6066                         data->whilem_c = data_fake.whilem_c;
6067                     }
6068                     if (flags & SCF_DO_STCLASS)
6069                         ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6070                 }
6071             }
6072             if (flags & SCF_DO_SUBSTR) {
6073                 data->pos_min += min1;
6074                 data->pos_delta += max1 - min1;
6075                 if (max1 != min1 || is_inf)
6076                     data->cur_is_floating = 1; /* float */
6077             }
6078             min += min1;
6079             if (delta != SSize_t_MAX) {
6080                 if (SSize_t_MAX - (max1 - min1) >= delta)
6081                     delta += max1 - min1;
6082                 else
6083                     delta = SSize_t_MAX;
6084             }
6085             if (flags & SCF_DO_STCLASS_OR) {
6086                 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6087                 if (min1) {
6088                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6089                     flags &= ~SCF_DO_STCLASS;
6090                 }
6091             }
6092             else if (flags & SCF_DO_STCLASS_AND) {
6093                 if (min1) {
6094                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6095                     flags &= ~SCF_DO_STCLASS;
6096                 }
6097                 else {
6098                     /* Switch to OR mode: cache the old value of
6099                      * data->start_class */
6100                     INIT_AND_WITHP;
6101                     StructCopy(data->start_class, and_withp, regnode_ssc);
6102                     flags &= ~SCF_DO_STCLASS_AND;
6103                     StructCopy(&accum, data->start_class, regnode_ssc);
6104                     flags |= SCF_DO_STCLASS_OR;
6105                 }
6106             }
6107             scan= tail;
6108             continue;
6109         }
6110 #else
6111         else if (PL_regkind[OP(scan)] == TRIE) {
6112             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6113             U8*bang=NULL;
6114
6115             min += trie->minlen;
6116             delta += (trie->maxlen - trie->minlen);
6117             flags &= ~SCF_DO_STCLASS; /* xxx */
6118             if (flags & SCF_DO_SUBSTR) {
6119                 /* Cannot expect anything... */
6120                 scan_commit(pRExC_state, data, minlenp, is_inf);
6121                 data->pos_min += trie->minlen;
6122                 data->pos_delta += (trie->maxlen - trie->minlen);
6123                 if (trie->maxlen != trie->minlen)
6124                     data->cur_is_floating = 1; /* float */
6125             }
6126             if (trie->jump) /* no more substrings -- for now /grr*/
6127                flags &= ~SCF_DO_SUBSTR;
6128         }
6129 #endif /* old or new */
6130 #endif /* TRIE_STUDY_OPT */
6131
6132         /* Else: zero-length, ignore. */
6133         scan = regnext(scan);
6134     }
6135
6136   finish:
6137     if (frame) {
6138         /* we need to unwind recursion. */
6139         depth = depth - 1;
6140
6141         DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6142         DEBUG_PEEP("fend", scan, depth, flags);
6143
6144         /* restore previous context */
6145         last = frame->last_regnode;
6146         scan = frame->next_regnode;
6147         stopparen = frame->stopparen;
6148         recursed_depth = frame->prev_recursed_depth;
6149
6150         RExC_frame_last = frame->prev_frame;
6151         frame = frame->this_prev_frame;
6152         goto fake_study_recurse;
6153     }
6154
6155     assert(!frame);
6156     DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6157
6158     *scanp = scan;
6159     *deltap = is_inf_internal ? SSize_t_MAX : delta;
6160
6161     if (flags & SCF_DO_SUBSTR && is_inf)
6162         data->pos_delta = SSize_t_MAX - data->pos_min;
6163     if (is_par > (I32)U8_MAX)
6164         is_par = 0;
6165     if (is_par && pars==1 && data) {
6166         data->flags |= SF_IN_PAR;
6167         data->flags &= ~SF_HAS_PAR;
6168     }
6169     else if (pars && data) {
6170         data->flags |= SF_HAS_PAR;
6171         data->flags &= ~SF_IN_PAR;
6172     }
6173     if (flags & SCF_DO_STCLASS_OR)
6174         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6175     if (flags & SCF_TRIE_RESTUDY)
6176         data->flags |=  SCF_TRIE_RESTUDY;
6177
6178     DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6179
6180     {
6181         SSize_t final_minlen= min < stopmin ? min : stopmin;
6182
6183         if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6184             if (final_minlen > SSize_t_MAX - delta)
6185                 RExC_maxlen = SSize_t_MAX;
6186             else if (RExC_maxlen < final_minlen + delta)
6187                 RExC_maxlen = final_minlen + delta;
6188         }
6189         return final_minlen;
6190     }
6191     NOT_REACHED; /* NOTREACHED */
6192 }
6193
6194 STATIC U32
6195 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6196 {
6197     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6198
6199     PERL_ARGS_ASSERT_ADD_DATA;
6200
6201     Renewc(RExC_rxi->data,
6202            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6203            char, struct reg_data);
6204     if(count)
6205         Renew(RExC_rxi->data->what, count + n, U8);
6206     else
6207         Newx(RExC_rxi->data->what, n, U8);
6208     RExC_rxi->data->count = count + n;
6209     Copy(s, RExC_rxi->data->what + count, n, U8);
6210     return count;
6211 }
6212
6213 /*XXX: todo make this not included in a non debugging perl, but appears to be
6214  * used anyway there, in 'use re' */
6215 #ifndef PERL_IN_XSUB_RE
6216 void
6217 Perl_reginitcolors(pTHX)
6218 {
6219     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6220     if (s) {
6221         char *t = savepv(s);
6222         int i = 0;
6223         PL_colors[0] = t;
6224         while (++i < 6) {
6225             t = strchr(t, '\t');
6226             if (t) {
6227                 *t = '\0';
6228                 PL_colors[i] = ++t;
6229             }
6230             else
6231                 PL_colors[i] = t = (char *)"";
6232         }
6233     } else {
6234         int i = 0;
6235         while (i < 6)
6236             PL_colors[i++] = (char *)"";
6237     }
6238     PL_colorset = 1;
6239 }
6240 #endif
6241
6242
6243 #ifdef TRIE_STUDY_OPT
6244 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething)            \
6245     STMT_START {                                            \
6246         if (                                                \
6247               (data.flags & SCF_TRIE_RESTUDY)               \
6248               && ! restudied++                              \
6249         ) {                                                 \
6250             dOsomething;                                    \
6251             goto reStudy;                                   \
6252         }                                                   \
6253     } STMT_END
6254 #else
6255 #define CHECK_RESTUDY_GOTO_butfirst
6256 #endif
6257
6258 /*
6259  * pregcomp - compile a regular expression into internal code
6260  *
6261  * Decides which engine's compiler to call based on the hint currently in
6262  * scope
6263  */
6264
6265 #ifndef PERL_IN_XSUB_RE
6266
6267 /* return the currently in-scope regex engine (or the default if none)  */
6268
6269 regexp_engine const *
6270 Perl_current_re_engine(pTHX)
6271 {
6272     if (IN_PERL_COMPILETIME) {
6273         HV * const table = GvHV(PL_hintgv);
6274         SV **ptr;
6275
6276         if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6277             return &PL_core_reg_engine;
6278         ptr = hv_fetchs(table, "regcomp", FALSE);
6279         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6280             return &PL_core_reg_engine;
6281         return INT2PTR(regexp_engine*, SvIV(*ptr));
6282     }
6283     else {
6284         SV *ptr;
6285         if (!PL_curcop->cop_hints_hash)
6286             return &PL_core_reg_engine;
6287         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6288         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6289             return &PL_core_reg_engine;
6290         return INT2PTR(regexp_engine*, SvIV(ptr));
6291     }
6292 }
6293
6294
6295 REGEXP *
6296 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6297 {
6298     regexp_engine const *eng = current_re_engine();
6299     GET_RE_DEBUG_FLAGS_DECL;
6300
6301     PERL_ARGS_ASSERT_PREGCOMP;
6302
6303     /* Dispatch a request to compile a regexp to correct regexp engine. */
6304     DEBUG_COMPILE_r({
6305         Perl_re_printf( aTHX_  "Using engine %" UVxf "\n",
6306                         PTR2UV(eng));
6307     });
6308     return CALLREGCOMP_ENG(eng, pattern, flags);
6309 }
6310 #endif
6311
6312 /* public(ish) entry point for the perl core's own regex compiling code.
6313  * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6314  * pattern rather than a list of OPs, and uses the internal engine rather
6315  * than the current one */
6316
6317 REGEXP *
6318 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6319 {
6320     SV *pat = pattern; /* defeat constness! */
6321     PERL_ARGS_ASSERT_RE_COMPILE;
6322     return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6323 #ifdef PERL_IN_XSUB_RE
6324                                 &my_reg_engine,
6325 #else
6326                                 &PL_core_reg_engine,
6327 #endif
6328                                 NULL, NULL, rx_flags, 0);
6329 }
6330
6331
6332 static void
6333 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6334 {
6335     int n;
6336
6337     if (--cbs->refcnt > 0)
6338         return;
6339     for (n = 0; n < cbs->count; n++) {
6340         REGEXP *rx = cbs->cb[n].src_regex;
6341         if (rx) {
6342             cbs->cb[n].src_regex = NULL;
6343             SvREFCNT_dec_NN(rx);
6344         }
6345     }
6346     Safefree(cbs->cb);
6347     Safefree(cbs);
6348 }
6349
6350
6351 static struct reg_code_blocks *
6352 S_alloc_code_blocks(pTHX_  int ncode)
6353 {
6354      struct reg_code_blocks *cbs;
6355     Newx(cbs, 1, struct reg_code_blocks);
6356     cbs->count = ncode;
6357     cbs->refcnt = 1;
6358     SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6359     if (ncode)
6360         Newx(cbs->cb, ncode, struct reg_code_block);
6361     else
6362         cbs->cb = NULL;
6363     return cbs;
6364 }
6365
6366
6367 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6368  * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6369  * point to the realloced string and length.
6370  *
6371  * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6372  * stuff added */
6373
6374 static void
6375 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6376                     char **pat_p, STRLEN *plen_p, int num_code_blocks)
6377 {
6378     U8 *const src = (U8*)*pat_p;
6379     U8 *dst, *d;
6380     int n=0;
6381     STRLEN s = 0;
6382     bool do_end = 0;
6383     GET_RE_DEBUG_FLAGS_DECL;
6384
6385     DEBUG_PARSE_r(Perl_re_printf( aTHX_
6386         "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6387
6388     /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6389     Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6390     d = dst;
6391
6392     while (s < *plen_p) {
6393         append_utf8_from_native_byte(src[s], &d);
6394
6395         if (n < num_code_blocks) {
6396             assert(pRExC_state->code_blocks);
6397             if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6398                 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6399                 assert(*(d - 1) == '(');
6400                 do_end = 1;
6401             }
6402             else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6403                 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6404                 assert(*(d - 1) == ')');
6405                 do_end = 0;
6406                 n++;
6407             }
6408         }
6409         s++;
6410     }
6411     *d = '\0';
6412     *plen_p = d - dst;
6413     *pat_p = (char*) dst;
6414     SAVEFREEPV(*pat_p);
6415     RExC_orig_utf8 = RExC_utf8 = 1;
6416 }
6417
6418
6419
6420 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6421  * while recording any code block indices, and handling overloading,
6422  * nested qr// objects etc.  If pat is null, it will allocate a new
6423  * string, or just return the first arg, if there's only one.
6424  *
6425  * Returns the malloced/updated pat.
6426  * patternp and pat_count is the array of SVs to be concatted;
6427  * oplist is the optional list of ops that generated the SVs;
6428  * recompile_p is a pointer to a boolean that will be set if
6429  *   the regex will need to be recompiled.
6430  * delim, if non-null is an SV that will be inserted between each element
6431  */
6432
6433 static SV*
6434 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6435                 SV *pat, SV ** const patternp, int pat_count,
6436                 OP *oplist, bool *recompile_p, SV *delim)
6437 {
6438     SV **svp;
6439     int n = 0;
6440     bool use_delim = FALSE;
6441     bool alloced = FALSE;
6442
6443     /* if we know we have at least two args, create an empty string,
6444      * then concatenate args to that. For no args, return an empty string */
6445     if (!pat && pat_count != 1) {
6446         pat = newSVpvs("");
6447         SAVEFREESV(pat);
6448         alloced = TRUE;
6449     }
6450
6451     for (svp = patternp; svp < patternp + pat_count; svp++) {
6452         SV *sv;
6453         SV *rx  = NULL;
6454         STRLEN orig_patlen = 0;
6455         bool code = 0;
6456         SV *msv = use_delim ? delim : *svp;
6457         if (!msv) msv = &PL_sv_undef;
6458
6459         /* if we've got a delimiter, we go round the loop twice for each
6460          * svp slot (except the last), using the delimiter the second
6461          * time round */
6462         if (use_delim) {
6463             svp--;
6464             use_delim = FALSE;
6465         }
6466         else if (delim)
6467             use_delim = TRUE;
6468
6469         if (SvTYPE(msv) == SVt_PVAV) {
6470             /* we've encountered an interpolated array within
6471              * the pattern, e.g. /...@a..../. Expand the list of elements,
6472              * then recursively append elements.
6473              * The code in this block is based on S_pushav() */
6474
6475             AV *const av = (AV*)msv;
6476             const SSize_t maxarg = AvFILL(av) + 1;
6477             SV **array;
6478
6479             if (oplist) {
6480                 assert(oplist->op_type == OP_PADAV
6481                     || oplist->op_type == OP_RV2AV);
6482                 oplist = OpSIBLING(oplist);
6483             }
6484
6485             if (SvRMAGICAL(av)) {
6486                 SSize_t i;
6487
6488                 Newx(array, maxarg, SV*);
6489                 SAVEFREEPV(array);
6490                 for (i=0; i < maxarg; i++) {
6491                     SV ** const svp = av_fetch(av, i, FALSE);
6492                     array[i] = svp ? *svp : &PL_sv_undef;
6493                 }
6494             }
6495             else
6496                 array = AvARRAY(av);
6497
6498             pat = S_concat_pat(aTHX_ pRExC_state, pat,
6499                                 array, maxarg, NULL, recompile_p,
6500                                 /* $" */
6501                                 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6502
6503             continue;
6504         }
6505
6506
6507         /* we make the assumption here that each op in the list of
6508          * op_siblings maps to one SV pushed onto the stack,
6509          * except for code blocks, with have both an OP_NULL and
6510          * and OP_CONST.
6511          * This allows us to match up the list of SVs against the
6512          * list of OPs to find the next code block.
6513          *
6514          * Note that       PUSHMARK PADSV PADSV ..
6515          * is optimised to
6516          *                 PADRANGE PADSV  PADSV  ..
6517          * so the alignment still works. */
6518
6519         if (oplist) {
6520             if (oplist->op_type == OP_NULL
6521                 && (oplist->op_flags & OPf_SPECIAL))
6522             {
6523                 assert(n < pRExC_state->code_blocks->count);
6524                 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6525                 pRExC_state->code_blocks->cb[n].block = oplist;
6526                 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6527                 n++;
6528                 code = 1;
6529                 oplist = OpSIBLING(oplist); /* skip CONST */
6530                 assert(oplist);
6531             }
6532             oplist = OpSIBLING(oplist);;
6533         }
6534
6535         /* apply magic and QR overloading to arg */
6536
6537         SvGETMAGIC(msv);
6538         if (SvROK(msv) && SvAMAGIC(msv)) {
6539             SV *sv = AMG_CALLunary(msv, regexp_amg);
6540             if (sv) {
6541                 if (SvROK(sv))
6542                     sv = SvRV(sv);
6543                 if (SvTYPE(sv) != SVt_REGEXP)
6544                     Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6545                 msv = sv;
6546             }
6547         }
6548
6549         /* try concatenation overload ... */
6550         if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6551                 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6552         {
6553             sv_setsv(pat, sv);
6554             /* overloading involved: all bets are off over literal
6555              * code. Pretend we haven't seen it */
6556             if (n)
6557                 pRExC_state->code_blocks->count -= n;
6558             n = 0;
6559         }
6560         else  {
6561             /* ... or failing that, try "" overload */
6562             while (SvAMAGIC(msv)
6563                     && (sv = AMG_CALLunary(msv, string_amg))
6564                     && sv != msv
6565                     &&  !(   SvROK(msv)
6566                           && SvROK(sv)
6567                           && SvRV(msv) == SvRV(sv))
6568             ) {
6569                 msv = sv;
6570                 SvGETMAGIC(msv);
6571             }
6572             if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6573                 msv = SvRV(msv);
6574
6575             if (pat) {
6576                 /* this is a partially unrolled
6577                  *     sv_catsv_nomg(pat, msv);
6578                  * that allows us to adjust code block indices if
6579                  * needed */
6580                 STRLEN dlen;
6581                 char *dst = SvPV_force_nomg(pat, dlen);
6582                 orig_patlen = dlen;
6583                 if (SvUTF8(msv) && !SvUTF8(pat)) {
6584                     S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6585                     sv_setpvn(pat, dst, dlen);
6586                     SvUTF8_on(pat);
6587                 }
6588                 sv_catsv_nomg(pat, msv);
6589                 rx = msv;
6590             }
6591             else {
6592                 /* We have only one SV to process, but we need to verify
6593                  * it is properly null terminated or we will fail asserts
6594                  * later. In theory we probably shouldn't get such SV's,
6595                  * but if we do we should handle it gracefully. */
6596                 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
6597                     /* not a string, or a string with a trailing null */
6598                     pat = msv;
6599                 } else {
6600                     /* a string with no trailing null, we need to copy it
6601                      * so it has a trailing null */
6602                     pat = sv_2mortal(newSVsv(msv));
6603                 }
6604             }
6605
6606             if (code)
6607                 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
6608         }
6609
6610         /* extract any code blocks within any embedded qr//'s */
6611         if (rx && SvTYPE(rx) == SVt_REGEXP
6612             && RX_ENGINE((REGEXP*)rx)->op_comp)
6613         {
6614
6615             RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6616             if (ri->code_blocks && ri->code_blocks->count) {
6617                 int i;
6618                 /* the presence of an embedded qr// with code means
6619                  * we should always recompile: the text of the
6620                  * qr// may not have changed, but it may be a
6621                  * different closure than last time */
6622                 *recompile_p = 1;
6623                 if (pRExC_state->code_blocks) {
6624                     int new_count = pRExC_state->code_blocks->count
6625                             + ri->code_blocks->count;
6626                     Renew(pRExC_state->code_blocks->cb,
6627                             new_count, struct reg_code_block);
6628                     pRExC_state->code_blocks->count = new_count;
6629                 }
6630                 else
6631                     pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
6632                                                     ri->code_blocks->count);
6633
6634                 for (i=0; i < ri->code_blocks->count; i++) {
6635                     struct reg_code_block *src, *dst;
6636                     STRLEN offset =  orig_patlen
6637                         + ReANY((REGEXP *)rx)->pre_prefix;
6638                     assert(n < pRExC_state->code_blocks->count);
6639                     src = &ri->code_blocks->cb[i];
6640                     dst = &pRExC_state->code_blocks->cb[n];
6641                     dst->start      = src->start + offset;
6642                     dst->end        = src->end   + offset;
6643                     dst->block      = src->block;
6644                     dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
6645                                             src->src_regex
6646                                                 ? src->src_regex
6647                                                 : (REGEXP*)rx);
6648                     n++;
6649                 }
6650             }
6651         }
6652     }
6653     /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6654     if (alloced)
6655         SvSETMAGIC(pat);
6656
6657     return pat;
6658 }
6659
6660
6661
6662 /* see if there are any run-time code blocks in the pattern.
6663  * False positives are allowed */
6664
6665 static bool
6666 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6667                     char *pat, STRLEN plen)
6668 {
6669     int n = 0;
6670     STRLEN s;
6671
6672     PERL_UNUSED_CONTEXT;
6673
6674     for (s = 0; s < plen; s++) {
6675         if (   pRExC_state->code_blocks
6676             && n < pRExC_state->code_blocks->count
6677             && s == pRExC_state->code_blocks->cb[n].start)
6678         {
6679             s = pRExC_state->code_blocks->cb[n].end;
6680             n++;
6681             continue;
6682         }
6683         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
6684          * positives here */
6685         if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
6686             (pat[s+2] == '{'
6687                 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
6688         )
6689             return 1;
6690     }
6691     return 0;
6692 }
6693
6694 /* Handle run-time code blocks. We will already have compiled any direct
6695  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
6696  * copy of it, but with any literal code blocks blanked out and
6697  * appropriate chars escaped; then feed it into
6698  *
6699  *    eval "qr'modified_pattern'"
6700  *
6701  * For example,
6702  *
6703  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
6704  *
6705  * becomes
6706  *
6707  *    qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
6708  *
6709  * After eval_sv()-ing that, grab any new code blocks from the returned qr
6710  * and merge them with any code blocks of the original regexp.
6711  *
6712  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
6713  * instead, just save the qr and return FALSE; this tells our caller that
6714  * the original pattern needs upgrading to utf8.
6715  */
6716
6717 static bool
6718 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6719     char *pat, STRLEN plen)
6720 {
6721     SV *qr;
6722
6723     GET_RE_DEBUG_FLAGS_DECL;
6724
6725     if (pRExC_state->runtime_code_qr) {
6726         /* this is the second time we've been called; this should
6727          * only happen if the main pattern got upgraded to utf8
6728          * during compilation; re-use the qr we compiled first time
6729          * round (which should be utf8 too)
6730          */
6731         qr = pRExC_state->runtime_code_qr;
6732         pRExC_state->runtime_code_qr = NULL;
6733         assert(RExC_utf8 && SvUTF8(qr));
6734     }
6735     else {
6736         int n = 0;
6737         STRLEN s;
6738         char *p, *newpat;
6739         int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
6740         SV *sv, *qr_ref;
6741         dSP;
6742
6743         /* determine how many extra chars we need for ' and \ escaping */
6744         for (s = 0; s < plen; s++) {
6745             if (pat[s] == '\'' || pat[s] == '\\')
6746                 newlen++;
6747         }
6748
6749         Newx(newpat, newlen, char);
6750         p = newpat;
6751         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
6752
6753         for (s = 0; s < plen; s++) {
6754             if (   pRExC_state->code_blocks
6755                 && n < pRExC_state->code_blocks->count
6756                 && s == pRExC_state->code_blocks->cb[n].start)
6757             {
6758                 /* blank out literal code block */
6759                 assert(pat[s] == '(');
6760                 while (s <= pRExC_state->code_blocks->cb[n].end) {
6761                     *p++ = '_';
6762                     s++;
6763                 }
6764                 s--;
6765                 n++;
6766                 continue;
6767             }
6768             if (pat[s] == '\'' || pat[s] == '\\')
6769                 *p++ = '\\';
6770             *p++ = pat[s];
6771         }
6772         *p++ = '\'';
6773         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
6774             *p++ = 'x';
6775             if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
6776                 *p++ = 'x';
6777             }
6778         }
6779         *p++ = '\0';
6780         DEBUG_COMPILE_r({
6781             Perl_re_printf( aTHX_
6782                 "%sre-parsing pattern for runtime code:%s %s\n",
6783                 PL_colors[4], PL_colors[5], newpat);
6784         });
6785
6786         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
6787         Safefree(newpat);
6788
6789         ENTER;
6790         SAVETMPS;
6791         save_re_context();
6792         PUSHSTACKi(PERLSI_REQUIRE);
6793         /* G_RE_REPARSING causes the toker to collapse \\ into \ when
6794          * parsing qr''; normally only q'' does this. It also alters
6795          * hints handling */
6796         eval_sv(sv, G_SCALAR|G_RE_REPARSING);
6797         SvREFCNT_dec_NN(sv);
6798         SPAGAIN;
6799         qr_ref = POPs;
6800         PUTBACK;
6801         {
6802             SV * const errsv = ERRSV;
6803             if (SvTRUE_NN(errsv))
6804                 /* use croak_sv ? */
6805                 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
6806         }
6807         assert(SvROK(qr_ref));
6808         qr = SvRV(qr_ref);
6809         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
6810         /* the leaving below frees the tmp qr_ref.
6811          * Give qr a life of its own */
6812         SvREFCNT_inc(qr);
6813         POPSTACK;
6814         FREETMPS;
6815         LEAVE;
6816
6817     }
6818
6819     if (!RExC_utf8 && SvUTF8(qr)) {
6820         /* first time through; the pattern got upgraded; save the
6821          * qr for the next time through */
6822         assert(!pRExC_state->runtime_code_qr);
6823         pRExC_state->runtime_code_qr = qr;
6824         return 0;
6825     }
6826
6827
6828     /* extract any code blocks within the returned qr//  */
6829
6830
6831     /* merge the main (r1) and run-time (r2) code blocks into one */
6832     {
6833         RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
6834         struct reg_code_block *new_block, *dst;
6835         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
6836         int i1 = 0, i2 = 0;
6837         int r1c, r2c;
6838
6839         if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
6840         {
6841             SvREFCNT_dec_NN(qr);
6842             return 1;
6843         }
6844
6845         if (!r1->code_blocks)
6846             r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
6847
6848         r1c = r1->code_blocks->count;
6849         r2c = r2->code_blocks->count;
6850
6851         Newx(new_block, r1c + r2c, struct reg_code_block);
6852
6853         dst = new_block;
6854
6855         while (i1 < r1c || i2 < r2c) {
6856             struct reg_code_block *src;
6857             bool is_qr = 0;
6858
6859             if (i1 == r1c) {
6860                 src = &r2->code_blocks->cb[i2++];
6861                 is_qr = 1;
6862             }
6863             else if (i2 == r2c)
6864                 src = &r1->code_blocks->cb[i1++];
6865             else if (  r1->code_blocks->cb[i1].start
6866                      < r2->code_blocks->cb[i2].start)
6867             {
6868                 src = &r1->code_blocks->cb[i1++];
6869                 assert(src->end < r2->code_blocks->cb[i2].start);
6870             }
6871             else {
6872                 assert(  r1->code_blocks->cb[i1].start
6873                        > r2->code_blocks->cb[i2].start);
6874                 src = &r2->code_blocks->cb[i2++];
6875                 is_qr = 1;
6876                 assert(src->end < r1->code_blocks->cb[i1].start);
6877             }
6878
6879             assert(pat[src->start] == '(');
6880             assert(pat[src->end]   == ')');
6881             dst->start      = src->start;
6882             dst->end        = src->end;
6883             dst->block      = src->block;
6884             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
6885                                     : src->src_regex;
6886             dst++;
6887         }
6888         r1->code_blocks->count += r2c;
6889         Safefree(r1->code_blocks->cb);
6890         r1->code_blocks->cb = new_block;
6891     }
6892
6893     SvREFCNT_dec_NN(qr);
6894     return 1;
6895 }
6896
6897
6898 STATIC bool
6899 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
6900                       struct reg_substr_datum  *rsd,
6901                       struct scan_data_substrs *sub,
6902                       STRLEN longest_length)
6903 {
6904     /* This is the common code for setting up the floating and fixed length
6905      * string data extracted from Perl_re_op_compile() below.  Returns a boolean
6906      * as to whether succeeded or not */
6907
6908     I32 t;
6909     SSize_t ml;
6910     bool eol  = cBOOL(sub->flags & SF_BEFORE_EOL);
6911     bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
6912
6913     if (! (longest_length
6914            || (eol /* Can't have SEOL and MULTI */
6915                && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
6916           )
6917             /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
6918         || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
6919     {
6920         return FALSE;
6921     }
6922
6923     /* copy the information about the longest from the reg_scan_data
6924         over to the program. */
6925     if (SvUTF8(sub->str)) {
6926         rsd->substr      = NULL;
6927         rsd->utf8_substr = sub->str;
6928     } else {
6929         rsd->substr      = sub->str;
6930         rsd->utf8_substr = NULL;
6931     }
6932     /* end_shift is how many chars that must be matched that
6933         follow this item. We calculate it ahead of time as once the
6934         lookbehind offset is added in we lose the ability to correctly
6935         calculate it.*/
6936     ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
6937     rsd->end_shift = ml - sub->min_offset
6938         - longest_length
6939             /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
6940              * intead? - DAPM
6941             + (SvTAIL(sub->str) != 0)
6942             */
6943         + sub->lookbehind;
6944
6945     t = (eol/* Can't have SEOL and MULTI */
6946          && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
6947     fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
6948
6949     return TRUE;
6950 }
6951
6952 STATIC void
6953 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
6954 {
6955     /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
6956      * properly wrapped with the right modifiers */
6957
6958     bool has_p     = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
6959     bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
6960                                                 != REGEX_DEPENDS_CHARSET);
6961
6962     /* The caret is output if there are any defaults: if not all the STD
6963         * flags are set, or if no character set specifier is needed */
6964     bool has_default =
6965                 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
6966                 || ! has_charset);
6967     bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
6968                                                 == REG_RUN_ON_COMMENT_SEEN);
6969     U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
6970                         >> RXf_PMf_STD_PMMOD_SHIFT);
6971     const char *fptr = STD_PAT_MODS;        /*"msixxn"*/
6972     char *p;
6973     STRLEN pat_len = RExC_precomp_end - RExC_precomp;
6974
6975     /* We output all the necessary flags; we never output a minus, as all
6976         * those are defaults, so are
6977         * covered by the caret */
6978     const STRLEN wraplen = pat_len + has_p + has_runon
6979         + has_default       /* If needs a caret */
6980         + PL_bitcount[reganch] /* 1 char for each set standard flag */
6981
6982             /* If needs a character set specifier */
6983         + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
6984         + (sizeof("(?:)") - 1);
6985
6986     PERL_ARGS_ASSERT_SET_REGEX_PV;
6987
6988     /* make sure PL_bitcount bounds not exceeded */
6989     assert(sizeof(STD_PAT_MODS) <= 8);
6990
6991     p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
6992     SvPOK_on(Rx);
6993     if (RExC_utf8)
6994         SvFLAGS(Rx) |= SVf_UTF8;
6995     *p++='('; *p++='?';
6996
6997     /* If a default, cover it using the caret */
6998     if (has_default) {
6999         *p++= DEFAULT_PAT_MOD;
7000     }
7001     if (has_charset) {
7002         STRLEN len;
7003         const char* name;
7004
7005         name = get_regex_charset_name(RExC_rx->extflags, &len);
7006         if strEQ(name, DEPENDS_PAT_MODS) {  /* /d under UTF-8 => /u */
7007             assert(RExC_utf8);
7008             name = UNICODE_PAT_MODS;
7009             len = sizeof(UNICODE_PAT_MODS) - 1;
7010         }
7011         Copy(name, p, len, char);
7012         p += len;
7013     }
7014     if (has_p)
7015         *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7016     {
7017         char ch;
7018         while((ch = *fptr++)) {
7019             if(reganch & 1)
7020                 *p++ = ch;
7021             reganch >>= 1;
7022         }
7023     }
7024
7025     *p++ = ':';
7026     Copy(RExC_precomp, p, pat_len, char);
7027     assert ((RX_WRAPPED(Rx) - p) < 16);
7028     RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7029     p += pat_len;
7030
7031     /* Adding a trailing \n causes this to compile properly:
7032             my $R = qr / A B C # D E/x; /($R)/
7033         Otherwise the parens are considered part of the comment */
7034     if (has_runon)
7035         *p++ = '\n';
7036     *p++ = ')';
7037     *p = 0;
7038     SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7039 }
7040
7041 /*
7042  * Perl_re_op_compile - the perl internal RE engine's function to compile a
7043  * regular expression into internal code.
7044  * The pattern may be passed either as:
7045  *    a list of SVs (patternp plus pat_count)
7046  *    a list of OPs (expr)
7047  * If both are passed, the SV list is used, but the OP list indicates
7048  * which SVs are actually pre-compiled code blocks
7049  *
7050  * The SVs in the list have magic and qr overloading applied to them (and
7051  * the list may be modified in-place with replacement SVs in the latter
7052  * case).
7053  *
7054  * If the pattern hasn't changed from old_re, then old_re will be
7055  * returned.
7056  *
7057  * eng is the current engine. If that engine has an op_comp method, then
7058  * handle directly (i.e. we assume that op_comp was us); otherwise, just
7059  * do the initial concatenation of arguments and pass on to the external
7060  * engine.
7061  *
7062  * If is_bare_re is not null, set it to a boolean indicating whether the
7063  * arg list reduced (after overloading) to a single bare regex which has
7064  * been returned (i.e. /$qr/).
7065  *
7066  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7067  *
7068  * pm_flags contains the PMf_* flags, typically based on those from the
7069  * pm_flags field of the related PMOP. Currently we're only interested in
7070  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
7071  *
7072  * For many years this code had an initial sizing pass that calculated
7073  * (sometimes incorrectly, leading to security holes) the size needed for the
7074  * compiled pattern.  That was changed by commit
7075  * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7076  * node at a time, as parsing goes along.  Patches welcome to fix any obsolete
7077  * references to this sizing pass.
7078  *
7079  * Now, an initial crude guess as to the size needed is made, based on the
7080  * length of the pattern.  Patches welcome to improve that guess.  That amount
7081  * of space is malloc'd and then immediately freed, and then clawed back node
7082  * by node.  This design is to minimze, to the extent possible, memory churn
7083  * when doing the the reallocs.
7084  *
7085  * A separate parentheses counting pass may be needed in some cases.
7086  * (Previously the sizing pass did this.)  Patches welcome to reduce the number
7087  * of these cases.
7088  *
7089  * The existence of a sizing pass necessitated design decisions that are no
7090  * longer needed.  There are potential areas of simplification.
7091  *
7092  * Beware that the optimization-preparation code in here knows about some
7093  * of the structure of the compiled regexp.  [I'll say.]
7094  */
7095
7096 REGEXP *
7097 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7098                     OP *expr, const regexp_engine* eng, REGEXP *old_re,
7099                      bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7100 {
7101     REGEXP *Rx;         /* Capital 'R' means points to a REGEXP */
7102     STRLEN plen;
7103     char *exp;
7104     regnode *scan;
7105     I32 flags;
7106     SSize_t minlen = 0;
7107     U32 rx_flags;
7108     SV *pat;
7109     SV** new_patternp = patternp;
7110
7111     /* these are all flags - maybe they should be turned
7112      * into a single int with different bit masks */
7113     I32 sawlookahead = 0;
7114     I32 sawplus = 0;
7115     I32 sawopen = 0;
7116     I32 sawminmod = 0;
7117
7118     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7119     bool recompile = 0;
7120     bool runtime_code = 0;
7121     scan_data_t data;
7122     RExC_state_t RExC_state;
7123     RExC_state_t * const pRExC_state = &RExC_state;
7124 #ifdef TRIE_STUDY_OPT
7125     int restudied = 0;
7126     RExC_state_t copyRExC_state;
7127 #endif
7128     GET_RE_DEBUG_FLAGS_DECL;
7129
7130     PERL_ARGS_ASSERT_RE_OP_COMPILE;
7131
7132     DEBUG_r(if (!PL_colorset) reginitcolors());
7133
7134     /* Initialize these here instead of as-needed, as is quick and avoids
7135      * having to test them each time otherwise */
7136     if (! PL_InBitmap) {
7137 #ifdef DEBUGGING
7138         char * dump_len_string;
7139 #endif
7140
7141         /* This is calculated here, because the Perl program that generates the
7142          * static global ones doesn't currently have access to
7143          * NUM_ANYOF_CODE_POINTS */
7144         PL_InBitmap = _new_invlist(2);
7145         PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,
7146                                                     NUM_ANYOF_CODE_POINTS - 1);
7147 #ifdef DEBUGGING
7148         dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
7149         if (   ! dump_len_string
7150             || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
7151         {
7152             PL_dump_re_max_len = 60;    /* A reasonable default */
7153         }
7154 #endif
7155     }
7156
7157     pRExC_state->warn_text = NULL;
7158     pRExC_state->code_blocks = NULL;
7159
7160     if (is_bare_re)
7161         *is_bare_re = FALSE;
7162
7163     if (expr && (expr->op_type == OP_LIST ||
7164                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7165         /* allocate code_blocks if needed */
7166         OP *o;
7167         int ncode = 0;
7168
7169         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7170             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7171                 ncode++; /* count of DO blocks */
7172
7173         if (ncode)
7174             pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7175     }
7176
7177     if (!pat_count) {
7178         /* compile-time pattern with just OP_CONSTs and DO blocks */
7179
7180         int n;
7181         OP *o;
7182
7183         /* find how many CONSTs there are */
7184         assert(expr);
7185         n = 0;
7186         if (expr->op_type == OP_CONST)
7187             n = 1;
7188         else
7189             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7190                 if (o->op_type == OP_CONST)
7191                     n++;
7192             }
7193
7194         /* fake up an SV array */
7195
7196         assert(!new_patternp);
7197         Newx(new_patternp, n, SV*);
7198         SAVEFREEPV(new_patternp);
7199         pat_count = n;
7200
7201         n = 0;
7202         if (expr->op_type == OP_CONST)
7203             new_patternp[n] = cSVOPx_sv(expr);
7204         else
7205             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7206                 if (o->op_type == OP_CONST)
7207                     new_patternp[n++] = cSVOPo_sv;
7208             }
7209
7210     }
7211
7212     DEBUG_PARSE_r(Perl_re_printf( aTHX_
7213         "Assembling pattern from %d elements%s\n", pat_count,
7214             orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7215
7216     /* set expr to the first arg op */
7217
7218     if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7219          && expr->op_type != OP_CONST)
7220     {
7221             expr = cLISTOPx(expr)->op_first;
7222             assert(   expr->op_type == OP_PUSHMARK
7223                    || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7224                    || expr->op_type == OP_PADRANGE);
7225             expr = OpSIBLING(expr);
7226     }
7227
7228     pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7229                         expr, &recompile, NULL);
7230
7231     /* handle bare (possibly after overloading) regex: foo =~ $re */
7232     {
7233         SV *re = pat;
7234         if (SvROK(re))
7235             re = SvRV(re);
7236         if (SvTYPE(re) == SVt_REGEXP) {
7237             if (is_bare_re)
7238                 *is_bare_re = TRUE;
7239             SvREFCNT_inc(re);
7240             DEBUG_PARSE_r(Perl_re_printf( aTHX_
7241                 "Precompiled pattern%s\n",
7242                     orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7243
7244             return (REGEXP*)re;
7245         }
7246     }
7247
7248     exp = SvPV_nomg(pat, plen);
7249
7250     if (!eng->op_comp) {
7251         if ((SvUTF8(pat) && IN_BYTES)
7252                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7253         {
7254             /* make a temporary copy; either to convert to bytes,
7255              * or to avoid repeating get-magic / overloaded stringify */
7256             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7257                                         (IN_BYTES ? 0 : SvUTF8(pat)));
7258         }
7259         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7260     }
7261
7262     /* ignore the utf8ness if the pattern is 0 length */
7263     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7264
7265     RExC_uni_semantics = RExC_utf8; /* UTF-8 implies unicode semantics;
7266                                        otherwise we may find later this should
7267                                        be 1 */
7268     RExC_contains_locale = 0;
7269     RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7270     RExC_in_script_run = 0;
7271     RExC_study_started = 0;
7272     pRExC_state->runtime_code_qr = NULL;
7273     RExC_frame_head= NULL;
7274     RExC_frame_last= NULL;
7275     RExC_frame_count= 0;
7276     RExC_latest_warn_offset = 0;
7277     RExC_use_BRANCHJ = 0;
7278     RExC_total_parens = 0;
7279     RExC_open_parens = NULL;
7280     RExC_close_parens = NULL;
7281     RExC_paren_names = NULL;
7282     RExC_size = 0;
7283     RExC_seen_d_op = FALSE;
7284 #ifdef DEBUGGING
7285     RExC_paren_name_list = NULL;
7286 #endif
7287
7288     DEBUG_r({
7289         RExC_mysv1= sv_newmortal();
7290         RExC_mysv2= sv_newmortal();
7291     });
7292
7293     DEBUG_COMPILE_r({
7294             SV *dsv= sv_newmortal();
7295             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7296             Perl_re_printf( aTHX_  "%sCompiling REx%s %s\n",
7297                           PL_colors[4], PL_colors[5], s);
7298         });
7299
7300     /* we jump here if we have to recompile, e.g., from upgrading the pattern
7301      * to utf8 */
7302
7303     if ((pm_flags & PMf_USE_RE_EVAL)
7304                 /* this second condition covers the non-regex literal case,
7305                  * i.e.  $foo =~ '(?{})'. */
7306                 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7307     )
7308         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7309
7310   redo_parse:
7311     /* return old regex if pattern hasn't changed */
7312     /* XXX: note in the below we have to check the flags as well as the
7313      * pattern.
7314      *
7315      * Things get a touch tricky as we have to compare the utf8 flag
7316      * independently from the compile flags.  */
7317
7318     if (   old_re
7319         && !recompile
7320         && !!RX_UTF8(old_re) == !!RExC_utf8
7321         && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7322         && RX_PRECOMP(old_re)
7323         && RX_PRELEN(old_re) == plen
7324         && memEQ(RX_PRECOMP(old_re), exp, plen)
7325         && !runtime_code /* with runtime code, always recompile */ )
7326     {
7327         return old_re;
7328     }
7329
7330     /* Allocate the pattern's SV */
7331     RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7332     RExC_rx = ReANY(Rx);
7333     if ( RExC_rx == NULL )
7334         FAIL("Regexp out of space");
7335
7336     rx_flags = orig_rx_flags;
7337
7338     if (initial_charset == REGEX_DEPENDS_CHARSET && RExC_uni_semantics) {
7339
7340         /* Set to use unicode semantics if the pattern is in utf8 and has the
7341          * 'depends' charset specified, as it means unicode when utf8  */
7342         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7343     }
7344
7345     RExC_pm_flags = pm_flags;
7346
7347     if (runtime_code) {
7348         assert(TAINTING_get || !TAINT_get);
7349         if (TAINT_get)
7350             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7351
7352         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7353             /* whoops, we have a non-utf8 pattern, whilst run-time code
7354              * got compiled as utf8. Try again with a utf8 pattern */
7355             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7356                 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7357             goto redo_parse;
7358         }
7359     }
7360     assert(!pRExC_state->runtime_code_qr);
7361
7362     RExC_sawback = 0;
7363
7364     RExC_seen = 0;
7365     RExC_maxlen = 0;
7366     RExC_in_lookbehind = 0;
7367     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7368 #ifdef EBCDIC
7369     RExC_recode_x_to_native = 0;
7370 #endif
7371     RExC_in_multi_char_class = 0;
7372
7373     RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7374     RExC_precomp_end = RExC_end = exp + plen;
7375     RExC_nestroot = 0;
7376     RExC_whilem_seen = 0;
7377     RExC_end_op = NULL;
7378     RExC_recurse = NULL;
7379     RExC_study_chunk_recursed = NULL;
7380     RExC_study_chunk_recursed_bytes= 0;
7381     RExC_recurse_count = 0;
7382     pRExC_state->code_index = 0;
7383
7384     /* Initialize the string in the compiled pattern.  This is so that there is
7385      * something to output if necessary */
7386     set_regex_pv(pRExC_state, Rx);
7387
7388     DEBUG_PARSE_r({
7389         Perl_re_printf( aTHX_
7390             "Starting parse and generation\n");
7391         RExC_lastnum=0;
7392         RExC_lastparse=NULL;
7393     });
7394
7395     /* Allocate space and zero-initialize. Note, the two step process
7396        of zeroing when in debug mode, thus anything assigned has to
7397        happen after that */
7398     if (!  RExC_size) {
7399
7400         /* On the first pass of the parse, we guess how big this will be.  Then
7401          * we grow in one operation to that amount and then give it back.  As
7402          * we go along, we re-allocate what we need.
7403          *
7404          * XXX Currently the guess is essentially that the pattern will be an
7405          * EXACT node with one byte input, one byte output.  This is crude, and
7406          * better heuristics are welcome.
7407          *
7408          * On any subsequent passes, we guess what we actually computed in the
7409          * latest earlier pass.  Such a pass probably didn't complete so is
7410          * missing stuff.  We could improve those guesses by knowing where the
7411          * parse stopped, and use the length so far plus apply the above
7412          * assumption to what's left. */
7413         RExC_size = STR_SZ(RExC_end - RExC_start);
7414     }
7415
7416     Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7417     if ( RExC_rxi == NULL )
7418         FAIL("Regexp out of space");
7419
7420     Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7421     RXi_SET( RExC_rx, RExC_rxi );
7422
7423     /* We start from 0 (over from 0 in the case this is a reparse.  The first
7424      * node parsed will give back any excess memory we have allocated so far).
7425      * */
7426     RExC_size = 0;
7427
7428     /* non-zero initialization begins here */
7429     RExC_rx->engine= eng;
7430     RExC_rx->extflags = rx_flags;
7431     RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7432
7433     if (pm_flags & PMf_IS_QR) {
7434         RExC_rxi->code_blocks = pRExC_state->code_blocks;
7435         if (RExC_rxi->code_blocks) {
7436             RExC_rxi->code_blocks->refcnt++;
7437         }
7438     }
7439
7440     RExC_rx->intflags = 0;
7441
7442     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
7443     RExC_parse = exp;
7444
7445     /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7446      * code makes sure the final byte is an uncounted NUL.  But should this
7447      * ever not be the case, lots of things could read beyond the end of the
7448      * buffer: loops like
7449      *      while(isFOO(*RExC_parse)) RExC_parse++;
7450      *      strchr(RExC_parse, "foo");
7451      * etc.  So it is worth noting. */
7452     assert(*RExC_end == '\0');
7453
7454     RExC_naughty = 0;
7455     RExC_npar = 1;
7456     RExC_emit_start = RExC_rxi->program;
7457     pRExC_state->code_index = 0;
7458
7459     *((char*) RExC_emit_start) = (char) REG_MAGIC;
7460     RExC_emit = 1;
7461
7462     /* Do the parse */
7463     if (reg(pRExC_state, 0, &flags, 1)) {
7464
7465         /* Success!, But if RExC_total_parens < 0, we need to redo the parse
7466          * knowing how many parens there actually are */
7467         if (RExC_total_parens < 0) {
7468             flags |= RESTART_PARSE;
7469         }
7470
7471         /* We have that number in RExC_npar */
7472         RExC_total_parens = RExC_npar;
7473     }
7474     else if (! MUST_RESTART(flags)) {
7475         ReREFCNT_dec(Rx);
7476         Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7477     }
7478
7479     /* Here, we either have success, or we have to redo the parse for some reason */
7480     if (MUST_RESTART(flags)) {
7481
7482         /* It's possible to write a regexp in ascii that represents Unicode
7483         codepoints outside of the byte range, such as via \x{100}. If we
7484         detect such a sequence we have to convert the entire pattern to utf8
7485         and then recompile, as our sizing calculation will have been based
7486         on 1 byte == 1 character, but we will need to use utf8 to encode
7487         at least some part of the pattern, and therefore must convert the whole
7488         thing.
7489         -- dmq */
7490         if (flags & NEED_UTF8) {
7491
7492             /* We have stored the offset of the final warning output so far.
7493              * That must be adjusted.  Any variant characters between the start
7494              * of the pattern and this warning count for 2 bytes in the final,
7495              * so just add them again */
7496             if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7497                 RExC_latest_warn_offset +=
7498                             variant_under_utf8_count((U8 *) exp, (U8 *) exp
7499                                                 + RExC_latest_warn_offset);
7500             }
7501             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7502             pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7503             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7504         }
7505         else {
7506             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7507         }
7508
7509         if (RExC_total_parens > 0) {
7510             /* Make enough room for all the known parens, and zero it */
7511             Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7512             Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7513             RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
7514
7515             Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7516             Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7517         }
7518         else { /* Parse did not complete.  Reinitialize the parentheses
7519                   structures */
7520             RExC_total_parens = 0;
7521             if (RExC_open_parens) {
7522                 Safefree(RExC_open_parens);
7523                 RExC_open_parens = NULL;
7524             }
7525             if (RExC_close_parens) {
7526                 Safefree(RExC_close_parens);
7527                 RExC_close_parens = NULL;
7528             }
7529         }
7530
7531         /* Clean up what we did in this parse */
7532         SvREFCNT_dec_NN(RExC_rx_sv);
7533
7534         goto redo_parse;
7535     }
7536
7537     /* In a stable state, as here, this must be true */
7538     assert(RExC_size = RExC_emit + 1);
7539
7540     /* Here, we have successfully parsed and generated the pattern's program
7541      * for the regex engine.  We are ready to finish things up and look for
7542      * optimizations. */
7543
7544     /* Update the string to compile, with correct modifiers, etc */
7545     set_regex_pv(pRExC_state, Rx);
7546
7547     RExC_rx->nparens = RExC_total_parens - 1;
7548
7549     /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7550     if (RExC_whilem_seen > 15)
7551         RExC_whilem_seen = 15;
7552
7553     DEBUG_PARSE_r({
7554         Perl_re_printf( aTHX_
7555             "Required size %" IVdf " nodes\n", (IV)RExC_size);
7556         RExC_lastnum=0;
7557         RExC_lastparse=NULL;
7558     });
7559
7560 #ifdef RE_TRACK_PATTERN_OFFSETS
7561     DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7562                           "%s %" UVuf " bytes for offset annotations.\n",
7563                           RExC_offsets ? "Got" : "Couldn't get",
7564                           (UV)((RExC_offsets[0] * 2 + 1))));
7565     DEBUG_OFFSETS_r(if (RExC_offsets) {
7566         const STRLEN len = RExC_offsets[0];
7567         STRLEN i;
7568         GET_RE_DEBUG_FLAGS_DECL;
7569         Perl_re_printf( aTHX_
7570                       "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7571         for (i = 1; i <= len; i++) {
7572             if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7573                 Perl_re_printf( aTHX_  "%" UVuf ":%" UVuf "[%" UVuf "] ",
7574                 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7575         }
7576         Perl_re_printf( aTHX_  "\n");
7577     });
7578
7579 #else
7580     SetProgLen(RExC_rxi,RExC_size);
7581 #endif
7582
7583     DEBUG_OPTIMISE_r(
7584         Perl_re_printf( aTHX_  "Starting post parse optimization\n");
7585     );
7586
7587     /* XXXX To minimize changes to RE engine we always allocate
7588        3-units-long substrs field. */
7589     Newx(RExC_rx->substrs, 1, struct reg_substr_data);
7590     if (RExC_recurse_count) {
7591         Newx(RExC_recurse, RExC_recurse_count, regnode *);
7592         SAVEFREEPV(RExC_recurse);
7593     }
7594
7595     if (RExC_seen & REG_RECURSE_SEEN) {
7596         /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
7597          * So its 1 if there are no parens. */
7598         RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
7599                                          ((RExC_total_parens & 0x07) != 0);
7600         Newx(RExC_study_chunk_recursed,
7601              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7602         SAVEFREEPV(RExC_study_chunk_recursed);
7603     }
7604
7605   reStudy:
7606     RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7607     DEBUG_r(
7608         RExC_study_chunk_recursed_count= 0;
7609     );
7610     Zero(RExC_rx->substrs, 1, struct reg_substr_data);
7611     if (RExC_study_chunk_recursed) {
7612         Zero(RExC_study_chunk_recursed,
7613              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7614     }
7615
7616
7617 #ifdef TRIE_STUDY_OPT
7618     if (!restudied) {
7619         StructCopy(&zero_scan_data, &data, scan_data_t);
7620         copyRExC_state = RExC_state;
7621     } else {
7622         U32 seen=RExC_seen;
7623         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
7624
7625         RExC_state = copyRExC_state;
7626         if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7627             RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7628         else
7629             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7630         StructCopy(&zero_scan_data, &data, scan_data_t);
7631     }
7632 #else
7633     StructCopy(&zero_scan_data, &data, scan_data_t);
7634 #endif
7635
7636     /* Dig out information for optimizations. */
7637     RExC_rx->extflags = RExC_flags; /* was pm_op */
7638     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7639
7640     if (UTF)
7641         SvUTF8_on(Rx);  /* Unicode in it? */
7642     RExC_rxi->regstclass = NULL;
7643     if (RExC_naughty >= TOO_NAUGHTY)    /* Probably an expensive pattern. */
7644         RExC_rx->intflags |= PREGf_NAUGHTY;
7645     scan = RExC_rxi->program + 1;               /* First BRANCH. */
7646
7647     /* testing for BRANCH here tells us whether there is "must appear"
7648        data in the pattern. If there is then we can use it for optimisations */
7649     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /*  Only one top-level choice.
7650                                                   */
7651         SSize_t fake;
7652         STRLEN longest_length[2];
7653         regnode_ssc ch_class; /* pointed to by data */
7654         int stclass_flag;
7655         SSize_t last_close = 0; /* pointed to by data */
7656         regnode *first= scan;
7657         regnode *first_next= regnext(first);
7658         int i;
7659
7660         /*
7661          * Skip introductions and multiplicators >= 1
7662          * so that we can extract the 'meat' of the pattern that must
7663          * match in the large if() sequence following.
7664          * NOTE that EXACT is NOT covered here, as it is normally
7665          * picked up by the optimiser separately.
7666          *
7667          * This is unfortunate as the optimiser isnt handling lookahead
7668          * properly currently.
7669          *
7670          */
7671         while ((OP(first) == OPEN && (sawopen = 1)) ||
7672                /* An OR of *one* alternative - should not happen now. */
7673             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
7674             /* for now we can't handle lookbehind IFMATCH*/
7675             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
7676             (OP(first) == PLUS) ||
7677             (OP(first) == MINMOD) ||
7678                /* An {n,m} with n>0 */
7679             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
7680             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
7681         {
7682                 /*
7683                  * the only op that could be a regnode is PLUS, all the rest
7684                  * will be regnode_1 or regnode_2.
7685                  *
7686                  * (yves doesn't think this is true)
7687                  */
7688                 if (OP(first) == PLUS)
7689                     sawplus = 1;
7690                 else {
7691                     if (OP(first) == MINMOD)
7692                         sawminmod = 1;
7693                     first += regarglen[OP(first)];
7694                 }
7695                 first = NEXTOPER(first);
7696                 first_next= regnext(first);
7697         }
7698
7699         /* Starting-point info. */
7700       again:
7701         DEBUG_PEEP("first:", first, 0, 0);
7702         /* Ignore EXACT as we deal with it later. */
7703         if (PL_regkind[OP(first)] == EXACT) {
7704             if (OP(first) == EXACT || OP(first) == EXACTL)
7705                 NOOP;   /* Empty, get anchored substr later. */
7706             else
7707                 RExC_rxi->regstclass = first;
7708         }
7709 #ifdef TRIE_STCLASS
7710         else if (PL_regkind[OP(first)] == TRIE &&
7711                 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
7712         {
7713             /* this can happen only on restudy */
7714             RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
7715         }
7716 #endif
7717         else if (REGNODE_SIMPLE(OP(first)))
7718             RExC_rxi->regstclass = first;
7719         else if (PL_regkind[OP(first)] == BOUND ||
7720                  PL_regkind[OP(first)] == NBOUND)
7721             RExC_rxi->regstclass = first;
7722         else if (PL_regkind[OP(first)] == BOL) {
7723             RExC_rx->intflags |= (OP(first) == MBOL
7724                            ? PREGf_ANCH_MBOL
7725                            : PREGf_ANCH_SBOL);
7726             first = NEXTOPER(first);
7727             goto again;
7728         }
7729         else if (OP(first) == GPOS) {
7730             RExC_rx->intflags |= PREGf_ANCH_GPOS;
7731             first = NEXTOPER(first);
7732             goto again;
7733         }
7734         else if ((!sawopen || !RExC_sawback) &&
7735             !sawlookahead &&
7736             (OP(first) == STAR &&
7737             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
7738             !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
7739         {
7740             /* turn .* into ^.* with an implied $*=1 */
7741             const int type =
7742                 (OP(NEXTOPER(first)) == REG_ANY)
7743                     ? PREGf_ANCH_MBOL
7744                     : PREGf_ANCH_SBOL;
7745             RExC_rx->intflags |= (type | PREGf_IMPLICIT);
7746             first = NEXTOPER(first);
7747             goto again;
7748         }
7749         if (sawplus && !sawminmod && !sawlookahead
7750             && (!sawopen || !RExC_sawback)
7751             && !pRExC_state->code_blocks) /* May examine pos and $& */
7752             /* x+ must match at the 1st pos of run of x's */
7753             RExC_rx->intflags |= PREGf_SKIP;
7754
7755         /* Scan is after the zeroth branch, first is atomic matcher. */
7756 #ifdef TRIE_STUDY_OPT
7757         DEBUG_PARSE_r(
7758             if (!restudied)
7759                 Perl_re_printf( aTHX_  "first at %" IVdf "\n",
7760                               (IV)(first - scan + 1))
7761         );
7762 #else
7763         DEBUG_PARSE_r(
7764             Perl_re_printf( aTHX_  "first at %" IVdf "\n",
7765                 (IV)(first - scan + 1))
7766         );
7767 #endif
7768
7769
7770         /*
7771         * If there's something expensive in the r.e., find the
7772         * longest literal string that must appear and make it the
7773         * regmust.  Resolve ties in favor of later strings, since
7774         * the regstart check works with the beginning of the r.e.
7775         * and avoiding duplication strengthens checking.  Not a
7776         * strong reason, but sufficient in the absence of others.
7777         * [Now we resolve ties in favor of the earlier string if
7778         * it happens that c_offset_min has been invalidated, since the
7779         * earlier string may buy us something the later one won't.]
7780         */
7781
7782         data.substrs[0].str = newSVpvs("");
7783         data.substrs[1].str = newSVpvs("");
7784         data.last_found = newSVpvs("");
7785         data.cur_is_floating = 0; /* initially any found substring is fixed */
7786         ENTER_with_name("study_chunk");
7787         SAVEFREESV(data.substrs[0].str);
7788         SAVEFREESV(data.substrs[1].str);
7789         SAVEFREESV(data.last_found);
7790         first = scan;
7791         if (!RExC_rxi->regstclass) {
7792             ssc_init(pRExC_state, &ch_class);
7793             data.start_class = &ch_class;
7794             stclass_flag = SCF_DO_STCLASS_AND;
7795         } else                          /* XXXX Check for BOUND? */
7796             stclass_flag = 0;
7797         data.last_closep = &last_close;
7798
7799         DEBUG_RExC_seen();
7800         /*
7801          * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
7802          * (NO top level branches)
7803          */
7804         minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
7805                              scan + RExC_size, /* Up to end */
7806             &data, -1, 0, NULL,
7807             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
7808                           | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
7809             0);
7810
7811
7812         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
7813
7814
7815         if ( RExC_total_parens == 1 && !data.cur_is_floating
7816              && data.last_start_min == 0 && data.last_end > 0
7817              && !RExC_seen_zerolen
7818              && !(RExC_seen & REG_VERBARG_SEEN)
7819              && !(RExC_seen & REG_GPOS_SEEN)
7820         ){
7821             RExC_rx->extflags |= RXf_CHECK_ALL;
7822         }
7823         scan_commit(pRExC_state, &data,&minlen, 0);
7824
7825
7826         /* XXX this is done in reverse order because that's the way the
7827          * code was before it was parameterised. Don't know whether it
7828          * actually needs doing in reverse order. DAPM */
7829         for (i = 1; i >= 0; i--) {
7830             longest_length[i] = CHR_SVLEN(data.substrs[i].str);
7831
7832             if (   !(   i
7833                      && SvCUR(data.substrs[0].str)  /* ok to leave SvCUR */
7834                      &&    data.substrs[0].min_offset
7835                         == data.substrs[1].min_offset
7836                      &&    SvCUR(data.substrs[0].str)
7837                         == SvCUR(data.substrs[1].str)
7838                     )
7839                 && S_setup_longest (aTHX_ pRExC_state,
7840                                         &(RExC_rx->substrs->data[i]),
7841                                         &(data.substrs[i]),
7842                                         longest_length[i]))
7843             {
7844                 RExC_rx->substrs->data[i].min_offset =
7845                         data.substrs[i].min_offset - data.substrs[i].lookbehind;
7846
7847                 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
7848                 /* Don't offset infinity */
7849                 if (data.substrs[i].max_offset < SSize_t_MAX)
7850                     RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
7851                 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
7852             }
7853             else {
7854                 RExC_rx->substrs->data[i].substr      = NULL;
7855                 RExC_rx->substrs->data[i].utf8_substr = NULL;
7856                 longest_length[i] = 0;
7857             }
7858         }
7859
7860         LEAVE_with_name("study_chunk");
7861
7862         if (RExC_rxi->regstclass
7863             && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
7864             RExC_rxi->regstclass = NULL;
7865
7866         if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
7867               || RExC_rx->substrs->data[0].min_offset)
7868             && stclass_flag
7869             && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
7870             && is_ssc_worth_it(pRExC_state, data.start_class))
7871         {
7872             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
7873
7874             ssc_finalize(pRExC_state, data.start_class);
7875
7876             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
7877             StructCopy(data.start_class,
7878                        (regnode_ssc*)RExC_rxi->data->data[n],
7879                        regnode_ssc);
7880             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
7881             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
7882             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
7883                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
7884                       Perl_re_printf( aTHX_
7885                                     "synthetic stclass \"%s\".\n",
7886                                     SvPVX_const(sv));});
7887             data.start_class = NULL;
7888         }
7889
7890         /* A temporary algorithm prefers floated substr to fixed one of
7891          * same length to dig more info. */
7892         i = (longest_length[0] <= longest_length[1]);
7893         RExC_rx->substrs->check_ix = i;
7894         RExC_rx->check_end_shift  = RExC_rx->substrs->data[i].end_shift;
7895         RExC_rx->check_substr     = RExC_rx->substrs->data[i].substr;
7896         RExC_rx->check_utf8       = RExC_rx->substrs->data[i].utf8_substr;
7897         RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
7898         RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
7899         if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
7900             RExC_rx->intflags |= PREGf_NOSCAN;
7901
7902         if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
7903             RExC_rx->extflags |= RXf_USE_INTUIT;
7904             if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
7905                 RExC_rx->extflags |= RXf_INTUIT_TAIL;
7906         }
7907
7908         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
7909         if ( (STRLEN)minlen < longest_length[1] )
7910             minlen= longest_length[1];
7911         if ( (STRLEN)minlen < longest_length[0] )
7912             minlen= longest_length[0];
7913         */
7914     }
7915     else {
7916         /* Several toplevels. Best we can is to set minlen. */
7917         SSize_t fake;
7918         regnode_ssc ch_class;
7919         SSize_t last_close = 0;
7920
7921         DEBUG_PARSE_r(Perl_re_printf( aTHX_  "\nMulti Top Level\n"));
7922
7923         scan = RExC_rxi->program + 1;
7924         ssc_init(pRExC_state, &ch_class);
7925         data.start_class = &ch_class;
7926         data.last_closep = &last_close;
7927
7928         DEBUG_RExC_seen();
7929         /*
7930          * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
7931          * (patterns WITH top level branches)
7932          */
7933         minlen = study_chunk(pRExC_state,
7934             &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
7935             SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
7936                                                       ? SCF_TRIE_DOING_RESTUDY
7937                                                       : 0),
7938             0);
7939
7940         CHECK_RESTUDY_GOTO_butfirst(NOOP);
7941
7942         RExC_rx->check_substr = NULL;
7943         RExC_rx->check_utf8 = NULL;
7944         RExC_rx->substrs->data[0].substr      = NULL;
7945         RExC_rx->substrs->data[0].utf8_substr = NULL;
7946         RExC_rx->substrs->data[1].substr      = NULL;
7947         RExC_rx->substrs->data[1].utf8_substr = NULL;
7948
7949         if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
7950             && is_ssc_worth_it(pRExC_state, data.start_class))
7951         {
7952             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
7953
7954             ssc_finalize(pRExC_state, data.start_class);
7955
7956             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
7957             StructCopy(data.start_class,
7958                        (regnode_ssc*)RExC_rxi->data->data[n],
7959                        regnode_ssc);
7960             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
7961             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
7962             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
7963                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
7964                       Perl_re_printf( aTHX_
7965                                     "synthetic stclass \"%s\".\n",
7966                                     SvPVX_const(sv));});
7967             data.start_class = NULL;
7968         }
7969     }
7970
7971     if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
7972         RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
7973         RExC_rx->maxlen = REG_INFTY;
7974     }
7975     else {
7976         RExC_rx->maxlen = RExC_maxlen;
7977     }
7978
7979     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
7980        the "real" pattern. */
7981     DEBUG_OPTIMISE_r({
7982         Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
7983                       (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
7984     });
7985     RExC_rx->minlenret = minlen;
7986     if (RExC_rx->minlen < minlen)
7987         RExC_rx->minlen = minlen;
7988
7989     if (RExC_seen & REG_RECURSE_SEEN ) {
7990         RExC_rx->intflags |= PREGf_RECURSE_SEEN;
7991         Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
7992     }
7993     if (RExC_seen & REG_GPOS_SEEN)
7994         RExC_rx->intflags |= PREGf_GPOS_SEEN;
7995     if (RExC_seen & REG_LOOKBEHIND_SEEN)
7996         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
7997                                                 lookbehind */
7998     if (pRExC_state->code_blocks)
7999         RExC_rx->extflags |= RXf_EVAL_SEEN;
8000     if (RExC_seen & REG_VERBARG_SEEN)
8001     {
8002         RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8003         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8004     }
8005     if (RExC_seen & REG_CUTGROUP_SEEN)
8006         RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8007     if (pm_flags & PMf_USE_RE_EVAL)
8008         RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8009     if (RExC_paren_names)
8010         RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8011     else
8012         RXp_PAREN_NAMES(RExC_rx) = NULL;
8013
8014     /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8015      * so it can be used in pp.c */
8016     if (RExC_rx->intflags & PREGf_ANCH)
8017         RExC_rx->extflags |= RXf_IS_ANCHORED;
8018
8019
8020     {
8021         /* this is used to identify "special" patterns that might result
8022          * in Perl NOT calling the regex engine and instead doing the match "itself",
8023          * particularly special cases in split//. By having the regex compiler
8024          * do this pattern matching at a regop level (instead of by inspecting the pattern)
8025          * we avoid weird issues with equivalent patterns resulting in different behavior,
8026          * AND we allow non Perl engines to get the same optimizations by the setting the
8027          * flags appropriately - Yves */
8028         regnode *first = RExC_rxi->program + 1;
8029         U8 fop = OP(first);
8030         regnode *next = regnext(first);
8031         U8 nop = OP(next);
8032
8033         if (PL_regkind[fop] == NOTHING && nop == END)
8034             RExC_rx->extflags |= RXf_NULL;
8035         else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8036             /* when fop is SBOL first->flags will be true only when it was
8037              * produced by parsing /\A/, and not when parsing /^/. This is
8038              * very important for the split code as there we want to
8039              * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8040              * See rt #122761 for more details. -- Yves */
8041             RExC_rx->extflags |= RXf_START_ONLY;
8042         else if (fop == PLUS
8043                  && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8044                  && nop == END)
8045             RExC_rx->extflags |= RXf_WHITE;
8046         else if ( RExC_rx->extflags & RXf_SPLIT
8047                   && (fop == EXACT || fop == EXACTL)
8048                   && STR_LEN(first) == 1
8049                   && *(STRING(first)) == ' '
8050                   && nop == END )
8051             RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8052
8053     }
8054
8055     if (RExC_contains_locale) {
8056         RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8057     }
8058
8059 #ifdef DEBUGGING
8060     if (RExC_paren_names) {
8061         RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8062         RExC_rxi->data->data[RExC_rxi->name_list_idx]
8063                                    = (void*)SvREFCNT_inc(RExC_paren_name_list);
8064     } else
8065 #endif
8066     RExC_rxi->name_list_idx = 0;
8067
8068     while ( RExC_recurse_count > 0 ) {
8069         const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8070         /*
8071          * This data structure is set up in study_chunk() and is used
8072          * to calculate the distance between a GOSUB regopcode and
8073          * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8074          * it refers to.
8075          *
8076          * If for some reason someone writes code that optimises
8077          * away a GOSUB opcode then the assert should be changed to
8078          * an if(scan) to guard the ARG2L_SET() - Yves
8079          *
8080          */
8081         assert(scan && OP(scan) == GOSUB);
8082         ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8083     }
8084
8085     Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8086     /* assume we don't need to swap parens around before we match */
8087     DEBUG_TEST_r({
8088         Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8089             (unsigned long)RExC_study_chunk_recursed_count);
8090     });
8091     DEBUG_DUMP_r({
8092         DEBUG_RExC_seen();
8093         Perl_re_printf( aTHX_ "Final program:\n");
8094         regdump(RExC_rx);
8095     });
8096
8097     if (RExC_open_parens) {
8098         Safefree(RExC_open_parens);
8099         RExC_open_parens = NULL;
8100     }
8101     if (RExC_close_parens) {
8102         Safefree(RExC_close_parens);
8103         RExC_close_parens = NULL;
8104     }
8105
8106 #ifdef USE_ITHREADS
8107     /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8108      * by setting the regexp SV to readonly-only instead. If the
8109      * pattern's been recompiled, the USEDness should remain. */
8110     if (old_re && SvREADONLY(old_re))
8111         SvREADONLY_on(Rx);
8112 #endif
8113     return Rx;
8114 }
8115
8116
8117 SV*
8118 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8119                     const U32 flags)
8120 {
8121     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8122
8123     PERL_UNUSED_ARG(value);
8124
8125     if (flags & RXapif_FETCH) {
8126         return reg_named_buff_fetch(rx, key, flags);
8127     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8128         Perl_croak_no_modify();
8129         return NULL;
8130     } else if (flags & RXapif_EXISTS) {
8131         return reg_named_buff_exists(rx, key, flags)
8132             ? &PL_sv_yes
8133             : &PL_sv_no;
8134     } else if (flags & RXapif_REGNAMES) {
8135         return reg_named_buff_all(rx, flags);
8136     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8137         return reg_named_buff_scalar(rx, flags);
8138     } else {
8139         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8140         return NULL;
8141     }
8142 }
8143
8144 SV*
8145 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8146                          const U32 flags)
8147 {
8148     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8149     PERL_UNUSED_ARG(lastkey);
8150
8151     if (flags & RXapif_FIRSTKEY)
8152         return reg_named_buff_firstkey(rx, flags);
8153     else if (flags & RXapif_NEXTKEY)
8154         return reg_named_buff_nextkey(rx, flags);
8155     else {
8156         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8157                                             (int)flags);
8158         return NULL;
8159     }
8160 }
8161
8162 SV*
8163 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8164                           const U32 flags)
8165 {
8166     SV *ret;
8167     struct regexp *const rx = ReANY(r);
8168
8169     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8170
8171     if (rx && RXp_PAREN_NAMES(rx)) {
8172         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8173         if (he_str) {
8174             IV i;
8175             SV* sv_dat=HeVAL(he_str);
8176             I32 *nums=(I32*)SvPVX(sv_dat);
8177             AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8178             for ( i=0; i<SvIVX(sv_dat); i++ ) {
8179                 if ((I32)(rx->nparens) >= nums[i]
8180                     && rx->offs[nums[i]].start != -1
8181                     && rx->offs[nums[i]].end != -1)
8182                 {
8183                     ret = newSVpvs("");
8184                     CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8185                     if (!retarray)
8186                         return ret;
8187                 } else {
8188                     if (retarray)
8189                         ret = newSVsv(&PL_sv_undef);
8190                 }
8191                 if (retarray)
8192                     av_push(retarray, ret);
8193             }
8194             if (retarray)
8195                 return newRV_noinc(MUTABLE_SV(retarray));
8196         }
8197     }
8198     return NULL;
8199 }
8200
8201 bool
8202 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8203                            const U32 flags)
8204 {
8205     struct regexp *const rx = ReANY(r);
8206
8207     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8208
8209     if (rx && RXp_PAREN_NAMES(rx)) {
8210         if (flags & RXapif_ALL) {
8211             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8212         } else {
8213             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8214             if (sv) {
8215                 SvREFCNT_dec_NN(sv);
8216                 return TRUE;
8217             } else {
8218                 return FALSE;
8219             }
8220         }
8221     } else {
8222         return FALSE;
8223     }
8224 }
8225
8226 SV*
8227 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8228 {
8229     struct regexp *const rx = ReANY(r);
8230
8231     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8232
8233     if ( rx && RXp_PAREN_NAMES(rx) ) {
8234         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8235
8236         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8237     } else {
8238         return FALSE;
8239     }
8240 }
8241
8242 SV*
8243 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8244 {
8245     struct regexp *const rx = ReANY(r);
8246     GET_RE_DEBUG_FLAGS_DECL;
8247
8248     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8249
8250     if (rx && RXp_PAREN_NAMES(rx)) {
8251         HV *hv = RXp_PAREN_NAMES(rx);
8252         HE *temphe;
8253         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8254             IV i;
8255             IV parno = 0;
8256             SV* sv_dat = HeVAL(temphe);
8257             I32 *nums = (I32*)SvPVX(sv_dat);
8258             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8259                 if ((I32)(rx->lastparen) >= nums[i] &&
8260                     rx->offs[nums[i]].start != -1 &&
8261                     rx->offs[nums[i]].end != -1)
8262                 {
8263                     parno = nums[i];
8264                     break;
8265                 }
8266             }
8267             if (parno || flags & RXapif_ALL) {
8268                 return newSVhek(HeKEY_hek(temphe));
8269             }
8270         }
8271     }
8272     return NULL;
8273 }
8274
8275 SV*
8276 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8277 {
8278     SV *ret;
8279     AV *av;
8280     SSize_t length;
8281     struct regexp *const rx = ReANY(r);
8282
8283     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8284
8285     if (rx && RXp_PAREN_NAMES(rx)) {
8286         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8287             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8288         } else if (flags & RXapif_ONE) {
8289             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8290             av = MUTABLE_AV(SvRV(ret));
8291             length = av_tindex(av);
8292             SvREFCNT_dec_NN(ret);
8293             return newSViv(length + 1);
8294         } else {
8295             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8296                                                 (int)flags);
8297             return NULL;
8298         }
8299     }
8300     return &PL_sv_undef;
8301 }
8302
8303 SV*
8304 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8305 {
8306     struct regexp *const rx = ReANY(r);
8307     AV *av = newAV();
8308
8309     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8310
8311     if (rx && RXp_PAREN_NAMES(rx)) {
8312         HV *hv= RXp_PAREN_NAMES(rx);
8313         HE *temphe;
8314         (void)hv_iterinit(hv);
8315         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8316             IV i;
8317             IV parno = 0;
8318             SV* sv_dat = HeVAL(temphe);
8319             I32 *nums = (I32*)SvPVX(sv_dat);
8320             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8321                 if ((I32)(rx->lastparen) >= nums[i] &&
8322                     rx->offs[nums[i]].start != -1 &&
8323                     rx->offs[nums[i]].end != -1)
8324                 {
8325                     parno = nums[i];
8326                     break;
8327                 }
8328             }
8329             if (parno || flags & RXapif_ALL) {
8330                 av_push(av, newSVhek(HeKEY_hek(temphe)));
8331             }
8332         }
8333     }
8334
8335     return newRV_noinc(MUTABLE_SV(av));
8336 }
8337
8338 void
8339 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8340                              SV * const sv)
8341 {
8342     struct regexp *const rx = ReANY(r);
8343     char *s = NULL;
8344     SSize_t i = 0;
8345     SSize_t s1, t1;
8346     I32 n = paren;
8347
8348     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8349
8350     if (      n == RX_BUFF_IDX_CARET_PREMATCH
8351            || n == RX_BUFF_IDX_CARET_FULLMATCH
8352            || n == RX_BUFF_IDX_CARET_POSTMATCH
8353        )
8354     {
8355         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8356         if (!keepcopy) {
8357             /* on something like
8358              *    $r = qr/.../;
8359              *    /$qr/p;
8360              * the KEEPCOPY is set on the PMOP rather than the regex */
8361             if (PL_curpm && r == PM_GETRE(PL_curpm))
8362                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8363         }
8364         if (!keepcopy)
8365             goto ret_undef;
8366     }
8367
8368     if (!rx->subbeg)
8369         goto ret_undef;
8370
8371     if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8372         /* no need to distinguish between them any more */
8373         n = RX_BUFF_IDX_FULLMATCH;
8374
8375     if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8376         && rx->offs[0].start != -1)
8377     {
8378         /* $`, ${^PREMATCH} */
8379         i = rx->offs[0].start;
8380         s = rx->subbeg;
8381     }
8382     else
8383     if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8384         && rx->offs[0].end != -1)
8385     {
8386         /* $', ${^POSTMATCH} */
8387         s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8388         i = rx->sublen + rx->suboffset - rx->offs[0].end;
8389     }
8390     else
8391     if ( 0 <= n && n <= (I32)rx->nparens &&
8392         (s1 = rx->offs[n].start) != -1 &&
8393         (t1 = rx->offs[n].end) != -1)
8394     {
8395         /* $&, ${^MATCH},  $1 ... */
8396         i = t1 - s1;
8397         s = rx->subbeg + s1 - rx->suboffset;
8398     } else {
8399         goto ret_undef;
8400     }
8401
8402     assert(s >= rx->subbeg);
8403     assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8404     if (i >= 0) {
8405 #ifdef NO_TAINT_SUPPORT
8406         sv_setpvn(sv, s, i);
8407 #else
8408         const int oldtainted = TAINT_get;
8409         TAINT_NOT;
8410         sv_setpvn(sv, s, i);
8411         TAINT_set(oldtainted);
8412 #endif
8413         if (RXp_MATCH_UTF8(rx))
8414             SvUTF8_on(sv);
8415         else
8416             SvUTF8_off(sv);
8417         if (TAINTING_get) {
8418             if (RXp_MATCH_TAINTED(rx)) {
8419                 if (SvTYPE(sv) >= SVt_PVMG) {
8420                     MAGIC* const mg = SvMAGIC(sv);
8421                     MAGIC* mgt;
8422                     TAINT;
8423                     SvMAGIC_set(sv, mg->mg_moremagic);
8424                     SvTAINT(sv);
8425                     if ((mgt = SvMAGIC(sv))) {
8426                         mg->mg_moremagic = mgt;
8427                         SvMAGIC_set(sv, mg);
8428                     }
8429                 } else {
8430                     TAINT;
8431                     SvTAINT(sv);
8432                 }
8433             } else
8434                 SvTAINTED_off(sv);
8435         }
8436     } else {
8437       ret_undef:
8438         sv_set_undef(sv);
8439         return;
8440     }
8441 }
8442
8443 void
8444 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8445                                                          SV const * const value)
8446 {
8447     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8448
8449     PERL_UNUSED_ARG(rx);
8450     PERL_UNUSED_ARG(paren);
8451     PERL_UNUSED_ARG(value);
8452
8453     if (!PL_localizing)
8454         Perl_croak_no_modify();
8455 }
8456
8457 I32
8458 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8459                               const I32 paren)
8460 {
8461     struct regexp *const rx = ReANY(r);
8462     I32 i;
8463     I32 s1, t1;
8464
8465     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8466
8467     if (   paren == RX_BUFF_IDX_CARET_PREMATCH
8468         || paren == RX_BUFF_IDX_CARET_FULLMATCH
8469         || paren == RX_BUFF_IDX_CARET_POSTMATCH
8470     )
8471     {
8472         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8473         if (!keepcopy) {
8474             /* on something like
8475              *    $r = qr/.../;
8476              *    /$qr/p;
8477              * the KEEPCOPY is set on the PMOP rather than the regex */
8478             if (PL_curpm && r == PM_GETRE(PL_curpm))
8479                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8480         }
8481         if (!keepcopy)
8482             goto warn_undef;
8483     }
8484
8485     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8486     switch (paren) {
8487       case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8488       case RX_BUFF_IDX_PREMATCH:       /* $` */
8489         if (rx->offs[0].start != -1) {
8490                         i = rx->offs[0].start;
8491                         if (i > 0) {
8492                                 s1 = 0;
8493                                 t1 = i;
8494                                 goto getlen;
8495                         }
8496             }
8497         return 0;
8498
8499       case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8500       case RX_BUFF_IDX_POSTMATCH:       /* $' */
8501             if (rx->offs[0].end != -1) {
8502                         i = rx->sublen - rx->offs[0].end;
8503                         if (i > 0) {
8504                                 s1 = rx->offs[0].end;
8505                                 t1 = rx->sublen;
8506                                 goto getlen;
8507                         }
8508             }
8509         return 0;
8510
8511       default: /* $& / ${^MATCH}, $1, $2, ... */
8512             if (paren <= (I32)rx->nparens &&
8513             (s1 = rx->offs[paren].start) != -1 &&
8514             (t1 = rx->offs[paren].end) != -1)
8515             {
8516             i = t1 - s1;
8517             goto getlen;
8518         } else {
8519           warn_undef:
8520             if (ckWARN(WARN_UNINITIALIZED))
8521                 report_uninit((const SV *)sv);
8522             return 0;
8523         }
8524     }
8525   getlen:
8526     if (i > 0 && RXp_MATCH_UTF8(rx)) {
8527         const char * const s = rx->subbeg - rx->suboffset + s1;
8528         const U8 *ep;
8529         STRLEN el;
8530
8531         i = t1 - s1;
8532         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8533                         i = el;
8534     }
8535     return i;
8536 }
8537
8538 SV*
8539 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8540 {
8541     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8542         PERL_UNUSED_ARG(rx);
8543         if (0)
8544             return NULL;
8545         else
8546             return newSVpvs("Regexp");
8547 }
8548
8549 /* Scans the name of a named buffer from the pattern.
8550  * If flags is REG_RSN_RETURN_NULL returns null.
8551  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8552  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8553  * to the parsed name as looked up in the RExC_paren_names hash.
8554  * If there is an error throws a vFAIL().. type exception.
8555  */
8556
8557 #define REG_RSN_RETURN_NULL    0
8558 #define REG_RSN_RETURN_NAME    1
8559 #define REG_RSN_RETURN_DATA    2
8560
8561 STATIC SV*
8562 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8563 {
8564     char *name_start = RExC_parse;
8565     SV* sv_name;
8566
8567     PERL_ARGS_ASSERT_REG_SCAN_NAME;
8568
8569     assert (RExC_parse <= RExC_end);
8570     if (RExC_parse == RExC_end) NOOP;
8571     else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
8572          /* Note that the code here assumes well-formed UTF-8.  Skip IDFIRST by
8573           * using do...while */
8574         if (UTF)
8575             do {
8576                 RExC_parse += UTF8SKIP(RExC_parse);
8577             } while (   RExC_parse < RExC_end
8578                      && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
8579         else
8580             do {
8581                 RExC_parse++;
8582             } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
8583     } else {
8584         RExC_parse++; /* so the <- from the vFAIL is after the offending
8585                          character */
8586         vFAIL("Group name must start with a non-digit word character");
8587     }
8588     sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8589                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8590     if ( flags == REG_RSN_RETURN_NAME)
8591         return sv_name;
8592     else if (flags==REG_RSN_RETURN_DATA) {
8593         HE *he_str = NULL;
8594         SV *sv_dat = NULL;
8595         if ( ! sv_name )      /* should not happen*/
8596             Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8597         if (RExC_paren_names)
8598             he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8599         if ( he_str )
8600             sv_dat = HeVAL(he_str);
8601         if ( ! sv_dat ) {   /* Didn't find group */
8602
8603             /* It might be a forward reference; we can't fail until we
8604                 * know, by completing the parse to get all the groups, and
8605                 * then reparsing */
8606             if (RExC_total_parens > 0)  {
8607                 vFAIL("Reference to nonexistent named group");
8608             }
8609             else {
8610                 REQUIRE_PARENS_PASS;
8611             }
8612         }
8613         return sv_dat;
8614     }
8615
8616     Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8617                      (unsigned long) flags);
8618 }
8619
8620 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
8621     int num;                                                    \
8622     if (RExC_lastparse!=RExC_parse) {                           \
8623         Perl_re_printf( aTHX_  "%s",                            \
8624             Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse,        \
8625                 RExC_end - RExC_parse, 16,                      \
8626                 "", "",                                         \
8627                 PERL_PV_ESCAPE_UNI_DETECT |                     \
8628                 PERL_PV_PRETTY_ELLIPSES   |                     \
8629                 PERL_PV_PRETTY_LTGT       |                     \
8630                 PERL_PV_ESCAPE_RE         |                     \
8631                 PERL_PV_PRETTY_EXACTSIZE                        \
8632             )                                                   \
8633         );                                                      \
8634     } else                                                      \
8635         Perl_re_printf( aTHX_ "%16s","");                       \
8636                                                                 \
8637     num=REG_NODE_NUM(REGNODE_p(RExC_emit));                     \
8638     if (RExC_lastnum!=num)                                      \
8639        Perl_re_printf( aTHX_ "|%4d", num);                      \
8640     else                                                        \
8641        Perl_re_printf( aTHX_ "|%4s","");                        \
8642     Perl_re_printf( aTHX_ "|%*s%-4s",                           \
8643         (int)((depth*2)), "",                                   \
8644         (funcname)                                              \
8645     );                                                          \
8646     RExC_lastnum=num;                                           \
8647     RExC_lastparse=RExC_parse;                                  \
8648 })
8649
8650
8651
8652 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
8653     DEBUG_PARSE_MSG((funcname));                            \
8654     Perl_re_printf( aTHX_ "%4s","\n");                                  \
8655 })
8656 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({\
8657     DEBUG_PARSE_MSG((funcname));                            \
8658     Perl_re_printf( aTHX_ fmt "\n",args);                               \
8659 })
8660
8661 /* This section of code defines the inversion list object and its methods.  The
8662  * interfaces are highly subject to change, so as much as possible is static to
8663  * this file.  An inversion list is here implemented as a malloc'd C UV array
8664  * as an SVt_INVLIST scalar.
8665  *
8666  * An inversion list for Unicode is an array of code points, sorted by ordinal
8667  * number.  Each element gives the code point that begins a range that extends
8668  * up-to but not including the code point given by the next element.  The final
8669  * element gives the first code point of a range that extends to the platform's
8670  * infinity.  The even-numbered elements (invlist[0], invlist[2], invlist[4],
8671  * ...) give ranges whose code points are all in the inversion list.  We say
8672  * that those ranges are in the set.  The odd-numbered elements give ranges
8673  * whose code points are not in the inversion list, and hence not in the set.
8674  * Thus, element [0] is the first code point in the list.  Element [1]
8675  * is the first code point beyond that not in the list; and element [2] is the
8676  * first code point beyond that that is in the list.  In other words, the first
8677  * range is invlist[0]..(invlist[1]-1), and all code points in that range are
8678  * in the inversion list.  The second range is invlist[1]..(invlist[2]-1), and
8679  * all code points in that range are not in the inversion list.  The third
8680  * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
8681  * list, and so forth.  Thus every element whose index is divisible by two
8682  * gives the beginning of a range that is in the list, and every element whose
8683  * index is not divisible by two gives the beginning of a range not in the
8684  * list.  If the final element's index is divisible by two, the inversion list
8685  * extends to the platform's infinity; otherwise the highest code point in the
8686  * inversion list is the contents of that element minus 1.
8687  *
8688  * A range that contains just a single code point N will look like
8689  *  invlist[i]   == N
8690  *  invlist[i+1] == N+1
8691  *
8692  * If N is UV_MAX (the highest representable code point on the machine), N+1 is
8693  * impossible to represent, so element [i+1] is omitted.  The single element
8694  * inversion list
8695  *  invlist[0] == UV_MAX
8696  * contains just UV_MAX, but is interpreted as matching to infinity.
8697  *
8698  * Taking the complement (inverting) an inversion list is quite simple, if the
8699  * first element is 0, remove it; otherwise add a 0 element at the beginning.
8700  * This implementation reserves an element at the beginning of each inversion
8701  * list to always contain 0; there is an additional flag in the header which
8702  * indicates if the list begins at the 0, or is offset to begin at the next
8703  * element.  This means that the inversion list can be inverted without any
8704  * copying; just flip the flag.
8705  *
8706  * More about inversion lists can be found in "Unicode Demystified"
8707  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
8708  *
8709  * The inversion list data structure is currently implemented as an SV pointing
8710  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
8711  * array of UV whose memory management is automatically handled by the existing
8712  * facilities for SV's.
8713  *
8714  * Some of the methods should always be private to the implementation, and some
8715  * should eventually be made public */
8716
8717 /* The header definitions are in F<invlist_inline.h> */
8718
8719 #ifndef PERL_IN_XSUB_RE
8720
8721 PERL_STATIC_INLINE UV*
8722 S__invlist_array_init(SV* const invlist, const bool will_have_0)
8723 {
8724     /* Returns a pointer to the first element in the inversion list's array.
8725      * This is called upon initialization of an inversion list.  Where the
8726      * array begins depends on whether the list has the code point U+0000 in it
8727      * or not.  The other parameter tells it whether the code that follows this
8728      * call is about to put a 0 in the inversion list or not.  The first
8729      * element is either the element reserved for 0, if TRUE, or the element
8730      * after it, if FALSE */
8731
8732     bool* offset = get_invlist_offset_addr(invlist);
8733     UV* zero_addr = (UV *) SvPVX(invlist);
8734
8735     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
8736
8737     /* Must be empty */
8738     assert(! _invlist_len(invlist));
8739
8740     *zero_addr = 0;
8741
8742     /* 1^1 = 0; 1^0 = 1 */
8743     *offset = 1 ^ will_have_0;
8744     return zero_addr + *offset;
8745 }
8746
8747 PERL_STATIC_INLINE void
8748 S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
8749 {
8750     /* Sets the current number of elements stored in the inversion list.
8751      * Updates SvCUR correspondingly */
8752     PERL_UNUSED_CONTEXT;
8753     PERL_ARGS_ASSERT_INVLIST_SET_LEN;
8754
8755     assert(is_invlist(invlist));
8756
8757     SvCUR_set(invlist,
8758               (len == 0)
8759                ? 0
8760                : TO_INTERNAL_SIZE(len + offset));
8761     assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
8762 }
8763
8764 STATIC void
8765 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
8766 {
8767     /* Replaces the inversion list in 'dest' with the one from 'src'.  It
8768      * steals the list from 'src', so 'src' is made to have a NULL list.  This
8769      * is similar to what SvSetMagicSV() would do, if it were implemented on
8770      * inversion lists, though this routine avoids a copy */
8771
8772     const UV src_len          = _invlist_len(src);
8773     const bool src_offset     = *get_invlist_offset_addr(src);
8774     const STRLEN src_byte_len = SvLEN(src);
8775     char * array              = SvPVX(src);
8776
8777     const int oldtainted = TAINT_get;
8778
8779     PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
8780
8781     assert(is_invlist(src));
8782     assert(is_invlist(dest));
8783     assert(! invlist_is_iterating(src));
8784     assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
8785
8786     /* Make sure it ends in the right place with a NUL, as our inversion list
8787      * manipulations aren't careful to keep this true, but sv_usepvn_flags()
8788      * asserts it */
8789     array[src_byte_len - 1] = '\0';
8790
8791     TAINT_NOT;      /* Otherwise it breaks */
8792     sv_usepvn_flags(dest,
8793                     (char *) array,
8794                     src_byte_len - 1,
8795
8796                     /* This flag is documented to cause a copy to be avoided */
8797                     SV_HAS_TRAILING_NUL);
8798     TAINT_set(oldtainted);
8799     SvPV_set(src, 0);
8800     SvLEN_set(src, 0);
8801     SvCUR_set(src, 0);
8802
8803     /* Finish up copying over the other fields in an inversion list */
8804     *get_invlist_offset_addr(dest) = src_offset;
8805     invlist_set_len(dest, src_len, src_offset);
8806     *get_invlist_previous_index_addr(dest) = 0;
8807     invlist_iterfinish(dest);
8808 }
8809
8810 PERL_STATIC_INLINE IV*
8811 S_get_invlist_previous_index_addr(SV* invlist)
8812 {
8813     /* Return the address of the IV that is reserved to hold the cached index
8814      * */
8815     PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
8816
8817     assert(is_invlist(invlist));
8818
8819     return &(((XINVLIST*) SvANY(invlist))->prev_index);
8820 }
8821
8822 PERL_STATIC_INLINE IV
8823 S_invlist_previous_index(SV* const invlist)
8824 {
8825     /* Returns cached index of previous search */
8826
8827     PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
8828
8829     return *get_invlist_previous_index_addr(invlist);
8830 }
8831
8832 PERL_STATIC_INLINE void
8833 S_invlist_set_previous_index(SV* const invlist, const IV index)
8834 {
8835     /* Caches <index> for later retrieval */
8836
8837     PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
8838
8839     assert(index == 0 || index < (int) _invlist_len(invlist));
8840
8841     *get_invlist_previous_index_addr(invlist) = index;
8842 }
8843
8844 PERL_STATIC_INLINE void
8845 S_invlist_trim(SV* invlist)
8846 {
8847     /* Free the not currently-being-used space in an inversion list */
8848
8849     /* But don't free up the space needed for the 0 UV that is always at the
8850      * beginning of the list, nor the trailing NUL */
8851     const UV min_size = TO_INTERNAL_SIZE(1) + 1;
8852
8853     PERL_ARGS_ASSERT_INVLIST_TRIM;
8854
8855     assert(is_invlist(invlist));
8856
8857     SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
8858 }
8859
8860 PERL_STATIC_INLINE void
8861 S_invlist_clear(pTHX_ SV* invlist)    /* Empty the inversion list */
8862 {
8863     PERL_ARGS_ASSERT_INVLIST_CLEAR;
8864
8865     assert(is_invlist(invlist));
8866
8867     invlist_set_len(invlist, 0, 0);
8868     invlist_trim(invlist);
8869 }
8870
8871 #endif /* ifndef PERL_IN_XSUB_RE */
8872
8873 PERL_STATIC_INLINE bool
8874 S_invlist_is_iterating(SV* const invlist)
8875 {
8876     PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
8877
8878     return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
8879 }
8880
8881 #ifndef PERL_IN_XSUB_RE
8882
8883 PERL_STATIC_INLINE UV
8884 S_invlist_max(SV* const invlist)
8885 {
8886     /* Returns the maximum number of elements storable in the inversion list's
8887      * array, without having to realloc() */
8888
8889     PERL_ARGS_ASSERT_INVLIST_MAX;
8890
8891     assert(is_invlist(invlist));
8892
8893     /* Assumes worst case, in which the 0 element is not counted in the
8894      * inversion list, so subtracts 1 for that */
8895     return SvLEN(invlist) == 0  /* This happens under _new_invlist_C_array */
8896            ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
8897            : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
8898 }
8899
8900 STATIC void
8901 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
8902 {
8903     PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
8904
8905     /* First 1 is in case the zero element isn't in the list; second 1 is for
8906      * trailing NUL */
8907     SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
8908     invlist_set_len(invlist, 0, 0);
8909
8910     /* Force iterinit() to be used to get iteration to work */
8911     invlist_iterfinish(invlist);
8912
8913     *get_invlist_previous_index_addr(invlist) = 0;
8914 }
8915
8916 SV*
8917 Perl__new_invlist(pTHX_ IV initial_size)
8918 {
8919
8920     /* Return a pointer to a newly constructed inversion list, with enough
8921      * space to store 'initial_size' elements.  If that number is negative, a
8922      * system default is used instead */
8923
8924     SV* new_list;
8925
8926     if (initial_size < 0) {
8927         initial_size = 10;
8928     }
8929
8930     /* Allocate the initial space */
8931     new_list = newSV_type(SVt_INVLIST);
8932
8933     initialize_invlist_guts(new_list, initial_size);
8934
8935     return new_list;
8936 }
8937
8938 SV*
8939 Perl__new_invlist_C_array(pTHX_ const UV* const list)
8940 {
8941     /* Return a pointer to a newly constructed inversion list, initialized to
8942      * point to <list>, which has to be in the exact correct inversion list
8943      * form, including internal fields.  Thus this is a dangerous routine that
8944      * should not be used in the wrong hands.  The passed in 'list' contains
8945      * several header fields at the beginning that are not part of the
8946      * inversion list body proper */
8947
8948     const STRLEN length = (STRLEN) list[0];
8949     const UV version_id =          list[1];
8950     const bool offset   =    cBOOL(list[2]);
8951 #define HEADER_LENGTH 3
8952     /* If any of the above changes in any way, you must change HEADER_LENGTH
8953      * (if appropriate) and regenerate INVLIST_VERSION_ID by running
8954      *      perl -E 'say int(rand 2**31-1)'
8955      */
8956 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
8957                                         data structure type, so that one being
8958                                         passed in can be validated to be an
8959                                         inversion list of the correct vintage.
8960                                        */
8961
8962     SV* invlist = newSV_type(SVt_INVLIST);
8963
8964     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
8965
8966     if (version_id != INVLIST_VERSION_ID) {
8967         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
8968     }
8969
8970     /* The generated array passed in includes header elements that aren't part
8971      * of the list proper, so start it just after them */
8972     SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
8973
8974     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
8975                                shouldn't touch it */
8976
8977     *(get_invlist_offset_addr(invlist)) = offset;
8978
8979     /* The 'length' passed to us is the physical number of elements in the
8980      * inversion list.  But if there is an offset the logical number is one
8981      * less than that */
8982     invlist_set_len(invlist, length  - offset, offset);
8983
8984     invlist_set_previous_index(invlist, 0);
8985
8986     /* Initialize the iteration pointer. */
8987     invlist_iterfinish(invlist);
8988
8989     SvREADONLY_on(invlist);
8990
8991     return invlist;
8992 }
8993
8994 STATIC void
8995 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
8996 {
8997     /* Grow the maximum size of an inversion list */
8998
8999     PERL_ARGS_ASSERT_INVLIST_EXTEND;
9000
9001     assert(is_invlist(invlist));
9002
9003     /* Add one to account for the zero element at the beginning which may not
9004      * be counted by the calling parameters */
9005     SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
9006 }
9007
9008 STATIC void
9009 S__append_range_to_invlist(pTHX_ SV* const invlist,
9010                                  const UV start, const UV end)
9011 {
9012    /* Subject to change or removal.  Append the range from 'start' to 'end' at
9013     * the end of the inversion list.  The range must be above any existing
9014     * ones. */
9015
9016     UV* array;
9017     UV max = invlist_max(invlist);
9018     UV len = _invlist_len(invlist);
9019     bool offset;
9020
9021     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9022
9023     if (len == 0) { /* Empty lists must be initialized */
9024         offset = start != 0;
9025         array = _invlist_array_init(invlist, ! offset);
9026     }
9027     else {
9028         /* Here, the existing list is non-empty. The current max entry in the
9029          * list is generally the first value not in the set, except when the
9030          * set extends to the end of permissible values, in which case it is
9031          * the first entry in that final set, and so this call is an attempt to
9032          * append out-of-order */
9033
9034         UV final_element = len - 1;
9035         array = invlist_array(invlist);
9036         if (   array[final_element] > start
9037             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9038         {
9039             Perl_croak(aTHX_ "panic: attempting to append to an inversion list, but wasn't at the end of the list, final=%" UVuf ", start=%" UVuf ", match=%c",
9040                      array[final_element], start,
9041                      ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9042         }
9043
9044         /* Here, it is a legal append.  If the new range begins 1 above the end
9045          * of the range below it, it is extending the range below it, so the
9046          * new first value not in the set is one greater than the newly
9047          * extended range.  */
9048         offset = *get_invlist_offset_addr(invlist);
9049         if (array[final_element] == start) {
9050             if (end != UV_MAX) {
9051                 array[final_element] = end + 1;
9052             }
9053             else {
9054                 /* But if the end is the maximum representable on the machine,
9055                  * assume that infinity was actually what was meant.  Just let
9056                  * the range that this would extend to have no end */
9057                 invlist_set_len(invlist, len - 1, offset);
9058             }
9059             return;
9060         }
9061     }
9062
9063     /* Here the new range doesn't extend any existing set.  Add it */
9064
9065     len += 2;   /* Includes an element each for the start and end of range */
9066
9067     /* If wll overflow the existing space, extend, which may cause the array to
9068      * be moved */
9069     if (max < len) {
9070         invlist_extend(invlist, len);
9071
9072         /* Have to set len here to avoid assert failure in invlist_array() */
9073         invlist_set_len(invlist, len, offset);
9074
9075         array = invlist_array(invlist);
9076     }
9077     else {
9078         invlist_set_len(invlist, len, offset);
9079     }
9080
9081     /* The next item on the list starts the range, the one after that is
9082      * one past the new range.  */
9083     array[len - 2] = start;
9084     if (end != UV_MAX) {
9085         array[len - 1] = end + 1;
9086     }
9087     else {
9088         /* But if the end is the maximum representable on the machine, just let
9089          * the range have no end */
9090         invlist_set_len(invlist, len - 1, offset);
9091     }
9092 }
9093
9094 SSize_t
9095 Perl__invlist_search(SV* const invlist, const UV cp)
9096 {
9097     /* Searches the inversion list for the entry that contains the input code
9098      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
9099      * return value is the index into the list's array of the range that
9100      * contains <cp>, that is, 'i' such that
9101      *  array[i] <= cp < array[i+1]
9102      */
9103
9104     IV low = 0;
9105     IV mid;
9106     IV high = _invlist_len(invlist);
9107     const IV highest_element = high - 1;
9108     const UV* array;
9109
9110     PERL_ARGS_ASSERT__INVLIST_SEARCH;
9111
9112     /* If list is empty, return failure. */
9113     if (high == 0) {
9114         return -1;
9115     }
9116
9117     /* (We can't get the array unless we know the list is non-empty) */
9118     array = invlist_array(invlist);
9119
9120     mid = invlist_previous_index(invlist);
9121     assert(mid >=0);
9122     if (mid > highest_element) {
9123         mid = highest_element;
9124     }
9125
9126     /* <mid> contains the cache of the result of the previous call to this
9127      * function (0 the first time).  See if this call is for the same result,
9128      * or if it is for mid-1.  This is under the theory that calls to this
9129      * function will often be for related code points that are near each other.
9130      * And benchmarks show that caching gives better results.  We also test
9131      * here if the code point is within the bounds of the list.  These tests
9132      * replace others that would have had to be made anyway to make sure that
9133      * the array bounds were not exceeded, and these give us extra information
9134      * at the same time */
9135     if (cp >= array[mid]) {
9136         if (cp >= array[highest_element]) {
9137             return highest_element;
9138         }
9139
9140         /* Here, array[mid] <= cp < array[highest_element].  This means that
9141          * the final element is not the answer, so can exclude it; it also
9142          * means that <mid> is not the final element, so can refer to 'mid + 1'
9143          * safely */
9144         if (cp < array[mid + 1]) {
9145             return mid;
9146         }
9147         high--;
9148         low = mid + 1;
9149     }
9150     else { /* cp < aray[mid] */
9151         if (cp < array[0]) { /* Fail if outside the array */
9152             return -1;
9153         }
9154         high = mid;
9155         if (cp >= array[mid - 1]) {
9156             goto found_entry;
9157         }
9158     }
9159
9160     /* Binary search.  What we are looking for is <i> such that
9161      *  array[i] <= cp < array[i+1]
9162      * The loop below converges on the i+1.  Note that there may not be an
9163      * (i+1)th element in the array, and things work nonetheless */
9164     while (low < high) {
9165         mid = (low + high) / 2;
9166         assert(mid <= highest_element);
9167         if (array[mid] <= cp) { /* cp >= array[mid] */
9168             low = mid + 1;
9169
9170             /* We could do this extra test to exit the loop early.
9171             if (cp < array[low]) {
9172                 return mid;
9173             }
9174             */
9175         }
9176         else { /* cp < array[mid] */
9177             high = mid;
9178         }
9179     }
9180
9181   found_entry:
9182     high--;
9183     invlist_set_previous_index(invlist, high);
9184     return high;
9185 }
9186
9187 void
9188 Perl__invlist_populate_swatch(SV* const invlist,
9189                               const UV start, const UV end, U8* swatch)
9190 {
9191     /* populates a swatch of a swash the same way swatch_get() does in utf8.c,
9192      * but is used when the swash has an inversion list.  This makes this much
9193      * faster, as it uses a binary search instead of a linear one.  This is
9194      * intimately tied to that function, and perhaps should be in utf8.c,
9195      * except it is intimately tied to inversion lists as well.  It assumes
9196      * that <swatch> is all 0's on input */
9197
9198     UV current = start;
9199     const IV len = _invlist_len(invlist);
9200     IV i;
9201     const UV * array;
9202
9203     PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
9204
9205     if (len == 0) { /* Empty inversion list */
9206         return;
9207     }
9208
9209     array = invlist_array(invlist);
9210
9211     /* Find which element it is */
9212     i = _invlist_search(invlist, start);
9213
9214     /* We populate from <start> to <end> */
9215     while (current < end) {
9216         UV upper;
9217
9218         /* The inversion list gives the results for every possible code point
9219          * after the first one in the list.  Only those ranges whose index is
9220          * even are ones that the inversion list matches.  For the odd ones,
9221          * and if the initial code point is not in the list, we have to skip
9222          * forward to the next element */
9223         if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
9224             i++;
9225             if (i >= len) { /* Finished if beyond the end of the array */
9226                 return;
9227             }
9228             current = array[i];
9229             if (current >= end) {   /* Finished if beyond the end of what we
9230                                        are populating */
9231                 if (LIKELY(end < UV_MAX)) {
9232                     return;
9233                 }
9234
9235                 /* We get here when the upper bound is the maximum
9236                  * representable on the machine, and we are looking for just
9237                  * that code point.  Have to special case it */
9238                 i = len;
9239                 goto join_end_of_list;
9240             }
9241         }
9242         assert(current >= start);
9243
9244         /* The current range ends one below the next one, except don't go past
9245          * <end> */
9246         i++;
9247         upper = (i < len && array[i] < end) ? array[i] : end;
9248
9249         /* Here we are in a range that matches.  Populate a bit in the 3-bit U8
9250          * for each code point in it */
9251         for (; current < upper; current++) {
9252             const STRLEN offset = (STRLEN)(current - start);
9253             swatch[offset >> 3] |= 1 << (offset & 7);
9254         }
9255
9256       join_end_of_list:
9257
9258         /* Quit if at the end of the list */
9259         if (i >= len) {
9260
9261             /* But first, have to deal with the highest possible code point on
9262              * the platform.  The previous code assumes that <end> is one
9263              * beyond where we want to populate, but that is impossible at the
9264              * platform's infinity, so have to handle it specially */
9265             if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
9266             {
9267                 const STRLEN offset = (STRLEN)(end - start);
9268                 swatch[offset >> 3] |= 1 << (offset & 7);
9269             }
9270             return;
9271         }
9272
9273         /* Advance to the next range, which will be for code points not in the
9274          * inversion list */
9275         current = array[i];
9276     }
9277
9278     return;
9279 }
9280
9281 void
9282 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9283                                          const bool complement_b, SV** output)
9284 {
9285     /* Take the union of two inversion lists and point '*output' to it.  On
9286      * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9287      * even 'a' or 'b').  If to an inversion list, the contents of the original
9288      * list will be replaced by the union.  The first list, 'a', may be
9289      * NULL, in which case a copy of the second list is placed in '*output'.
9290      * If 'complement_b' is TRUE, the union is taken of the complement
9291      * (inversion) of 'b' instead of b itself.
9292      *
9293      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9294      * Richard Gillam, published by Addison-Wesley, and explained at some
9295      * length there.  The preface says to incorporate its examples into your
9296      * code at your own risk.
9297      *
9298      * The algorithm is like a merge sort. */
9299
9300     const UV* array_a;    /* a's array */
9301     const UV* array_b;
9302     UV len_a;       /* length of a's array */
9303     UV len_b;
9304
9305     SV* u;                      /* the resulting union */
9306     UV* array_u;
9307     UV len_u = 0;
9308
9309     UV i_a = 0;             /* current index into a's array */
9310     UV i_b = 0;
9311     UV i_u = 0;
9312
9313     /* running count, as explained in the algorithm source book; items are
9314      * stopped accumulating and are output when the count changes to/from 0.
9315      * The count is incremented when we start a range that's in an input's set,
9316      * and decremented when we start a range that's not in a set.  So this
9317      * variable can be 0, 1, or 2.  When it is 0 neither input is in their set,
9318      * and hence nothing goes into the union; 1, just one of the inputs is in
9319      * its set (and its current range gets added to the union); and 2 when both
9320      * inputs are in their sets.  */
9321     UV count = 0;
9322
9323     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9324     assert(a != b);
9325     assert(*output == NULL || is_invlist(*output));
9326
9327     len_b = _invlist_len(b);
9328     if (len_b == 0) {
9329
9330         /* Here, 'b' is empty, hence it's complement is all possible code
9331          * points.  So if the union includes the complement of 'b', it includes
9332          * everything, and we need not even look at 'a'.  It's easiest to
9333          * create a new inversion list that matches everything.  */
9334         if (complement_b) {
9335             SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9336
9337             if (*output == NULL) { /* If the output didn't exist, just point it
9338                                       at the new list */
9339                 *output = everything;
9340             }
9341             else { /* Otherwise, replace its contents with the new list */
9342                 invlist_replace_list_destroys_src(*output, everything);
9343                 SvREFCNT_dec_NN(everything);
9344             }
9345
9346             return;
9347         }
9348
9349         /* Here, we don't want the complement of 'b', and since 'b' is empty,
9350          * the union will come entirely from 'a'.  If 'a' is NULL or empty, the
9351          * output will be empty */
9352
9353         if (a == NULL || _invlist_len(a) == 0) {
9354             if (*output == NULL) {
9355                 *output = _new_invlist(0);
9356             }
9357             else {
9358                 invlist_clear(*output);
9359             }
9360             return;
9361         }
9362
9363         /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9364          * union.  We can just return a copy of 'a' if '*output' doesn't point
9365          * to an existing list */
9366         if (*output == NULL) {
9367             *output = invlist_clone(a, NULL);
9368             return;
9369         }
9370
9371         /* If the output is to overwrite 'a', we have a no-op, as it's
9372          * already in 'a' */
9373         if (*output == a) {
9374             return;
9375         }
9376
9377         /* Here, '*output' is to be overwritten by 'a' */
9378         u = invlist_clone(a, NULL);
9379         invlist_replace_list_destroys_src(*output, u);
9380         SvREFCNT_dec_NN(u);
9381
9382         return;
9383     }
9384
9385     /* Here 'b' is not empty.  See about 'a' */
9386
9387     if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9388
9389         /* Here, 'a' is empty (and b is not).  That means the union will come
9390          * entirely from 'b'.  If '*output' is NULL, we can directly return a
9391          * clone of 'b'.  Otherwise, we replace the contents of '*output' with
9392          * the clone */
9393
9394         SV ** dest = (*output == NULL) ? output : &u;
9395         *dest = invlist_clone(b, NULL);
9396         if (complement_b) {
9397             _invlist_invert(*dest);
9398         }
9399
9400         if (dest == &u) {
9401             invlist_replace_list_destroys_src(*output, u);
9402             SvREFCNT_dec_NN(u);
9403         }
9404
9405         return;
9406     }
9407
9408     /* Here both lists exist and are non-empty */
9409     array_a = invlist_array(a);
9410     array_b = invlist_array(b);
9411
9412     /* If are to take the union of 'a' with the complement of b, set it
9413      * up so are looking at b's complement. */
9414     if (complement_b) {
9415
9416         /* To complement, we invert: if the first element is 0, remove it.  To
9417          * do this, we just pretend the array starts one later */
9418         if (array_b[0] == 0) {
9419             array_b++;
9420             len_b--;
9421         }
9422         else {
9423
9424             /* But if the first element is not zero, we pretend the list starts
9425              * at the 0 that is always stored immediately before the array. */
9426             array_b--;
9427             len_b++;
9428         }
9429     }
9430
9431     /* Size the union for the worst case: that the sets are completely
9432      * disjoint */
9433     u = _new_invlist(len_a + len_b);
9434
9435     /* Will contain U+0000 if either component does */
9436     array_u = _invlist_array_init(u, (    len_a > 0 && array_a[0] == 0)
9437                                       || (len_b > 0 && array_b[0] == 0));
9438
9439     /* Go through each input list item by item, stopping when have exhausted
9440      * one of them */
9441     while (i_a < len_a && i_b < len_b) {
9442         UV cp;      /* The element to potentially add to the union's array */
9443         bool cp_in_set;   /* is it in the the input list's set or not */
9444
9445         /* We need to take one or the other of the two inputs for the union.
9446          * Since we are merging two sorted lists, we take the smaller of the
9447          * next items.  In case of a tie, we take first the one that is in its
9448          * set.  If we first took the one not in its set, it would decrement
9449          * the count, possibly to 0 which would cause it to be output as ending
9450          * the range, and the next time through we would take the same number,
9451          * and output it again as beginning the next range.  By doing it the
9452          * opposite way, there is no possibility that the count will be
9453          * momentarily decremented to 0, and thus the two adjoining ranges will
9454          * be seamlessly merged.  (In a tie and both are in the set or both not
9455          * in the set, it doesn't matter which we take first.) */
9456         if (       array_a[i_a] < array_b[i_b]
9457             || (   array_a[i_a] == array_b[i_b]
9458                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9459         {
9460             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9461             cp = array_a[i_a++];
9462         }
9463         else {
9464             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9465             cp = array_b[i_b++];
9466         }
9467
9468         /* Here, have chosen which of the two inputs to look at.  Only output
9469          * if the running count changes to/from 0, which marks the
9470          * beginning/end of a range that's in the set */
9471         if (cp_in_set) {
9472             if (count == 0) {
9473                 array_u[i_u++] = cp;
9474             }
9475             count++;
9476         }
9477         else {
9478             count--;
9479             if (count == 0) {
9480                 array_u[i_u++] = cp;
9481             }
9482         }
9483     }
9484
9485
9486     /* The loop above increments the index into exactly one of the input lists
9487      * each iteration, and ends when either index gets to its list end.  That
9488      * means the other index is lower than its end, and so something is
9489      * remaining in that one.  We decrement 'count', as explained below, if
9490      * that list is in its set.  (i_a and i_b each currently index the element
9491      * beyond the one we care about.) */
9492     if (   (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9493         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9494     {
9495         count--;
9496     }
9497
9498     /* Above we decremented 'count' if the list that had unexamined elements in
9499      * it was in its set.  This has made it so that 'count' being non-zero
9500      * means there isn't anything left to output; and 'count' equal to 0 means
9501      * that what is left to output is precisely that which is left in the
9502      * non-exhausted input list.
9503      *
9504      * To see why, note first that the exhausted input obviously has nothing
9505      * left to add to the union.  If it was in its set at its end, that means
9506      * the set extends from here to the platform's infinity, and hence so does
9507      * the union and the non-exhausted set is irrelevant.  The exhausted set
9508      * also contributed 1 to 'count'.  If 'count' was 2, it got decremented to
9509      * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9510      * 'count' remains at 1.  This is consistent with the decremented 'count'
9511      * != 0 meaning there's nothing left to add to the union.
9512      *
9513      * But if the exhausted input wasn't in its set, it contributed 0 to
9514      * 'count', and the rest of the union will be whatever the other input is.
9515      * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9516      * otherwise it gets decremented to 0.  This is consistent with 'count'
9517      * == 0 meaning the remainder of the union is whatever is left in the
9518      * non-exhausted list. */
9519     if (count != 0) {
9520         len_u = i_u;
9521     }
9522     else {
9523         IV copy_count = len_a - i_a;
9524         if (copy_count > 0) {   /* The non-exhausted input is 'a' */
9525             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9526         }
9527         else { /* The non-exhausted input is b */
9528             copy_count = len_b - i_b;
9529             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9530         }
9531         len_u = i_u + copy_count;
9532     }
9533
9534     /* Set the result to the final length, which can change the pointer to
9535      * array_u, so re-find it.  (Note that it is unlikely that this will
9536      * change, as we are shrinking the space, not enlarging it) */
9537     if (len_u != _invlist_len(u)) {
9538         invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9539         invlist_trim(u);
9540         array_u = invlist_array(u);
9541     }
9542
9543     if (*output == NULL) {  /* Simply return the new inversion list */
9544         *output = u;
9545     }
9546     else {
9547         /* Otherwise, overwrite the inversion list that was in '*output'.  We
9548          * could instead free '*output', and then set it to 'u', but experience
9549          * has shown [perl #127392] that if the input is a mortal, we can get a
9550          * huge build-up of these during regex compilation before they get
9551          * freed. */
9552         invlist_replace_list_destroys_src(*output, u);
9553         SvREFCNT_dec_NN(u);
9554     }
9555
9556     return;
9557 }
9558
9559 void
9560 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9561                                                const bool complement_b, SV** i)
9562 {
9563     /* Take the intersection of two inversion lists and point '*i' to it.  On
9564      * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9565      * even 'a' or 'b').  If to an inversion list, the contents of the original
9566      * list will be replaced by the intersection.  The first list, 'a', may be
9567      * NULL, in which case '*i' will be an empty list.  If 'complement_b' is
9568      * TRUE, the result will be the intersection of 'a' and the complement (or
9569      * inversion) of 'b' instead of 'b' directly.
9570      *
9571      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9572      * Richard Gillam, published by Addison-Wesley, and explained at some
9573      * length there.  The preface says to incorporate its examples into your
9574      * code at your own risk.  In fact, it had bugs
9575      *
9576      * The algorithm is like a merge sort, and is essentially the same as the
9577      * union above
9578      */
9579
9580     const UV* array_a;          /* a's array */
9581     const UV* array_b;
9582     UV len_a;   /* length of a's array */
9583     UV len_b;
9584
9585     SV* r;                   /* the resulting intersection */
9586     UV* array_r;
9587     UV len_r = 0;
9588
9589     UV i_a = 0;             /* current index into a's array */
9590     UV i_b = 0;
9591     UV i_r = 0;
9592
9593     /* running count of how many of the two inputs are postitioned at ranges
9594      * that are in their sets.  As explained in the algorithm source book,
9595      * items are stopped accumulating and are output when the count changes
9596      * to/from 2.  The count is incremented when we start a range that's in an
9597      * input's set, and decremented when we start a range that's not in a set.
9598      * Only when it is 2 are we in the intersection. */
9599     UV count = 0;
9600
9601     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9602     assert(a != b);
9603     assert(*i == NULL || is_invlist(*i));
9604
9605     /* Special case if either one is empty */
9606     len_a = (a == NULL) ? 0 : _invlist_len(a);
9607     if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9608         if (len_a != 0 && complement_b) {
9609
9610             /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9611              * must be empty.  Here, also we are using 'b's complement, which
9612              * hence must be every possible code point.  Thus the intersection
9613              * is simply 'a'. */
9614
9615             if (*i == a) {  /* No-op */
9616                 return;
9617             }
9618
9619             if (*i == NULL) {
9620                 *i = invlist_clone(a, NULL);
9621                 return;
9622             }
9623
9624             r = invlist_clone(a, NULL);
9625             invlist_replace_list_destroys_src(*i, r);
9626             SvREFCNT_dec_NN(r);
9627             return;
9628         }
9629
9630         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
9631          * intersection must be empty */
9632         if (*i == NULL) {
9633             *i = _new_invlist(0);
9634             return;
9635         }
9636
9637         invlist_clear(*i);
9638         return;
9639     }
9640
9641     /* Here both lists exist and are non-empty */
9642     array_a = invlist_array(a);
9643     array_b = invlist_array(b);
9644
9645     /* If are to take the intersection of 'a' with the complement of b, set it
9646      * up so are looking at b's complement. */
9647     if (complement_b) {
9648
9649         /* To complement, we invert: if the first element is 0, remove it.  To
9650          * do this, we just pretend the array starts one later */
9651         if (array_b[0] == 0) {
9652             array_b++;
9653             len_b--;
9654         }
9655         else {
9656
9657             /* But if the first element is not zero, we pretend the list starts
9658              * at the 0 that is always stored immediately before the array. */
9659             array_b--;
9660             len_b++;
9661         }
9662     }
9663
9664     /* Size the intersection for the worst case: that the intersection ends up
9665      * fragmenting everything to be completely disjoint */
9666     r= _new_invlist(len_a + len_b);
9667
9668     /* Will contain U+0000 iff both components do */
9669     array_r = _invlist_array_init(r,    len_a > 0 && array_a[0] == 0
9670                                      && len_b > 0 && array_b[0] == 0);
9671
9672     /* Go through each list item by item, stopping when have exhausted one of
9673      * them */
9674     while (i_a < len_a && i_b < len_b) {
9675         UV cp;      /* The element to potentially add to the intersection's
9676                        array */
9677         bool cp_in_set; /* Is it in the input list's set or not */
9678
9679         /* We need to take one or the other of the two inputs for the
9680          * intersection.  Since we are merging two sorted lists, we take the
9681          * smaller of the next items.  In case of a tie, we take first the one
9682          * that is not in its set (a difference from the union algorithm).  If
9683          * we first took the one in its set, it would increment the count,
9684          * possibly to 2 which would cause it to be output as starting a range
9685          * in the intersection, and the next time through we would take that
9686          * same number, and output it again as ending the set.  By doing the
9687          * opposite of this, there is no possibility that the count will be
9688          * momentarily incremented to 2.  (In a tie and both are in the set or
9689          * both not in the set, it doesn't matter which we take first.) */
9690         if (       array_a[i_a] < array_b[i_b]
9691             || (   array_a[i_a] == array_b[i_b]
9692                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9693         {
9694             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9695             cp = array_a[i_a++];
9696         }
9697         else {
9698             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9699             cp= array_b[i_b++];
9700         }
9701
9702         /* Here, have chosen which of the two inputs to look at.  Only output
9703          * if the running count changes to/from 2, which marks the
9704          * beginning/end of a range that's in the intersection */
9705         if (cp_in_set) {
9706             count++;
9707             if (count == 2) {
9708                 array_r[i_r++] = cp;
9709             }
9710         }
9711         else {
9712             if (count == 2) {
9713                 array_r[i_r++] = cp;
9714             }
9715             count--;
9716         }
9717
9718     }
9719
9720     /* The loop above increments the index into exactly one of the input lists
9721      * each iteration, and ends when either index gets to its list end.  That
9722      * means the other index is lower than its end, and so something is
9723      * remaining in that one.  We increment 'count', as explained below, if the
9724      * exhausted list was in its set.  (i_a and i_b each currently index the
9725      * element beyond the one we care about.) */
9726     if (   (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9727         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9728     {
9729         count++;
9730     }
9731
9732     /* Above we incremented 'count' if the exhausted list was in its set.  This
9733      * has made it so that 'count' being below 2 means there is nothing left to
9734      * output; otheriwse what's left to add to the intersection is precisely
9735      * that which is left in the non-exhausted input list.
9736      *
9737      * To see why, note first that the exhausted input obviously has nothing
9738      * left to affect the intersection.  If it was in its set at its end, that
9739      * means the set extends from here to the platform's infinity, and hence
9740      * anything in the non-exhausted's list will be in the intersection, and
9741      * anything not in it won't be.  Hence, the rest of the intersection is
9742      * precisely what's in the non-exhausted list  The exhausted set also
9743      * contributed 1 to 'count', meaning 'count' was at least 1.  Incrementing
9744      * it means 'count' is now at least 2.  This is consistent with the
9745      * incremented 'count' being >= 2 means to add the non-exhausted list to
9746      * the intersection.
9747      *
9748      * But if the exhausted input wasn't in its set, it contributed 0 to
9749      * 'count', and the intersection can't include anything further; the
9750      * non-exhausted set is irrelevant.  'count' was at most 1, and doesn't get
9751      * incremented.  This is consistent with 'count' being < 2 meaning nothing
9752      * further to add to the intersection. */
9753     if (count < 2) { /* Nothing left to put in the intersection. */
9754         len_r = i_r;
9755     }
9756     else { /* copy the non-exhausted list, unchanged. */
9757         IV copy_count = len_a - i_a;
9758         if (copy_count > 0) {   /* a is the one with stuff left */
9759             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9760         }
9761         else {  /* b is the one with stuff left */
9762             copy_count = len_b - i_b;
9763             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9764         }
9765         len_r = i_r + copy_count;
9766     }
9767
9768     /* Set the result to the final length, which can change the pointer to
9769      * array_r, so re-find it.  (Note that it is unlikely that this will
9770      * change, as we are shrinking the space, not enlarging it) */
9771     if (len_r != _invlist_len(r)) {
9772         invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9773         invlist_trim(r);
9774         array_r = invlist_array(r);
9775     }
9776
9777     if (*i == NULL) { /* Simply return the calculated intersection */
9778         *i = r;
9779     }
9780     else { /* Otherwise, replace the existing inversion list in '*i'.  We could
9781               instead free '*i', and then set it to 'r', but experience has
9782               shown [perl #127392] that if the input is a mortal, we can get a
9783               huge build-up of these during regex compilation before they get
9784               freed. */
9785         if (len_r) {
9786             invlist_replace_list_destroys_src(*i, r);
9787         }
9788         else {
9789             invlist_clear(*i);
9790         }
9791         SvREFCNT_dec_NN(r);
9792     }
9793
9794     return;
9795 }
9796
9797 SV*
9798 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
9799 {
9800     /* Add the range from 'start' to 'end' inclusive to the inversion list's
9801      * set.  A pointer to the inversion list is returned.  This may actually be
9802      * a new list, in which case the passed in one has been destroyed.  The
9803      * passed-in inversion list can be NULL, in which case a new one is created
9804      * with just the one range in it.  The new list is not necessarily
9805      * NUL-terminated.  Space is not freed if the inversion list shrinks as a
9806      * result of this function.  The gain would not be large, and in many
9807      * cases, this is called multiple times on a single inversion list, so
9808      * anything freed may almost immediately be needed again.
9809      *
9810      * This used to mostly call the 'union' routine, but that is much more
9811      * heavyweight than really needed for a single range addition */
9812
9813     UV* array;              /* The array implementing the inversion list */
9814     UV len;                 /* How many elements in 'array' */
9815     SSize_t i_s;            /* index into the invlist array where 'start'
9816                                should go */
9817     SSize_t i_e = 0;        /* And the index where 'end' should go */
9818     UV cur_highest;         /* The highest code point in the inversion list
9819                                upon entry to this function */
9820
9821     /* This range becomes the whole inversion list if none already existed */
9822     if (invlist == NULL) {
9823         invlist = _new_invlist(2);
9824         _append_range_to_invlist(invlist, start, end);
9825         return invlist;
9826     }
9827
9828     /* Likewise, if the inversion list is currently empty */
9829     len = _invlist_len(invlist);
9830     if (len == 0) {
9831         _append_range_to_invlist(invlist, start, end);
9832         return invlist;
9833     }
9834
9835     /* Starting here, we have to know the internals of the list */
9836     array = invlist_array(invlist);
9837
9838     /* If the new range ends higher than the current highest ... */
9839     cur_highest = invlist_highest(invlist);
9840     if (end > cur_highest) {
9841
9842         /* If the whole range is higher, we can just append it */
9843         if (start > cur_highest) {
9844             _append_range_to_invlist(invlist, start, end);
9845             return invlist;
9846         }
9847
9848         /* Otherwise, add the portion that is higher ... */
9849         _append_range_to_invlist(invlist, cur_highest + 1, end);
9850
9851         /* ... and continue on below to handle the rest.  As a result of the
9852          * above append, we know that the index of the end of the range is the
9853          * final even numbered one of the array.  Recall that the final element
9854          * always starts a range that extends to infinity.  If that range is in
9855          * the set (meaning the set goes from here to infinity), it will be an
9856          * even index, but if it isn't in the set, it's odd, and the final
9857          * range in the set is one less, which is even. */
9858         if (end == UV_MAX) {
9859             i_e = len;
9860         }
9861         else {
9862             i_e = len - 2;
9863         }
9864     }
9865
9866     /* We have dealt with appending, now see about prepending.  If the new
9867      * range starts lower than the current lowest ... */
9868     if (start < array[0]) {
9869
9870         /* Adding something which has 0 in it is somewhat tricky, and uncommon.
9871          * Let the union code handle it, rather than having to know the
9872          * trickiness in two code places.  */
9873         if (UNLIKELY(start == 0)) {
9874             SV* range_invlist;
9875
9876             range_invlist = _new_invlist(2);
9877             _append_range_to_invlist(range_invlist, start, end);
9878
9879             _invlist_union(invlist, range_invlist, &invlist);
9880
9881             SvREFCNT_dec_NN(range_invlist);
9882
9883             return invlist;
9884         }
9885
9886         /* If the whole new range comes before the first entry, and doesn't
9887          * extend it, we have to insert it as an additional range */
9888         if (end < array[0] - 1) {
9889             i_s = i_e = -1;
9890             goto splice_in_new_range;
9891         }
9892
9893         /* Here the new range adjoins the existing first range, extending it
9894          * downwards. */
9895         array[0] = start;
9896
9897         /* And continue on below to handle the rest.  We know that the index of
9898          * the beginning of the range is the first one of the array */
9899         i_s = 0;
9900     }
9901     else { /* Not prepending any part of the new range to the existing list.
9902             * Find where in the list it should go.  This finds i_s, such that:
9903             *     invlist[i_s] <= start < array[i_s+1]
9904             */
9905         i_s = _invlist_search(invlist, start);
9906     }
9907
9908     /* At this point, any extending before the beginning of the inversion list
9909      * and/or after the end has been done.  This has made it so that, in the
9910      * code below, each endpoint of the new range is either in a range that is
9911      * in the set, or is in a gap between two ranges that are.  This means we
9912      * don't have to worry about exceeding the array bounds.
9913      *
9914      * Find where in the list the new range ends (but we can skip this if we
9915      * have already determined what it is, or if it will be the same as i_s,
9916      * which we already have computed) */
9917     if (i_e == 0) {
9918         i_e = (start == end)
9919               ? i_s
9920               : _invlist_search(invlist, end);
9921     }
9922
9923     /* Here generally invlist[i_e] <= end < array[i_e+1].  But if invlist[i_e]
9924      * is a range that goes to infinity there is no element at invlist[i_e+1],
9925      * so only the first relation holds. */
9926
9927     if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
9928
9929         /* Here, the ranges on either side of the beginning of the new range
9930          * are in the set, and this range starts in the gap between them.
9931          *
9932          * The new range extends the range above it downwards if the new range
9933          * ends at or above that range's start */
9934         const bool extends_the_range_above = (   end == UV_MAX
9935                                               || end + 1 >= array[i_s+1]);
9936
9937         /* The new range extends the range below it upwards if it begins just
9938          * after where that range ends */
9939         if (start == array[i_s]) {
9940
9941             /* If the new range fills the entire gap between the other ranges,
9942              * they will get merged together.  Other ranges may also get
9943              * merged, depending on how many of them the new range spans.  In
9944              * the general case, we do the merge later, just once, after we
9945              * figure out how many to merge.  But in the case where the new
9946              * range exactly spans just this one gap (possibly extending into
9947              * the one above), we do the merge here, and an early exit.  This
9948              * is done here to avoid having to special case later. */
9949             if (i_e - i_s <= 1) {
9950
9951                 /* If i_e - i_s == 1, it means that the new range terminates
9952                  * within the range above, and hence 'extends_the_range_above'
9953                  * must be true.  (If the range above it extends to infinity,
9954                  * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
9955                  * will be 0, so no harm done.) */
9956                 if (extends_the_range_above) {
9957                     Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
9958                     invlist_set_len(invlist,
9959                                     len - 2,
9960                                     *(get_invlist_offset_addr(invlist)));
9961                     return invlist;
9962                 }
9963
9964                 /* Here, i_e must == i_s.  We keep them in sync, as they apply
9965                  * to the same range, and below we are about to decrement i_s
9966                  * */
9967                 i_e--;
9968             }
9969
9970             /* Here, the new range is adjacent to the one below.  (It may also
9971              * span beyond the range above, but that will get resolved later.)
9972              * Extend the range below to include this one. */
9973             array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
9974             i_s--;
9975             start = array[i_s];
9976         }
9977         else if (extends_the_range_above) {
9978
9979             /* Here the new range only extends the range above it, but not the
9980              * one below.  It merges with the one above.  Again, we keep i_e
9981              * and i_s in sync if they point to the same range */
9982             if (i_e == i_s) {
9983                 i_e++;
9984             }
9985             i_s++;
9986             array[i_s] = start;
9987         }
9988     }
9989
9990     /* Here, we've dealt with the new range start extending any adjoining
9991      * existing ranges.
9992      *
9993      * If the new range extends to infinity, it is now the final one,
9994      * regardless of what was there before */
9995     if (UNLIKELY(end == UV_MAX)) {
9996         invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
9997         return invlist;
9998     }
9999
10000     /* If i_e started as == i_s, it has also been dealt with,
10001      * and been updated to the new i_s, which will fail the following if */
10002     if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10003
10004         /* Here, the ranges on either side of the end of the new range are in
10005          * the set, and this range ends in the gap between them.
10006          *
10007          * If this range is adjacent to (hence extends) the range above it, it
10008          * becomes part of that range; likewise if it extends the range below,
10009          * it becomes part of that range */
10010         if (end + 1 == array[i_e+1]) {
10011             i_e++;
10012             array[i_e] = start;
10013         }
10014         else if (start <= array[i_e]) {
10015             array[i_e] = end + 1;
10016             i_e--;
10017         }
10018     }
10019
10020     if (i_s == i_e) {
10021
10022         /* If the range fits entirely in an existing range (as possibly already
10023          * extended above), it doesn't add anything new */
10024         if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10025             return invlist;
10026         }
10027
10028         /* Here, no part of the range is in the list.  Must add it.  It will
10029          * occupy 2 more slots */
10030       splice_in_new_range:
10031
10032         invlist_extend(invlist, len + 2);
10033         array = invlist_array(invlist);
10034         /* Move the rest of the array down two slots. Don't include any
10035          * trailing NUL */
10036         Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10037
10038         /* Do the actual splice */
10039         array[i_e+1] = start;
10040         array[i_e+2] = end + 1;
10041         invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10042         return invlist;
10043     }
10044
10045     /* Here the new range crossed the boundaries of a pre-existing range.  The
10046      * code above has adjusted things so that both ends are in ranges that are
10047      * in the set.  This means everything in between must also be in the set.
10048      * Just squash things together */
10049     Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10050     invlist_set_len(invlist,
10051                     len - i_e + i_s,
10052                     *(get_invlist_offset_addr(invlist)));
10053
10054     return invlist;
10055 }
10056
10057 SV*
10058 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10059                                  UV** other_elements_ptr)
10060 {
10061     /* Create and return an inversion list whose contents are to be populated
10062      * by the caller.  The caller gives the number of elements (in 'size') and
10063      * the very first element ('element0').  This function will set
10064      * '*other_elements_ptr' to an array of UVs, where the remaining elements
10065      * are to be placed.
10066      *
10067      * Obviously there is some trust involved that the caller will properly
10068      * fill in the other elements of the array.
10069      *
10070      * (The first element needs to be passed in, as the underlying code does
10071      * things differently depending on whether it is zero or non-zero) */
10072
10073     SV* invlist = _new_invlist(size);
10074     bool offset;
10075
10076     PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10077
10078     invlist = add_cp_to_invlist(invlist, element0);
10079     offset = *get_invlist_offset_addr(invlist);
10080
10081     invlist_set_len(invlist, size, offset);
10082     *other_elements_ptr = invlist_array(invlist) + 1;
10083     return invlist;
10084 }
10085
10086 #endif
10087
10088 PERL_STATIC_INLINE SV*
10089 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
10090     return _add_range_to_invlist(invlist, cp, cp);
10091 }
10092
10093 #ifndef PERL_IN_XSUB_RE
10094 void
10095 Perl__invlist_invert(pTHX_ SV* const invlist)
10096 {
10097     /* Complement the input inversion list.  This adds a 0 if the list didn't
10098      * have a zero; removes it otherwise.  As described above, the data
10099      * structure is set up so that this is very efficient */
10100
10101     PERL_ARGS_ASSERT__INVLIST_INVERT;
10102
10103     assert(! invlist_is_iterating(invlist));
10104
10105     /* The inverse of matching nothing is matching everything */
10106     if (_invlist_len(invlist) == 0) {
10107         _append_range_to_invlist(invlist, 0, UV_MAX);
10108         return;
10109     }
10110
10111     *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10112 }
10113
10114 SV*
10115 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10116 {
10117
10118     /* Return a new inversion list that is a copy of the input one, which is
10119      * unchanged.  The new list will not be mortal even if the old one was. */
10120
10121     const STRLEN nominal_length = _invlist_len(invlist);    /* Why not +1 XXX */
10122     const STRLEN physical_length = SvCUR(invlist);
10123     const bool offset = *(get_invlist_offset_addr(invlist));
10124
10125     PERL_ARGS_ASSERT_INVLIST_CLONE;
10126
10127     /* Need to allocate extra space to accommodate Perl's addition of a
10128      * trailing NUL to SvPV's, since it thinks they are always strings */
10129     if (new_invlist == NULL) {
10130         new_invlist = _new_invlist(nominal_length);
10131     }
10132     else {
10133         sv_upgrade(new_invlist, SVt_INVLIST);
10134         initialize_invlist_guts(new_invlist, nominal_length);
10135     }
10136
10137     *(get_invlist_offset_addr(new_invlist)) = offset;
10138     invlist_set_len(new_invlist, nominal_length, offset);
10139     Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10140
10141     return new_invlist;
10142 }
10143
10144 #endif
10145
10146 PERL_STATIC_INLINE STRLEN*
10147 S_get_invlist_iter_addr(SV* invlist)
10148 {
10149     /* Return the address of the UV that contains the current iteration
10150      * position */
10151
10152     PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
10153
10154     assert(is_invlist(invlist));
10155
10156     return &(((XINVLIST*) SvANY(invlist))->iterator);
10157 }
10158
10159 PERL_STATIC_INLINE void
10160 S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */
10161 {
10162     PERL_ARGS_ASSERT_INVLIST_ITERINIT;
10163
10164     *get_invlist_iter_addr(invlist) = 0;
10165 }
10166
10167 PERL_STATIC_INLINE void
10168 S_invlist_iterfinish(SV* invlist)
10169 {
10170     /* Terminate iterator for invlist.  This is to catch development errors.
10171      * Any iteration that is interrupted before completed should call this
10172      * function.  Functions that add code points anywhere else but to the end
10173      * of an inversion list assert that they are not in the middle of an
10174      * iteration.  If they were, the addition would make the iteration
10175      * problematical: if the iteration hadn't reached the place where things
10176      * were being added, it would be ok */
10177
10178     PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
10179
10180     *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
10181 }
10182
10183 STATIC bool
10184 S_invlist_iternext(SV* invlist, UV* start, UV* end)
10185 {
10186     /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
10187      * This call sets in <*start> and <*end>, the next range in <invlist>.
10188      * Returns <TRUE> if successful and the next call will return the next
10189      * range; <FALSE> if was already at the end of the list.  If the latter,
10190      * <*start> and <*end> are unchanged, and the next call to this function
10191      * will start over at the beginning of the list */
10192
10193     STRLEN* pos = get_invlist_iter_addr(invlist);
10194     UV len = _invlist_len(invlist);
10195     UV *array;
10196
10197     PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
10198
10199     if (*pos >= len) {
10200         *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
10201         return FALSE;
10202     }
10203
10204     array = invlist_array(invlist);
10205
10206     *start = array[(*pos)++];
10207
10208     if (*pos >= len) {
10209         *end = UV_MAX;
10210     }
10211     else {
10212         *end = array[(*pos)++] - 1;
10213     }
10214
10215     return TRUE;
10216 }
10217
10218 PERL_STATIC_INLINE UV
10219 S_invlist_highest(SV* const invlist)
10220 {
10221     /* Returns the highest code point that matches an inversion list.  This API
10222      * has an ambiguity, as it returns 0 under either the highest is actually
10223      * 0, or if the list is empty.  If this distinction matters to you, check
10224      * for emptiness before calling this function */
10225
10226     UV len = _invlist_len(invlist);
10227     UV *array;
10228
10229     PERL_ARGS_ASSERT_INVLIST_HIGHEST;
10230
10231     if (len == 0) {
10232         return 0;
10233     }
10234
10235     array = invlist_array(invlist);
10236
10237     /* The last element in the array in the inversion list always starts a
10238      * range that goes to infinity.  That range may be for code points that are
10239      * matched in the inversion list, or it may be for ones that aren't
10240      * matched.  In the latter case, the highest code point in the set is one
10241      * less than the beginning of this range; otherwise it is the final element
10242      * of this range: infinity */
10243     return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
10244            ? UV_MAX
10245            : array[len - 1] - 1;
10246 }
10247
10248 STATIC SV *
10249 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10250 {
10251     /* Get the contents of an inversion list into a string SV so that they can
10252      * be printed out.  If 'traditional_style' is TRUE, it uses the format
10253      * traditionally done for debug tracing; otherwise it uses a format
10254      * suitable for just copying to the output, with blanks between ranges and
10255      * a dash between range components */
10256
10257     UV start, end;
10258     SV* output;
10259     const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10260     const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10261
10262     if (traditional_style) {
10263         output = newSVpvs("\n");
10264     }
10265     else {
10266         output = newSVpvs("");
10267     }
10268
10269     PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10270
10271     assert(! invlist_is_iterating(invlist));
10272
10273     invlist_iterinit(invlist);
10274     while (invlist_iternext(invlist, &start, &end)) {
10275         if (end == UV_MAX) {
10276             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFINITY%c",
10277                                           start, intra_range_delimiter,
10278                                                  inter_range_delimiter);
10279         }
10280         else if (end != start) {
10281             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10282                                           start,
10283                                                    intra_range_delimiter,
10284                                                   end, inter_range_delimiter);
10285         }
10286         else {
10287             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10288                                           start, inter_range_delimiter);
10289         }
10290     }
10291
10292     if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10293         SvCUR_set(output, SvCUR(output) - 1);
10294     }
10295
10296     return output;
10297 }
10298
10299 #ifndef PERL_IN_XSUB_RE
10300 void
10301 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10302                          const char * const indent, SV* const invlist)
10303 {
10304     /* Designed to be called only by do_sv_dump().  Dumps out the ranges of the
10305      * inversion list 'invlist' to 'file' at 'level'  Each line is prefixed by
10306      * the string 'indent'.  The output looks like this:
10307          [0] 0x000A .. 0x000D
10308          [2] 0x0085
10309          [4] 0x2028 .. 0x2029
10310          [6] 0x3104 .. INFINITY
10311      * This means that the first range of code points matched by the list are
10312      * 0xA through 0xD; the second range contains only the single code point
10313      * 0x85, etc.  An inversion list is an array of UVs.  Two array elements
10314      * are used to define each range (except if the final range extends to
10315      * infinity, only a single element is needed).  The array index of the
10316      * first element for the corresponding range is given in brackets. */
10317
10318     UV start, end;
10319     STRLEN count = 0;
10320
10321     PERL_ARGS_ASSERT__INVLIST_DUMP;
10322
10323     if (invlist_is_iterating(invlist)) {
10324         Perl_dump_indent(aTHX_ level, file,
10325              "%sCan't dump inversion list because is in middle of iterating\n",
10326              indent);
10327         return;
10328     }
10329
10330     invlist_iterinit(invlist);
10331     while (invlist_iternext(invlist, &start, &end)) {
10332         if (end == UV_MAX) {
10333             Perl_dump_indent(aTHX_ level, file,
10334                                        "%s[%" UVuf "] 0x%04" UVXf " .. INFINITY\n",
10335                                    indent, (UV)count, start);
10336         }
10337         else if (end != start) {
10338             Perl_dump_indent(aTHX_ level, file,
10339                                     "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10340                                 indent, (UV)count, start,         end);
10341         }
10342         else {
10343             Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10344                                             indent, (UV)count, start);
10345         }
10346         count += 2;
10347     }
10348 }
10349
10350 #endif
10351
10352 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10353 bool
10354 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10355 {
10356     /* Return a boolean as to if the two passed in inversion lists are
10357      * identical.  The final argument, if TRUE, says to take the complement of
10358      * the second inversion list before doing the comparison */
10359
10360     const UV* array_a = invlist_array(a);
10361     const UV* array_b = invlist_array(b);
10362     UV len_a = _invlist_len(a);
10363     UV len_b = _invlist_len(b);
10364
10365     PERL_ARGS_ASSERT__INVLISTEQ;
10366
10367     /* If are to compare 'a' with the complement of b, set it
10368      * up so are looking at b's complement. */
10369     if (complement_b) {
10370
10371         /* The complement of nothing is everything, so <a> would have to have
10372          * just one element, starting at zero (ending at infinity) */
10373         if (len_b == 0) {
10374             return (len_a == 1 && array_a[0] == 0);
10375         }
10376         else if (array_b[0] == 0) {
10377
10378             /* Otherwise, to complement, we invert.  Here, the first element is
10379              * 0, just remove it.  To do this, we just pretend the array starts
10380              * one later */
10381
10382             array_b++;
10383             len_b--;
10384         }
10385         else {
10386
10387             /* But if the first element is not zero, we pretend the list starts
10388              * at the 0 that is always stored immediately before the array. */
10389             array_b--;
10390             len_b++;
10391         }
10392     }
10393
10394     return    len_a == len_b
10395            && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10396
10397 }
10398 #endif
10399
10400 /*
10401  * As best we can, determine the characters that can match the start of
10402  * the given EXACTF-ish node.
10403  *
10404  * Returns the invlist as a new SV*; it is the caller's responsibility to
10405  * call SvREFCNT_dec() when done with it.
10406  */
10407 STATIC SV*
10408 S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10409 {
10410     const U8 * s = (U8*)STRING(node);
10411     SSize_t bytelen = STR_LEN(node);
10412     UV uc;
10413     /* Start out big enough for 2 separate code points */
10414     SV* invlist = _new_invlist(4);
10415
10416     PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST;
10417
10418     if (! UTF) {
10419         uc = *s;
10420
10421         /* We punt and assume can match anything if the node begins
10422          * with a multi-character fold.  Things are complicated.  For
10423          * example, /ffi/i could match any of:
10424          *  "\N{LATIN SMALL LIGATURE FFI}"
10425          *  "\N{LATIN SMALL LIGATURE FF}I"
10426          *  "F\N{LATIN SMALL LIGATURE FI}"
10427          *  plus several other things; and making sure we have all the
10428          *  possibilities is hard. */
10429         if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10430             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10431         }
10432         else {
10433             /* Any Latin1 range character can potentially match any
10434              * other depending on the locale */
10435             if (OP(node) == EXACTFL) {
10436                 _invlist_union(invlist, PL_Latin1, &invlist);
10437             }
10438             else {
10439                 /* But otherwise, it matches at least itself.  We can
10440                  * quickly tell if it has a distinct fold, and if so,
10441                  * it matches that as well */
10442                 invlist = add_cp_to_invlist(invlist, uc);
10443                 if (IS_IN_SOME_FOLD_L1(uc))
10444                     invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10445             }
10446
10447             /* Some characters match above-Latin1 ones under /i.  This
10448              * is true of EXACTFL ones when the locale is UTF-8 */
10449             if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10450                 && (! isASCII(uc) || (OP(node) != EXACTFAA
10451                                     && OP(node) != EXACTFAA_NO_TRIE)))
10452             {
10453                 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10454             }
10455         }
10456     }
10457     else {  /* Pattern is UTF-8 */
10458         U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10459         const U8* e = s + bytelen;
10460         IV fc;
10461
10462         fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10463
10464         /* The only code points that aren't folded in a UTF EXACTFish
10465          * node are are the problematic ones in EXACTFL nodes */
10466         if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10467             /* We need to check for the possibility that this EXACTFL
10468              * node begins with a multi-char fold.  Therefore we fold
10469              * the first few characters of it so that we can make that
10470              * check */
10471             U8 *d = folded;
10472             int i;
10473
10474             fc = -1;
10475             for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10476                 if (isASCII(*s)) {
10477                     *(d++) = (U8) toFOLD(*s);
10478                     if (fc < 0) {       /* Save the first fold */
10479                         fc = *(d-1);
10480                     }
10481                     s++;
10482                 }
10483                 else {
10484                     STRLEN len;
10485                     UV fold = toFOLD_utf8_safe(s, e, d, &len);
10486                     if (fc < 0) {       /* Save the first fold */
10487                         fc = fold;
10488                     }
10489                     d += len;
10490                     s += UTF8SKIP(s);
10491                 }
10492             }
10493
10494             /* And set up so the code below that looks in this folded
10495              * buffer instead of the node's string */
10496             e = d;
10497             s = folded;
10498         }
10499
10500         /* When we reach here 's' points to the fold of the first
10501          * character(s) of the node; and 'e' points to far enough along
10502          * the folded string to be just past any possible multi-char
10503          * fold.
10504          *
10505          * Unlike the non-UTF-8 case, the macro for determining if a
10506          * string is a multi-char fold requires all the characters to
10507          * already be folded.  This is because of all the complications
10508          * if not.  Note that they are folded anyway, except in EXACTFL
10509          * nodes.  Like the non-UTF case above, we punt if the node
10510          * begins with a multi-char fold  */
10511
10512         if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10513             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10514         }
10515         else {  /* Single char fold */
10516             unsigned int k;
10517             unsigned int first_folds_to;
10518             const unsigned int * remaining_folds_to_list;
10519             Size_t folds_to_count;
10520
10521             /* It matches itself */
10522             invlist = add_cp_to_invlist(invlist, fc);
10523
10524             /* ... plus all the things that fold to it, which are found in
10525              * PL_utf8_foldclosures */
10526             folds_to_count = _inverse_folds(fc, &first_folds_to,
10527                                                 &remaining_folds_to_list);
10528             for (k = 0; k < folds_to_count; k++) {
10529                 UV c = (k == 0) ? first_folds_to : remaining_folds_to_list[k-1];
10530
10531                 /* /aa doesn't allow folds between ASCII and non- */
10532                 if (   (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10533                     && isASCII(c) != isASCII(fc))
10534                 {
10535                     continue;
10536                 }
10537
10538                 invlist = add_cp_to_invlist(invlist, c);
10539             }
10540         }
10541     }
10542
10543     return invlist;
10544 }
10545
10546 #undef HEADER_LENGTH
10547 #undef TO_INTERNAL_SIZE
10548 #undef FROM_INTERNAL_SIZE
10549 #undef INVLIST_VERSION_ID
10550
10551 /* End of inversion list object */
10552
10553 STATIC void
10554 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10555 {
10556     /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10557      * constructs, and updates RExC_flags with them.  On input, RExC_parse
10558      * should point to the first flag; it is updated on output to point to the
10559      * final ')' or ':'.  There needs to be at least one flag, or this will
10560      * abort */
10561
10562     /* for (?g), (?gc), and (?o) warnings; warning
10563        about (?c) will warn about (?g) -- japhy    */
10564
10565 #define WASTED_O  0x01
10566 #define WASTED_G  0x02
10567 #define WASTED_C  0x04
10568 #define WASTED_GC (WASTED_G|WASTED_C)
10569     I32 wastedflags = 0x00;
10570     U32 posflags = 0, negflags = 0;
10571     U32 *flagsp = &posflags;
10572     char has_charset_modifier = '\0';
10573     regex_charset cs;
10574     bool has_use_defaults = FALSE;
10575     const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10576     int x_mod_count = 0;
10577
10578     PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10579
10580     /* '^' as an initial flag sets certain defaults */
10581     if (UCHARAT(RExC_parse) == '^') {
10582         RExC_parse++;
10583         has_use_defaults = TRUE;
10584         STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10585         set_regex_charset(&RExC_flags, (RExC_uni_semantics)
10586                                         ? REGEX_UNICODE_CHARSET
10587                                         : REGEX_DEPENDS_CHARSET);
10588     }
10589
10590     cs = get_regex_charset(RExC_flags);
10591     if (cs == REGEX_DEPENDS_CHARSET
10592         && (RExC_uni_semantics))
10593     {
10594         cs = REGEX_UNICODE_CHARSET;
10595     }
10596
10597     while (RExC_parse < RExC_end) {
10598         /* && strchr("iogcmsx", *RExC_parse) */
10599         /* (?g), (?gc) and (?o) are useless here
10600            and must be globally applied -- japhy */
10601         switch (*RExC_parse) {
10602
10603             /* Code for the imsxn flags */
10604             CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10605
10606             case LOCALE_PAT_MOD:
10607                 if (has_charset_modifier) {
10608                     goto excess_modifier;
10609                 }
10610                 else if (flagsp == &negflags) {
10611                     goto neg_modifier;
10612                 }
10613                 cs = REGEX_LOCALE_CHARSET;
10614                 has_charset_modifier = LOCALE_PAT_MOD;
10615                 break;
10616             case UNICODE_PAT_MOD:
10617                 if (has_charset_modifier) {
10618                     goto excess_modifier;
10619                 }
10620                 else if (flagsp == &negflags) {
10621                     goto neg_modifier;
10622                 }
10623                 cs = REGEX_UNICODE_CHARSET;
10624                 has_charset_modifier = UNICODE_PAT_MOD;
10625                 break;
10626             case ASCII_RESTRICT_PAT_MOD:
10627                 if (flagsp == &negflags) {
10628                     goto neg_modifier;
10629                 }
10630                 if (has_charset_modifier) {
10631                     if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10632                         goto excess_modifier;
10633                     }
10634                     /* Doubled modifier implies more restricted */
10635                     cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10636                 }
10637                 else {
10638                     cs = REGEX_ASCII_RESTRICTED_CHARSET;
10639                 }
10640                 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10641                 break;
10642             case DEPENDS_PAT_MOD:
10643                 if (has_use_defaults) {
10644                     goto fail_modifiers;
10645                 }
10646                 else if (flagsp == &negflags) {
10647                     goto neg_modifier;
10648                 }
10649                 else if (has_charset_modifier) {
10650                     goto excess_modifier;
10651                 }
10652
10653                 /* The dual charset means unicode semantics if the
10654                  * pattern (or target, not known until runtime) are
10655                  * utf8, or something in the pattern indicates unicode
10656                  * semantics */
10657                 cs = (RExC_uni_semantics)
10658                      ? REGEX_UNICODE_CHARSET
10659                      : REGEX_DEPENDS_CHARSET;
10660                 has_charset_modifier = DEPENDS_PAT_MOD;
10661                 break;
10662               excess_modifier:
10663                 RExC_parse++;
10664                 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10665                     vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10666                 }
10667                 else if (has_charset_modifier == *(RExC_parse - 1)) {
10668                     vFAIL2("Regexp modifier \"%c\" may not appear twice",
10669                                         *(RExC_parse - 1));
10670                 }
10671                 else {
10672                     vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10673                 }
10674                 NOT_REACHED; /*NOTREACHED*/
10675               neg_modifier:
10676                 RExC_parse++;
10677                 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10678                                     *(RExC_parse - 1));
10679                 NOT_REACHED; /*NOTREACHED*/
10680             case ONCE_PAT_MOD: /* 'o' */
10681             case GLOBAL_PAT_MOD: /* 'g' */
10682                 if (ckWARN(WARN_REGEXP)) {
10683                     const I32 wflagbit = *RExC_parse == 'o'
10684                                          ? WASTED_O
10685                                          : WASTED_G;
10686                     if (! (wastedflags & wflagbit) ) {
10687                         wastedflags |= wflagbit;
10688                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10689                         vWARN5(
10690                             RExC_parse + 1,
10691                             "Useless (%s%c) - %suse /%c modifier",
10692                             flagsp == &negflags ? "?-" : "?",
10693                             *RExC_parse,
10694                             flagsp == &negflags ? "don't " : "",
10695                             *RExC_parse
10696                         );
10697                     }
10698                 }
10699                 break;
10700
10701             case CONTINUE_PAT_MOD: /* 'c' */
10702                 if (ckWARN(WARN_REGEXP)) {
10703                     if (! (wastedflags & WASTED_C) ) {
10704                         wastedflags |= WASTED_GC;
10705                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10706                         vWARN3(
10707                             RExC_parse + 1,
10708                             "Useless (%sc) - %suse /gc modifier",
10709                             flagsp == &negflags ? "?-" : "?",
10710                             flagsp == &negflags ? "don't " : ""
10711                         );
10712                     }
10713                 }
10714                 break;
10715             case KEEPCOPY_PAT_MOD: /* 'p' */
10716                 if (flagsp == &negflags) {
10717                     ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10718                 } else {
10719                     *flagsp |= RXf_PMf_KEEPCOPY;
10720                 }
10721                 break;
10722             case '-':
10723                 /* A flag is a default iff it is following a minus, so
10724                  * if there is a minus, it means will be trying to
10725                  * re-specify a default which is an error */
10726                 if (has_use_defaults || flagsp == &negflags) {
10727                     goto fail_modifiers;
10728                 }
10729                 flagsp = &negflags;
10730                 wastedflags = 0;  /* reset so (?g-c) warns twice */
10731                 x_mod_count = 0;
10732                 break;
10733             case ':':
10734             case ')':
10735
10736                 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
10737                     negflags |= RXf_PMf_EXTENDED_MORE;
10738                 }
10739                 RExC_flags |= posflags;
10740
10741                 if (negflags & RXf_PMf_EXTENDED) {
10742                     negflags |= RXf_PMf_EXTENDED_MORE;
10743                 }
10744                 RExC_flags &= ~negflags;
10745                 set_regex_charset(&RExC_flags, cs);
10746
10747                 return;
10748             default:
10749               fail_modifiers:
10750                 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10751                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10752                 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
10753                       UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10754                 NOT_REACHED; /*NOTREACHED*/
10755         }
10756
10757         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10758     }
10759
10760     vFAIL("Sequence (?... not terminated");
10761 }
10762
10763 /*
10764  - reg - regular expression, i.e. main body or parenthesized thing
10765  *
10766  * Caller must absorb opening parenthesis.
10767  *
10768  * Combining parenthesis handling with the base level of regular expression
10769  * is a trifle forced, but the need to tie the tails of the branches to what
10770  * follows makes it hard to avoid.
10771  */
10772 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10773 #ifdef DEBUGGING
10774 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10775 #else
10776 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10777 #endif
10778
10779 PERL_STATIC_INLINE regnode_offset
10780 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10781                              I32 *flagp,
10782                              char * parse_start,
10783                              char ch
10784                       )
10785 {
10786     regnode_offset ret;
10787     char* name_start = RExC_parse;
10788     U32 num = 0;
10789     SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
10790     GET_RE_DEBUG_FLAGS_DECL;
10791
10792     PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
10793
10794     if (RExC_parse == name_start || *RExC_parse != ch) {
10795         /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
10796         vFAIL2("Sequence %.3s... not terminated", parse_start);
10797     }
10798
10799     if (sv_dat) {
10800         num = add_data( pRExC_state, STR_WITH_LEN("S"));
10801         RExC_rxi->data->data[num]=(void*)sv_dat;
10802         SvREFCNT_inc_simple_void_NN(sv_dat);
10803     }
10804     RExC_sawback = 1;
10805     ret = reganode(pRExC_state,
10806                    ((! FOLD)
10807                      ? NREF
10808                      : (ASCII_FOLD_RESTRICTED)
10809                        ? NREFFA
10810                        : (AT_LEAST_UNI_SEMANTICS)
10811                          ? NREFFU
10812                          : (LOC)
10813                            ? NREFFL
10814                            : NREFF),
10815                     num);
10816     *flagp |= HASWIDTH;
10817
10818     Set_Node_Offset(REGNODE_p(ret), parse_start+1);
10819     Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
10820
10821     nextchar(pRExC_state);
10822     return ret;
10823 }
10824
10825 /* On success, returns the offset at which any next node should be placed into
10826  * the regex engine program being compiled.
10827  *
10828  * Returns 0 otherwise, with *flagp set to indicate why:
10829  *  TRYAGAIN        at the end of (?) that only sets flags.
10830  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
10831  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
10832  *  Otherwise would only return 0 if regbranch() returns 0, which cannot
10833  *  happen.  */
10834 STATIC regnode_offset
10835 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
10836     /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
10837      * 2 is like 1, but indicates that nextchar() has been called to advance
10838      * RExC_parse beyond the '('.  Things like '(?' are indivisible tokens, and
10839      * this flag alerts us to the need to check for that */
10840 {
10841     regnode_offset ret = 0;    /* Will be the head of the group. */
10842     regnode_offset br;
10843     regnode_offset lastbr;
10844     regnode_offset ender = 0;
10845     I32 parno = 0;
10846     I32 flags;
10847     U32 oregflags = RExC_flags;
10848     bool have_branch = 0;
10849     bool is_open = 0;
10850     I32 freeze_paren = 0;
10851     I32 after_freeze = 0;
10852     I32 num; /* numeric backreferences */
10853
10854     char * parse_start = RExC_parse; /* MJD */
10855     char * const oregcomp_parse = RExC_parse;
10856
10857     GET_RE_DEBUG_FLAGS_DECL;
10858
10859     PERL_ARGS_ASSERT_REG;
10860     DEBUG_PARSE("reg ");
10861
10862     *flagp = 0;                         /* Tentatively. */
10863
10864     /* Having this true makes it feasible to have a lot fewer tests for the
10865      * parse pointer being in scope.  For example, we can write
10866      *      while(isFOO(*RExC_parse)) RExC_parse++;
10867      * instead of
10868      *      while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
10869      */
10870     assert(*RExC_end == '\0');
10871
10872     /* Make an OPEN node, if parenthesized. */
10873     if (paren) {
10874
10875         /* Under /x, space and comments can be gobbled up between the '(' and
10876          * here (if paren ==2).  The forms '(*VERB' and '(?...' disallow such
10877          * intervening space, as the sequence is a token, and a token should be
10878          * indivisible */
10879         bool has_intervening_patws = (paren == 2)
10880                                   && *(RExC_parse - 1) != '(';
10881
10882         if (RExC_parse >= RExC_end) {
10883             vFAIL("Unmatched (");
10884         }
10885
10886         if (paren == 'r') {     /* Atomic script run */
10887             paren = '>';
10888             goto parse_rest;
10889         }
10890         else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
10891             char *start_verb = RExC_parse + 1;
10892             STRLEN verb_len;
10893             char *start_arg = NULL;
10894             unsigned char op = 0;
10895             int arg_required = 0;
10896             int internal_argval = -1; /* if >-1 we are not allowed an argument*/
10897             bool has_upper = FALSE;
10898
10899             if (has_intervening_patws) {
10900                 RExC_parse++;   /* past the '*' */
10901
10902                 /* For strict backwards compatibility, don't change the message
10903                  * now that we also have lowercase operands */
10904                 if (isUPPER(*RExC_parse)) {
10905                     vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
10906                 }
10907                 else {
10908                     vFAIL("In '(*...)', the '(' and '*' must be adjacent");
10909                 }
10910             }
10911             while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
10912                 if ( *RExC_parse == ':' ) {
10913                     start_arg = RExC_parse + 1;
10914                     break;
10915                 }
10916                 else if (! UTF) {
10917                     if (isUPPER(*RExC_parse)) {
10918                         has_upper = TRUE;
10919                     }
10920                     RExC_parse++;
10921                 }
10922                 else {
10923                     RExC_parse += UTF8SKIP(RExC_parse);
10924                 }
10925             }
10926             verb_len = RExC_parse - start_verb;
10927             if ( start_arg ) {
10928                 if (RExC_parse >= RExC_end) {
10929                     goto unterminated_verb_pattern;
10930                 }
10931
10932                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10933                 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
10934                     RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10935                 }
10936                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
10937                   unterminated_verb_pattern:
10938                     if (has_upper) {
10939                         vFAIL("Unterminated verb pattern argument");
10940                     }
10941                     else {
10942                         vFAIL("Unterminated '(*...' argument");
10943                     }
10944                 }
10945             } else {
10946                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
10947                     if (has_upper) {
10948                         vFAIL("Unterminated verb pattern");
10949                     }
10950                     else {
10951                         vFAIL("Unterminated '(*...' construct");
10952                     }
10953                 }
10954             }
10955
10956             /* Here, we know that RExC_parse < RExC_end */
10957
10958             switch ( *start_verb ) {
10959             case 'A':  /* (*ACCEPT) */
10960                 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
10961                     op = ACCEPT;
10962                     internal_argval = RExC_nestroot;
10963                 }
10964                 break;
10965             case 'C':  /* (*COMMIT) */
10966                 if ( memEQs(start_verb, verb_len,"COMMIT") )
10967                     op = COMMIT;
10968                 break;
10969             case 'F':  /* (*FAIL) */
10970                 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
10971                     op = OPFAIL;
10972                 }
10973                 break;
10974             case ':':  /* (*:NAME) */
10975             case 'M':  /* (*MARK:NAME) */
10976                 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
10977                     op = MARKPOINT;
10978                     arg_required = 1;
10979                 }
10980                 break;
10981             case 'P':  /* (*PRUNE) */
10982                 if ( memEQs(start_verb, verb_len,"PRUNE") )
10983                     op = PRUNE;
10984                 break;
10985             case 'S':   /* (*SKIP) */
10986                 if ( memEQs(start_verb, verb_len,"SKIP") )
10987                     op = SKIP;
10988                 break;
10989             case 'T':  /* (*THEN) */
10990                 /* [19:06] <TimToady> :: is then */
10991                 if ( memEQs(start_verb, verb_len,"THEN") ) {
10992                     op = CUTGROUP;
10993                     RExC_seen |= REG_CUTGROUP_SEEN;
10994                 }
10995                 break;
10996             case 'a':
10997                 if (   memEQs(start_verb, verb_len, "asr")
10998                     || memEQs(start_verb, verb_len, "atomic_script_run"))
10999                 {
11000                     paren = 'r';        /* Mnemonic: recursed run */
11001                     goto script_run;
11002                 }
11003                 else if (memEQs(start_verb, verb_len, "atomic")) {
11004                     paren = 't';    /* AtOMIC */
11005                     goto alpha_assertions;
11006                 }
11007                 break;
11008             case 'p':
11009                 if (   memEQs(start_verb, verb_len, "plb")
11010                     || memEQs(start_verb, verb_len, "positive_lookbehind"))
11011                 {
11012                     paren = 'b';
11013                     goto lookbehind_alpha_assertions;
11014                 }
11015                 else if (   memEQs(start_verb, verb_len, "pla")
11016                          || memEQs(start_verb, verb_len, "positive_lookahead"))
11017                 {
11018                     paren = 'a';
11019                     goto alpha_assertions;
11020                 }
11021                 break;
11022             case 'n':
11023                 if (   memEQs(start_verb, verb_len, "nlb")
11024                     || memEQs(start_verb, verb_len, "negative_lookbehind"))
11025                 {
11026                     paren = 'B';
11027                     goto lookbehind_alpha_assertions;
11028                 }
11029                 else if (   memEQs(start_verb, verb_len, "nla")
11030                          || memEQs(start_verb, verb_len, "negative_lookahead"))
11031                 {
11032                     paren = 'A';
11033                     goto alpha_assertions;
11034                 }
11035                 break;
11036             case 's':
11037                 if (   memEQs(start_verb, verb_len, "sr")
11038                     || memEQs(start_verb, verb_len, "script_run"))
11039                 {
11040                     regnode_offset atomic;
11041
11042                     paren = 's';
11043
11044                    script_run:
11045
11046                     /* This indicates Unicode rules. */
11047                     REQUIRE_UNI_RULES(flagp, 0);
11048
11049                     if (! start_arg) {
11050                         goto no_colon;
11051                     }
11052
11053                     RExC_parse = start_arg;
11054
11055                     if (RExC_in_script_run) {
11056
11057                         /*  Nested script runs are treated as no-ops, because
11058                          *  if the nested one fails, the outer one must as
11059                          *  well.  It could fail sooner, and avoid (??{} with
11060                          *  side effects, but that is explicitly documented as
11061                          *  undefined behavior. */
11062
11063                         ret = 0;
11064
11065                         if (paren == 's') {
11066                             paren = ':';
11067                             goto parse_rest;
11068                         }
11069
11070                         /* But, the atomic part of a nested atomic script run
11071                          * isn't a no-op, but can be treated just like a '(?>'
11072                          * */
11073                         paren = '>';
11074                         goto parse_rest;
11075                     }
11076
11077                     /* By doing this here, we avoid extra warnings for nested
11078                      * script runs */
11079                     ckWARNexperimental(RExC_parse,
11080                         WARN_EXPERIMENTAL__SCRIPT_RUN,
11081                         "The script_run feature is experimental");
11082
11083                     if (paren == 's') {
11084                         /* Here, we're starting a new regular script run */
11085                         ret = reg_node(pRExC_state, SROPEN);
11086                         RExC_in_script_run = 1;
11087                         is_open = 1;
11088                         goto parse_rest;
11089                     }
11090
11091                     /* Here, we are starting an atomic script run.  This is
11092                      * handled by recursing to deal with the atomic portion
11093                      * separately, enclosed in SROPEN ... SRCLOSE nodes */
11094
11095                     ret = reg_node(pRExC_state, SROPEN);
11096
11097                     RExC_in_script_run = 1;
11098
11099                     atomic = reg(pRExC_state, 'r', &flags, depth);
11100                     if (flags & (RESTART_PARSE|NEED_UTF8)) {
11101                         *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11102                         return 0;
11103                     }
11104
11105                     REGTAIL(pRExC_state, ret, atomic);
11106
11107                     REGTAIL(pRExC_state, atomic,
11108                            reg_node(pRExC_state, SRCLOSE));
11109
11110                     RExC_in_script_run = 0;
11111                     return ret;
11112                 }
11113
11114                 break;
11115
11116             lookbehind_alpha_assertions:
11117                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11118                 RExC_in_lookbehind++;
11119                 /*FALLTHROUGH*/
11120
11121             alpha_assertions:
11122                 ckWARNexperimental(RExC_parse,
11123                         WARN_EXPERIMENTAL__ALPHA_ASSERTIONS,
11124                         "The alpha_assertions feature is experimental");
11125
11126                 RExC_seen_zerolen++;
11127
11128                 if (! start_arg) {
11129                     goto no_colon;
11130                 }
11131
11132                 /* An empty negative lookahead assertion simply is failure */
11133                 if (paren == 'A' && RExC_parse == start_arg) {
11134                     ret=reganode(pRExC_state, OPFAIL, 0);
11135                     nextchar(pRExC_state);
11136                     return ret;
11137                 }
11138
11139                 RExC_parse = start_arg;
11140                 goto parse_rest;
11141
11142               no_colon:
11143                 vFAIL2utf8f(
11144                 "'(*%" UTF8f "' requires a terminating ':'",
11145                 UTF8fARG(UTF, verb_len, start_verb));
11146                 NOT_REACHED; /*NOTREACHED*/
11147
11148             } /* End of switch */
11149             if ( ! op ) {
11150                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11151                 if (has_upper || verb_len == 0) {
11152                     vFAIL2utf8f(
11153                     "Unknown verb pattern '%" UTF8f "'",
11154                     UTF8fARG(UTF, verb_len, start_verb));
11155                 }
11156                 else {
11157                     vFAIL2utf8f(
11158                     "Unknown '(*...)' construct '%" UTF8f "'",
11159                     UTF8fARG(UTF, verb_len, start_verb));
11160                 }
11161             }
11162             if ( RExC_parse == start_arg ) {
11163                 start_arg = NULL;
11164             }
11165             if ( arg_required && !start_arg ) {
11166                 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11167                     verb_len, start_verb);
11168             }
11169             if (internal_argval == -1) {
11170                 ret = reganode(pRExC_state, op, 0);
11171             } else {
11172                 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11173             }
11174             RExC_seen |= REG_VERBARG_SEEN;
11175             if (start_arg) {
11176                 SV *sv = newSVpvn( start_arg,
11177                                     RExC_parse - start_arg);
11178                 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11179                                         STR_WITH_LEN("S"));
11180                 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11181                 FLAGS(REGNODE_p(ret)) = 1;
11182             } else {
11183                 FLAGS(REGNODE_p(ret)) = 0;
11184             }
11185             if ( internal_argval != -1 )
11186                 ARG2L_SET(REGNODE_p(ret), internal_argval);
11187             nextchar(pRExC_state);
11188             return ret;
11189         }
11190         else if (*RExC_parse == '?') { /* (?...) */
11191             bool is_logical = 0;
11192             const char * const seqstart = RExC_parse;
11193             const char * endptr;
11194             if (has_intervening_patws) {
11195                 RExC_parse++;
11196                 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11197             }
11198
11199             RExC_parse++;           /* past the '?' */
11200             paren = *RExC_parse;    /* might be a trailing NUL, if not
11201                                        well-formed */
11202             RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11203             if (RExC_parse > RExC_end) {
11204                 paren = '\0';
11205             }
11206             ret = 0;                    /* For look-ahead/behind. */
11207             switch (paren) {
11208
11209             case 'P':   /* (?P...) variants for those used to PCRE/Python */
11210                 paren = *RExC_parse;
11211                 if ( paren == '<') {    /* (?P<...>) named capture */
11212                     RExC_parse++;
11213                     if (RExC_parse >= RExC_end) {
11214                         vFAIL("Sequence (?P<... not terminated");
11215                     }
11216                     goto named_capture;
11217                 }
11218                 else if (paren == '>') {   /* (?P>name) named recursion */
11219                     RExC_parse++;
11220                     if (RExC_parse >= RExC_end) {
11221                         vFAIL("Sequence (?P>... not terminated");
11222                     }
11223                     goto named_recursion;
11224                 }
11225                 else if (paren == '=') {   /* (?P=...)  named backref */
11226                     RExC_parse++;
11227                     return handle_named_backref(pRExC_state, flagp,
11228                                                 parse_start, ')');
11229                 }
11230                 RExC_parse += SKIP_IF_CHAR(RExC_parse);
11231                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11232                 vFAIL3("Sequence (%.*s...) not recognized",
11233                                 RExC_parse-seqstart, seqstart);
11234                 NOT_REACHED; /*NOTREACHED*/
11235             case '<':           /* (?<...) */
11236                 if (*RExC_parse == '!')
11237                     paren = ',';
11238                 else if (*RExC_parse != '=')
11239               named_capture:
11240                 {               /* (?<...>) */
11241                     char *name_start;
11242                     SV *svname;
11243                     paren= '>';
11244                 /* FALLTHROUGH */
11245             case '\'':          /* (?'...') */
11246                     name_start = RExC_parse;
11247                     svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11248                     if (   RExC_parse == name_start
11249                         || RExC_parse >= RExC_end
11250                         || *RExC_parse != paren)
11251                     {
11252                         vFAIL2("Sequence (?%c... not terminated",
11253                             paren=='>' ? '<' : paren);
11254                     }
11255                     {
11256                         HE *he_str;
11257                         SV *sv_dat = NULL;
11258                         if (!svname) /* shouldn't happen */
11259                             Perl_croak(aTHX_
11260                                 "panic: reg_scan_name returned NULL");
11261                         if (!RExC_paren_names) {
11262                             RExC_paren_names= newHV();
11263                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
11264 #ifdef DEBUGGING
11265                             RExC_paren_name_list= newAV();
11266                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11267 #endif
11268                         }
11269                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11270                         if ( he_str )
11271                             sv_dat = HeVAL(he_str);
11272                         if ( ! sv_dat ) {
11273                             /* croak baby croak */
11274                             Perl_croak(aTHX_
11275                                 "panic: paren_name hash element allocation failed");
11276                         } else if ( SvPOK(sv_dat) ) {
11277                             /* (?|...) can mean we have dupes so scan to check
11278                                its already been stored. Maybe a flag indicating
11279                                we are inside such a construct would be useful,
11280                                but the arrays are likely to be quite small, so
11281                                for now we punt -- dmq */
11282                             IV count = SvIV(sv_dat);
11283                             I32 *pv = (I32*)SvPVX(sv_dat);
11284                             IV i;
11285                             for ( i = 0 ; i < count ; i++ ) {
11286                                 if ( pv[i] == RExC_npar ) {
11287                                     count = 0;
11288                                     break;
11289                                 }
11290                             }
11291                             if ( count ) {
11292                                 pv = (I32*)SvGROW(sv_dat,
11293                                                 SvCUR(sv_dat) + sizeof(I32)+1);
11294                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11295                                 pv[count] = RExC_npar;
11296                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11297                             }
11298                         } else {
11299                             (void)SvUPGRADE(sv_dat, SVt_PVNV);
11300                             sv_setpvn(sv_dat, (char *)&(RExC_npar),
11301                                                                 sizeof(I32));
11302                             SvIOK_on(sv_dat);
11303                             SvIV_set(sv_dat, 1);
11304                         }
11305 #ifdef DEBUGGING
11306                         /* Yes this does cause a memory leak in debugging Perls
11307                          * */
11308                         if (!av_store(RExC_paren_name_list,
11309                                       RExC_npar, SvREFCNT_inc_NN(svname)))
11310                             SvREFCNT_dec_NN(svname);
11311 #endif
11312
11313                         /*sv_dump(sv_dat);*/
11314                     }
11315                     nextchar(pRExC_state);
11316                     paren = 1;
11317                     goto capturing_parens;
11318                 }
11319
11320                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11321                 RExC_in_lookbehind++;
11322                 RExC_parse++;
11323                 if (RExC_parse >= RExC_end) {
11324                     vFAIL("Sequence (?... not terminated");
11325                 }
11326
11327                 /* FALLTHROUGH */
11328             case '=':           /* (?=...) */
11329                 RExC_seen_zerolen++;
11330                 break;
11331             case '!':           /* (?!...) */
11332                 RExC_seen_zerolen++;
11333                 /* check if we're really just a "FAIL" assertion */
11334                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11335                                         FALSE /* Don't force to /x */ );
11336                 if (*RExC_parse == ')') {
11337                     ret=reganode(pRExC_state, OPFAIL, 0);
11338                     nextchar(pRExC_state);
11339                     return ret;
11340                 }
11341                 break;
11342             case '|':           /* (?|...) */
11343                 /* branch reset, behave like a (?:...) except that
11344                    buffers in alternations share the same numbers */
11345                 paren = ':';
11346                 after_freeze = freeze_paren = RExC_npar;
11347
11348                 /* XXX This construct currently requires an extra pass.
11349                  * Investigation would be required to see if that could be
11350                  * changed */
11351                 REQUIRE_PARENS_PASS;
11352                 break;
11353             case ':':           /* (?:...) */
11354             case '>':           /* (?>...) */
11355                 break;
11356             case '$':           /* (?$...) */
11357             case '@':           /* (?@...) */
11358                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11359                 break;
11360             case '0' :           /* (?0) */
11361             case 'R' :           /* (?R) */
11362                 if (RExC_parse == RExC_end || *RExC_parse != ')')
11363                     FAIL("Sequence (?R) not terminated");
11364                 num = 0;
11365                 RExC_seen |= REG_RECURSE_SEEN;
11366
11367                 /* XXX These constructs currently require an extra pass.
11368                  * It probably could be changed */
11369                 REQUIRE_PARENS_PASS;
11370
11371                 *flagp |= POSTPONED;
11372                 goto gen_recurse_regop;
11373                 /*notreached*/
11374             /* named and numeric backreferences */
11375             case '&':            /* (?&NAME) */
11376                 parse_start = RExC_parse - 1;
11377               named_recursion:
11378                 {
11379                     SV *sv_dat = reg_scan_name(pRExC_state,
11380                                                REG_RSN_RETURN_DATA);
11381                    num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11382                 }
11383                 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11384                     vFAIL("Sequence (?&... not terminated");
11385                 goto gen_recurse_regop;
11386                 /* NOTREACHED */
11387             case '+':
11388                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
11389                     RExC_parse++;
11390                     vFAIL("Illegal pattern");
11391                 }
11392                 goto parse_recursion;
11393                 /* NOTREACHED*/
11394             case '-': /* (?-1) */
11395                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
11396                     RExC_parse--; /* rewind to let it be handled later */
11397                     goto parse_flags;
11398                 }
11399                 /* FALLTHROUGH */
11400             case '1': case '2': case '3': case '4': /* (?1) */
11401             case '5': case '6': case '7': case '8': case '9':
11402                 RExC_parse = (char *) seqstart + 1;  /* Point to the digit */
11403               parse_recursion:
11404                 {
11405                     bool is_neg = FALSE;
11406                     UV unum;
11407                     parse_start = RExC_parse - 1; /* MJD */
11408                     if (*RExC_parse == '-') {
11409                         RExC_parse++;
11410                         is_neg = TRUE;
11411                     }
11412                     endptr = RExC_end;
11413                     if (grok_atoUV(RExC_parse, &unum, &endptr)
11414                         && unum <= I32_MAX
11415                     ) {
11416                         num = (I32)unum;
11417                         RExC_parse = (char*)endptr;
11418                     } else
11419                         num = I32_MAX;
11420                     if (is_neg) {
11421                         /* Some limit for num? */
11422                         num = -num;
11423                     }
11424                 }
11425                 if (*RExC_parse!=')')
11426                     vFAIL("Expecting close bracket");
11427
11428               gen_recurse_regop:
11429                 if ( paren == '-' ) {
11430                     /*
11431                     Diagram of capture buffer numbering.
11432                     Top line is the normal capture buffer numbers
11433                     Bottom line is the negative indexing as from
11434                     the X (the (?-2))
11435
11436                     +   1 2    3 4 5 X          6 7
11437                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11438                     -   5 4    3 2 1 X          x x
11439
11440                     */
11441                     num = RExC_npar + num;
11442                     if (num < 1)  {
11443
11444                         /* It might be a forward reference; we can't fail until
11445                          * we know, by completing the parse to get all the
11446                          * groups, and then reparsing */
11447                         if (RExC_total_parens > 0)  {
11448                             RExC_parse++;
11449                             vFAIL("Reference to nonexistent group");
11450                         }
11451                         else {
11452                             REQUIRE_PARENS_PASS;
11453                         }
11454                     }
11455                 } else if ( paren == '+' ) {
11456                     num = RExC_npar + num - 1;
11457                 }
11458                 /* We keep track how many GOSUB items we have produced.
11459                    To start off the ARG2L() of the GOSUB holds its "id",
11460                    which is used later in conjunction with RExC_recurse
11461                    to calculate the offset we need to jump for the GOSUB,
11462                    which it will store in the final representation.
11463                    We have to defer the actual calculation until much later
11464                    as the regop may move.
11465                  */
11466
11467                 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11468                 if (num >= RExC_npar) {
11469
11470                     /* It might be a forward reference; we can't fail until we
11471                      * know, by completing the parse to get all the groups, and
11472                      * then reparsing */
11473                     if (RExC_total_parens > 0)  {
11474                         if (num >= RExC_total_parens) {
11475                             RExC_parse++;
11476                             vFAIL("Reference to nonexistent group");
11477                         }
11478                     }
11479                     else {
11480                         REQUIRE_PARENS_PASS;
11481                     }
11482                 }
11483                 RExC_recurse_count++;
11484                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11485                     "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11486                             22, "|    |", (int)(depth * 2 + 1), "",
11487                             (UV)ARG(REGNODE_p(ret)),
11488                             (IV)ARG2L(REGNODE_p(ret))));
11489                 RExC_seen |= REG_RECURSE_SEEN;
11490
11491                 Set_Node_Length(REGNODE_p(ret),
11492                                 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11493                 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11494
11495                 *flagp |= POSTPONED;
11496                 assert(*RExC_parse == ')');
11497                 nextchar(pRExC_state);
11498                 return ret;
11499
11500             /* NOTREACHED */
11501
11502             case '?':           /* (??...) */
11503                 is_logical = 1;
11504                 if (*RExC_parse != '{') {
11505                     RExC_parse += SKIP_IF_CHAR(RExC_parse);
11506                     /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11507                     vFAIL2utf8f(
11508                         "Sequence (%" UTF8f "...) not recognized",
11509                         UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11510                     NOT_REACHED; /*NOTREACHED*/
11511                 }
11512                 *flagp |= POSTPONED;
11513                 paren = '{';
11514                 RExC_parse++;
11515                 /* FALLTHROUGH */
11516             case '{':           /* (?{...}) */
11517             {
11518                 U32 n = 0;
11519                 struct reg_code_block *cb;
11520                 OP * o;
11521
11522                 RExC_seen_zerolen++;
11523
11524                 if (   !pRExC_state->code_blocks
11525                     || pRExC_state->code_index
11526                                         >= pRExC_state->code_blocks->count
11527                     || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11528                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11529                             - RExC_start)
11530                 ) {
11531                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
11532                         FAIL("panic: Sequence (?{...}): no code block found\n");
11533                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
11534                 }
11535                 /* this is a pre-compiled code block (?{...}) */
11536                 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11537                 RExC_parse = RExC_start + cb->end;
11538                 o = cb->block;
11539                 if (cb->src_regex) {
11540                     n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11541                     RExC_rxi->data->data[n] =
11542                         (void*)SvREFCNT_inc((SV*)cb->src_regex);
11543                     RExC_rxi->data->data[n+1] = (void*)o;
11544                 }
11545                 else {
11546                     n = add_data(pRExC_state,
11547                             (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11548                     RExC_rxi->data->data[n] = (void*)o;
11549                 }
11550                 pRExC_state->code_index++;
11551                 nextchar(pRExC_state);
11552
11553                 if (is_logical) {
11554                     regnode_offset eval;
11555                     ret = reg_node(pRExC_state, LOGICAL);
11556
11557                     eval = reg2Lanode(pRExC_state, EVAL,
11558                                        n,
11559
11560                                        /* for later propagation into (??{})
11561                                         * return value */
11562                                        RExC_flags & RXf_PMf_COMPILETIME
11563                                       );
11564                     FLAGS(REGNODE_p(ret)) = 2;
11565                     REGTAIL(pRExC_state, ret, eval);
11566                     /* deal with the length of this later - MJD */
11567                     return ret;
11568                 }
11569                 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11570                 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11571                 Set_Node_Offset(REGNODE_p(ret), parse_start);
11572                 return ret;
11573             }
11574             case '(':           /* (?(?{...})...) and (?(?=...)...) */
11575             {
11576                 int is_define= 0;
11577                 const int DEFINE_len = sizeof("DEFINE") - 1;
11578                 if (    RExC_parse < RExC_end - 1
11579                     && (   (       RExC_parse[0] == '?'        /* (?(?...)) */
11580                             && (   RExC_parse[1] == '='
11581                                 || RExC_parse[1] == '!'
11582                                 || RExC_parse[1] == '<'
11583                                 || RExC_parse[1] == '{'))
11584                         || (       RExC_parse[0] == '*'        /* (?(*...)) */
11585                             && (   memBEGINs(RExC_parse + 1,
11586                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11587                                          "pla:")
11588                                 || memBEGINs(RExC_parse + 1,
11589                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11590                                          "plb:")
11591                                 || memBEGINs(RExC_parse + 1,
11592                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11593                                          "nla:")
11594                                 || memBEGINs(RExC_parse + 1,
11595                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11596                                          "nlb:")
11597                                 || memBEGINs(RExC_parse + 1,
11598                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11599                                          "positive_lookahead:")
11600                                 || memBEGINs(RExC_parse + 1,
11601                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11602                                          "positive_lookbehind:")
11603                                 || memBEGINs(RExC_parse + 1,
11604                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11605                                          "negative_lookahead:")
11606                                 || memBEGINs(RExC_parse + 1,
11607                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11608                                          "negative_lookbehind:"))))
11609                 ) { /* Lookahead or eval. */
11610                     I32 flag;
11611                     regnode_offset tail;
11612
11613                     ret = reg_node(pRExC_state, LOGICAL);
11614                     FLAGS(REGNODE_p(ret)) = 1;
11615
11616                     tail = reg(pRExC_state, 1, &flag, depth+1);
11617                     RETURN_FAIL_ON_RESTART(flag, flagp);
11618                     REGTAIL(pRExC_state, ret, tail);
11619                     goto insert_if;
11620                 }
11621                 else if (   RExC_parse[0] == '<'     /* (?(<NAME>)...) */
11622                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11623                 {
11624                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
11625                     char *name_start= RExC_parse++;
11626                     U32 num = 0;
11627                     SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11628                     if (   RExC_parse == name_start
11629                         || RExC_parse >= RExC_end
11630                         || *RExC_parse != ch)
11631                     {
11632                         vFAIL2("Sequence (?(%c... not terminated",
11633                             (ch == '>' ? '<' : ch));
11634                     }
11635                     RExC_parse++;
11636                     if (sv_dat) {
11637                         num = add_data( pRExC_state, STR_WITH_LEN("S"));
11638                         RExC_rxi->data->data[num]=(void*)sv_dat;
11639                         SvREFCNT_inc_simple_void_NN(sv_dat);
11640                     }
11641                     ret = reganode(pRExC_state, NGROUPP, num);
11642                     goto insert_if_check_paren;
11643                 }
11644                 else if (memBEGINs(RExC_parse,
11645                                    (STRLEN) (RExC_end - RExC_parse),
11646                                    "DEFINE"))
11647                 {
11648                     ret = reganode(pRExC_state, DEFINEP, 0);
11649                     RExC_parse += DEFINE_len;
11650                     is_define = 1;
11651                     goto insert_if_check_paren;
11652                 }
11653                 else if (RExC_parse[0] == 'R') {
11654                     RExC_parse++;
11655                     /* parno == 0 => /(?(R)YES|NO)/  "in any form of recursion OR eval"
11656                      * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
11657                      * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
11658                      */
11659                     parno = 0;
11660                     if (RExC_parse[0] == '0') {
11661                         parno = 1;
11662                         RExC_parse++;
11663                     }
11664                     else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
11665                         UV uv;
11666                         endptr = RExC_end;
11667                         if (grok_atoUV(RExC_parse, &uv, &endptr)
11668                             && uv <= I32_MAX
11669                         ) {
11670                             parno = (I32)uv + 1;
11671                             RExC_parse = (char*)endptr;
11672                         }
11673                         /* else "Switch condition not recognized" below */
11674                     } else if (RExC_parse[0] == '&') {
11675                         SV *sv_dat;
11676                         RExC_parse++;
11677                         sv_dat = reg_scan_name(pRExC_state,
11678                                                REG_RSN_RETURN_DATA);
11679                         if (sv_dat)
11680                             parno = 1 + *((I32 *)SvPVX(sv_dat));
11681                     }
11682                     ret = reganode(pRExC_state, INSUBP, parno);
11683                     goto insert_if_check_paren;
11684                 }
11685                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
11686                     /* (?(1)...) */
11687                     char c;
11688                     UV uv;
11689                     endptr = RExC_end;
11690                     if (grok_atoUV(RExC_parse, &uv, &endptr)
11691                         && uv <= I32_MAX
11692                     ) {
11693                         parno = (I32)uv;
11694                         RExC_parse = (char*)endptr;
11695                     }
11696                     else {
11697                         vFAIL("panic: grok_atoUV returned FALSE");
11698                     }
11699                     ret = reganode(pRExC_state, GROUPP, parno);
11700
11701                  insert_if_check_paren:
11702                     if (UCHARAT(RExC_parse) != ')') {
11703                         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11704                         vFAIL("Switch condition not recognized");
11705                     }
11706                     nextchar(pRExC_state);
11707                   insert_if:
11708                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
11709                     br = regbranch(pRExC_state, &flags, 1, depth+1);
11710                     if (br == 0) {
11711                         RETURN_FAIL_ON_RESTART(flags,flagp);
11712                         FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11713                               (UV) flags);
11714                     } else
11715                         REGTAIL(pRExC_state, br, reganode(pRExC_state,
11716                                                           LONGJMP, 0));
11717                     c = UCHARAT(RExC_parse);
11718                     nextchar(pRExC_state);
11719                     if (flags&HASWIDTH)
11720                         *flagp |= HASWIDTH;
11721                     if (c == '|') {
11722                         if (is_define)
11723                             vFAIL("(?(DEFINE)....) does not allow branches");
11724
11725                         /* Fake one for optimizer.  */
11726                         lastbr = reganode(pRExC_state, IFTHEN, 0);
11727
11728                         if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
11729                             RETURN_FAIL_ON_RESTART(flags, flagp);
11730                             FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11731                                   (UV) flags);
11732                         }
11733                         REGTAIL(pRExC_state, ret, lastbr);
11734                         if (flags&HASWIDTH)
11735                             *flagp |= HASWIDTH;
11736                         c = UCHARAT(RExC_parse);
11737                         nextchar(pRExC_state);
11738                     }
11739                     else
11740                         lastbr = 0;
11741                     if (c != ')') {
11742                         if (RExC_parse >= RExC_end)
11743                             vFAIL("Switch (?(condition)... not terminated");
11744                         else
11745                             vFAIL("Switch (?(condition)... contains too many branches");
11746                     }
11747                     ender = reg_node(pRExC_state, TAIL);
11748                     REGTAIL(pRExC_state, br, ender);
11749                     if (lastbr) {
11750                         REGTAIL(pRExC_state, lastbr, ender);
11751                         REGTAIL(pRExC_state, REGNODE_OFFSET(
11752                                                 NEXTOPER(
11753                                                 NEXTOPER(REGNODE_p(lastbr)))),
11754                                              ender);
11755                     }
11756                     else
11757                         REGTAIL(pRExC_state, ret, ender);
11758 #if 0  /* Removing this doesn't cause failures in the test suite -- khw */
11759                     RExC_size++; /* XXX WHY do we need this?!!
11760                                     For large programs it seems to be required
11761                                     but I can't figure out why. -- dmq*/
11762 #endif
11763                     return ret;
11764                 }
11765                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11766                 vFAIL("Unknown switch condition (?(...))");
11767             }
11768             case '[':           /* (?[ ... ]) */
11769                 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
11770                                          oregcomp_parse);
11771             case 0: /* A NUL */
11772                 RExC_parse--; /* for vFAIL to print correctly */
11773                 vFAIL("Sequence (? incomplete");
11774                 break;
11775             default: /* e.g., (?i) */
11776                 RExC_parse = (char *) seqstart + 1;
11777               parse_flags:
11778                 parse_lparen_question_flags(pRExC_state);
11779                 if (UCHARAT(RExC_parse) != ':') {
11780                     if (RExC_parse < RExC_end)
11781                         nextchar(pRExC_state);
11782                     *flagp = TRYAGAIN;
11783                     return 0;
11784                 }
11785                 paren = ':';
11786                 nextchar(pRExC_state);
11787                 ret = 0;
11788                 goto parse_rest;
11789             } /* end switch */
11790         }
11791         else {
11792             if (*RExC_parse == '{') {
11793                 ckWARNregdep(RExC_parse + 1,
11794                             "Unescaped left brace in regex is "
11795                             "deprecated here (and will be fatal "
11796                             "in Perl 5.32), passed through");
11797             }
11798             /* Not bothering to indent here, as the above 'else' is temporary
11799              * */
11800         if (!(RExC_flags & RXf_PMf_NOCAPTURE)) {   /* (...) */
11801           capturing_parens:
11802             parno = RExC_npar;
11803             RExC_npar++;
11804             if (RExC_total_parens <= 0) {
11805                 /* If we are in our first pass through (and maybe only pass),
11806                  * we  need to allocate memory for the capturing parentheses
11807                  * data structures.  Since we start at npar=1, when it reaches
11808                  * 2, for the first time it has something to put in it.  Above
11809                  * 2 means we extend what we already have */
11810                 if (RExC_npar == 2) {
11811                     /* setup RExC_open_parens, which holds the address of each
11812                      * OPEN tag, and to make things simpler for the 0 index the
11813                      * start of the program - this is used later for offsets */
11814                     Newxz(RExC_open_parens, RExC_npar, regnode_offset);
11815                     RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
11816
11817                     /* setup RExC_close_parens, which holds the address of each
11818                      * CLOSE tag, and to make things simpler for the 0 index
11819                      * the end of the program - this is used later for offsets
11820                      * */
11821                     Newxz(RExC_close_parens, RExC_npar, regnode_offset);
11822                     /* we dont know where end op starts yet, so we dont need to
11823                      * set RExC_close_parens[0] like we do RExC_open_parens[0]
11824                      * above */
11825                 }
11826                 else {
11827                     Renew(RExC_open_parens, RExC_npar, regnode_offset);
11828                     Zero(RExC_open_parens + RExC_npar - 1, 1, regnode_offset);
11829
11830                     Renew(RExC_close_parens, RExC_npar, regnode_offset);
11831                     Zero(RExC_close_parens + RExC_npar - 1, 1, regnode_offset);
11832                 }
11833             }
11834
11835             ret = reganode(pRExC_state, OPEN, parno);
11836             if (!RExC_nestroot)
11837                 RExC_nestroot = parno;
11838             if (RExC_open_parens && !RExC_open_parens[parno])
11839             {
11840                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11841                     "%*s%*s Setting open paren #%" IVdf " to %d\n",
11842                     22, "|    |", (int)(depth * 2 + 1), "",
11843                     (IV)parno, REG_NODE_NUM(REGNODE_p(ret))));
11844                 RExC_open_parens[parno]= ret;
11845             }
11846
11847             Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
11848             Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
11849             is_open = 1;
11850         } else {
11851             /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
11852             paren = ':';
11853             ret = 0;
11854         }
11855         }
11856     }
11857     else                        /* ! paren */
11858         ret = 0;
11859
11860    parse_rest:
11861     /* Pick up the branches, linking them together. */
11862     parse_start = RExC_parse;   /* MJD */
11863     br = regbranch(pRExC_state, &flags, 1, depth+1);
11864
11865     /*     branch_len = (paren != 0); */
11866
11867     if (br == 0) {
11868         RETURN_FAIL_ON_RESTART(flags, flagp);
11869         FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
11870     }
11871     if (*RExC_parse == '|') {
11872         if (RExC_use_BRANCHJ) {
11873             reginsert(pRExC_state, BRANCHJ, br, depth+1);
11874         }
11875         else {                  /* MJD */
11876             reginsert(pRExC_state, BRANCH, br, depth+1);
11877             Set_Node_Length(REGNODE_p(br), paren != 0);
11878             Set_Node_Offset_To_R(br, parse_start-RExC_start);
11879         }
11880         have_branch = 1;
11881     }
11882     else if (paren == ':') {
11883         *flagp |= flags&SIMPLE;
11884     }
11885     if (is_open) {                              /* Starts with OPEN. */
11886         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
11887     }
11888     else if (paren != '?')              /* Not Conditional */
11889         ret = br;
11890     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
11891     lastbr = br;
11892     while (*RExC_parse == '|') {
11893         if (RExC_use_BRANCHJ) {
11894             ender = reganode(pRExC_state, LONGJMP, 0);
11895
11896             /* Append to the previous. */
11897             REGTAIL(pRExC_state,
11898                     REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
11899                     ender);
11900         }
11901         nextchar(pRExC_state);
11902         if (freeze_paren) {
11903             if (RExC_npar > after_freeze)
11904                 after_freeze = RExC_npar;
11905             RExC_npar = freeze_paren;
11906         }
11907         br = regbranch(pRExC_state, &flags, 0, depth+1);
11908
11909         if (br == 0) {
11910             RETURN_FAIL_ON_RESTART(flags, flagp);
11911             FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
11912         }
11913         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
11914         lastbr = br;
11915         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
11916     }
11917
11918     if (have_branch || paren != ':') {
11919         regnode * br;
11920
11921         /* Make a closing node, and hook it on the end. */
11922         switch (paren) {
11923         case ':':
11924             ender = reg_node(pRExC_state, TAIL);
11925             break;
11926         case 1: case 2:
11927             ender = reganode(pRExC_state, CLOSE, parno);
11928             if ( RExC_close_parens ) {
11929                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11930                         "%*s%*s Setting close paren #%" IVdf " to %d\n",
11931                         22, "|    |", (int)(depth * 2 + 1), "",
11932                         (IV)parno, REG_NODE_NUM(REGNODE_p(ender))));
11933                 RExC_close_parens[parno]= ender;
11934                 if (RExC_nestroot == parno)
11935                     RExC_nestroot = 0;
11936             }
11937             Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
11938             Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
11939             break;
11940         case 's':
11941             ender = reg_node(pRExC_state, SRCLOSE);
11942             RExC_in_script_run = 0;
11943             break;
11944         case '<':
11945         case 'a':
11946         case 'A':
11947         case 'b':
11948         case 'B':
11949         case ',':
11950         case '=':
11951         case '!':
11952             *flagp &= ~HASWIDTH;
11953             /* FALLTHROUGH */
11954         case 't':   /* aTomic */
11955         case '>':
11956             ender = reg_node(pRExC_state, SUCCEED);
11957             break;
11958         case 0:
11959             ender = reg_node(pRExC_state, END);
11960             assert(!RExC_end_op); /* there can only be one! */
11961             RExC_end_op = REGNODE_p(ender);
11962             if (RExC_close_parens) {
11963                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11964                     "%*s%*s Setting close paren #0 (END) to %d\n",
11965                     22, "|    |", (int)(depth * 2 + 1), "",
11966                     REG_NODE_NUM(REGNODE_p(ender))));
11967
11968                 RExC_close_parens[0]= ender;
11969             }
11970             break;
11971         }
11972         DEBUG_PARSE_r(
11973             DEBUG_PARSE_MSG("lsbr");
11974             regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
11975             regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
11976             Perl_re_printf( aTHX_  "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
11977                           SvPV_nolen_const(RExC_mysv1),
11978                           (IV)REG_NODE_NUM(REGNODE_p(lastbr)),
11979                           SvPV_nolen_const(RExC_mysv2),
11980                           (IV)REG_NODE_NUM(REGNODE_p(ender)),
11981                           (IV)(ender - lastbr)
11982             );
11983         );
11984         REGTAIL(pRExC_state, lastbr, ender);
11985
11986         if (have_branch) {
11987             char is_nothing= 1;
11988             if (depth==1)
11989                 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
11990
11991             /* Hook the tails of the branches to the closing node. */
11992             for (br = REGNODE_p(ret); br; br = regnext(br)) {
11993                 const U8 op = PL_regkind[OP(br)];
11994                 if (op == BRANCH) {
11995                     REGTAIL_STUDY(pRExC_state,
11996                                   REGNODE_OFFSET(NEXTOPER(br)),
11997                                   ender);
11998                     if ( OP(NEXTOPER(br)) != NOTHING
11999                          || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12000                         is_nothing= 0;
12001                 }
12002                 else if (op == BRANCHJ) {
12003                     REGTAIL_STUDY(pRExC_state,
12004                                   REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12005                                   ender);
12006                     /* for now we always disable this optimisation * /
12007                     if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12008                          || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12009                     */
12010                         is_nothing= 0;
12011                 }
12012             }
12013             if (is_nothing) {
12014                 regnode * ret_as_regnode = REGNODE_p(ret);
12015                 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12016                                ? regnext(ret_as_regnode)
12017                                : ret_as_regnode;
12018                 DEBUG_PARSE_r(
12019                     DEBUG_PARSE_MSG("NADA");
12020                     regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12021                                      NULL, pRExC_state);
12022                     regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12023                                      NULL, pRExC_state);
12024                     Perl_re_printf( aTHX_  "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12025                                   SvPV_nolen_const(RExC_mysv1),
12026                                   (IV)REG_NODE_NUM(ret_as_regnode),
12027                                   SvPV_nolen_const(RExC_mysv2),
12028                                   (IV)REG_NODE_NUM(REGNODE_p(ender)),
12029                                   (IV)(ender - ret)
12030                     );
12031                 );
12032                 OP(br)= NOTHING;
12033                 if (OP(REGNODE_p(ender)) == TAIL) {
12034                     NEXT_OFF(br)= 0;
12035                     RExC_emit= REGNODE_OFFSET(br) + 1;
12036                 } else {
12037                     regnode *opt;
12038                     for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12039                         OP(opt)= OPTIMIZED;
12040                     NEXT_OFF(br)= REGNODE_p(ender) - br;
12041                 }
12042             }
12043         }
12044     }
12045
12046     {
12047         const char *p;
12048          /* Even/odd or x=don't care: 010101x10x */
12049         static const char parens[] = "=!aA<,>Bbt";
12050          /* flag below is set to 0 up through 'A'; 1 for larger */
12051
12052         if (paren && (p = strchr(parens, paren))) {
12053             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12054             int flag = (p - parens) > 3;
12055
12056             if (paren == '>' || paren == 't') {
12057                 node = SUSPEND, flag = 0;
12058             }
12059
12060             reginsert(pRExC_state, node, ret, depth+1);
12061             Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12062             Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12063             FLAGS(REGNODE_p(ret)) = flag;
12064             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
12065         }
12066     }
12067
12068     /* Check for proper termination. */
12069     if (paren) {
12070         /* restore original flags, but keep (?p) and, if we've changed from /d
12071          * rules to /u, keep the /u */
12072         RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12073         if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12074             set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12075         }
12076         if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12077             RExC_parse = oregcomp_parse;
12078             vFAIL("Unmatched (");
12079         }
12080         nextchar(pRExC_state);
12081     }
12082     else if (!paren && RExC_parse < RExC_end) {
12083         if (*RExC_parse == ')') {
12084             RExC_parse++;
12085             vFAIL("Unmatched )");
12086         }
12087         else
12088             FAIL("Junk on end of regexp");      /* "Can't happen". */
12089         NOT_REACHED; /* NOTREACHED */
12090     }
12091
12092     if (RExC_in_lookbehind) {
12093         RExC_in_lookbehind--;
12094     }
12095     if (after_freeze > RExC_npar)
12096         RExC_npar = after_freeze;
12097     return(ret);
12098 }
12099
12100 /*
12101  - regbranch - one alternative of an | operator
12102  *
12103  * Implements the concatenation operator.
12104  *
12105  * On success, returns the offset at which any next node should be placed into
12106  * the regex engine program being compiled.
12107  *
12108  * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12109  * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12110  * UTF-8
12111  */
12112 STATIC regnode_offset
12113 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12114 {
12115     regnode_offset ret;
12116     regnode_offset chain = 0;
12117     regnode_offset latest;
12118     I32 flags = 0, c = 0;
12119     GET_RE_DEBUG_FLAGS_DECL;
12120
12121     PERL_ARGS_ASSERT_REGBRANCH;
12122
12123     DEBUG_PARSE("brnc");
12124
12125     if (first)
12126         ret = 0;
12127     else {
12128         if (RExC_use_BRANCHJ)
12129             ret = reganode(pRExC_state, BRANCHJ, 0);
12130         else {
12131             ret = reg_node(pRExC_state, BRANCH);
12132             Set_Node_Length(REGNODE_p(ret), 1);
12133         }
12134     }
12135
12136     *flagp = WORST;                     /* Tentatively. */
12137
12138     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12139                             FALSE /* Don't force to /x */ );
12140     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12141         flags &= ~TRYAGAIN;
12142         latest = regpiece(pRExC_state, &flags, depth+1);
12143         if (latest == 0) {
12144             if (flags & TRYAGAIN)
12145                 continue;
12146             RETURN_FAIL_ON_RESTART(flags, flagp);
12147             FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12148         }
12149         else if (ret == 0)
12150             ret = latest;
12151         *flagp |= flags&(HASWIDTH|POSTPONED);
12152         if (chain == 0)         /* First piece. */
12153             *flagp |= flags&SPSTART;
12154         else {
12155             /* FIXME adding one for every branch after the first is probably
12156              * excessive now we have TRIE support. (hv) */
12157             MARK_NAUGHTY(1);
12158             if (     chain > (SSize_t) BRANCH_MAX_OFFSET
12159                 && ! RExC_use_BRANCHJ)
12160             {
12161                 /* XXX We could just redo this branch, but figuring out what
12162                  * bookkeeping needs to be reset is a pain */
12163                 REQUIRE_BRANCHJ(flagp, 0);
12164             }
12165             REGTAIL(pRExC_state, chain, latest);
12166         }
12167         chain = latest;
12168         c++;
12169     }
12170     if (chain == 0) {   /* Loop ran zero times. */
12171         chain = reg_node(pRExC_state, NOTHING);
12172         if (ret == 0)
12173             ret = chain;
12174     }
12175     if (c == 1) {
12176         *flagp |= flags&SIMPLE;
12177     }
12178
12179     return ret;
12180 }
12181
12182 /*
12183  - regpiece - something followed by possible quantifier * + ? {n,m}
12184  *
12185  * Note that the branching code sequences used for ? and the general cases
12186  * of * and + are somewhat optimized:  they use the same NOTHING node as
12187  * both the endmarker for their branch list and the body of the last branch.
12188  * It might seem that this node could be dispensed with entirely, but the
12189  * endmarker role is not redundant.
12190  *
12191  * On success, returns the offset at which any next node should be placed into
12192  * the regex engine program being compiled.
12193  *
12194  * Returns 0 otherwise, with *flagp set to indicate why:
12195  *  TRYAGAIN        if regatom() returns 0 with TRYAGAIN.
12196  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
12197  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12198  */
12199 STATIC regnode_offset
12200 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12201 {
12202     regnode_offset ret;
12203     char op;
12204     char *next;
12205     I32 flags;
12206     const char * const origparse = RExC_parse;
12207     I32 min;
12208     I32 max = REG_INFTY;
12209 #ifdef RE_TRACK_PATTERN_OFFSETS
12210     char *parse_start;
12211 #endif
12212     const char *maxpos = NULL;
12213     UV uv;
12214
12215     /* Save the original in case we change the emitted regop to a FAIL. */
12216     const regnode_offset orig_emit = RExC_emit;
12217
12218     GET_RE_DEBUG_FLAGS_DECL;
12219
12220     PERL_ARGS_ASSERT_REGPIECE;
12221
12222     DEBUG_PARSE("piec");
12223
12224     ret = regatom(pRExC_state, &flags, depth+1);
12225     if (ret == 0) {
12226         RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12227         FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12228     }
12229
12230     op = *RExC_parse;
12231
12232     if (op == '{' && regcurly(RExC_parse)) {
12233         maxpos = NULL;
12234 #ifdef RE_TRACK_PATTERN_OFFSETS
12235         parse_start = RExC_parse; /* MJD */
12236 #endif
12237         next = RExC_parse + 1;
12238         while (isDIGIT(*next) || *next == ',') {
12239             if (*next == ',') {
12240                 if (maxpos)
12241                     break;
12242                 else
12243                     maxpos = next;
12244             }
12245             next++;
12246         }
12247         if (*next == '}') {             /* got one */
12248             const char* endptr;
12249             if (!maxpos)
12250                 maxpos = next;
12251             RExC_parse++;
12252             if (isDIGIT(*RExC_parse)) {
12253                 endptr = RExC_end;
12254                 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12255                     vFAIL("Invalid quantifier in {,}");
12256                 if (uv >= REG_INFTY)
12257                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12258                 min = (I32)uv;
12259             } else {
12260                 min = 0;
12261             }
12262             if (*maxpos == ',')
12263                 maxpos++;
12264             else
12265                 maxpos = RExC_parse;
12266             if (isDIGIT(*maxpos)) {
12267                 endptr = RExC_end;
12268                 if (!grok_atoUV(maxpos, &uv, &endptr))
12269                     vFAIL("Invalid quantifier in {,}");
12270                 if (uv >= REG_INFTY)
12271                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12272                 max = (I32)uv;
12273             } else {
12274                 max = REG_INFTY;                /* meaning "infinity" */
12275             }
12276             RExC_parse = next;
12277             nextchar(pRExC_state);
12278             if (max < min) {    /* If can't match, warn and optimize to fail
12279                                    unconditionally */
12280                 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12281                 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12282                 NEXT_OFF(REGNODE_p(orig_emit)) =
12283                                     regarglen[OPFAIL] + NODE_STEP_REGNODE;
12284                 return ret;
12285             }
12286             else if (min == max && *RExC_parse == '?')
12287             {
12288                 ckWARN2reg(RExC_parse + 1,
12289                            "Useless use of greediness modifier '%c'",
12290                            *RExC_parse);
12291             }
12292
12293           do_curly:
12294             if ((flags&SIMPLE)) {
12295                 if (min == 0 && max == REG_INFTY) {
12296                     reginsert(pRExC_state, STAR, ret, depth+1);
12297                     MARK_NAUGHTY(4);
12298                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12299                     goto nest_check;
12300                 }
12301                 if (min == 1 && max == REG_INFTY) {
12302                     reginsert(pRExC_state, PLUS, ret, depth+1);
12303                     MARK_NAUGHTY(3);
12304                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12305                     goto nest_check;
12306                 }
12307                 MARK_NAUGHTY_EXP(2, 2);
12308                 reginsert(pRExC_state, CURLY, ret, depth+1);
12309                 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12310                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12311             }
12312             else {
12313                 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12314
12315                 FLAGS(REGNODE_p(w)) = 0;
12316                 REGTAIL(pRExC_state, ret, w);
12317                 if (RExC_use_BRANCHJ) {
12318                     reginsert(pRExC_state, LONGJMP, ret, depth+1);
12319                     reginsert(pRExC_state, NOTHING, ret, depth+1);
12320                     NEXT_OFF(REGNODE_p(ret)) = 3;       /* Go over LONGJMP. */
12321                 }
12322                 reginsert(pRExC_state, CURLYX, ret, depth+1);
12323                                 /* MJD hk */
12324                 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12325                 Set_Node_Length(REGNODE_p(ret),
12326                                 op == '{' ? (RExC_parse - parse_start) : 1);
12327
12328                 if (RExC_use_BRANCHJ)
12329                     NEXT_OFF(REGNODE_p(ret)) = 3;   /* Go over NOTHING to
12330                                                        LONGJMP. */
12331                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
12332                 RExC_whilem_seen++;
12333                 MARK_NAUGHTY_EXP(1, 4);     /* compound interest */
12334             }
12335             FLAGS(REGNODE_p(ret)) = 0;
12336
12337             if (min > 0)
12338                 *flagp = WORST;
12339             if (max > 0)
12340                 *flagp |= HASWIDTH;
12341             ARG1_SET(REGNODE_p(ret), (U16)min);
12342             ARG2_SET(REGNODE_p(ret), (U16)max);
12343             if (max == REG_INFTY)
12344                 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12345
12346             goto nest_check;
12347         }
12348     }
12349
12350     if (!ISMULT1(op)) {
12351         *flagp = flags;
12352         return(ret);
12353     }
12354
12355 #if 0                           /* Now runtime fix should be reliable. */
12356
12357     /* if this is reinstated, don't forget to put this back into perldiag:
12358
12359             =item Regexp *+ operand could be empty at {#} in regex m/%s/
12360
12361            (F) The part of the regexp subject to either the * or + quantifier
12362            could match an empty string. The {#} shows in the regular
12363            expression about where the problem was discovered.
12364
12365     */
12366
12367     if (!(flags&HASWIDTH) && op != '?')
12368       vFAIL("Regexp *+ operand could be empty");
12369 #endif
12370
12371 #ifdef RE_TRACK_PATTERN_OFFSETS
12372     parse_start = RExC_parse;
12373 #endif
12374     nextchar(pRExC_state);
12375
12376     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12377
12378     if (op == '*') {
12379         min = 0;
12380         goto do_curly;
12381     }
12382     else if (op == '+') {
12383         min = 1;
12384         goto do_curly;
12385     }
12386     else if (op == '?') {
12387         min = 0; max = 1;
12388         goto do_curly;
12389     }
12390   nest_check:
12391     if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12392         ckWARN2reg(RExC_parse,
12393                    "%" UTF8f " matches null string many times",
12394                    UTF8fARG(UTF, (RExC_parse >= origparse
12395                                  ? RExC_parse - origparse
12396                                  : 0),
12397                    origparse));
12398     }
12399
12400     if (*RExC_parse == '?') {
12401         nextchar(pRExC_state);
12402         reginsert(pRExC_state, MINMOD, ret, depth+1);
12403         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
12404     }
12405     else if (*RExC_parse == '+') {
12406         regnode_offset ender;
12407         nextchar(pRExC_state);
12408         ender = reg_node(pRExC_state, SUCCEED);
12409         REGTAIL(pRExC_state, ret, ender);
12410         reginsert(pRExC_state, SUSPEND, ret, depth+1);
12411         ender = reg_node(pRExC_state, TAIL);
12412         REGTAIL(pRExC_state, ret, ender);
12413     }
12414
12415     if (ISMULT2(RExC_parse)) {
12416         RExC_parse++;
12417         vFAIL("Nested quantifiers");
12418     }
12419
12420     return(ret);
12421 }
12422
12423 STATIC bool
12424 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12425                 regnode_offset * node_p,
12426                 UV * code_point_p,
12427                 int * cp_count,
12428                 I32 * flagp,
12429                 const bool strict,
12430                 const U32 depth
12431     )
12432 {
12433  /* This routine teases apart the various meanings of \N and returns
12434   * accordingly.  The input parameters constrain which meaning(s) is/are valid
12435   * in the current context.
12436   *
12437   * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12438   *
12439   * If <code_point_p> is not NULL, the context is expecting the result to be a
12440   * single code point.  If this \N instance turns out to a single code point,
12441   * the function returns TRUE and sets *code_point_p to that code point.
12442   *
12443   * If <node_p> is not NULL, the context is expecting the result to be one of
12444   * the things representable by a regnode.  If this \N instance turns out to be
12445   * one such, the function generates the regnode, returns TRUE and sets *node_p
12446   * to point to the offset of that regnode into the regex engine program being
12447   * compiled.
12448   *
12449   * If this instance of \N isn't legal in any context, this function will
12450   * generate a fatal error and not return.
12451   *
12452   * On input, RExC_parse should point to the first char following the \N at the
12453   * time of the call.  On successful return, RExC_parse will have been updated
12454   * to point to just after the sequence identified by this routine.  Also
12455   * *flagp has been updated as needed.
12456   *
12457   * When there is some problem with the current context and this \N instance,
12458   * the function returns FALSE, without advancing RExC_parse, nor setting
12459   * *node_p, nor *code_point_p, nor *flagp.
12460   *
12461   * If <cp_count> is not NULL, the caller wants to know the length (in code
12462   * points) that this \N sequence matches.  This is set, and the input is
12463   * parsed for errors, even if the function returns FALSE, as detailed below.
12464   *
12465   * There are 5 possibilities here, as detailed in the next 5 paragraphs.
12466   *
12467   * Probably the most common case is for the \N to specify a single code point.
12468   * *cp_count will be set to 1, and *code_point_p will be set to that code
12469   * point.
12470   *
12471   * Another possibility is for the input to be an empty \N{}, which for
12472   * backwards compatibility we accept.  *cp_count will be set to 0. *node_p
12473   * will be set to a generated NOTHING node.
12474   *
12475   * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12476   * set to 0. *node_p will be set to a generated REG_ANY node.
12477   *
12478   * The fourth possibility is that \N resolves to a sequence of more than one
12479   * code points.  *cp_count will be set to the number of code points in the
12480   * sequence. *node_p will be set to a generated node returned by this
12481   * function calling S_reg().
12482   *
12483   * The final possibility is that it is premature to be calling this function;
12484   * the parse needs to be restarted.  This can happen when this changes from
12485   * /d to /u rules, or when the pattern needs to be upgraded to UTF-8.  The
12486   * latter occurs only when the fourth possibility would otherwise be in
12487   * effect, and is because one of those code points requires the pattern to be
12488   * recompiled as UTF-8.  The function returns FALSE, and sets the
12489   * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate.  When this
12490   * happens, the caller needs to desist from continuing parsing, and return
12491   * this information to its caller.  This is not set for when there is only one
12492   * code point, as this can be called as part of an ANYOF node, and they can
12493   * store above-Latin1 code points without the pattern having to be in UTF-8.
12494   *
12495   * For non-single-quoted regexes, the tokenizer has resolved character and
12496   * sequence names inside \N{...} into their Unicode values, normalizing the
12497   * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12498   * hex-represented code points in the sequence.  This is done there because
12499   * the names can vary based on what charnames pragma is in scope at the time,
12500   * so we need a way to take a snapshot of what they resolve to at the time of
12501   * the original parse. [perl #56444].
12502   *
12503   * That parsing is skipped for single-quoted regexes, so we may here get
12504   * '\N{NAME}'.  This is a fatal error.  These names have to be resolved by the
12505   * parser.  But if the single-quoted regex is something like '\N{U+41}', that
12506   * is legal and handled here.  The code point is Unicode, and has to be
12507   * translated into the native character set for non-ASCII platforms.
12508   */
12509
12510     char * endbrace;    /* points to '}' following the name */
12511     char* p = RExC_parse; /* Temporary */
12512
12513     SV * substitute_parse = NULL;
12514     char *orig_end;
12515     char *save_start;
12516     I32 flags;
12517     Size_t count = 0;   /* code point count kept internally by this function */
12518
12519     GET_RE_DEBUG_FLAGS_DECL;
12520
12521     PERL_ARGS_ASSERT_GROK_BSLASH_N;
12522
12523     GET_RE_DEBUG_FLAGS;
12524
12525     assert(cBOOL(node_p) ^ cBOOL(code_point_p));  /* Exactly one should be set */
12526     assert(! (node_p && cp_count));               /* At most 1 should be set */
12527
12528     if (cp_count) {     /* Initialize return for the most common case */
12529         *cp_count = 1;
12530     }
12531
12532     /* The [^\n] meaning of \N ignores spaces and comments under the /x
12533      * modifier.  The other meanings do not, so use a temporary until we find
12534      * out which we are being called with */
12535     skip_to_be_ignored_text(pRExC_state, &p,
12536                             FALSE /* Don't force to /x */ );
12537
12538     /* Disambiguate between \N meaning a named character versus \N meaning
12539      * [^\n].  The latter is assumed when the {...} following the \N is a legal
12540      * quantifier, or there is no '{' at all */
12541     if (*p != '{' || regcurly(p)) {
12542         RExC_parse = p;
12543         if (cp_count) {
12544             *cp_count = -1;
12545         }
12546
12547         if (! node_p) {
12548             return FALSE;
12549         }
12550
12551         *node_p = reg_node(pRExC_state, REG_ANY);
12552         *flagp |= HASWIDTH|SIMPLE;
12553         MARK_NAUGHTY(1);
12554         Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
12555         return TRUE;
12556     }
12557
12558     /* The test above made sure that the next real character is a '{', but
12559      * under the /x modifier, it could be separated by space (or a comment and
12560      * \n) and this is not allowed (for consistency with \x{...} and the
12561      * tokenizer handling of \N{NAME}). */
12562     if (*RExC_parse != '{') {
12563         vFAIL("Missing braces on \\N{}");
12564     }
12565
12566     RExC_parse++;       /* Skip past the '{' */
12567
12568     endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
12569     if (! endbrace) { /* no trailing brace */
12570         vFAIL2("Missing right brace on \\%c{}", 'N');
12571     }
12572
12573     /* Here, we have decided it should be a named character or sequence */
12574     REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode
12575                                         semantics */
12576
12577     if (endbrace == RExC_parse) {   /* empty: \N{} */
12578         if (strict) {
12579             RExC_parse++;   /* Position after the "}" */
12580             vFAIL("Zero length \\N{}");
12581         }
12582         if (cp_count) {
12583             *cp_count = 0;
12584         }
12585         nextchar(pRExC_state);
12586         if (! node_p) {
12587             return FALSE;
12588         }
12589
12590         *node_p = reg_node(pRExC_state, NOTHING);
12591         return TRUE;
12592     }
12593
12594     /* If we haven't got something that begins with 'U+', then it didn't get lexed. */
12595     if (   endbrace - RExC_parse < 2
12596         || strnNE(RExC_parse, "U+", 2))
12597     {
12598         RExC_parse = endbrace;  /* position msg's '<--HERE' */
12599         vFAIL("\\N{NAME} must be resolved by the lexer");
12600     }
12601
12602         /* This code purposely indented below because of future changes coming */
12603
12604         /* We can get to here when the input is \N{U+...} or when toke.c has
12605          * converted a name to the \N{U+...} form.  This include changing a
12606          * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
12607
12608         RExC_parse += 2;    /* Skip past the 'U+' */
12609
12610         /* Code points are separated by dots.  The '}' terminates the whole
12611          * thing. */
12612
12613         do {    /* Loop until the ending brace */
12614             UV cp = 0;
12615             char * start_digit;     /* The first of the current code point */
12616             if (! isXDIGIT(*RExC_parse)) {
12617                 RExC_parse++;
12618                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12619             }
12620
12621             start_digit = RExC_parse;
12622             count++;
12623
12624             /* Loop through the hex digits of the current code point */
12625             do {
12626                 /* Adding this digit will shift the result 4 bits.  If that
12627                  * result would be above the legal max, it's overflow */
12628                 if (cp > MAX_LEGAL_CP >> 4) {
12629
12630                     /* Find the end of the code point */
12631                     do {
12632                         RExC_parse ++;
12633                     } while (isXDIGIT(*RExC_parse) || *RExC_parse == '_');
12634
12635                     /* Be sure to synchronize this message with the similar one
12636                      * in utf8.c */
12637                     vFAIL4("Use of code point 0x%.*s is not allowed; the"
12638                         " permissible max is 0x%" UVxf,
12639                         (int) (RExC_parse - start_digit), start_digit,
12640                         MAX_LEGAL_CP);
12641                 }
12642
12643                 /* Accumulate this (valid) digit into the running total */
12644                 cp  = (cp << 4) + READ_XDIGIT(RExC_parse);
12645
12646                 /* READ_XDIGIT advanced the input pointer.  Ignore a single
12647                  * underscore separator */
12648                 if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) {
12649                     RExC_parse++;
12650                 }
12651             } while (isXDIGIT(*RExC_parse));
12652
12653             /* Here, have accumulated the next code point */
12654             if (RExC_parse >= endbrace) {   /* If done ... */
12655                 if (count != 1) {
12656                     goto do_concat;
12657                 }
12658
12659                 /* Here, is a single code point; fail if doesn't want that */
12660                 if (! code_point_p) {
12661                     RExC_parse = p;
12662                     return FALSE;
12663                 }
12664
12665                 /* A single code point is easy to handle; just return it */
12666                 *code_point_p = UNI_TO_NATIVE(cp);
12667                 RExC_parse = endbrace;
12668                 nextchar(pRExC_state);
12669                 return TRUE;
12670             }
12671
12672             /* Here, the only legal thing would be a multiple character
12673              * sequence (of the form "\N{U+c1.c2. ... }".   So the next
12674              * character must be a dot (and the one after that can't be the
12675              * endbrace, or we'd have something like \N{U+100.} ) */
12676             if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
12677                 RExC_parse += (RExC_orig_utf8)  /* point to after 1st invalid */
12678                                 ? UTF8SKIP(RExC_parse)
12679                                 : 1;
12680                 if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */
12681                     RExC_parse = endbrace;
12682                 }
12683                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12684             }
12685
12686             /* Here, looks like its really a multiple character sequence.  Fail
12687              * if that's not what the caller wants.  But continue with counting
12688              * and error checking if they still want a count */
12689             if (! node_p && ! cp_count) {
12690                 return FALSE;
12691             }
12692
12693             /* What is done here is to convert this to a sub-pattern of the
12694              * form \x{char1}\x{char2}...  and then call reg recursively to
12695              * parse it (enclosing in "(?: ... )" ).  That way, it retains its
12696              * atomicness, while not having to worry about special handling
12697              * that some code points may have.  We don't create a subpattern,
12698              * but go through the motions of code point counting and error
12699              * checking, if the caller doesn't want a node returned. */
12700
12701             if (node_p && count == 1) {
12702                 substitute_parse = newSVpvs("?:");
12703             }
12704
12705           do_concat:
12706
12707             if (node_p) {
12708                 /* Convert to notation the rest of the code understands */
12709                 sv_catpvs(substitute_parse, "\\x{");
12710                 sv_catpvn(substitute_parse, start_digit,
12711                                             RExC_parse - start_digit);
12712                 sv_catpvs(substitute_parse, "}");
12713             }
12714
12715             /* Move to after the dot (or ending brace the final time through.)
12716              * */
12717             RExC_parse++;
12718             count++;
12719
12720         } while (RExC_parse < endbrace);
12721
12722         if (! node_p) { /* Doesn't want the node */
12723             assert (cp_count);
12724
12725             *cp_count = count;
12726             return FALSE;
12727         }
12728
12729         sv_catpvs(substitute_parse, ")");
12730
12731 #ifdef EBCDIC
12732         /* The values are Unicode, and therefore have to be converted to native
12733          * on a non-Unicode (meaning non-ASCII) platform. */
12734         RExC_recode_x_to_native = 1;
12735 #endif
12736
12737     /* Here, we have the string the name evaluates to, ready to be parsed,
12738      * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
12739      * constructs.  This can be called from within a substitute parse already.
12740      * The error reporting mechanism doesn't work for 2 levels of this, but the
12741      * code above has validated this new construct, so there should be no
12742      * errors generated by the below.  And this isn' an exact copy, so the
12743      * mechanism to seamlessly deal with this won't work, so turn off warnings
12744      * during it */
12745     save_start = RExC_start;
12746     orig_end = RExC_end;
12747
12748     RExC_parse = RExC_start = SvPVX(substitute_parse);
12749     RExC_end = RExC_parse + SvCUR(substitute_parse);
12750     TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
12751
12752     *node_p = reg(pRExC_state, 1, &flags, depth+1);
12753
12754     /* Restore the saved values */
12755     RESTORE_WARNINGS;
12756     RExC_start = save_start;
12757     RExC_parse = endbrace;
12758     RExC_end = orig_end;
12759 #ifdef EBCDIC
12760     RExC_recode_x_to_native = 0;
12761 #endif
12762
12763     SvREFCNT_dec_NN(substitute_parse);
12764
12765     if (! *node_p) {
12766         RETURN_FAIL_ON_RESTART(flags, flagp);
12767         FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
12768             (UV) flags);
12769     }
12770     *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
12771
12772     nextchar(pRExC_state);
12773
12774     return TRUE;
12775 }
12776
12777
12778 PERL_STATIC_INLINE U8
12779 S_compute_EXACTish(RExC_state_t *pRExC_state)
12780 {
12781     U8 op;
12782
12783     PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
12784
12785     if (! FOLD) {
12786         return (LOC)
12787                 ? EXACTL
12788                 : EXACT;
12789     }
12790
12791     op = get_regex_charset(RExC_flags);
12792     if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
12793         op--; /* /a is same as /u, and map /aa's offset to what /a's would have
12794                  been, so there is no hole */
12795     }
12796
12797     return op + EXACTF;
12798 }
12799
12800 PERL_STATIC_INLINE void
12801 S_alloc_maybe_populate_EXACT(pTHX_ RExC_state_t *pRExC_state,
12802                          regnode_offset node, I32* flagp, STRLEN len,
12803                          UV code_point, bool downgradable)
12804 {
12805     /* This knows the details about sizing an EXACTish node, setting flags for
12806      * it (by setting <*flagp>, and potentially populating it with a single
12807      * character.
12808      *
12809      * If <len> (the length in bytes) is non-zero, this function assumes that
12810      * the node has already been populated, and just does the sizing.  In this
12811      * case <code_point> should be the final code point that has already been
12812      * placed into the node.  This value will be ignored except that under some
12813      * circumstances <*flagp> is set based on it.
12814      *
12815      * If <len> is zero, the function assumes that the node is to contain only
12816      * the single character given by <code_point> and calculates what <len>
12817      * should be.  It populates the node's STRING with <code_point> or its
12818      * fold if folding.
12819      *
12820      * In both cases <*flagp> is appropriately set
12821      *
12822      * It knows that under FOLD, the Latin Sharp S and UTF characters above
12823      * 255, must be folded (the former only when the rules indicate it can
12824      * match 'ss')
12825      *
12826      * When it does the populating, it looks at the flag 'downgradable'.  If
12827      * true with a node that folds, it checks if the single code point
12828      * participates in a fold, and if not downgrades the node to an EXACT.
12829      * This helps the optimizer */
12830
12831     bool len_passed_in = cBOOL(len != 0);
12832     U8 character[UTF8_MAXBYTES_CASE+1];
12833
12834     PERL_ARGS_ASSERT_ALLOC_MAYBE_POPULATE_EXACT;
12835
12836     if (! len_passed_in) {
12837         if (UTF) {
12838             if (UVCHR_IS_INVARIANT(code_point)) {
12839                 if (LOC || ! FOLD) {    /* /l defers folding until runtime */
12840                     *character = (U8) code_point;
12841                 }
12842                 else { /* Here is /i and not /l. */
12843                     *character = toFOLD((U8) code_point);
12844
12845                     /* We can downgrade to an EXACT node if this character
12846                      * isn't a folding one.  Note that this assumes that
12847                      * nothing above Latin1 folds to some other invariant than
12848                      * one of these alphabetics; otherwise we would also have
12849                      * to check:
12850                      *  && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
12851                      *      || ASCII_FOLD_RESTRICTED))
12852                      */
12853                     if (downgradable && PL_fold[code_point] == code_point) {
12854                         OP(REGNODE_p(node)) = EXACT;
12855                     }
12856                 }
12857                 len = 1;
12858             }
12859             else if (FOLD && (   ! LOC
12860                               || ! is_PROBLEMATIC_LOCALE_FOLD_cp(code_point)))
12861             {   /* Folding, and ok to do so now */
12862                 UV folded = _to_uni_fold_flags(
12863                                    code_point,
12864                                    character,
12865                                    &len,
12866                                    FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
12867                                                       ? FOLD_FLAGS_NOMIX_ASCII
12868                                                       : 0));
12869                 if (downgradable
12870                     && folded == code_point /* This quickly rules out many
12871                                                cases, avoiding the
12872                                                _invlist_contains_cp() overhead
12873                                                for those.  */
12874                     && ! _invlist_contains_cp(PL_utf8_foldable, code_point))
12875                 {
12876                     OP(REGNODE_p(node)) = (LOC)
12877                                ? EXACTL
12878                                : EXACT;
12879                 }
12880             }
12881             else if (code_point <= MAX_UTF8_TWO_BYTE) {
12882
12883                 /* Not folding this cp, and can output it directly */
12884                 *character = UTF8_TWO_BYTE_HI(code_point);
12885                 *(character + 1) = UTF8_TWO_BYTE_LO(code_point);
12886                 len = 2;
12887             }
12888             else {
12889                 uvchr_to_utf8( character, code_point);
12890                 len = UTF8SKIP(character);
12891             }
12892         } /* Else pattern isn't UTF8.  */
12893         else if (! FOLD) {
12894             *character = (U8) code_point;
12895             len = 1;
12896         } /* Else is folded non-UTF8 */
12897 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
12898    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
12899                                       || UNICODE_DOT_DOT_VERSION > 0)
12900         else if (LIKELY(code_point != LATIN_SMALL_LETTER_SHARP_S)) {
12901 #else
12902         else if (1) {
12903 #endif
12904             /* We don't fold any non-UTF8 except possibly the Sharp s  (see
12905              * comments at join_exact()); */
12906             *character = (U8) code_point;
12907             len = 1;
12908
12909             /* Can turn into an EXACT node if we know the fold at compile time,
12910              * and it folds to itself and doesn't particpate in other folds */
12911             if (downgradable
12912                 && ! LOC
12913                 && PL_fold_latin1[code_point] == code_point
12914                 && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
12915                     || (isASCII(code_point) && ASCII_FOLD_RESTRICTED)))
12916             {
12917                 OP(REGNODE_p(node)) = EXACT;
12918             }
12919         } /* else is Sharp s.  May need to fold it */
12920         else if (AT_LEAST_UNI_SEMANTICS && ! ASCII_FOLD_RESTRICTED) {
12921             *character = 's';
12922             *(character + 1) = 's';
12923             len = 2;
12924         }
12925         else {
12926             *character = LATIN_SMALL_LETTER_SHARP_S;
12927             len = 1;
12928         }
12929     }
12930
12931     if (downgradable) {
12932         change_engine_size(pRExC_state, STR_SZ(len));
12933     }
12934
12935     RExC_emit += STR_SZ(len);
12936     STR_LEN(REGNODE_p(node)) = len;
12937     if (! len_passed_in) {
12938         Copy((char *) character, STRING(REGNODE_p(node)), len, char);
12939     }
12940
12941     *flagp |= HASWIDTH;
12942
12943     /* A single character node is SIMPLE, except for the special-cased SHARP S
12944      * under /di. */
12945     if ((len == 1 || (UTF && len == UVCHR_SKIP(code_point)))
12946 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
12947    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
12948                                       || UNICODE_DOT_DOT_VERSION > 0)
12949         && ( code_point != LATIN_SMALL_LETTER_SHARP_S
12950             || ! FOLD || ! DEPENDS_SEMANTICS)
12951 #endif
12952     ) {
12953         *flagp |= SIMPLE;
12954     }
12955
12956     if (OP(REGNODE_p(node)) == EXACTFL) {
12957         RExC_contains_locale = 1;
12958     }
12959 }
12960
12961 STATIC bool
12962 S_new_regcurly(const char *s, const char *e)
12963 {
12964     /* This is a temporary function designed to match the most lenient form of
12965      * a {m,n} quantifier we ever envision, with either number omitted, and
12966      * spaces anywhere between/before/after them.
12967      *
12968      * If this function fails, then the string it matches is very unlikely to
12969      * ever be considered a valid quantifier, so we can allow the '{' that
12970      * begins it to be considered as a literal */
12971
12972     bool has_min = FALSE;
12973     bool has_max = FALSE;
12974
12975     PERL_ARGS_ASSERT_NEW_REGCURLY;
12976
12977     if (s >= e || *s++ != '{')
12978         return FALSE;
12979
12980     while (s < e && isSPACE(*s)) {
12981         s++;
12982     }
12983     while (s < e && isDIGIT(*s)) {
12984         has_min = TRUE;
12985         s++;
12986     }
12987     while (s < e && isSPACE(*s)) {
12988         s++;
12989     }
12990
12991     if (*s == ',') {
12992         s++;
12993         while (s < e && isSPACE(*s)) {
12994             s++;
12995         }
12996         while (s < e && isDIGIT(*s)) {
12997             has_max = TRUE;
12998             s++;
12999         }
13000         while (s < e && isSPACE(*s)) {
13001             s++;
13002         }
13003     }
13004
13005     return s < e && *s == '}' && (has_min || has_max);
13006 }
13007
13008 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
13009  * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
13010
13011 static I32
13012 S_backref_value(char *p, char *e)
13013 {
13014     const char* endptr = e;
13015     UV val;
13016     if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13017         return (I32)val;
13018     return I32_MAX;
13019 }
13020
13021
13022 /*
13023  - regatom - the lowest level
13024
13025    Try to identify anything special at the start of the current parse position.
13026    If there is, then handle it as required. This may involve generating a
13027    single regop, such as for an assertion; or it may involve recursing, such as
13028    to handle a () structure.
13029
13030    If the string doesn't start with something special then we gobble up
13031    as much literal text as we can.  If we encounter a quantifier, we have to
13032    back off the final literal character, as that quantifier applies to just it
13033    and not to the whole string of literals.
13034
13035    Once we have been able to handle whatever type of thing started the
13036    sequence, we return the offset into the regex engine program being compiled
13037    at which any  next regnode should be placed.
13038
13039    Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13040    Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13041    restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13042    Otherwise does not return 0.
13043
13044    Note: we have to be careful with escapes, as they can be both literal
13045    and special, and in the case of \10 and friends, context determines which.
13046
13047    A summary of the code structure is:
13048
13049    switch (first_byte) {
13050         cases for each special:
13051             handle this special;
13052             break;
13053         case '\\':
13054             switch (2nd byte) {
13055                 cases for each unambiguous special:
13056                     handle this special;
13057                     break;
13058                 cases for each ambigous special/literal:
13059                     disambiguate;
13060                     if (special)  handle here
13061                     else goto defchar;
13062                 default: // unambiguously literal:
13063                     goto defchar;
13064             }
13065         default:  // is a literal char
13066             // FALL THROUGH
13067         defchar:
13068             create EXACTish node for literal;
13069             while (more input and node isn't full) {
13070                 switch (input_byte) {
13071                    cases for each special;
13072                        make sure parse pointer is set so that the next call to
13073                            regatom will see this special first
13074                        goto loopdone; // EXACTish node terminated by prev. char
13075                    default:
13076                        append char to EXACTISH node;
13077                 }
13078                 get next input byte;
13079             }
13080         loopdone:
13081    }
13082    return the generated node;
13083
13084    Specifically there are two separate switches for handling
13085    escape sequences, with the one for handling literal escapes requiring
13086    a dummy entry for all of the special escapes that are actually handled
13087    by the other.
13088
13089 */
13090
13091 STATIC regnode_offset
13092 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13093 {
13094     regnode_offset ret = 0;
13095     I32 flags = 0;
13096     char *parse_start;
13097     U8 op;
13098     int invert = 0;
13099     U8 arg;
13100
13101     GET_RE_DEBUG_FLAGS_DECL;
13102
13103     *flagp = WORST;             /* Tentatively. */
13104
13105     DEBUG_PARSE("atom");
13106
13107     PERL_ARGS_ASSERT_REGATOM;
13108
13109   tryagain:
13110     parse_start = RExC_parse;
13111     assert(RExC_parse < RExC_end);
13112     switch ((U8)*RExC_parse) {
13113     case '^':
13114         RExC_seen_zerolen++;
13115         nextchar(pRExC_state);
13116         if (RExC_flags & RXf_PMf_MULTILINE)
13117             ret = reg_node(pRExC_state, MBOL);
13118         else
13119             ret = reg_node(pRExC_state, SBOL);
13120         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13121         break;
13122     case '$':
13123         nextchar(pRExC_state);
13124         if (*RExC_parse)
13125             RExC_seen_zerolen++;
13126         if (RExC_flags & RXf_PMf_MULTILINE)
13127             ret = reg_node(pRExC_state, MEOL);
13128         else
13129             ret = reg_node(pRExC_state, SEOL);
13130         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13131         break;
13132     case '.':
13133         nextchar(pRExC_state);
13134         if (RExC_flags & RXf_PMf_SINGLELINE)
13135             ret = reg_node(pRExC_state, SANY);
13136         else
13137             ret = reg_node(pRExC_state, REG_ANY);
13138         *flagp |= HASWIDTH|SIMPLE;
13139         MARK_NAUGHTY(1);
13140         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13141         break;
13142     case '[':
13143     {
13144         char * const oregcomp_parse = ++RExC_parse;
13145         ret = regclass(pRExC_state, flagp, depth+1,
13146                        FALSE, /* means parse the whole char class */
13147                        TRUE, /* allow multi-char folds */
13148                        FALSE, /* don't silence non-portable warnings. */
13149                        (bool) RExC_strict,
13150                        TRUE, /* Allow an optimized regnode result */
13151                        NULL);
13152         if (ret == 0) {
13153             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13154             FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13155                   (UV) *flagp);
13156         }
13157         if (*RExC_parse != ']') {
13158             RExC_parse = oregcomp_parse;
13159             vFAIL("Unmatched [");
13160         }
13161         nextchar(pRExC_state);
13162         Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13163         break;
13164     }
13165     case '(':
13166         nextchar(pRExC_state);
13167         ret = reg(pRExC_state, 2, &flags, depth+1);
13168         if (ret == 0) {
13169                 if (flags & TRYAGAIN) {
13170                     if (RExC_parse >= RExC_end) {
13171                          /* Make parent create an empty node if needed. */
13172                         *flagp |= TRYAGAIN;
13173                         return(0);
13174                     }
13175                     goto tryagain;
13176                 }
13177                 RETURN_FAIL_ON_RESTART(flags, flagp);
13178                 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13179                                                                  (UV) flags);
13180         }
13181         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13182         break;
13183     case '|':
13184     case ')':
13185         if (flags & TRYAGAIN) {
13186             *flagp |= TRYAGAIN;
13187             return 0;
13188         }
13189         vFAIL("Internal urp");
13190                                 /* Supposed to be caught earlier. */
13191         break;
13192     case '?':
13193     case '+':
13194     case '*':
13195         RExC_parse++;
13196         vFAIL("Quantifier follows nothing");
13197         break;
13198     case '\\':
13199         /* Special Escapes
13200
13201            This switch handles escape sequences that resolve to some kind
13202            of special regop and not to literal text. Escape sequences that
13203            resolve to literal text are handled below in the switch marked
13204            "Literal Escapes".
13205
13206            Every entry in this switch *must* have a corresponding entry
13207            in the literal escape switch. However, the opposite is not
13208            required, as the default for this switch is to jump to the
13209            literal text handling code.
13210         */
13211         RExC_parse++;
13212         switch ((U8)*RExC_parse) {
13213         /* Special Escapes */
13214         case 'A':
13215             RExC_seen_zerolen++;
13216             ret = reg_node(pRExC_state, SBOL);
13217             /* SBOL is shared with /^/ so we set the flags so we can tell
13218              * /\A/ from /^/ in split. */
13219             FLAGS(REGNODE_p(ret)) = 1;
13220             *flagp |= SIMPLE;
13221             goto finish_meta_pat;
13222         case 'G':
13223             ret = reg_node(pRExC_state, GPOS);
13224             RExC_seen |= REG_GPOS_SEEN;
13225             *flagp |= SIMPLE;
13226             goto finish_meta_pat;
13227         case 'K':
13228             RExC_seen_zerolen++;
13229             ret = reg_node(pRExC_state, KEEPS);
13230             *flagp |= SIMPLE;
13231             /* XXX:dmq : disabling in-place substitution seems to
13232              * be necessary here to avoid cases of memory corruption, as
13233              * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13234              */
13235             RExC_seen |= REG_LOOKBEHIND_SEEN;
13236             goto finish_meta_pat;
13237         case 'Z':
13238             ret = reg_node(pRExC_state, SEOL);
13239             *flagp |= SIMPLE;
13240             RExC_seen_zerolen++;                /* Do not optimize RE away */
13241             goto finish_meta_pat;
13242         case 'z':
13243             ret = reg_node(pRExC_state, EOS);
13244             *flagp |= SIMPLE;
13245             RExC_seen_zerolen++;                /* Do not optimize RE away */
13246             goto finish_meta_pat;
13247         case 'C':
13248             vFAIL("\\C no longer supported");
13249         case 'X':
13250             ret = reg_node(pRExC_state, CLUMP);
13251             *flagp |= HASWIDTH;
13252             goto finish_meta_pat;
13253
13254         case 'W':
13255             invert = 1;
13256             /* FALLTHROUGH */
13257         case 'w':
13258             arg = ANYOF_WORDCHAR;
13259             goto join_posix;
13260
13261         case 'B':
13262             invert = 1;
13263             /* FALLTHROUGH */
13264         case 'b':
13265           {
13266             regex_charset charset = get_regex_charset(RExC_flags);
13267
13268             RExC_seen_zerolen++;
13269             RExC_seen |= REG_LOOKBEHIND_SEEN;
13270             op = BOUND + charset;
13271
13272             if (op == BOUND) {
13273                 RExC_seen_d_op = TRUE;
13274             }
13275             else if (op == BOUNDL) {
13276                 RExC_contains_locale = 1;
13277             }
13278
13279             ret = reg_node(pRExC_state, op);
13280             *flagp |= SIMPLE;
13281             if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13282                 FLAGS(REGNODE_p(ret)) = TRADITIONAL_BOUND;
13283                 if (op > BOUNDA) {  /* /aa is same as /a */
13284                     OP(REGNODE_p(ret)) = BOUNDA;
13285                 }
13286             }
13287             else {
13288                 STRLEN length;
13289                 char name = *RExC_parse;
13290                 char * endbrace = NULL;
13291                 RExC_parse += 2;
13292                 if (RExC_parse < RExC_end) {
13293                     endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13294                 }
13295
13296                 if (! endbrace) {
13297                     vFAIL2("Missing right brace on \\%c{}", name);
13298                 }
13299                 /* XXX Need to decide whether to take spaces or not.  Should be
13300                  * consistent with \p{}, but that currently is SPACE, which
13301                  * means vertical too, which seems wrong
13302                  * while (isBLANK(*RExC_parse)) {
13303                     RExC_parse++;
13304                 }*/
13305                 if (endbrace == RExC_parse) {
13306                     RExC_parse++;  /* After the '}' */
13307                     vFAIL2("Empty \\%c{}", name);
13308                 }
13309                 length = endbrace - RExC_parse;
13310                 /*while (isBLANK(*(RExC_parse + length - 1))) {
13311                     length--;
13312                 }*/
13313                 switch (*RExC_parse) {
13314                     case 'g':
13315                         if (    length != 1
13316                             && (memNEs(RExC_parse + 1, length - 1, "cb")))
13317                         {
13318                             goto bad_bound_type;
13319                         }
13320                         FLAGS(REGNODE_p(ret)) = GCB_BOUND;
13321                         break;
13322                     case 'l':
13323                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13324                             goto bad_bound_type;
13325                         }
13326                         FLAGS(REGNODE_p(ret)) = LB_BOUND;
13327                         break;
13328                     case 's':
13329                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13330                             goto bad_bound_type;
13331                         }
13332                         FLAGS(REGNODE_p(ret)) = SB_BOUND;
13333                         break;
13334                     case 'w':
13335                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13336                             goto bad_bound_type;
13337                         }
13338                         FLAGS(REGNODE_p(ret)) = WB_BOUND;
13339                         break;
13340                     default:
13341                       bad_bound_type:
13342                         RExC_parse = endbrace;
13343                         vFAIL2utf8f(
13344                             "'%" UTF8f "' is an unknown bound type",
13345                             UTF8fARG(UTF, length, endbrace - length));
13346                         NOT_REACHED; /*NOTREACHED*/
13347                 }
13348                 RExC_parse = endbrace;
13349                 REQUIRE_UNI_RULES(flagp, 0);
13350
13351                 if (op >= BOUNDA) {  /* /aa is same as /a */
13352                     OP(REGNODE_p(ret)) = BOUNDU;
13353                     length += 4;
13354
13355                     /* Don't have to worry about UTF-8, in this message because
13356                      * to get here the contents of the \b must be ASCII */
13357                     ckWARN4reg(RExC_parse + 1,  /* Include the '}' in msg */
13358                               "Using /u for '%.*s' instead of /%s",
13359                               (unsigned) length,
13360                               endbrace - length + 1,
13361                               (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13362                               ? ASCII_RESTRICT_PAT_MODS
13363                               : ASCII_MORE_RESTRICT_PAT_MODS);
13364                 }
13365             }
13366
13367             if (invert) {
13368                 OP(REGNODE_p(ret)) += NBOUND - BOUND;
13369             }
13370             goto finish_meta_pat;
13371           }
13372
13373         case 'D':
13374             invert = 1;
13375             /* FALLTHROUGH */
13376         case 'd':
13377             arg = ANYOF_DIGIT;
13378             if (! DEPENDS_SEMANTICS) {
13379                 goto join_posix;
13380             }
13381
13382             /* \d doesn't have any matches in the upper Latin1 range, hence /d
13383              * is equivalent to /u.  Changing to /u saves some branches at
13384              * runtime */
13385             op = POSIXU;
13386             goto join_posix_op_known;
13387
13388         case 'R':
13389             ret = reg_node(pRExC_state, LNBREAK);
13390             *flagp |= HASWIDTH|SIMPLE;
13391             goto finish_meta_pat;
13392
13393         case 'H':
13394             invert = 1;
13395             /* FALLTHROUGH */
13396         case 'h':
13397             arg = ANYOF_BLANK;
13398             op = POSIXU;
13399             goto join_posix_op_known;
13400
13401         case 'V':
13402             invert = 1;
13403             /* FALLTHROUGH */
13404         case 'v':
13405             arg = ANYOF_VERTWS;
13406             op = POSIXU;
13407             goto join_posix_op_known;
13408
13409         case 'S':
13410             invert = 1;
13411             /* FALLTHROUGH */
13412         case 's':
13413             arg = ANYOF_SPACE;
13414
13415           join_posix:
13416
13417             op = POSIXD + get_regex_charset(RExC_flags);
13418             if (op > POSIXA) {  /* /aa is same as /a */
13419                 op = POSIXA;
13420             }
13421             else if (op == POSIXL) {
13422                 RExC_contains_locale = 1;
13423             }
13424             else if (op == POSIXD) {
13425                 RExC_seen_d_op = TRUE;
13426             }
13427
13428           join_posix_op_known:
13429
13430             if (invert) {
13431                 op += NPOSIXD - POSIXD;
13432             }
13433
13434             ret = reg_node(pRExC_state, op);
13435             FLAGS(REGNODE_p(ret)) = namedclass_to_classnum(arg);
13436
13437             *flagp |= HASWIDTH|SIMPLE;
13438             /* FALLTHROUGH */
13439
13440           finish_meta_pat:
13441             if (   UCHARAT(RExC_parse + 1) == '{'
13442                 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13443             {
13444                 RExC_parse += 2;
13445                 vFAIL("Unescaped left brace in regex is illegal here");
13446             }
13447             nextchar(pRExC_state);
13448             Set_Node_Length(REGNODE_p(ret), 2); /* MJD */
13449             break;
13450         case 'p':
13451         case 'P':
13452             RExC_parse--;
13453
13454             ret = regclass(pRExC_state, flagp, depth+1,
13455                            TRUE, /* means just parse this element */
13456                            FALSE, /* don't allow multi-char folds */
13457                            FALSE, /* don't silence non-portable warnings.  It
13458                                      would be a bug if these returned
13459                                      non-portables */
13460                            (bool) RExC_strict,
13461                            TRUE, /* Allow an optimized regnode result */
13462                            NULL);
13463             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13464             /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13465              * multi-char folds are allowed.  */
13466             if (!ret)
13467                 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13468                       (UV) *flagp);
13469
13470             RExC_parse--;
13471
13472             Set_Node_Offset(REGNODE_p(ret), parse_start);
13473             Set_Node_Cur_Length(REGNODE_p(ret), parse_start - 2);
13474             nextchar(pRExC_state);
13475             break;
13476         case 'N':
13477             /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13478              * \N{...} evaluates to a sequence of more than one code points).
13479              * The function call below returns a regnode, which is our result.
13480              * The parameters cause it to fail if the \N{} evaluates to a
13481              * single code point; we handle those like any other literal.  The
13482              * reason that the multicharacter case is handled here and not as
13483              * part of the EXACtish code is because of quantifiers.  In
13484              * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13485              * this way makes that Just Happen. dmq.
13486              * join_exact() will join this up with adjacent EXACTish nodes
13487              * later on, if appropriate. */
13488             ++RExC_parse;
13489             if (grok_bslash_N(pRExC_state,
13490                               &ret,     /* Want a regnode returned */
13491                               NULL,     /* Fail if evaluates to a single code
13492                                            point */
13493                               NULL,     /* Don't need a count of how many code
13494                                            points */
13495                               flagp,
13496                               RExC_strict,
13497                               depth)
13498             ) {
13499                 break;
13500             }
13501
13502             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13503
13504             /* Here, evaluates to a single code point.  Go get that */
13505             RExC_parse = parse_start;
13506             goto defchar;
13507
13508         case 'k':    /* Handle \k<NAME> and \k'NAME' */
13509       parse_named_seq:
13510         {
13511             char ch;
13512             if (   RExC_parse >= RExC_end - 1
13513                 || ((   ch = RExC_parse[1]) != '<'
13514                                       && ch != '\''
13515                                       && ch != '{'))
13516             {
13517                 RExC_parse++;
13518                 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13519                 vFAIL2("Sequence %.2s... not terminated", parse_start);
13520             } else {
13521                 RExC_parse += 2;
13522                 ret = handle_named_backref(pRExC_state,
13523                                            flagp,
13524                                            parse_start,
13525                                            (ch == '<')
13526                                            ? '>'
13527                                            : (ch == '{')
13528                                              ? '}'
13529                                              : '\'');
13530             }
13531             break;
13532         }
13533         case 'g':
13534         case '1': case '2': case '3': case '4':
13535         case '5': case '6': case '7': case '8': case '9':
13536             {
13537                 I32 num;
13538                 bool hasbrace = 0;
13539
13540                 if (*RExC_parse == 'g') {
13541                     bool isrel = 0;
13542
13543                     RExC_parse++;
13544                     if (*RExC_parse == '{') {
13545                         RExC_parse++;
13546                         hasbrace = 1;
13547                     }
13548                     if (*RExC_parse == '-') {
13549                         RExC_parse++;
13550                         isrel = 1;
13551                     }
13552                     if (hasbrace && !isDIGIT(*RExC_parse)) {
13553                         if (isrel) RExC_parse--;
13554                         RExC_parse -= 2;
13555                         goto parse_named_seq;
13556                     }
13557
13558                     if (RExC_parse >= RExC_end) {
13559                         goto unterminated_g;
13560                     }
13561                     num = S_backref_value(RExC_parse, RExC_end);
13562                     if (num == 0)
13563                         vFAIL("Reference to invalid group 0");
13564                     else if (num == I32_MAX) {
13565                          if (isDIGIT(*RExC_parse))
13566                             vFAIL("Reference to nonexistent group");
13567                         else
13568                           unterminated_g:
13569                             vFAIL("Unterminated \\g... pattern");
13570                     }
13571
13572                     if (isrel) {
13573                         num = RExC_npar - num;
13574                         if (num < 1)
13575                             vFAIL("Reference to nonexistent or unclosed group");
13576                     }
13577                 }
13578                 else {
13579                     num = S_backref_value(RExC_parse, RExC_end);
13580                     /* bare \NNN might be backref or octal - if it is larger
13581                      * than or equal RExC_npar then it is assumed to be an
13582                      * octal escape. Note RExC_npar is +1 from the actual
13583                      * number of parens. */
13584                     /* Note we do NOT check if num == I32_MAX here, as that is
13585                      * handled by the RExC_npar check */
13586
13587                     if (
13588                         /* any numeric escape < 10 is always a backref */
13589                         num > 9
13590                         /* any numeric escape < RExC_npar is a backref */
13591                         && num >= RExC_npar
13592                         /* cannot be an octal escape if it starts with 8 */
13593                         && *RExC_parse != '8'
13594                         /* cannot be an octal escape it it starts with 9 */
13595                         && *RExC_parse != '9'
13596                     ) {
13597                         /* Probably not meant to be a backref, instead likely
13598                          * to be an octal character escape, e.g. \35 or \777.
13599                          * The above logic should make it obvious why using
13600                          * octal escapes in patterns is problematic. - Yves */
13601                         RExC_parse = parse_start;
13602                         goto defchar;
13603                     }
13604                 }
13605
13606                 /* At this point RExC_parse points at a numeric escape like
13607                  * \12 or \88 or something similar, which we should NOT treat
13608                  * as an octal escape. It may or may not be a valid backref
13609                  * escape. For instance \88888888 is unlikely to be a valid
13610                  * backref. */
13611                 while (isDIGIT(*RExC_parse))
13612                     RExC_parse++;
13613                 if (hasbrace) {
13614                     if (*RExC_parse != '}')
13615                         vFAIL("Unterminated \\g{...} pattern");
13616                     RExC_parse++;
13617                 }
13618                 if (num >= (I32)RExC_npar) {
13619
13620                     /* It might be a forward reference; we can't fail until we
13621                      * know, by completing the parse to get all the groups, and
13622                      * then reparsing */
13623                     if (RExC_total_parens > 0)  {
13624                         if (num >= RExC_total_parens)  {
13625                             vFAIL("Reference to nonexistent group");
13626                         }
13627                     }
13628                     else {
13629                         REQUIRE_PARENS_PASS;
13630                     }
13631                 }
13632                 RExC_sawback = 1;
13633                 ret = reganode(pRExC_state,
13634                                ((! FOLD)
13635                                  ? REF
13636                                  : (ASCII_FOLD_RESTRICTED)
13637                                    ? REFFA
13638                                    : (AT_LEAST_UNI_SEMANTICS)
13639                                      ? REFFU
13640                                      : (LOC)
13641                                        ? REFFL
13642                                        : REFF),
13643                                 num);
13644                 if (OP(REGNODE_p(ret)) == REFF) {
13645                     RExC_seen_d_op = TRUE;
13646                 }
13647                 *flagp |= HASWIDTH;
13648
13649                 /* override incorrect value set in reganode MJD */
13650                 Set_Node_Offset(REGNODE_p(ret), parse_start);
13651                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
13652                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13653                                         FALSE /* Don't force to /x */ );
13654             }
13655             break;
13656         case '\0':
13657             if (RExC_parse >= RExC_end)
13658                 FAIL("Trailing \\");
13659             /* FALLTHROUGH */
13660         default:
13661             /* Do not generate "unrecognized" warnings here, we fall
13662                back into the quick-grab loop below */
13663             RExC_parse = parse_start;
13664             goto defchar;
13665         } /* end of switch on a \foo sequence */
13666         break;
13667
13668     case '#':
13669
13670         /* '#' comments should have been spaced over before this function was
13671          * called */
13672         assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
13673         /*
13674         if (RExC_flags & RXf_PMf_EXTENDED) {
13675             RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
13676             if (RExC_parse < RExC_end)
13677                 goto tryagain;
13678         }
13679         */
13680
13681         /* FALLTHROUGH */
13682
13683     default:
13684           defchar: {
13685
13686             /* Here, we have determined that the next thing is probably a
13687              * literal character.  RExC_parse points to the first byte of its
13688              * definition.  (It still may be an escape sequence that evaluates
13689              * to a single character) */
13690
13691             STRLEN len = 0;
13692             UV ender = 0;
13693             char *p;
13694             char *s;
13695
13696 /* This allows us to fill a node with just enough spare so that if the final
13697  * character folds, its expansion is guaranteed to fit */
13698 #define MAX_NODE_STRING_SIZE (255-UTF8_MAXBYTES_CASE)
13699
13700             char *s0;
13701             U8 upper_parse = MAX_NODE_STRING_SIZE;
13702
13703             /* We start out as an EXACT node, even if under /i, until we find a
13704              * character which is in a fold.  The algorithm now segregates into
13705              * separate nodes, characters that fold from those that don't under
13706              * /i.  (This hopefully will create nodes that are fixed strings
13707              * even under /i, giving the optimizer something to grab on to.)
13708              * So, if a node has something in it and the next character is in
13709              * the opposite category, that node is closed up, and the function
13710              * returns.  Then regatom is called again, and a new node is
13711              * created for the new category. */
13712             U8 node_type = EXACT;
13713
13714             /* Assume the node will be fully used; the excess is given back at
13715              * the end.  We can't make any other length assumptions, as a byte
13716              * input sequence could shrink down. */
13717             Ptrdiff_t initial_size = STR_SZ(256);
13718
13719             bool next_is_quantifier;
13720             char * oldp = NULL;
13721
13722             /* We can convert EXACTF nodes to EXACTFU if they contain only
13723              * characters that match identically regardless of the target
13724              * string's UTF8ness.  The reason to do this is that EXACTF is not
13725              * trie-able, EXACTFU is.
13726              *
13727              * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
13728              * contain only above-Latin1 characters (hence must be in UTF8),
13729              * which don't participate in folds with Latin1-range characters,
13730              * as the latter's folds aren't known until runtime. */
13731             bool maybe_exactfu = TRUE;
13732
13733             /* Allocate an EXACT node.  The node_type may change below to
13734              * another EXACTish node, but since the size of the node doesn't
13735              * change, it works */
13736             ret = regnode_guts(pRExC_state, node_type, initial_size, "exact");
13737             FILL_NODE(ret, node_type);
13738             RExC_emit++;
13739
13740             s = STRING(REGNODE_p(ret));
13741
13742             s0 = s;
13743
13744           reparse:
13745
13746             /* This breaks under rare circumstances.  If folding, we do not
13747              * want to split a node at a character that is a non-final in a
13748              * multi-char fold, as an input string could just happen to want to
13749              * match across the node boundary.  The code at the end of the loop
13750              * looks for this, and backs off until it finds not such a
13751              * character, but it is possible (though extremely, extremely
13752              * unlikely) for all characters in the node to be non-final fold
13753              * ones, in which case we just leave the node fully filled, and
13754              * hope that it doesn't match the string in just the wrong place */
13755
13756             assert( ! UTF     /* Is at the beginning of a character */
13757                    || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
13758                    || UTF8_IS_START(UCHARAT(RExC_parse)));
13759
13760
13761             /* Here, we have a literal character.  Find the maximal string of
13762              * them in the input that we can fit into a single EXACTish node.
13763              * We quit at the first non-literal or when the node gets full, or
13764              * under /i the categorization of folding/non-folding character
13765              * changes */
13766             for (p = RExC_parse; len < upper_parse && p < RExC_end; ) {
13767
13768                 /* In most cases each iteration adds one byte to the output.
13769                  * The exceptions override this */
13770                 Size_t added_len = 1;
13771
13772                 oldp = p;
13773
13774                 /* White space has already been ignored */
13775                 assert(   (RExC_flags & RXf_PMf_EXTENDED) == 0
13776                        || ! is_PATWS_safe((p), RExC_end, UTF));
13777
13778                 switch ((U8)*p) {
13779                 case '^':
13780                 case '$':
13781                 case '.':
13782                 case '[':
13783                 case '(':
13784                 case ')':
13785                 case '|':
13786                     goto loopdone;
13787                 case '\\':
13788                     /* Literal Escapes Switch
13789
13790                        This switch is meant to handle escape sequences that
13791                        resolve to a literal character.
13792
13793                        Every escape sequence that represents something
13794                        else, like an assertion or a char class, is handled
13795                        in the switch marked 'Special Escapes' above in this
13796                        routine, but also has an entry here as anything that
13797                        isn't explicitly mentioned here will be treated as
13798                        an unescaped equivalent literal.
13799                     */
13800
13801                     switch ((U8)*++p) {
13802
13803                     /* These are all the special escapes. */
13804                     case 'A':             /* Start assertion */
13805                     case 'b': case 'B':   /* Word-boundary assertion*/
13806                     case 'C':             /* Single char !DANGEROUS! */
13807                     case 'd': case 'D':   /* digit class */
13808                     case 'g': case 'G':   /* generic-backref, pos assertion */
13809                     case 'h': case 'H':   /* HORIZWS */
13810                     case 'k': case 'K':   /* named backref, keep marker */
13811                     case 'p': case 'P':   /* Unicode property */
13812                               case 'R':   /* LNBREAK */
13813                     case 's': case 'S':   /* space class */
13814                     case 'v': case 'V':   /* VERTWS */
13815                     case 'w': case 'W':   /* word class */
13816                     case 'X':             /* eXtended Unicode "combining
13817                                              character sequence" */
13818                     case 'z': case 'Z':   /* End of line/string assertion */
13819                         --p;
13820                         goto loopdone;
13821
13822                     /* Anything after here is an escape that resolves to a
13823                        literal. (Except digits, which may or may not)
13824                      */
13825                     case 'n':
13826                         ender = '\n';
13827                         p++;
13828                         break;
13829                     case 'N': /* Handle a single-code point named character. */
13830                         RExC_parse = p + 1;
13831                         if (! grok_bslash_N(pRExC_state,
13832                                             NULL,   /* Fail if evaluates to
13833                                                        anything other than a
13834                                                        single code point */
13835                                             &ender, /* The returned single code
13836                                                        point */
13837                                             NULL,   /* Don't need a count of
13838                                                        how many code points */
13839                                             flagp,
13840                                             RExC_strict,
13841                                             depth)
13842                         ) {
13843                             if (*flagp & NEED_UTF8)
13844                                 FAIL("panic: grok_bslash_N set NEED_UTF8");
13845                             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13846
13847                             /* Here, it wasn't a single code point.  Go close
13848                              * up this EXACTish node.  The switch() prior to
13849                              * this switch handles the other cases */
13850                             RExC_parse = p = oldp;
13851                             goto loopdone;
13852                         }
13853                         p = RExC_parse;
13854                         RExC_parse = parse_start;
13855                         if (ender > 0xff) {
13856                             REQUIRE_UTF8(flagp);
13857                         }
13858
13859                         /* The \N{} means the pattern, if previously /d,
13860                          * becomes /u.  That means it can't be an EXACTF node,
13861                          * but an EXACTFU */
13862                         if (node_type == EXACTF) {
13863                             node_type = EXACTFU;
13864
13865                             /* If the node already contains something that
13866                              * differs between EXACTF and EXACTFU, reparse it
13867                              * as EXACTFU */
13868                             if (! maybe_exactfu) {
13869                                 len = 0;
13870                                 s = s0;
13871                                 maybe_exactfu = TRUE;   /* Prob. unnecessary */
13872                                 goto reparse;
13873                             }
13874                         }
13875
13876                         break;
13877                     case 'r':
13878                         ender = '\r';
13879                         p++;
13880                         break;
13881                     case 't':
13882                         ender = '\t';
13883                         p++;
13884                         break;
13885                     case 'f':
13886                         ender = '\f';
13887                         p++;
13888                         break;
13889                     case 'e':
13890                         ender = ESC_NATIVE;
13891                         p++;
13892                         break;
13893                     case 'a':
13894                         ender = '\a';
13895                         p++;
13896                         break;
13897                     case 'o':
13898                         {
13899                             UV result;
13900                             const char* error_msg;
13901
13902                             bool valid = grok_bslash_o(&p,
13903                                                        RExC_end,
13904                                                        &result,
13905                                                        &error_msg,
13906                                                        TO_OUTPUT_WARNINGS(p),
13907                                                        (bool) RExC_strict,
13908                                                        TRUE, /* Output warnings
13909                                                                 for non-
13910                                                                 portables */
13911                                                        UTF);
13912                             if (! valid) {
13913                                 RExC_parse = p; /* going to die anyway; point
13914                                                    to exact spot of failure */
13915                                 vFAIL(error_msg);
13916                             }
13917                             UPDATE_WARNINGS_LOC(p - 1);
13918                             ender = result;
13919                             if (ender > 0xff) {
13920                                 REQUIRE_UTF8(flagp);
13921                             }
13922                             break;
13923                         }
13924                     case 'x':
13925                         {
13926                             UV result = UV_MAX; /* initialize to erroneous
13927                                                    value */
13928                             const char* error_msg;
13929
13930                             bool valid = grok_bslash_x(&p,
13931                                                        RExC_end,
13932                                                        &result,
13933                                                        &error_msg,
13934                                                        TO_OUTPUT_WARNINGS(p),
13935                                                        (bool) RExC_strict,
13936                                                        TRUE, /* Silence warnings
13937                                                                 for non-
13938                                                                 portables */
13939                                                        UTF);
13940                             if (! valid) {
13941                                 RExC_parse = p; /* going to die anyway; point
13942                                                    to exact spot of failure */
13943                                 vFAIL(error_msg);
13944                             }
13945                             UPDATE_WARNINGS_LOC(p - 1);
13946                             ender = result;
13947
13948                             if (ender < 0x100) {
13949 #ifdef EBCDIC
13950                                 if (RExC_recode_x_to_native) {
13951                                     ender = LATIN1_TO_NATIVE(ender);
13952                                 }
13953 #endif
13954                             }
13955                             else {
13956                                 REQUIRE_UTF8(flagp);
13957                             }
13958                             break;
13959                         }
13960                     case 'c':
13961                         p++;
13962                         ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p));
13963                         UPDATE_WARNINGS_LOC(p);
13964                         p++;
13965                         break;
13966                     case '8': case '9': /* must be a backreference */
13967                         --p;
13968                         /* we have an escape like \8 which cannot be an octal escape
13969                          * so we exit the loop, and let the outer loop handle this
13970                          * escape which may or may not be a legitimate backref. */
13971                         goto loopdone;
13972                     case '1': case '2': case '3':case '4':
13973                     case '5': case '6': case '7':
13974                         /* When we parse backslash escapes there is ambiguity
13975                          * between backreferences and octal escapes. Any escape
13976                          * from \1 - \9 is a backreference, any multi-digit
13977                          * escape which does not start with 0 and which when
13978                          * evaluated as decimal could refer to an already
13979                          * parsed capture buffer is a back reference. Anything
13980                          * else is octal.
13981                          *
13982                          * Note this implies that \118 could be interpreted as
13983                          * 118 OR as "\11" . "8" depending on whether there
13984                          * were 118 capture buffers defined already in the
13985                          * pattern.  */
13986
13987                         /* NOTE, RExC_npar is 1 more than the actual number of
13988                          * parens we have seen so far, hence the "<" as opposed
13989                          * to "<=" */
13990                         if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
13991                         {  /* Not to be treated as an octal constant, go
13992                                    find backref */
13993                             --p;
13994                             goto loopdone;
13995                         }
13996                         /* FALLTHROUGH */
13997                     case '0':
13998                         {
13999                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
14000                             STRLEN numlen = 3;
14001                             ender = grok_oct(p, &numlen, &flags, NULL);
14002                             if (ender > 0xff) {
14003                                 REQUIRE_UTF8(flagp);
14004                             }
14005                             p += numlen;
14006                             if (   isDIGIT(*p)  /* like \08, \178 */
14007                                 && ckWARN(WARN_REGEXP)
14008                                 && numlen < 3)
14009                             {
14010                                 reg_warn_non_literal_string(
14011                                          p + 1,
14012                                          form_short_octal_warning(p, numlen));
14013                             }
14014                         }
14015                         break;
14016                     case '\0':
14017                         if (p >= RExC_end)
14018                             FAIL("Trailing \\");
14019                         /* FALLTHROUGH */
14020                     default:
14021                         if (isALPHANUMERIC(*p)) {
14022                             /* An alpha followed by '{' is going to fail next
14023                              * iteration, so don't output this warning in that
14024                              * case */
14025                             if (! isALPHA(*p) || *(p + 1) != '{') {
14026                                 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14027                                                   " passed through", p);
14028                             }
14029                         }
14030                         goto normal_default;
14031                     } /* End of switch on '\' */
14032                     break;
14033                 case '{':
14034                     /* Trying to gain new uses for '{' without breaking too
14035                      * much existing code is hard.  The solution currently
14036                      * adopted is:
14037                      *  1)  If there is no ambiguity that a '{' should always
14038                      *      be taken literally, at the start of a construct, we
14039                      *      just do so.
14040                      *  2)  If the literal '{' conflicts with our desired use
14041                      *      of it as a metacharacter, we die.  The deprecation
14042                      *      cycles for this have come and gone.
14043                      *  3)  If there is ambiguity, we raise a simple warning.
14044                      *      This could happen, for example, if the user
14045                      *      intended it to introduce a quantifier, but slightly
14046                      *      misspelled the quantifier.  Without this warning,
14047                      *      the quantifier would silently be taken as a literal
14048                      *      string of characters instead of a meta construct */
14049                     if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14050                         if (      RExC_strict
14051                             || (  p > parse_start + 1
14052                                 && isALPHA_A(*(p - 1))
14053                                 && *(p - 2) == '\\')
14054                             || new_regcurly(p, RExC_end))
14055                         {
14056                             RExC_parse = p + 1;
14057                             vFAIL("Unescaped left brace in regex is "
14058                                   "illegal here");
14059                         }
14060                         ckWARNreg(p + 1, "Unescaped left brace in regex is"
14061                                          " passed through");
14062                     }
14063                     goto normal_default;
14064                 case '}':
14065                 case ']':
14066                     if (p > RExC_parse && RExC_strict) {
14067                         ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14068                     }
14069                     /*FALLTHROUGH*/
14070                 default:    /* A literal character */
14071                   normal_default:
14072                     if (! UTF8_IS_INVARIANT(*p) && UTF) {
14073                         STRLEN numlen;
14074                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14075                                                &numlen, UTF8_ALLOW_DEFAULT);
14076                         p += numlen;
14077                     }
14078                     else
14079                         ender = (U8) *p++;
14080                     break;
14081                 } /* End of switch on the literal */
14082
14083                 /* Here, have looked at the literal character, and <ender>
14084                  * contains its ordinal; <p> points to the character after it.
14085                  * We need to check if the next non-ignored thing is a
14086                  * quantifier.  Move <p> to after anything that should be
14087                  * ignored, which, as a side effect, positions <p> for the next
14088                  * loop iteration */
14089                 skip_to_be_ignored_text(pRExC_state, &p,
14090                                         FALSE /* Don't force to /x */ );
14091
14092                 /* If the next thing is a quantifier, it applies to this
14093                  * character only, which means that this character has to be in
14094                  * its own node and can't just be appended to the string in an
14095                  * existing node, so if there are already other characters in
14096                  * the node, close the node with just them, and set up to do
14097                  * this character again next time through, when it will be the
14098                  * only thing in its new node */
14099
14100                 next_is_quantifier =    LIKELY(p < RExC_end)
14101                                      && UNLIKELY(ISMULT2(p));
14102
14103                 if (next_is_quantifier && LIKELY(len)) {
14104                     p = oldp;
14105                     goto loopdone;
14106                 }
14107
14108                 /* Ready to add 'ender' to the node */
14109
14110                 if (! FOLD) {  /* The simple case, just append the literal */
14111
14112                       not_fold_common:
14113                         if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14114                             *(s++) = (char) ender;
14115                         }
14116                         else {
14117                             U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14118                             added_len = (char *) new_s - s;
14119                             s = (char *) new_s;
14120                         }
14121                 }
14122                 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14123
14124                     /* Here are folding under /l, and the code point is
14125                      * problematic.  If this is the first character in the
14126                      * node, change the node type to folding.   Otherwise, if
14127                      * this is the first problematic character, close up the
14128                      * existing node, so can start a new node with this one */
14129                     if (! len) {
14130                         node_type = EXACTFL;
14131                     }
14132                     else if (node_type == EXACT) {
14133                         p = oldp;
14134                         goto loopdone;
14135                     }
14136
14137                     /* This code point means we can't simplify things */
14138                     maybe_exactfu = FALSE;
14139
14140                     /* Here, we are adding a problematic fold character.
14141                      * "Problematic" in this context means that its fold isn't
14142                      * known until runtime.  (The non-problematic code points
14143                      * are the above-Latin1 ones that fold to also all
14144                      * above-Latin1.  Their folds don't vary no matter what the
14145                      * locale is.) But here we have characters whose fold
14146                      * depends on the locale.  We just add in the unfolded
14147                      * character, and wait until runtime to fold it */
14148                     goto not_fold_common;
14149                 }
14150                 else /* regular fold; see if actually is in a fold */
14151                      if (   (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14152                          || (ender > 255
14153                             && ! _invlist_contains_cp(PL_utf8_foldable, ender)))
14154                 {
14155                     /* Here, folding, but the character isn't in a fold.
14156                      *
14157                      * Start a new node if previous characters in the node were
14158                      * folded */
14159                     if (len && node_type != EXACT) {
14160                         p = oldp;
14161                         goto loopdone;
14162                     }
14163
14164                     /* Here, continuing a node with non-folded characters.  Add
14165                      * this one */
14166
14167                     if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14168                         *(s++) = (char) ender;
14169                     }
14170                     else {
14171                         s = (char *) uvchr_to_utf8((U8 *) s, ender);
14172                         added_len = UVCHR_SKIP(ender);
14173                     }
14174                 }
14175                 else {  /* Here, does participate in some fold */
14176
14177                     /* If this is the first character in the node, change its
14178                      * type to folding.  Otherwise, if this is the first
14179                      * folding character in the node, close up the existing
14180                      * node, so can start a new node with this one.  */
14181                     if (! len) {
14182                         node_type = compute_EXACTish(pRExC_state);
14183                     }
14184                     else if (node_type == EXACT) {
14185                         p = oldp;
14186                         goto loopdone;
14187                     }
14188
14189                     if (UTF) {  /* For UTF-8, we add the folded value */
14190                         if (UVCHR_IS_INVARIANT(ender)) {
14191                             *(s)++ = (U8) toFOLD(ender);
14192                         }
14193                         else {
14194                             ender = _to_uni_fold_flags(
14195                                     ender,
14196                                     (U8 *) s,
14197                                     &added_len,
14198                                     FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14199                                                     ? FOLD_FLAGS_NOMIX_ASCII
14200                                                     : 0));
14201                             s += added_len;
14202                         }
14203                     }
14204                     else {
14205
14206                         /* Here is non-UTF8; we don't normally store the folded
14207                          * value.  First, see if the character's fold differs
14208                          * between /d and /u. */
14209                         if (PL_fold[ender] != PL_fold_latin1[ender]) {
14210                             maybe_exactfu = FALSE;
14211                         }
14212
14213 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
14214    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
14215                                       || UNICODE_DOT_DOT_VERSION > 0)
14216
14217                         /* On non-ancient Unicode versions, this includes the
14218                          * multi-char fold SHARP S to 'ss' */
14219
14220                         else if (UNLIKELY(   ender == LATIN_SMALL_LETTER_SHARP_S
14221                                           || (   len
14222                                               && isALPHA_FOLD_EQ(ender, 's')
14223                                               && isALPHA_FOLD_EQ(*(s-1), 's'))))
14224                         {
14225
14226                             if (node_type == EXACTFU) {
14227                                 /* See comments for join_exact() as to why we
14228                                  * fold this non-UTF at compile time */
14229                                 if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14230                                     *(s++) = 's';
14231
14232                                     /* Let the code below add in the extra 's' */
14233                                     ender = 's';
14234                                     added_len = 2;
14235                                 }
14236                             }
14237                             else {
14238                                 maybe_exactfu = FALSE;
14239                             }
14240                         }
14241 #endif
14242
14243                         /* Even when folding, we store just the input
14244                          * character, as we have an array that finds its fold
14245                          * quickly */
14246                         *(s++) = (char) ender;
14247                     }
14248                 } /* End of adding current character to the node */
14249
14250                 len += added_len;
14251
14252                 if (next_is_quantifier) {
14253
14254                     /* Here, the next input is a quantifier, and to get here,
14255                      * the current character is the only one in the node. */
14256                     goto loopdone;
14257                 }
14258
14259             } /* End of loop through literal characters */
14260
14261             /* Here we have either exhausted the input or ran out of room in
14262              * the node.  (If we encountered a character that can't be in the
14263              * node, transfer is made directly to <loopdone>, and so we
14264              * wouldn't have fallen off the end of the loop.)  In the latter
14265              * case, we artificially have to split the node into two, because
14266              * we just don't have enough space to hold everything.  This
14267              * creates a problem if the final character participates in a
14268              * multi-character fold in the non-final position, as a match that
14269              * should have occurred won't, due to the way nodes are matched,
14270              * and our artificial boundary.  So back off until we find a non-
14271              * problematic character -- one that isn't at the beginning or
14272              * middle of such a fold.  (Either it doesn't participate in any
14273              * folds, or appears only in the final position of all the folds it
14274              * does participate in.)  A better solution with far fewer false
14275              * positives, and that would fill the nodes more completely, would
14276              * be to actually have available all the multi-character folds to
14277              * test against, and to back-off only far enough to be sure that
14278              * this node isn't ending with a partial one.  <upper_parse> is set
14279              * further below (if we need to reparse the node) to include just
14280              * up through that final non-problematic character that this code
14281              * identifies, so when it is set to less than the full node, we can
14282              * skip the rest of this */
14283             if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
14284
14285                 const STRLEN full_len = len;
14286
14287                 assert(len >= MAX_NODE_STRING_SIZE);
14288
14289                 /* Here, <s> points to the final byte of the final character.
14290                  * Look backwards through the string until find a non-
14291                  * problematic character */
14292
14293                 if (! UTF) {
14294
14295                     /* This has no multi-char folds to non-UTF characters */
14296                     if (ASCII_FOLD_RESTRICTED) {
14297                         goto loopdone;
14298                     }
14299
14300                     while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { }
14301                     len = s - s0 + 1;
14302                 }
14303                 else {
14304
14305                     /* Point to the first byte of the final character */
14306                     s = (char *) utf8_hop((U8 *) s, -1);
14307
14308                     while (s >= s0) {   /* Search backwards until find
14309                                            a non-problematic char */
14310                         if (UTF8_IS_INVARIANT(*s)) {
14311
14312                             /* There are no ascii characters that participate
14313                              * in multi-char folds under /aa.  In EBCDIC, the
14314                              * non-ascii invariants are all control characters,
14315                              * so don't ever participate in any folds. */
14316                             if (ASCII_FOLD_RESTRICTED
14317                                 || ! IS_NON_FINAL_FOLD(*s))
14318                             {
14319                                 break;
14320                             }
14321                         }
14322                         else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
14323                             if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE(
14324                                                                   *s, *(s+1))))
14325                             {
14326                                 break;
14327                             }
14328                         }
14329                         else if (! _invlist_contains_cp(
14330                                         PL_NonL1NonFinalFold,
14331                                         valid_utf8_to_uvchr((U8 *) s, NULL)))
14332                         {
14333                             break;
14334                         }
14335
14336                         /* Here, the current character is problematic in that
14337                          * it does occur in the non-final position of some
14338                          * fold, so try the character before it, but have to
14339                          * special case the very first byte in the string, so
14340                          * we don't read outside the string */
14341                         s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
14342                     } /* End of loop backwards through the string */
14343
14344                     /* If there were only problematic characters in the string,
14345                      * <s> will point to before s0, in which case the length
14346                      * should be 0, otherwise include the length of the
14347                      * non-problematic character just found */
14348                     len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
14349                 }
14350
14351                 /* Here, have found the final character, if any, that is
14352                  * non-problematic as far as ending the node without splitting
14353                  * it across a potential multi-char fold.  <len> contains the
14354                  * number of bytes in the node up-to and including that
14355                  * character, or is 0 if there is no such character, meaning
14356                  * the whole node contains only problematic characters.  In
14357                  * this case, give up and just take the node as-is.  We can't
14358                  * do any better */
14359                 if (len == 0) {
14360                     len = full_len;
14361
14362                     /* If the node ends in an 's' we make sure it stays EXACTF,
14363                      * as if it turns into an EXACTFU, it could later get
14364                      * joined with another 's' that would then wrongly match
14365                      * the sharp s */
14366                     if (maybe_exactfu && isALPHA_FOLD_EQ(ender, 's'))
14367                     {
14368                         maybe_exactfu = FALSE;
14369                     }
14370                 } else {
14371
14372                     /* Here, the node does contain some characters that aren't
14373                      * problematic.  If one such is the final character in the
14374                      * node, we are done */
14375                     if (len == full_len) {
14376                         goto loopdone;
14377                     }
14378                     else if (len + ((UTF) ? UTF8SKIP(s) : 1) == full_len) {
14379
14380                         /* If the final character is problematic, but the
14381                          * penultimate is not, back-off that last character to
14382                          * later start a new node with it */
14383                         p = oldp;
14384                         goto loopdone;
14385                     }
14386
14387                     /* Here, the final non-problematic character is earlier
14388                      * in the input than the penultimate character.  What we do
14389                      * is reparse from the beginning, going up only as far as
14390                      * this final ok one, thus guaranteeing that the node ends
14391                      * in an acceptable character.  The reason we reparse is
14392                      * that we know how far in the character is, but we don't
14393                      * know how to correlate its position with the input parse.
14394                      * An alternate implementation would be to build that
14395                      * correlation as we go along during the original parse,
14396                      * but that would entail extra work for every node, whereas
14397                      * this code gets executed only when the string is too
14398                      * large for the node, and the final two characters are
14399                      * problematic, an infrequent occurrence.  Yet another
14400                      * possible strategy would be to save the tail of the
14401                      * string, and the next time regatom is called, initialize
14402                      * with that.  The problem with this is that unless you
14403                      * back off one more character, you won't be guaranteed
14404                      * regatom will get called again, unless regbranch,
14405                      * regpiece ... are also changed.  If you do back off that
14406                      * extra character, so that there is input guaranteed to
14407                      * force calling regatom, you can't handle the case where
14408                      * just the first character in the node is acceptable.  I
14409                      * (khw) decided to try this method which doesn't have that
14410                      * pitfall; if performance issues are found, we can do a
14411                      * combination of the current approach plus that one */
14412                     upper_parse = len;
14413                     len = 0;
14414                     s = s0;
14415                     goto reparse;
14416                 }
14417             }   /* End of verifying node ends with an appropriate char */
14418
14419           loopdone:   /* Jumped to when encounters something that shouldn't be
14420                          in the node */
14421
14422             /* Free up any over-allocated space */
14423             change_engine_size(pRExC_state, - (initial_size - STR_SZ(len)));
14424
14425             /* I (khw) don't know if you can get here with zero length, but the
14426              * old code handled this situation by creating a zero-length EXACT
14427              * node.  Might as well be NOTHING instead */
14428             if (len == 0) {
14429                 OP(REGNODE_p(ret)) = NOTHING;
14430             }
14431             else {
14432                 OP(REGNODE_p(ret)) = node_type;
14433
14434                 /* If the node type is EXACT here, check to see if it
14435                  * should be EXACTL. */
14436                 if (node_type == EXACT) {
14437                     if (LOC) {
14438                         OP(REGNODE_p(ret)) = EXACTL;
14439                     }
14440                 }
14441
14442                 if (FOLD) {
14443                     /* If 'maybe_exactfu' is set, then there are no code points
14444                      * that match differently depending on UTF8ness of the
14445                      * target string (for /u), or depending on locale for /l */
14446                     if (maybe_exactfu) {
14447                         if (node_type == EXACTF) {
14448                             OP(REGNODE_p(ret)) = EXACTFU;
14449                         }
14450                         else if (node_type == EXACTFL) {
14451                             OP(REGNODE_p(ret)) = EXACTFLU8;
14452                         }
14453                     }
14454                     else if (node_type == EXACTF) {
14455                         RExC_seen_d_op = TRUE;
14456                     }
14457                 }
14458
14459                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, len, ender,
14460                                            FALSE /* Don't look to see if could
14461                                                     be turned into an EXACT
14462                                                     node, as we have already
14463                                                     computed that */
14464                                           );
14465             }
14466
14467             RExC_parse = p - 1;
14468             Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
14469             RExC_parse = p;
14470             {
14471                 /* len is STRLEN which is unsigned, need to copy to signed */
14472                 IV iv = len;
14473                 if (iv < 0)
14474                     vFAIL("Internal disaster");
14475             }
14476
14477         } /* End of label 'defchar:' */
14478         break;
14479     } /* End of giant switch on input character */
14480
14481     /* Position parse to next real character */
14482     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14483                                             FALSE /* Don't force to /x */ );
14484     if (   *RExC_parse == '{'
14485         && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
14486     {
14487         if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
14488             RExC_parse++;
14489             vFAIL("Unescaped left brace in regex is illegal here");
14490         }
14491         ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
14492                                   " passed through");
14493     }
14494
14495     return(ret);
14496 }
14497
14498
14499 STATIC void
14500 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
14501 {
14502     /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'.  It
14503      * sets up the bitmap and any flags, removing those code points from the
14504      * inversion list, setting it to NULL should it become completely empty */
14505
14506     PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
14507     assert(PL_regkind[OP(node)] == ANYOF);
14508
14509     ANYOF_BITMAP_ZERO(node);
14510     if (*invlist_ptr) {
14511
14512         /* This gets set if we actually need to modify things */
14513         bool change_invlist = FALSE;
14514
14515         UV start, end;
14516
14517         /* Start looking through *invlist_ptr */
14518         invlist_iterinit(*invlist_ptr);
14519         while (invlist_iternext(*invlist_ptr, &start, &end)) {
14520             UV high;
14521             int i;
14522
14523             if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
14524                 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
14525             }
14526
14527             /* Quit if are above what we should change */
14528             if (start >= NUM_ANYOF_CODE_POINTS) {
14529                 break;
14530             }
14531
14532             change_invlist = TRUE;
14533
14534             /* Set all the bits in the range, up to the max that we are doing */
14535             high = (end < NUM_ANYOF_CODE_POINTS - 1)
14536                    ? end
14537                    : NUM_ANYOF_CODE_POINTS - 1;
14538             for (i = start; i <= (int) high; i++) {
14539                 if (! ANYOF_BITMAP_TEST(node, i)) {
14540                     ANYOF_BITMAP_SET(node, i);
14541                 }
14542             }
14543         }
14544         invlist_iterfinish(*invlist_ptr);
14545
14546         /* Done with loop; remove any code points that are in the bitmap from
14547          * *invlist_ptr; similarly for code points above the bitmap if we have
14548          * a flag to match all of them anyways */
14549         if (change_invlist) {
14550             _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
14551         }
14552         if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
14553             _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
14554         }
14555
14556         /* If have completely emptied it, remove it completely */
14557         if (_invlist_len(*invlist_ptr) == 0) {
14558             SvREFCNT_dec_NN(*invlist_ptr);
14559             *invlist_ptr = NULL;
14560         }
14561     }
14562 }
14563
14564 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
14565    Character classes ([:foo:]) can also be negated ([:^foo:]).
14566    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
14567    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
14568    but trigger failures because they are currently unimplemented. */
14569
14570 #define POSIXCC_DONE(c)   ((c) == ':')
14571 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
14572 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
14573 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
14574
14575 #define WARNING_PREFIX              "Assuming NOT a POSIX class since "
14576 #define NO_BLANKS_POSIX_WARNING     "no blanks are allowed in one"
14577 #define SEMI_COLON_POSIX_WARNING    "a semi-colon was found instead of a colon"
14578
14579 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
14580
14581 /* 'posix_warnings' and 'warn_text' are names of variables in the following
14582  * routine. q.v. */
14583 #define ADD_POSIX_WARNING(p, text)  STMT_START {                            \
14584         if (posix_warnings) {                                               \
14585             if (! RExC_warn_text ) RExC_warn_text =                         \
14586                                          (AV *) sv_2mortal((SV *) newAV()); \
14587             av_push(RExC_warn_text, Perl_newSVpvf(aTHX_                     \
14588                                              WARNING_PREFIX                 \
14589                                              text                           \
14590                                              REPORT_LOCATION,               \
14591                                              REPORT_LOCATION_ARGS(p)));     \
14592         }                                                                   \
14593     } STMT_END
14594 #define CLEAR_POSIX_WARNINGS()                                              \
14595     STMT_START {                                                            \
14596         if (posix_warnings && RExC_warn_text)                               \
14597             av_clear(RExC_warn_text);                                       \
14598     } STMT_END
14599
14600 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret)                                \
14601     STMT_START {                                                            \
14602         CLEAR_POSIX_WARNINGS();                                             \
14603         return ret;                                                         \
14604     } STMT_END
14605
14606 STATIC int
14607 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
14608
14609     const char * const s,      /* Where the putative posix class begins.
14610                                   Normally, this is one past the '['.  This
14611                                   parameter exists so it can be somewhere
14612                                   besides RExC_parse. */
14613     char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
14614                                   NULL */
14615     AV ** posix_warnings,      /* Where to place any generated warnings, or
14616                                   NULL */
14617     const bool check_only      /* Don't die if error */
14618 )
14619 {
14620     /* This parses what the caller thinks may be one of the three POSIX
14621      * constructs:
14622      *  1) a character class, like [:blank:]
14623      *  2) a collating symbol, like [. .]
14624      *  3) an equivalence class, like [= =]
14625      * In the latter two cases, it croaks if it finds a syntactically legal
14626      * one, as these are not handled by Perl.
14627      *
14628      * The main purpose is to look for a POSIX character class.  It returns:
14629      *  a) the class number
14630      *      if it is a completely syntactically and semantically legal class.
14631      *      'updated_parse_ptr', if not NULL, is set to point to just after the
14632      *      closing ']' of the class
14633      *  b) OOB_NAMEDCLASS
14634      *      if it appears that one of the three POSIX constructs was meant, but
14635      *      its specification was somehow defective.  'updated_parse_ptr', if
14636      *      not NULL, is set to point to the character just after the end
14637      *      character of the class.  See below for handling of warnings.
14638      *  c) NOT_MEANT_TO_BE_A_POSIX_CLASS
14639      *      if it  doesn't appear that a POSIX construct was intended.
14640      *      'updated_parse_ptr' is not changed.  No warnings nor errors are
14641      *      raised.
14642      *
14643      * In b) there may be errors or warnings generated.  If 'check_only' is
14644      * TRUE, then any errors are discarded.  Warnings are returned to the
14645      * caller via an AV* created into '*posix_warnings' if it is not NULL.  If
14646      * instead it is NULL, warnings are suppressed.
14647      *
14648      * The reason for this function, and its complexity is that a bracketed
14649      * character class can contain just about anything.  But it's easy to
14650      * mistype the very specific posix class syntax but yielding a valid
14651      * regular bracketed class, so it silently gets compiled into something
14652      * quite unintended.
14653      *
14654      * The solution adopted here maintains backward compatibility except that
14655      * it adds a warning if it looks like a posix class was intended but
14656      * improperly specified.  The warning is not raised unless what is input
14657      * very closely resembles one of the 14 legal posix classes.  To do this,
14658      * it uses fuzzy parsing.  It calculates how many single-character edits it
14659      * would take to transform what was input into a legal posix class.  Only
14660      * if that number is quite small does it think that the intention was a
14661      * posix class.  Obviously these are heuristics, and there will be cases
14662      * where it errs on one side or another, and they can be tweaked as
14663      * experience informs.
14664      *
14665      * The syntax for a legal posix class is:
14666      *
14667      * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
14668      *
14669      * What this routine considers syntactically to be an intended posix class
14670      * is this (the comments indicate some restrictions that the pattern
14671      * doesn't show):
14672      *
14673      *  qr/(?x: \[?                         # The left bracket, possibly
14674      *                                      # omitted
14675      *          \h*                         # possibly followed by blanks
14676      *          (?: \^ \h* )?               # possibly a misplaced caret
14677      *          [:;]?                       # The opening class character,
14678      *                                      # possibly omitted.  A typo
14679      *                                      # semi-colon can also be used.
14680      *          \h*
14681      *          \^?                         # possibly a correctly placed
14682      *                                      # caret, but not if there was also
14683      *                                      # a misplaced one
14684      *          \h*
14685      *          .{3,15}                     # The class name.  If there are
14686      *                                      # deviations from the legal syntax,
14687      *                                      # its edit distance must be close
14688      *                                      # to a real class name in order
14689      *                                      # for it to be considered to be
14690      *                                      # an intended posix class.
14691      *          \h*
14692      *          [[:punct:]]?                # The closing class character,
14693      *                                      # possibly omitted.  If not a colon
14694      *                                      # nor semi colon, the class name
14695      *                                      # must be even closer to a valid
14696      *                                      # one
14697      *          \h*
14698      *          \]?                         # The right bracket, possibly
14699      *                                      # omitted.
14700      *     )/
14701      *
14702      * In the above, \h must be ASCII-only.
14703      *
14704      * These are heuristics, and can be tweaked as field experience dictates.
14705      * There will be cases when someone didn't intend to specify a posix class
14706      * that this warns as being so.  The goal is to minimize these, while
14707      * maximizing the catching of things intended to be a posix class that
14708      * aren't parsed as such.
14709      */
14710
14711     const char* p             = s;
14712     const char * const e      = RExC_end;
14713     unsigned complement       = 0;      /* If to complement the class */
14714     bool found_problem        = FALSE;  /* Assume OK until proven otherwise */
14715     bool has_opening_bracket  = FALSE;
14716     bool has_opening_colon    = FALSE;
14717     int class_number          = OOB_NAMEDCLASS; /* Out-of-bounds until find
14718                                                    valid class */
14719     const char * possible_end = NULL;   /* used for a 2nd parse pass */
14720     const char* name_start;             /* ptr to class name first char */
14721
14722     /* If the number of single-character typos the input name is away from a
14723      * legal name is no more than this number, it is considered to have meant
14724      * the legal name */
14725     int max_distance          = 2;
14726
14727     /* to store the name.  The size determines the maximum length before we
14728      * decide that no posix class was intended.  Should be at least
14729      * sizeof("alphanumeric") */
14730     UV input_text[15];
14731     STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
14732
14733     PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
14734
14735     CLEAR_POSIX_WARNINGS();
14736
14737     if (p >= e) {
14738         return NOT_MEANT_TO_BE_A_POSIX_CLASS;
14739     }
14740
14741     if (*(p - 1) != '[') {
14742         ADD_POSIX_WARNING(p, "it doesn't start with a '['");
14743         found_problem = TRUE;
14744     }
14745     else {
14746         has_opening_bracket = TRUE;
14747     }
14748
14749     /* They could be confused and think you can put spaces between the
14750      * components */
14751     if (isBLANK(*p)) {
14752         found_problem = TRUE;
14753
14754         do {
14755             p++;
14756         } while (p < e && isBLANK(*p));
14757
14758         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14759     }
14760
14761     /* For [. .] and [= =].  These are quite different internally from [: :],
14762      * so they are handled separately.  */
14763     if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
14764                                             and 1 for at least one char in it
14765                                           */
14766     {
14767         const char open_char  = *p;
14768         const char * temp_ptr = p + 1;
14769
14770         /* These two constructs are not handled by perl, and if we find a
14771          * syntactically valid one, we croak.  khw, who wrote this code, finds
14772          * this explanation of them very unclear:
14773          * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
14774          * And searching the rest of the internet wasn't very helpful either.
14775          * It looks like just about any byte can be in these constructs,
14776          * depending on the locale.  But unless the pattern is being compiled
14777          * under /l, which is very rare, Perl runs under the C or POSIX locale.
14778          * In that case, it looks like [= =] isn't allowed at all, and that
14779          * [. .] could be any single code point, but for longer strings the
14780          * constituent characters would have to be the ASCII alphabetics plus
14781          * the minus-hyphen.  Any sensible locale definition would limit itself
14782          * to these.  And any portable one definitely should.  Trying to parse
14783          * the general case is a nightmare (see [perl #127604]).  So, this code
14784          * looks only for interiors of these constructs that match:
14785          *      qr/.|[-\w]{2,}/
14786          * Using \w relaxes the apparent rules a little, without adding much
14787          * danger of mistaking something else for one of these constructs.
14788          *
14789          * [. .] in some implementations described on the internet is usable to
14790          * escape a character that otherwise is special in bracketed character
14791          * classes.  For example [.].] means a literal right bracket instead of
14792          * the ending of the class
14793          *
14794          * [= =] can legitimately contain a [. .] construct, but we don't
14795          * handle this case, as that [. .] construct will later get parsed
14796          * itself and croak then.  And [= =] is checked for even when not under
14797          * /l, as Perl has long done so.
14798          *
14799          * The code below relies on there being a trailing NUL, so it doesn't
14800          * have to keep checking if the parse ptr < e.
14801          */
14802         if (temp_ptr[1] == open_char) {
14803             temp_ptr++;
14804         }
14805         else while (    temp_ptr < e
14806                     && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
14807         {
14808             temp_ptr++;
14809         }
14810
14811         if (*temp_ptr == open_char) {
14812             temp_ptr++;
14813             if (*temp_ptr == ']') {
14814                 temp_ptr++;
14815                 if (! found_problem && ! check_only) {
14816                     RExC_parse = (char *) temp_ptr;
14817                     vFAIL3("POSIX syntax [%c %c] is reserved for future "
14818                             "extensions", open_char, open_char);
14819                 }
14820
14821                 /* Here, the syntax wasn't completely valid, or else the call
14822                  * is to check-only */
14823                 if (updated_parse_ptr) {
14824                     *updated_parse_ptr = (char *) temp_ptr;
14825                 }
14826
14827                 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
14828             }
14829         }
14830
14831         /* If we find something that started out to look like one of these
14832          * constructs, but isn't, we continue below so that it can be checked
14833          * for being a class name with a typo of '.' or '=' instead of a colon.
14834          * */
14835     }
14836
14837     /* Here, we think there is a possibility that a [: :] class was meant, and
14838      * we have the first real character.  It could be they think the '^' comes
14839      * first */
14840     if (*p == '^') {
14841         found_problem = TRUE;
14842         ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
14843         complement = 1;
14844         p++;
14845
14846         if (isBLANK(*p)) {
14847             found_problem = TRUE;
14848
14849             do {
14850                 p++;
14851             } while (p < e && isBLANK(*p));
14852
14853             ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14854         }
14855     }
14856
14857     /* But the first character should be a colon, which they could have easily
14858      * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
14859      * distinguish from a colon, so treat that as a colon).  */
14860     if (*p == ':') {
14861         p++;
14862         has_opening_colon = TRUE;
14863     }
14864     else if (*p == ';') {
14865         found_problem = TRUE;
14866         p++;
14867         ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
14868         has_opening_colon = TRUE;
14869     }
14870     else {
14871         found_problem = TRUE;
14872         ADD_POSIX_WARNING(p, "there must be a starting ':'");
14873
14874         /* Consider an initial punctuation (not one of the recognized ones) to
14875          * be a left terminator */
14876         if (*p != '^' && *p != ']' && isPUNCT(*p)) {
14877             p++;
14878         }
14879     }
14880
14881     /* They may think that you can put spaces between the components */
14882     if (isBLANK(*p)) {
14883         found_problem = TRUE;
14884
14885         do {
14886             p++;
14887         } while (p < e && isBLANK(*p));
14888
14889         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14890     }
14891
14892     if (*p == '^') {
14893
14894         /* We consider something like [^:^alnum:]] to not have been intended to
14895          * be a posix class, but XXX maybe we should */
14896         if (complement) {
14897             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
14898         }
14899
14900         complement = 1;
14901         p++;
14902     }
14903
14904     /* Again, they may think that you can put spaces between the components */
14905     if (isBLANK(*p)) {
14906         found_problem = TRUE;
14907
14908         do {
14909             p++;
14910         } while (p < e && isBLANK(*p));
14911
14912         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14913     }
14914
14915     if (*p == ']') {
14916
14917         /* XXX This ']' may be a typo, and something else was meant.  But
14918          * treating it as such creates enough complications, that that
14919          * possibility isn't currently considered here.  So we assume that the
14920          * ']' is what is intended, and if we've already found an initial '[',
14921          * this leaves this construct looking like [:] or [:^], which almost
14922          * certainly weren't intended to be posix classes */
14923         if (has_opening_bracket) {
14924             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
14925         }
14926
14927         /* But this function can be called when we parse the colon for
14928          * something like qr/[alpha:]]/, so we back up to look for the
14929          * beginning */
14930         p--;
14931
14932         if (*p == ';') {
14933             found_problem = TRUE;
14934             ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
14935         }
14936         else if (*p != ':') {
14937
14938             /* XXX We are currently very restrictive here, so this code doesn't
14939              * consider the possibility that, say, /[alpha.]]/ was intended to
14940              * be a posix class. */
14941             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
14942         }
14943
14944         /* Here we have something like 'foo:]'.  There was no initial colon,
14945          * and we back up over 'foo.  XXX Unlike the going forward case, we
14946          * don't handle typos of non-word chars in the middle */
14947         has_opening_colon = FALSE;
14948         p--;
14949
14950         while (p > RExC_start && isWORDCHAR(*p)) {
14951             p--;
14952         }
14953         p++;
14954
14955         /* Here, we have positioned ourselves to where we think the first
14956          * character in the potential class is */
14957     }
14958
14959     /* Now the interior really starts.  There are certain key characters that
14960      * can end the interior, or these could just be typos.  To catch both
14961      * cases, we may have to do two passes.  In the first pass, we keep on
14962      * going unless we come to a sequence that matches
14963      *      qr/ [[:punct:]] [[:blank:]]* \] /xa
14964      * This means it takes a sequence to end the pass, so two typos in a row if
14965      * that wasn't what was intended.  If the class is perfectly formed, just
14966      * this one pass is needed.  We also stop if there are too many characters
14967      * being accumulated, but this number is deliberately set higher than any
14968      * real class.  It is set high enough so that someone who thinks that
14969      * 'alphanumeric' is a correct name would get warned that it wasn't.
14970      * While doing the pass, we keep track of where the key characters were in
14971      * it.  If we don't find an end to the class, and one of the key characters
14972      * was found, we redo the pass, but stop when we get to that character.
14973      * Thus the key character was considered a typo in the first pass, but a
14974      * terminator in the second.  If two key characters are found, we stop at
14975      * the second one in the first pass.  Again this can miss two typos, but
14976      * catches a single one
14977      *
14978      * In the first pass, 'possible_end' starts as NULL, and then gets set to
14979      * point to the first key character.  For the second pass, it starts as -1.
14980      * */
14981
14982     name_start = p;
14983   parse_name:
14984     {
14985         bool has_blank               = FALSE;
14986         bool has_upper               = FALSE;
14987         bool has_terminating_colon   = FALSE;
14988         bool has_terminating_bracket = FALSE;
14989         bool has_semi_colon          = FALSE;
14990         unsigned int name_len        = 0;
14991         int punct_count              = 0;
14992
14993         while (p < e) {
14994
14995             /* Squeeze out blanks when looking up the class name below */
14996             if (isBLANK(*p) ) {
14997                 has_blank = TRUE;
14998                 found_problem = TRUE;
14999                 p++;
15000                 continue;
15001             }
15002
15003             /* The name will end with a punctuation */
15004             if (isPUNCT(*p)) {
15005                 const char * peek = p + 1;
15006
15007                 /* Treat any non-']' punctuation followed by a ']' (possibly
15008                  * with intervening blanks) as trying to terminate the class.
15009                  * ']]' is very likely to mean a class was intended (but
15010                  * missing the colon), but the warning message that gets
15011                  * generated shows the error position better if we exit the
15012                  * loop at the bottom (eventually), so skip it here. */
15013                 if (*p != ']') {
15014                     if (peek < e && isBLANK(*peek)) {
15015                         has_blank = TRUE;
15016                         found_problem = TRUE;
15017                         do {
15018                             peek++;
15019                         } while (peek < e && isBLANK(*peek));
15020                     }
15021
15022                     if (peek < e && *peek == ']') {
15023                         has_terminating_bracket = TRUE;
15024                         if (*p == ':') {
15025                             has_terminating_colon = TRUE;
15026                         }
15027                         else if (*p == ';') {
15028                             has_semi_colon = TRUE;
15029                             has_terminating_colon = TRUE;
15030                         }
15031                         else {
15032                             found_problem = TRUE;
15033                         }
15034                         p = peek + 1;
15035                         goto try_posix;
15036                     }
15037                 }
15038
15039                 /* Here we have punctuation we thought didn't end the class.
15040                  * Keep track of the position of the key characters that are
15041                  * more likely to have been class-enders */
15042                 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15043
15044                     /* Allow just one such possible class-ender not actually
15045                      * ending the class. */
15046                     if (possible_end) {
15047                         break;
15048                     }
15049                     possible_end = p;
15050                 }
15051
15052                 /* If we have too many punctuation characters, no use in
15053                  * keeping going */
15054                 if (++punct_count > max_distance) {
15055                     break;
15056                 }
15057
15058                 /* Treat the punctuation as a typo. */
15059                 input_text[name_len++] = *p;
15060                 p++;
15061             }
15062             else if (isUPPER(*p)) { /* Use lowercase for lookup */
15063                 input_text[name_len++] = toLOWER(*p);
15064                 has_upper = TRUE;
15065                 found_problem = TRUE;
15066                 p++;
15067             } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15068                 input_text[name_len++] = *p;
15069                 p++;
15070             }
15071             else {
15072                 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15073                 p+= UTF8SKIP(p);
15074             }
15075
15076             /* The declaration of 'input_text' is how long we allow a potential
15077              * class name to be, before saying they didn't mean a class name at
15078              * all */
15079             if (name_len >= C_ARRAY_LENGTH(input_text)) {
15080                 break;
15081             }
15082         }
15083
15084         /* We get to here when the possible class name hasn't been properly
15085          * terminated before:
15086          *   1) we ran off the end of the pattern; or
15087          *   2) found two characters, each of which might have been intended to
15088          *      be the name's terminator
15089          *   3) found so many punctuation characters in the purported name,
15090          *      that the edit distance to a valid one is exceeded
15091          *   4) we decided it was more characters than anyone could have
15092          *      intended to be one. */
15093
15094         found_problem = TRUE;
15095
15096         /* In the final two cases, we know that looking up what we've
15097          * accumulated won't lead to a match, even a fuzzy one. */
15098         if (   name_len >= C_ARRAY_LENGTH(input_text)
15099             || punct_count > max_distance)
15100         {
15101             /* If there was an intermediate key character that could have been
15102              * an intended end, redo the parse, but stop there */
15103             if (possible_end && possible_end != (char *) -1) {
15104                 possible_end = (char *) -1; /* Special signal value to say
15105                                                we've done a first pass */
15106                 p = name_start;
15107                 goto parse_name;
15108             }
15109
15110             /* Otherwise, it can't have meant to have been a class */
15111             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15112         }
15113
15114         /* If we ran off the end, and the final character was a punctuation
15115          * one, back up one, to look at that final one just below.  Later, we
15116          * will restore the parse pointer if appropriate */
15117         if (name_len && p == e && isPUNCT(*(p-1))) {
15118             p--;
15119             name_len--;
15120         }
15121
15122         if (p < e && isPUNCT(*p)) {
15123             if (*p == ']') {
15124                 has_terminating_bracket = TRUE;
15125
15126                 /* If this is a 2nd ']', and the first one is just below this
15127                  * one, consider that to be the real terminator.  This gives a
15128                  * uniform and better positioning for the warning message  */
15129                 if (   possible_end
15130                     && possible_end != (char *) -1
15131                     && *possible_end == ']'
15132                     && name_len && input_text[name_len - 1] == ']')
15133                 {
15134                     name_len--;
15135                     p = possible_end;
15136
15137                     /* And this is actually equivalent to having done the 2nd
15138                      * pass now, so set it to not try again */
15139                     possible_end = (char *) -1;
15140                 }
15141             }
15142             else {
15143                 if (*p == ':') {
15144                     has_terminating_colon = TRUE;
15145                 }
15146                 else if (*p == ';') {
15147                     has_semi_colon = TRUE;
15148                     has_terminating_colon = TRUE;
15149                 }
15150                 p++;
15151             }
15152         }
15153
15154     try_posix:
15155
15156         /* Here, we have a class name to look up.  We can short circuit the
15157          * stuff below for short names that can't possibly be meant to be a
15158          * class name.  (We can do this on the first pass, as any second pass
15159          * will yield an even shorter name) */
15160         if (name_len < 3) {
15161             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15162         }
15163
15164         /* Find which class it is.  Initially switch on the length of the name.
15165          * */
15166         switch (name_len) {
15167             case 4:
15168                 if (memEQs(name_start, 4, "word")) {
15169                     /* this is not POSIX, this is the Perl \w */
15170                     class_number = ANYOF_WORDCHAR;
15171                 }
15172                 break;
15173             case 5:
15174                 /* Names all of length 5: alnum alpha ascii blank cntrl digit
15175                  *                        graph lower print punct space upper
15176                  * Offset 4 gives the best switch position.  */
15177                 switch (name_start[4]) {
15178                     case 'a':
15179                         if (memBEGINs(name_start, 5, "alph")) /* alpha */
15180                             class_number = ANYOF_ALPHA;
15181                         break;
15182                     case 'e':
15183                         if (memBEGINs(name_start, 5, "spac")) /* space */
15184                             class_number = ANYOF_SPACE;
15185                         break;
15186                     case 'h':
15187                         if (memBEGINs(name_start, 5, "grap")) /* graph */
15188                             class_number = ANYOF_GRAPH;
15189                         break;
15190                     case 'i':
15191                         if (memBEGINs(name_start, 5, "asci")) /* ascii */
15192                             class_number = ANYOF_ASCII;
15193                         break;
15194                     case 'k':
15195                         if (memBEGINs(name_start, 5, "blan")) /* blank */
15196                             class_number = ANYOF_BLANK;
15197                         break;
15198                     case 'l':
15199                         if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
15200                             class_number = ANYOF_CNTRL;
15201                         break;
15202                     case 'm':
15203                         if (memBEGINs(name_start, 5, "alnu")) /* alnum */
15204                             class_number = ANYOF_ALPHANUMERIC;
15205                         break;
15206                     case 'r':
15207                         if (memBEGINs(name_start, 5, "lowe")) /* lower */
15208                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
15209                         else if (memBEGINs(name_start, 5, "uppe")) /* upper */
15210                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
15211                         break;
15212                     case 't':
15213                         if (memBEGINs(name_start, 5, "digi")) /* digit */
15214                             class_number = ANYOF_DIGIT;
15215                         else if (memBEGINs(name_start, 5, "prin")) /* print */
15216                             class_number = ANYOF_PRINT;
15217                         else if (memBEGINs(name_start, 5, "punc")) /* punct */
15218                             class_number = ANYOF_PUNCT;
15219                         break;
15220                 }
15221                 break;
15222             case 6:
15223                 if (memEQs(name_start, 6, "xdigit"))
15224                     class_number = ANYOF_XDIGIT;
15225                 break;
15226         }
15227
15228         /* If the name exactly matches a posix class name the class number will
15229          * here be set to it, and the input almost certainly was meant to be a
15230          * posix class, so we can skip further checking.  If instead the syntax
15231          * is exactly correct, but the name isn't one of the legal ones, we
15232          * will return that as an error below.  But if neither of these apply,
15233          * it could be that no posix class was intended at all, or that one
15234          * was, but there was a typo.  We tease these apart by doing fuzzy
15235          * matching on the name */
15236         if (class_number == OOB_NAMEDCLASS && found_problem) {
15237             const UV posix_names[][6] = {
15238                                                 { 'a', 'l', 'n', 'u', 'm' },
15239                                                 { 'a', 'l', 'p', 'h', 'a' },
15240                                                 { 'a', 's', 'c', 'i', 'i' },
15241                                                 { 'b', 'l', 'a', 'n', 'k' },
15242                                                 { 'c', 'n', 't', 'r', 'l' },
15243                                                 { 'd', 'i', 'g', 'i', 't' },
15244                                                 { 'g', 'r', 'a', 'p', 'h' },
15245                                                 { 'l', 'o', 'w', 'e', 'r' },
15246                                                 { 'p', 'r', 'i', 'n', 't' },
15247                                                 { 'p', 'u', 'n', 'c', 't' },
15248                                                 { 's', 'p', 'a', 'c', 'e' },
15249                                                 { 'u', 'p', 'p', 'e', 'r' },
15250                                                 { 'w', 'o', 'r', 'd' },
15251                                                 { 'x', 'd', 'i', 'g', 'i', 't' }
15252                                             };
15253             /* The names of the above all have added NULs to make them the same
15254              * size, so we need to also have the real lengths */
15255             const UV posix_name_lengths[] = {
15256                                                 sizeof("alnum") - 1,
15257                                                 sizeof("alpha") - 1,
15258                                                 sizeof("ascii") - 1,
15259                                                 sizeof("blank") - 1,
15260                                                 sizeof("cntrl") - 1,
15261                                                 sizeof("digit") - 1,
15262                                                 sizeof("graph") - 1,
15263                                                 sizeof("lower") - 1,
15264                                                 sizeof("print") - 1,
15265                                                 sizeof("punct") - 1,
15266                                                 sizeof("space") - 1,
15267                                                 sizeof("upper") - 1,
15268                                                 sizeof("word")  - 1,
15269                                                 sizeof("xdigit")- 1
15270                                             };
15271             unsigned int i;
15272             int temp_max = max_distance;    /* Use a temporary, so if we
15273                                                reparse, we haven't changed the
15274                                                outer one */
15275
15276             /* Use a smaller max edit distance if we are missing one of the
15277              * delimiters */
15278             if (   has_opening_bracket + has_opening_colon < 2
15279                 || has_terminating_bracket + has_terminating_colon < 2)
15280             {
15281                 temp_max--;
15282             }
15283
15284             /* See if the input name is close to a legal one */
15285             for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
15286
15287                 /* Short circuit call if the lengths are too far apart to be
15288                  * able to match */
15289                 if (abs( (int) (name_len - posix_name_lengths[i]))
15290                     > temp_max)
15291                 {
15292                     continue;
15293                 }
15294
15295                 if (edit_distance(input_text,
15296                                   posix_names[i],
15297                                   name_len,
15298                                   posix_name_lengths[i],
15299                                   temp_max
15300                                  )
15301                     > -1)
15302                 { /* If it is close, it probably was intended to be a class */
15303                     goto probably_meant_to_be;
15304                 }
15305             }
15306
15307             /* Here the input name is not close enough to a valid class name
15308              * for us to consider it to be intended to be a posix class.  If
15309              * we haven't already done so, and the parse found a character that
15310              * could have been terminators for the name, but which we absorbed
15311              * as typos during the first pass, repeat the parse, signalling it
15312              * to stop at that character */
15313             if (possible_end && possible_end != (char *) -1) {
15314                 possible_end = (char *) -1;
15315                 p = name_start;
15316                 goto parse_name;
15317             }
15318
15319             /* Here neither pass found a close-enough class name */
15320             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15321         }
15322
15323     probably_meant_to_be:
15324
15325         /* Here we think that a posix specification was intended.  Update any
15326          * parse pointer */
15327         if (updated_parse_ptr) {
15328             *updated_parse_ptr = (char *) p;
15329         }
15330
15331         /* If a posix class name was intended but incorrectly specified, we
15332          * output or return the warnings */
15333         if (found_problem) {
15334
15335             /* We set flags for these issues in the parse loop above instead of
15336              * adding them to the list of warnings, because we can parse it
15337              * twice, and we only want one warning instance */
15338             if (has_upper) {
15339                 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
15340             }
15341             if (has_blank) {
15342                 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15343             }
15344             if (has_semi_colon) {
15345                 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15346             }
15347             else if (! has_terminating_colon) {
15348                 ADD_POSIX_WARNING(p, "there is no terminating ':'");
15349             }
15350             if (! has_terminating_bracket) {
15351                 ADD_POSIX_WARNING(p, "there is no terminating ']'");
15352             }
15353
15354             if (   posix_warnings
15355                 && RExC_warn_text
15356                 && av_top_index(RExC_warn_text) > -1)
15357             {
15358                 *posix_warnings = RExC_warn_text;
15359             }
15360         }
15361         else if (class_number != OOB_NAMEDCLASS) {
15362             /* If it is a known class, return the class.  The class number
15363              * #defines are structured so each complement is +1 to the normal
15364              * one */
15365             CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
15366         }
15367         else if (! check_only) {
15368
15369             /* Here, it is an unrecognized class.  This is an error (unless the
15370             * call is to check only, which we've already handled above) */
15371             const char * const complement_string = (complement)
15372                                                    ? "^"
15373                                                    : "";
15374             RExC_parse = (char *) p;
15375             vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
15376                         complement_string,
15377                         UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
15378         }
15379     }
15380
15381     return OOB_NAMEDCLASS;
15382 }
15383 #undef ADD_POSIX_WARNING
15384
15385 STATIC unsigned  int
15386 S_regex_set_precedence(const U8 my_operator) {
15387
15388     /* Returns the precedence in the (?[...]) construct of the input operator,
15389      * specified by its character representation.  The precedence follows
15390      * general Perl rules, but it extends this so that ')' and ']' have (low)
15391      * precedence even though they aren't really operators */
15392
15393     switch (my_operator) {
15394         case '!':
15395             return 5;
15396         case '&':
15397             return 4;
15398         case '^':
15399         case '|':
15400         case '+':
15401         case '-':
15402             return 3;
15403         case ')':
15404             return 2;
15405         case ']':
15406             return 1;
15407     }
15408
15409     NOT_REACHED; /* NOTREACHED */
15410     return 0;   /* Silence compiler warning */
15411 }
15412
15413 STATIC regnode_offset
15414 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
15415                     I32 *flagp, U32 depth,
15416                     char * const oregcomp_parse)
15417 {
15418     /* Handle the (?[...]) construct to do set operations */
15419
15420     U8 curchar;                     /* Current character being parsed */
15421     UV start, end;                  /* End points of code point ranges */
15422     SV* final = NULL;               /* The end result inversion list */
15423     SV* result_string;              /* 'final' stringified */
15424     AV* stack;                      /* stack of operators and operands not yet
15425                                        resolved */
15426     AV* fence_stack = NULL;         /* A stack containing the positions in
15427                                        'stack' of where the undealt-with left
15428                                        parens would be if they were actually
15429                                        put there */
15430     /* The 'volatile' is a workaround for an optimiser bug
15431      * in Solaris Studio 12.3. See RT #127455 */
15432     volatile IV fence = 0;          /* Position of where most recent undealt-
15433                                        with left paren in stack is; -1 if none.
15434                                      */
15435     STRLEN len;                     /* Temporary */
15436     regnode_offset node;                  /* Temporary, and final regnode returned by
15437                                        this function */
15438     const bool save_fold = FOLD;    /* Temporary */
15439     char *save_end, *save_parse;    /* Temporaries */
15440     const bool in_locale = LOC;     /* we turn off /l during processing */
15441
15442     GET_RE_DEBUG_FLAGS_DECL;
15443
15444     PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
15445
15446     DEBUG_PARSE("xcls");
15447
15448     if (in_locale) {
15449         set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
15450     }
15451
15452     /* The use of this operator implies /u.  This is required so that the
15453      * compile time values are valid in all runtime cases */
15454     REQUIRE_UNI_RULES(flagp, 0);
15455
15456     ckWARNexperimental(RExC_parse,
15457                        WARN_EXPERIMENTAL__REGEX_SETS,
15458                        "The regex_sets feature is experimental");
15459
15460     /* Everything in this construct is a metacharacter.  Operands begin with
15461      * either a '\' (for an escape sequence), or a '[' for a bracketed
15462      * character class.  Any other character should be an operator, or
15463      * parenthesis for grouping.  Both types of operands are handled by calling
15464      * regclass() to parse them.  It is called with a parameter to indicate to
15465      * return the computed inversion list.  The parsing here is implemented via
15466      * a stack.  Each entry on the stack is a single character representing one
15467      * of the operators; or else a pointer to an operand inversion list. */
15468
15469 #define IS_OPERATOR(a) SvIOK(a)
15470 #define IS_OPERAND(a)  (! IS_OPERATOR(a))
15471
15472     /* The stack is kept in Łukasiewicz order.  (That's pronounced similar
15473      * to luke-a-shave-itch (or -itz), but people who didn't want to bother
15474      * with pronouncing it called it Reverse Polish instead, but now that YOU
15475      * know how to pronounce it you can use the correct term, thus giving due
15476      * credit to the person who invented it, and impressing your geek friends.
15477      * Wikipedia says that the pronounciation of "Ł" has been changing so that
15478      * it is now more like an English initial W (as in wonk) than an L.)
15479      *
15480      * This means that, for example, 'a | b & c' is stored on the stack as
15481      *
15482      * c  [4]
15483      * b  [3]
15484      * &  [2]
15485      * a  [1]
15486      * |  [0]
15487      *
15488      * where the numbers in brackets give the stack [array] element number.
15489      * In this implementation, parentheses are not stored on the stack.
15490      * Instead a '(' creates a "fence" so that the part of the stack below the
15491      * fence is invisible except to the corresponding ')' (this allows us to
15492      * replace testing for parens, by using instead subtraction of the fence
15493      * position).  As new operands are processed they are pushed onto the stack
15494      * (except as noted in the next paragraph).  New operators of higher
15495      * precedence than the current final one are inserted on the stack before
15496      * the lhs operand (so that when the rhs is pushed next, everything will be
15497      * in the correct positions shown above.  When an operator of equal or
15498      * lower precedence is encountered in parsing, all the stacked operations
15499      * of equal or higher precedence are evaluated, leaving the result as the
15500      * top entry on the stack.  This makes higher precedence operations
15501      * evaluate before lower precedence ones, and causes operations of equal
15502      * precedence to left associate.
15503      *
15504      * The only unary operator '!' is immediately pushed onto the stack when
15505      * encountered.  When an operand is encountered, if the top of the stack is
15506      * a '!", the complement is immediately performed, and the '!' popped.  The
15507      * resulting value is treated as a new operand, and the logic in the
15508      * previous paragraph is executed.  Thus in the expression
15509      *      [a] + ! [b]
15510      * the stack looks like
15511      *
15512      * !
15513      * a
15514      * +
15515      *
15516      * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
15517      * becomes
15518      *
15519      * !b
15520      * a
15521      * +
15522      *
15523      * A ')' is treated as an operator with lower precedence than all the
15524      * aforementioned ones, which causes all operations on the stack above the
15525      * corresponding '(' to be evaluated down to a single resultant operand.
15526      * Then the fence for the '(' is removed, and the operand goes through the
15527      * algorithm above, without the fence.
15528      *
15529      * A separate stack is kept of the fence positions, so that the position of
15530      * the latest so-far unbalanced '(' is at the top of it.
15531      *
15532      * The ']' ending the construct is treated as the lowest operator of all,
15533      * so that everything gets evaluated down to a single operand, which is the
15534      * result */
15535
15536     sv_2mortal((SV *)(stack = newAV()));
15537     sv_2mortal((SV *)(fence_stack = newAV()));
15538
15539     while (RExC_parse < RExC_end) {
15540         I32 top_index;              /* Index of top-most element in 'stack' */
15541         SV** top_ptr;               /* Pointer to top 'stack' element */
15542         SV* current = NULL;         /* To contain the current inversion list
15543                                        operand */
15544         SV* only_to_avoid_leaks;
15545
15546         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15547                                 TRUE /* Force /x */ );
15548         if (RExC_parse >= RExC_end) {   /* Fail */
15549             break;
15550         }
15551
15552         curchar = UCHARAT(RExC_parse);
15553
15554 redo_curchar:
15555
15556 #ifdef ENABLE_REGEX_SETS_DEBUGGING
15557                     /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
15558         DEBUG_U(dump_regex_sets_structures(pRExC_state,
15559                                            stack, fence, fence_stack));
15560 #endif
15561
15562         top_index = av_tindex_skip_len_mg(stack);
15563
15564         switch (curchar) {
15565             SV** stacked_ptr;       /* Ptr to something already on 'stack' */
15566             char stacked_operator;  /* The topmost operator on the 'stack'. */
15567             SV* lhs;                /* Operand to the left of the operator */
15568             SV* rhs;                /* Operand to the right of the operator */
15569             SV* fence_ptr;          /* Pointer to top element of the fence
15570                                        stack */
15571
15572             case '(':
15573
15574                 if (   RExC_parse < RExC_end - 1
15575                     && (UCHARAT(RExC_parse + 1) == '?'))
15576                 {
15577                     /* If is a '(?', could be an embedded '(?flags:(?[...])'.
15578                      * This happens when we have some thing like
15579                      *
15580                      *   my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
15581                      *   ...
15582                      *   qr/(?[ \p{Digit} & $thai_or_lao ])/;
15583                      *
15584                      * Here we would be handling the interpolated
15585                      * '$thai_or_lao'.  We handle this by a recursive call to
15586                      * ourselves which returns the inversion list the
15587                      * interpolated expression evaluates to.  We use the flags
15588                      * from the interpolated pattern. */
15589                     U32 save_flags = RExC_flags;
15590                     const char * save_parse;
15591
15592                     RExC_parse += 2;        /* Skip past the '(?' */
15593                     save_parse = RExC_parse;
15594
15595                     /* Parse any flags for the '(?' */
15596                     parse_lparen_question_flags(pRExC_state);
15597
15598                     if (RExC_parse == save_parse  /* Makes sure there was at
15599                                                      least one flag (or else
15600                                                      this embedding wasn't
15601                                                      compiled) */
15602                         || RExC_parse >= RExC_end - 4
15603                         || UCHARAT(RExC_parse) != ':'
15604                         || UCHARAT(++RExC_parse) != '('
15605                         || UCHARAT(++RExC_parse) != '?'
15606                         || UCHARAT(++RExC_parse) != '[')
15607                     {
15608
15609                         /* In combination with the above, this moves the
15610                          * pointer to the point just after the first erroneous
15611                          * character (or if there are no flags, to where they
15612                          * should have been) */
15613                         if (RExC_parse >= RExC_end - 4) {
15614                             RExC_parse = RExC_end;
15615                         }
15616                         else if (RExC_parse != save_parse) {
15617                             RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15618                         }
15619                         vFAIL("Expecting '(?flags:(?[...'");
15620                     }
15621
15622                     /* Recurse, with the meat of the embedded expression */
15623                     RExC_parse++;
15624                     (void) handle_regex_sets(pRExC_state, &current, flagp,
15625                                                     depth+1, oregcomp_parse);
15626
15627                     /* Here, 'current' contains the embedded expression's
15628                      * inversion list, and RExC_parse points to the trailing
15629                      * ']'; the next character should be the ')' */
15630                     RExC_parse++;
15631                     if (UCHARAT(RExC_parse) != ')')
15632                         vFAIL("Expecting close paren for nested extended charclass");
15633
15634                     /* Then the ')' matching the original '(' handled by this
15635                      * case: statement */
15636                     RExC_parse++;
15637                     if (UCHARAT(RExC_parse) != ')')
15638                         vFAIL("Expecting close paren for wrapper for nested extended charclass");
15639
15640                     RExC_parse++;
15641                     RExC_flags = save_flags;
15642                     goto handle_operand;
15643                 }
15644
15645                 /* A regular '('.  Look behind for illegal syntax */
15646                 if (top_index - fence >= 0) {
15647                     /* If the top entry on the stack is an operator, it had
15648                      * better be a '!', otherwise the entry below the top
15649                      * operand should be an operator */
15650                     if (   ! (top_ptr = av_fetch(stack, top_index, FALSE))
15651                         || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
15652                         || (   IS_OPERAND(*top_ptr)
15653                             && (   top_index - fence < 1
15654                                 || ! (stacked_ptr = av_fetch(stack,
15655                                                              top_index - 1,
15656                                                              FALSE))
15657                                 || ! IS_OPERATOR(*stacked_ptr))))
15658                     {
15659                         RExC_parse++;
15660                         vFAIL("Unexpected '(' with no preceding operator");
15661                     }
15662                 }
15663
15664                 /* Stack the position of this undealt-with left paren */
15665                 av_push(fence_stack, newSViv(fence));
15666                 fence = top_index + 1;
15667                 break;
15668
15669             case '\\':
15670                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
15671                  * multi-char folds are allowed.  */
15672                 if (!regclass(pRExC_state, flagp, depth+1,
15673                               TRUE, /* means parse just the next thing */
15674                               FALSE, /* don't allow multi-char folds */
15675                               FALSE, /* don't silence non-portable warnings.  */
15676                               TRUE,  /* strict */
15677                               FALSE, /* Require return to be an ANYOF */
15678                               &current))
15679                 {
15680                     FAIL2("panic: regclass returned failure to handle_sets, "
15681                           "flags=%#" UVxf, (UV) *flagp);
15682                 }
15683
15684                 /* regclass() will return with parsing just the \ sequence,
15685                  * leaving the parse pointer at the next thing to parse */
15686                 RExC_parse--;
15687                 goto handle_operand;
15688
15689             case '[':   /* Is a bracketed character class */
15690             {
15691                 /* See if this is a [:posix:] class. */
15692                 bool is_posix_class = (OOB_NAMEDCLASS
15693                             < handle_possible_posix(pRExC_state,
15694                                                 RExC_parse + 1,
15695                                                 NULL,
15696                                                 NULL,
15697                                                 TRUE /* checking only */));
15698                 /* If it is a posix class, leave the parse pointer at the '['
15699                  * to fool regclass() into thinking it is part of a
15700                  * '[[:posix:]]'. */
15701                 if (! is_posix_class) {
15702                     RExC_parse++;
15703                 }
15704
15705                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
15706                  * multi-char folds are allowed.  */
15707                 if (!regclass(pRExC_state, flagp, depth+1,
15708                                 is_posix_class, /* parse the whole char
15709                                                     class only if not a
15710                                                     posix class */
15711                                 FALSE, /* don't allow multi-char folds */
15712                                 TRUE, /* silence non-portable warnings. */
15713                                 TRUE, /* strict */
15714                                 FALSE, /* Require return to be an ANYOF */
15715                                 &current))
15716                 {
15717                     FAIL2("panic: regclass returned failure to handle_sets, "
15718                           "flags=%#" UVxf, (UV) *flagp);
15719                 }
15720
15721                 if (! current) {
15722                     break;
15723                 }
15724
15725                 /* function call leaves parse pointing to the ']', except if we
15726                  * faked it */
15727                 if (is_posix_class) {
15728                     RExC_parse--;
15729                 }
15730
15731                 goto handle_operand;
15732             }
15733
15734             case ']':
15735                 if (top_index >= 1) {
15736                     goto join_operators;
15737                 }
15738
15739                 /* Only a single operand on the stack: are done */
15740                 goto done;
15741
15742             case ')':
15743                 if (av_tindex_skip_len_mg(fence_stack) < 0) {
15744                     if (UCHARAT(RExC_parse - 1) == ']')  {
15745                         break;
15746                     }
15747                     RExC_parse++;
15748                     vFAIL("Unexpected ')'");
15749                 }
15750
15751                 /* If nothing after the fence, is missing an operand */
15752                 if (top_index - fence < 0) {
15753                     RExC_parse++;
15754                     goto bad_syntax;
15755                 }
15756                 /* If at least two things on the stack, treat this as an
15757                   * operator */
15758                 if (top_index - fence >= 1) {
15759                     goto join_operators;
15760                 }
15761
15762                 /* Here only a single thing on the fenced stack, and there is a
15763                  * fence.  Get rid of it */
15764                 fence_ptr = av_pop(fence_stack);
15765                 assert(fence_ptr);
15766                 fence = SvIV(fence_ptr);
15767                 SvREFCNT_dec_NN(fence_ptr);
15768                 fence_ptr = NULL;
15769
15770                 if (fence < 0) {
15771                     fence = 0;
15772                 }
15773
15774                 /* Having gotten rid of the fence, we pop the operand at the
15775                  * stack top and process it as a newly encountered operand */
15776                 current = av_pop(stack);
15777                 if (IS_OPERAND(current)) {
15778                     goto handle_operand;
15779                 }
15780
15781                 RExC_parse++;
15782                 goto bad_syntax;
15783
15784             case '&':
15785             case '|':
15786             case '+':
15787             case '-':
15788             case '^':
15789
15790                 /* These binary operators should have a left operand already
15791                  * parsed */
15792                 if (   top_index - fence < 0
15793                     || top_index - fence == 1
15794                     || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
15795                     || ! IS_OPERAND(*top_ptr))
15796                 {
15797                     goto unexpected_binary;
15798                 }
15799
15800                 /* If only the one operand is on the part of the stack visible
15801                  * to us, we just place this operator in the proper position */
15802                 if (top_index - fence < 2) {
15803
15804                     /* Place the operator before the operand */
15805
15806                     SV* lhs = av_pop(stack);
15807                     av_push(stack, newSVuv(curchar));
15808                     av_push(stack, lhs);
15809                     break;
15810                 }
15811
15812                 /* But if there is something else on the stack, we need to
15813                  * process it before this new operator if and only if the
15814                  * stacked operation has equal or higher precedence than the
15815                  * new one */
15816
15817              join_operators:
15818
15819                 /* The operator on the stack is supposed to be below both its
15820                  * operands */
15821                 if (   ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
15822                     || IS_OPERAND(*stacked_ptr))
15823                 {
15824                     /* But if not, it's legal and indicates we are completely
15825                      * done if and only if we're currently processing a ']',
15826                      * which should be the final thing in the expression */
15827                     if (curchar == ']') {
15828                         goto done;
15829                     }
15830
15831                   unexpected_binary:
15832                     RExC_parse++;
15833                     vFAIL2("Unexpected binary operator '%c' with no "
15834                            "preceding operand", curchar);
15835                 }
15836                 stacked_operator = (char) SvUV(*stacked_ptr);
15837
15838                 if (regex_set_precedence(curchar)
15839                     > regex_set_precedence(stacked_operator))
15840                 {
15841                     /* Here, the new operator has higher precedence than the
15842                      * stacked one.  This means we need to add the new one to
15843                      * the stack to await its rhs operand (and maybe more
15844                      * stuff).  We put it before the lhs operand, leaving
15845                      * untouched the stacked operator and everything below it
15846                      * */
15847                     lhs = av_pop(stack);
15848                     assert(IS_OPERAND(lhs));
15849
15850                     av_push(stack, newSVuv(curchar));
15851                     av_push(stack, lhs);
15852                     break;
15853                 }
15854
15855                 /* Here, the new operator has equal or lower precedence than
15856                  * what's already there.  This means the operation already
15857                  * there should be performed now, before the new one. */
15858
15859                 rhs = av_pop(stack);
15860                 if (! IS_OPERAND(rhs)) {
15861
15862                     /* This can happen when a ! is not followed by an operand,
15863                      * like in /(?[\t &!])/ */
15864                     goto bad_syntax;
15865                 }
15866
15867                 lhs = av_pop(stack);
15868
15869                 if (! IS_OPERAND(lhs)) {
15870
15871                     /* This can happen when there is an empty (), like in
15872                      * /(?[[0]+()+])/ */
15873                     goto bad_syntax;
15874                 }
15875
15876                 switch (stacked_operator) {
15877                     case '&':
15878                         _invlist_intersection(lhs, rhs, &rhs);
15879                         break;
15880
15881                     case '|':
15882                     case '+':
15883                         _invlist_union(lhs, rhs, &rhs);
15884                         break;
15885
15886                     case '-':
15887                         _invlist_subtract(lhs, rhs, &rhs);
15888                         break;
15889
15890                     case '^':   /* The union minus the intersection */
15891                     {
15892                         SV* i = NULL;
15893                         SV* u = NULL;
15894
15895                         _invlist_union(lhs, rhs, &u);
15896                         _invlist_intersection(lhs, rhs, &i);
15897                         _invlist_subtract(u, i, &rhs);
15898                         SvREFCNT_dec_NN(i);
15899                         SvREFCNT_dec_NN(u);
15900                         break;
15901                     }
15902                 }
15903                 SvREFCNT_dec(lhs);
15904
15905                 /* Here, the higher precedence operation has been done, and the
15906                  * result is in 'rhs'.  We overwrite the stacked operator with
15907                  * the result.  Then we redo this code to either push the new
15908                  * operator onto the stack or perform any higher precedence
15909                  * stacked operation */
15910                 only_to_avoid_leaks = av_pop(stack);
15911                 SvREFCNT_dec(only_to_avoid_leaks);
15912                 av_push(stack, rhs);
15913                 goto redo_curchar;
15914
15915             case '!':   /* Highest priority, right associative */
15916
15917                 /* If what's already at the top of the stack is another '!",
15918                  * they just cancel each other out */
15919                 if (   (top_ptr = av_fetch(stack, top_index, FALSE))
15920                     && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
15921                 {
15922                     only_to_avoid_leaks = av_pop(stack);
15923                     SvREFCNT_dec(only_to_avoid_leaks);
15924                 }
15925                 else { /* Otherwise, since it's right associative, just push
15926                           onto the stack */
15927                     av_push(stack, newSVuv(curchar));
15928                 }
15929                 break;
15930
15931             default:
15932                 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15933                 if (RExC_parse >= RExC_end) {
15934                     break;
15935                 }
15936                 vFAIL("Unexpected character");
15937
15938           handle_operand:
15939
15940             /* Here 'current' is the operand.  If something is already on the
15941              * stack, we have to check if it is a !.  But first, the code above
15942              * may have altered the stack in the time since we earlier set
15943              * 'top_index'.  */
15944
15945             top_index = av_tindex_skip_len_mg(stack);
15946             if (top_index - fence >= 0) {
15947                 /* If the top entry on the stack is an operator, it had better
15948                  * be a '!', otherwise the entry below the top operand should
15949                  * be an operator */
15950                 top_ptr = av_fetch(stack, top_index, FALSE);
15951                 assert(top_ptr);
15952                 if (IS_OPERATOR(*top_ptr)) {
15953
15954                     /* The only permissible operator at the top of the stack is
15955                      * '!', which is applied immediately to this operand. */
15956                     curchar = (char) SvUV(*top_ptr);
15957                     if (curchar != '!') {
15958                         SvREFCNT_dec(current);
15959                         vFAIL2("Unexpected binary operator '%c' with no "
15960                                 "preceding operand", curchar);
15961                     }
15962
15963                     _invlist_invert(current);
15964
15965                     only_to_avoid_leaks = av_pop(stack);
15966                     SvREFCNT_dec(only_to_avoid_leaks);
15967
15968                     /* And we redo with the inverted operand.  This allows
15969                      * handling multiple ! in a row */
15970                     goto handle_operand;
15971                 }
15972                           /* Single operand is ok only for the non-binary ')'
15973                            * operator */
15974                 else if ((top_index - fence == 0 && curchar != ')')
15975                          || (top_index - fence > 0
15976                              && (! (stacked_ptr = av_fetch(stack,
15977                                                            top_index - 1,
15978                                                            FALSE))
15979                                  || IS_OPERAND(*stacked_ptr))))
15980                 {
15981                     SvREFCNT_dec(current);
15982                     vFAIL("Operand with no preceding operator");
15983                 }
15984             }
15985
15986             /* Here there was nothing on the stack or the top element was
15987              * another operand.  Just add this new one */
15988             av_push(stack, current);
15989
15990         } /* End of switch on next parse token */
15991
15992         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15993     } /* End of loop parsing through the construct */
15994
15995     vFAIL("Syntax error in (?[...])");
15996
15997   done:
15998
15999     if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16000         if (RExC_parse < RExC_end) {
16001             RExC_parse++;
16002         }
16003
16004         vFAIL("Unexpected ']' with no following ')' in (?[...");
16005     }
16006
16007     if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16008         vFAIL("Unmatched (");
16009     }
16010
16011     if (av_tindex_skip_len_mg(stack) < 0   /* Was empty */
16012         || ((final = av_pop(stack)) == NULL)
16013         || ! IS_OPERAND(final)
16014         || ! is_invlist(final)
16015         || av_tindex_skip_len_mg(stack) >= 0)  /* More left on stack */
16016     {
16017       bad_syntax:
16018         SvREFCNT_dec(final);
16019         vFAIL("Incomplete expression within '(?[ ])'");
16020     }
16021
16022     /* Here, 'final' is the resultant inversion list from evaluating the
16023      * expression.  Return it if so requested */
16024     if (return_invlist) {
16025         *return_invlist = final;
16026         return END;
16027     }
16028
16029     /* Otherwise generate a resultant node, based on 'final'.  regclass() is
16030      * expecting a string of ranges and individual code points */
16031     invlist_iterinit(final);
16032     result_string = newSVpvs("");
16033     while (invlist_iternext(final, &start, &end)) {
16034         if (start == end) {
16035             Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16036         }
16037         else {
16038             Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}",
16039                                                      start,          end);
16040         }
16041     }
16042
16043     /* About to generate an ANYOF (or similar) node from the inversion list we
16044      * have calculated */
16045     save_parse = RExC_parse;
16046     RExC_parse = SvPV(result_string, len);
16047     save_end = RExC_end;
16048     RExC_end = RExC_parse + len;
16049     TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16050
16051     /* We turn off folding around the call, as the class we have constructed
16052      * already has all folding taken into consideration, and we don't want
16053      * regclass() to add to that */
16054     RExC_flags &= ~RXf_PMf_FOLD;
16055     /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16056      * folds are allowed.  */
16057     node = regclass(pRExC_state, flagp, depth+1,
16058                     FALSE, /* means parse the whole char class */
16059                     FALSE, /* don't allow multi-char folds */
16060                     TRUE, /* silence non-portable warnings.  The above may very
16061                              well have generated non-portable code points, but
16062                              they're valid on this machine */
16063                     FALSE, /* similarly, no need for strict */
16064                     FALSE, /* Require return to be an ANYOF */
16065                     NULL
16066                 );
16067
16068     RESTORE_WARNINGS;
16069     RExC_parse = save_parse + 1;
16070     RExC_end = save_end;
16071     SvREFCNT_dec_NN(final);
16072     SvREFCNT_dec_NN(result_string);
16073
16074     if (save_fold) {
16075         RExC_flags |= RXf_PMf_FOLD;
16076     }
16077
16078     if (!node)
16079         FAIL2("panic: regclass returned failure to handle_sets, flags=%#" UVxf,
16080                     PTR2UV(flagp));
16081
16082     /* Fix up the node type if we are in locale.  (We have pretended we are
16083      * under /u for the purposes of regclass(), as this construct will only
16084      * work under UTF-8 locales.  But now we change the opcode to be ANYOFL (so
16085      * as to cause any warnings about bad locales to be output in regexec.c),
16086      * and add the flag that indicates to check if not in a UTF-8 locale.  The
16087      * reason we above forbid optimization into something other than an ANYOF
16088      * node is simply to minimize the number of code changes in regexec.c.
16089      * Otherwise we would have to create new EXACTish node types and deal with
16090      * them.  This decision could be revisited should this construct become
16091      * popular.
16092      *
16093      * (One might think we could look at the resulting ANYOF node and suppress
16094      * the flag if everything is above 255, as those would be UTF-8 only,
16095      * but this isn't true, as the components that led to that result could
16096      * have been locale-affected, and just happen to cancel each other out
16097      * under UTF-8 locales.) */
16098     if (in_locale) {
16099         set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16100
16101         assert(OP(REGNODE_p(node)) == ANYOF);
16102
16103         OP(REGNODE_p(node)) = ANYOFL;
16104         ANYOF_FLAGS(REGNODE_p(node))
16105                 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16106     }
16107
16108     nextchar(pRExC_state);
16109     Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16110     return node;
16111 }
16112
16113 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16114
16115 STATIC void
16116 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
16117                              AV * stack, const IV fence, AV * fence_stack)
16118 {   /* Dumps the stacks in handle_regex_sets() */
16119
16120     const SSize_t stack_top = av_tindex_skip_len_mg(stack);
16121     const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
16122     SSize_t i;
16123
16124     PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
16125
16126     PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
16127
16128     if (stack_top < 0) {
16129         PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
16130     }
16131     else {
16132         PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
16133         for (i = stack_top; i >= 0; i--) {
16134             SV ** element_ptr = av_fetch(stack, i, FALSE);
16135             if (! element_ptr) {
16136             }
16137
16138             if (IS_OPERATOR(*element_ptr)) {
16139                 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
16140                                             (int) i, (int) SvIV(*element_ptr));
16141             }
16142             else {
16143                 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
16144                 sv_dump(*element_ptr);
16145             }
16146         }
16147     }
16148
16149     if (fence_stack_top < 0) {
16150         PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
16151     }
16152     else {
16153         PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
16154         for (i = fence_stack_top; i >= 0; i--) {
16155             SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
16156             if (! element_ptr) {
16157             }
16158
16159             PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
16160                                             (int) i, (int) SvIV(*element_ptr));
16161         }
16162     }
16163 }
16164
16165 #endif
16166
16167 #undef IS_OPERATOR
16168 #undef IS_OPERAND
16169
16170 STATIC void
16171 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
16172 {
16173     /* This adds the Latin1/above-Latin1 folding rules.
16174      *
16175      * This should be called only for a Latin1-range code points, cp, which is
16176      * known to be involved in a simple fold with other code points above
16177      * Latin1.  It would give false results if /aa has been specified.
16178      * Multi-char folds are outside the scope of this, and must be handled
16179      * specially. */
16180
16181     PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
16182
16183     assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
16184
16185     /* The rules that are valid for all Unicode versions are hard-coded in */
16186     switch (cp) {
16187         case 'k':
16188         case 'K':
16189           *invlist =
16190              add_cp_to_invlist(*invlist, KELVIN_SIGN);
16191             break;
16192         case 's':
16193         case 'S':
16194           *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
16195             break;
16196         case MICRO_SIGN:
16197           *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
16198           *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
16199             break;
16200         case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
16201         case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
16202           *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
16203             break;
16204         case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
16205           *invlist = add_cp_to_invlist(*invlist,
16206                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
16207             break;
16208
16209         default:    /* Other code points are checked against the data for the
16210                        current Unicode version */
16211           {
16212             Size_t folds_to_count;
16213             unsigned int first_folds_to;
16214             const unsigned int * remaining_folds_to_list;
16215             UV folded_cp;
16216
16217             if (isASCII(cp)) {
16218                 folded_cp = toFOLD(cp);
16219             }
16220             else {
16221                 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
16222                 Size_t dummy_len;
16223                 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
16224             }
16225
16226             if (folded_cp > 255) {
16227                 *invlist = add_cp_to_invlist(*invlist, folded_cp);
16228             }
16229
16230             folds_to_count = _inverse_folds(folded_cp, &first_folds_to,
16231                                                     &remaining_folds_to_list);
16232             if (folds_to_count == 0) {
16233
16234                 /* Use deprecated warning to increase the chances of this being
16235                  * output */
16236                 ckWARN2reg_d(RExC_parse,
16237                         "Perl folding rules are not up-to-date for 0x%02X;"
16238                         " please use the perlbug utility to report;", cp);
16239             }
16240             else {
16241                 unsigned int i;
16242
16243                 if (first_folds_to > 255) {
16244                     *invlist = add_cp_to_invlist(*invlist, first_folds_to);
16245                 }
16246                 for (i = 0; i < folds_to_count - 1; i++) {
16247                     if (remaining_folds_to_list[i] > 255) {
16248                         *invlist = add_cp_to_invlist(*invlist,
16249                                                     remaining_folds_to_list[i]);
16250                     }
16251                 }
16252             }
16253             break;
16254          }
16255     }
16256 }
16257
16258 STATIC void
16259 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
16260 {
16261     /* Output the elements of the array given by '*posix_warnings' as REGEXP
16262      * warnings. */
16263
16264     SV * msg;
16265     const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
16266
16267     PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
16268
16269     if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
16270         return;
16271     }
16272
16273     while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
16274         if (first_is_fatal) {           /* Avoid leaking this */
16275             av_undef(posix_warnings);   /* This isn't necessary if the
16276                                             array is mortal, but is a
16277                                             fail-safe */
16278             (void) sv_2mortal(msg);
16279             PREPARE_TO_DIE;
16280         }
16281         Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
16282         SvREFCNT_dec_NN(msg);
16283     }
16284
16285     UPDATE_WARNINGS_LOC(RExC_parse);
16286 }
16287
16288 STATIC AV *
16289 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
16290 {
16291     /* This adds the string scalar <multi_string> to the array
16292      * <multi_char_matches>.  <multi_string> is known to have exactly
16293      * <cp_count> code points in it.  This is used when constructing a
16294      * bracketed character class and we find something that needs to match more
16295      * than a single character.
16296      *
16297      * <multi_char_matches> is actually an array of arrays.  Each top-level
16298      * element is an array that contains all the strings known so far that are
16299      * the same length.  And that length (in number of code points) is the same
16300      * as the index of the top-level array.  Hence, the [2] element is an
16301      * array, each element thereof is a string containing TWO code points;
16302      * while element [3] is for strings of THREE characters, and so on.  Since
16303      * this is for multi-char strings there can never be a [0] nor [1] element.
16304      *
16305      * When we rewrite the character class below, we will do so such that the
16306      * longest strings are written first, so that it prefers the longest
16307      * matching strings first.  This is done even if it turns out that any
16308      * quantifier is non-greedy, out of this programmer's (khw) laziness.  Tom
16309      * Christiansen has agreed that this is ok.  This makes the test for the
16310      * ligature 'ffi' come before the test for 'ff', for example */
16311
16312     AV* this_array;
16313     AV** this_array_ptr;
16314
16315     PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
16316
16317     if (! multi_char_matches) {
16318         multi_char_matches = newAV();
16319     }
16320
16321     if (av_exists(multi_char_matches, cp_count)) {
16322         this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
16323         this_array = *this_array_ptr;
16324     }
16325     else {
16326         this_array = newAV();
16327         av_store(multi_char_matches, cp_count,
16328                  (SV*) this_array);
16329     }
16330     av_push(this_array, multi_string);
16331
16332     return multi_char_matches;
16333 }
16334
16335 /* The names of properties whose definitions are not known at compile time are
16336  * stored in this SV, after a constant heading.  So if the length has been
16337  * changed since initialization, then there is a run-time definition. */
16338 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION                            \
16339                                         (SvCUR(listsv) != initial_listsv_len)
16340
16341 /* There is a restricted set of white space characters that are legal when
16342  * ignoring white space in a bracketed character class.  This generates the
16343  * code to skip them.
16344  *
16345  * There is a line below that uses the same white space criteria but is outside
16346  * this macro.  Both here and there must use the same definition */
16347 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p)                          \
16348     STMT_START {                                                        \
16349         if (do_skip) {                                                  \
16350             while (isBLANK_A(UCHARAT(p)))                               \
16351             {                                                           \
16352                 p++;                                                    \
16353             }                                                           \
16354         }                                                               \
16355     } STMT_END
16356
16357 STATIC regnode_offset
16358 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
16359                  const bool stop_at_1,  /* Just parse the next thing, don't
16360                                            look for a full character class */
16361                  bool allow_multi_folds,
16362                  const bool silence_non_portable,   /* Don't output warnings
16363                                                        about too large
16364                                                        characters */
16365                  const bool strict,
16366                  bool optimizable,                  /* ? Allow a non-ANYOF return
16367                                                        node */
16368                  SV** ret_invlist  /* Return an inversion list, not a node */
16369           )
16370 {
16371     /* parse a bracketed class specification.  Most of these will produce an
16372      * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
16373      * EXACTFish node; [[:ascii:]], a POSIXA node; etc.  It is more complex
16374      * under /i with multi-character folds: it will be rewritten following the
16375      * paradigm of this example, where the <multi-fold>s are characters which
16376      * fold to multiple character sequences:
16377      *      /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
16378      * gets effectively rewritten as:
16379      *      /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
16380      * reg() gets called (recursively) on the rewritten version, and this
16381      * function will return what it constructs.  (Actually the <multi-fold>s
16382      * aren't physically removed from the [abcdefghi], it's just that they are
16383      * ignored in the recursion by means of a flag:
16384      * <RExC_in_multi_char_class>.)
16385      *
16386      * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
16387      * characters, with the corresponding bit set if that character is in the
16388      * list.  For characters above this, a range list or swash is used.  There
16389      * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
16390      * determinable at compile time
16391      *
16392      * On success, returns the offset at which any next node should be placed
16393      * into the regex engine program being compiled.
16394      *
16395      * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
16396      * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
16397      * UTF-8
16398      */
16399
16400     UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
16401     IV range = 0;
16402     UV value = OOB_UNICODE, save_value = OOB_UNICODE;
16403     regnode_offset ret;
16404     STRLEN numlen;
16405     int namedclass = OOB_NAMEDCLASS;
16406     char *rangebegin = NULL;
16407     bool need_class = 0;
16408     SV *listsv = NULL;
16409     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
16410                                       than just initialized.  */
16411     SV* properties = NULL;    /* Code points that match \p{} \P{} */
16412     SV* posixes = NULL;     /* Code points that match classes like [:word:],
16413                                extended beyond the Latin1 range.  These have to
16414                                be kept separate from other code points for much
16415                                of this function because their handling  is
16416                                different under /i, and for most classes under
16417                                /d as well */
16418     SV* nposixes = NULL;    /* Similarly for [:^word:].  These are kept
16419                                separate for a while from the non-complemented
16420                                versions because of complications with /d
16421                                matching */
16422     SV* simple_posixes = NULL; /* But under some conditions, the classes can be
16423                                   treated more simply than the general case,
16424                                   leading to less compilation and execution
16425                                   work */
16426     UV element_count = 0;   /* Number of distinct elements in the class.
16427                                Optimizations may be possible if this is tiny */
16428     AV * multi_char_matches = NULL; /* Code points that fold to more than one
16429                                        character; used under /i */
16430     UV n;
16431     char * stop_ptr = RExC_end;    /* where to stop parsing */
16432
16433     /* ignore unescaped whitespace? */
16434     const bool skip_white = cBOOL(   ret_invlist
16435                                   || (RExC_flags & RXf_PMf_EXTENDED_MORE));
16436
16437     /* Unicode properties are stored in a swash; this holds the current one
16438      * being parsed.  If this swash is the only above-latin1 component of the
16439      * character class, an optimization is to pass it directly on to the
16440      * execution engine.  Otherwise, it is set to NULL to indicate that there
16441      * are other things in the class that have to be dealt with at execution
16442      * time */
16443     SV* swash = NULL;           /* Code points that match \p{} \P{} */
16444
16445     /* Set if a component of this character class is user-defined; just passed
16446      * on to the engine */
16447     bool has_user_defined_property = FALSE;
16448
16449     /* inversion list of code points this node matches only when the target
16450      * string is in UTF-8.  These are all non-ASCII, < 256.  (Because is under
16451      * /d) */
16452     SV* has_upper_latin1_only_utf8_matches = NULL;
16453
16454     /* Inversion list of code points this node matches regardless of things
16455      * like locale, folding, utf8ness of the target string */
16456     SV* cp_list = NULL;
16457
16458     /* Like cp_list, but code points on this list need to be checked for things
16459      * that fold to/from them under /i */
16460     SV* cp_foldable_list = NULL;
16461
16462     /* Like cp_list, but code points on this list are valid only when the
16463      * runtime locale is UTF-8 */
16464     SV* only_utf8_locale_list = NULL;
16465
16466     /* In a range, if one of the endpoints is non-character-set portable,
16467      * meaning that it hard-codes a code point that may mean a different
16468      * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
16469      * mnemonic '\t' which each mean the same character no matter which
16470      * character set the platform is on. */
16471     unsigned int non_portable_endpoint = 0;
16472
16473     /* Is the range unicode? which means on a platform that isn't 1-1 native
16474      * to Unicode (i.e. non-ASCII), each code point in it should be considered
16475      * to be a Unicode value.  */
16476     bool unicode_range = FALSE;
16477     bool invert = FALSE;    /* Is this class to be complemented */
16478
16479     bool warn_super = ALWAYS_WARN_SUPER;
16480
16481     const regnode_offset orig_emit = RExC_emit; /* Save the original RExC_emit in
16482         case we need to change the emitted regop to an EXACT. */
16483     const char * orig_parse = RExC_parse;
16484     bool posixl_matches_all = FALSE; /* Does /l class have both e.g. \W,\w ? */
16485
16486     /* This variable is used to mark where the end in the input is of something
16487      * that looks like a POSIX construct but isn't.  During the parse, when
16488      * something looks like it could be such a construct is encountered, it is
16489      * checked for being one, but not if we've already checked this area of the
16490      * input.  Only after this position is reached do we check again */
16491     char *not_posix_region_end = RExC_parse - 1;
16492
16493     AV* posix_warnings = NULL;
16494     const bool do_posix_warnings = ckWARN(WARN_REGEXP);
16495     U8 op = END;    /* The returned node-type, initialized to an impossible
16496                        one.  */
16497     U8 anyof_flags = 0;   /* flag bits if the node is an ANYOF-type */
16498     U32 posixl = 0;       /* bit field of posix classes matched under /l */
16499     bool use_anyofd = FALSE; /* ? Is this to be an ANYOFD node */
16500
16501     GET_RE_DEBUG_FLAGS_DECL;
16502
16503     PERL_ARGS_ASSERT_REGCLASS;
16504 #ifndef DEBUGGING
16505     PERL_UNUSED_ARG(depth);
16506 #endif
16507
16508
16509     /* If wants an inversion list returned, we can't optimize to something
16510      * else. */
16511     if (ret_invlist) {
16512         optimizable = FALSE;
16513     }
16514
16515     DEBUG_PARSE("clas");
16516
16517 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */      \
16518     || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0          \
16519                                    && UNICODE_DOT_DOT_VERSION == 0)
16520     allow_multi_folds = FALSE;
16521 #endif
16522
16523     listsv = newSVpvs_flags("# comment\n", SVs_TEMP);
16524     initial_listsv_len = SvCUR(listsv);
16525     SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated.  */
16526
16527     SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16528
16529     assert(RExC_parse <= RExC_end);
16530
16531     if (UCHARAT(RExC_parse) == '^') {   /* Complement the class */
16532         RExC_parse++;
16533         invert = TRUE;
16534         allow_multi_folds = FALSE;
16535         MARK_NAUGHTY(1);
16536         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16537     }
16538
16539     /* Check that they didn't say [:posix:] instead of [[:posix:]] */
16540     if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
16541         int maybe_class = handle_possible_posix(pRExC_state,
16542                                                 RExC_parse,
16543                                                 &not_posix_region_end,
16544                                                 NULL,
16545                                                 TRUE /* checking only */);
16546         if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
16547             ckWARN4reg(not_posix_region_end,
16548                     "POSIX syntax [%c %c] belongs inside character classes%s",
16549                     *RExC_parse, *RExC_parse,
16550                     (maybe_class == OOB_NAMEDCLASS)
16551                     ? ((POSIXCC_NOTYET(*RExC_parse))
16552                         ? " (but this one isn't implemented)"
16553                         : " (but this one isn't fully valid)")
16554                     : ""
16555                     );
16556         }
16557     }
16558
16559     /* If the caller wants us to just parse a single element, accomplish this
16560      * by faking the loop ending condition */
16561     if (stop_at_1 && RExC_end > RExC_parse) {
16562         stop_ptr = RExC_parse + 1;
16563     }
16564
16565     /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
16566     if (UCHARAT(RExC_parse) == ']')
16567         goto charclassloop;
16568
16569     while (1) {
16570
16571         if (   posix_warnings
16572             && av_tindex_skip_len_mg(posix_warnings) >= 0
16573             && RExC_parse > not_posix_region_end)
16574         {
16575             /* Warnings about posix class issues are considered tentative until
16576              * we are far enough along in the parse that we can no longer
16577              * change our mind, at which point we output them.  This is done
16578              * each time through the loop so that a later class won't zap them
16579              * before they have been dealt with. */
16580             output_posix_warnings(pRExC_state, posix_warnings);
16581         }
16582
16583         if  (RExC_parse >= stop_ptr) {
16584             break;
16585         }
16586
16587         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16588
16589         if  (UCHARAT(RExC_parse) == ']') {
16590             break;
16591         }
16592
16593       charclassloop:
16594
16595         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
16596         save_value = value;
16597         save_prevvalue = prevvalue;
16598
16599         if (!range) {
16600             rangebegin = RExC_parse;
16601             element_count++;
16602             non_portable_endpoint = 0;
16603         }
16604         if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
16605             value = utf8n_to_uvchr((U8*)RExC_parse,
16606                                    RExC_end - RExC_parse,
16607                                    &numlen, UTF8_ALLOW_DEFAULT);
16608             RExC_parse += numlen;
16609         }
16610         else
16611             value = UCHARAT(RExC_parse++);
16612
16613         if (value == '[') {
16614             char * posix_class_end;
16615             namedclass = handle_possible_posix(pRExC_state,
16616                                                RExC_parse,
16617                                                &posix_class_end,
16618                                                do_posix_warnings ? &posix_warnings : NULL,
16619                                                FALSE    /* die if error */);
16620             if (namedclass > OOB_NAMEDCLASS) {
16621
16622                 /* If there was an earlier attempt to parse this particular
16623                  * posix class, and it failed, it was a false alarm, as this
16624                  * successful one proves */
16625                 if (   posix_warnings
16626                     && av_tindex_skip_len_mg(posix_warnings) >= 0
16627                     && not_posix_region_end >= RExC_parse
16628                     && not_posix_region_end <= posix_class_end)
16629                 {
16630                     av_undef(posix_warnings);
16631                 }
16632
16633                 RExC_parse = posix_class_end;
16634             }
16635             else if (namedclass == OOB_NAMEDCLASS) {
16636                 not_posix_region_end = posix_class_end;
16637             }
16638             else {
16639                 namedclass = OOB_NAMEDCLASS;
16640             }
16641         }
16642         else if (   RExC_parse - 1 > not_posix_region_end
16643                  && MAYBE_POSIXCC(value))
16644         {
16645             (void) handle_possible_posix(
16646                         pRExC_state,
16647                         RExC_parse - 1,  /* -1 because parse has already been
16648                                             advanced */
16649                         &not_posix_region_end,
16650                         do_posix_warnings ? &posix_warnings : NULL,
16651                         TRUE /* checking only */);
16652         }
16653         else if (  strict && ! skip_white
16654                  && (   _generic_isCC(value, _CC_VERTSPACE)
16655                      || is_VERTWS_cp_high(value)))
16656         {
16657             vFAIL("Literal vertical space in [] is illegal except under /x");
16658         }
16659         else if (value == '\\') {
16660             /* Is a backslash; get the code point of the char after it */
16661
16662             if (RExC_parse >= RExC_end) {
16663                 vFAIL("Unmatched [");
16664             }
16665
16666             if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
16667                 value = utf8n_to_uvchr((U8*)RExC_parse,
16668                                    RExC_end - RExC_parse,
16669                                    &numlen, UTF8_ALLOW_DEFAULT);
16670                 RExC_parse += numlen;
16671             }
16672             else
16673                 value = UCHARAT(RExC_parse++);
16674
16675             /* Some compilers cannot handle switching on 64-bit integer
16676              * values, therefore value cannot be an UV.  Yes, this will
16677              * be a problem later if we want switch on Unicode.
16678              * A similar issue a little bit later when switching on
16679              * namedclass. --jhi */
16680
16681             /* If the \ is escaping white space when white space is being
16682              * skipped, it means that that white space is wanted literally, and
16683              * is already in 'value'.  Otherwise, need to translate the escape
16684              * into what it signifies. */
16685             if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
16686
16687             case 'w':   namedclass = ANYOF_WORDCHAR;    break;
16688             case 'W':   namedclass = ANYOF_NWORDCHAR;   break;
16689             case 's':   namedclass = ANYOF_SPACE;       break;
16690             case 'S':   namedclass = ANYOF_NSPACE;      break;
16691             case 'd':   namedclass = ANYOF_DIGIT;       break;
16692             case 'D':   namedclass = ANYOF_NDIGIT;      break;
16693             case 'v':   namedclass = ANYOF_VERTWS;      break;
16694             case 'V':   namedclass = ANYOF_NVERTWS;     break;
16695             case 'h':   namedclass = ANYOF_HORIZWS;     break;
16696             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
16697             case 'N':  /* Handle \N{NAME} in class */
16698                 {
16699                     const char * const backslash_N_beg = RExC_parse - 2;
16700                     int cp_count;
16701
16702                     if (! grok_bslash_N(pRExC_state,
16703                                         NULL,      /* No regnode */
16704                                         &value,    /* Yes single value */
16705                                         &cp_count, /* Multiple code pt count */
16706                                         flagp,
16707                                         strict,
16708                                         depth)
16709                     ) {
16710
16711                         if (*flagp & NEED_UTF8)
16712                             FAIL("panic: grok_bslash_N set NEED_UTF8");
16713
16714                         RETURN_FAIL_ON_RESTART_FLAGP(flagp);
16715
16716                         if (cp_count < 0) {
16717                             vFAIL("\\N in a character class must be a named character: \\N{...}");
16718                         }
16719                         else if (cp_count == 0) {
16720                             ckWARNreg(RExC_parse,
16721                               "Ignoring zero length \\N{} in character class");
16722                         }
16723                         else { /* cp_count > 1 */
16724                             if (! RExC_in_multi_char_class) {
16725                                 if (invert || range || *RExC_parse == '-') {
16726                                     if (strict) {
16727                                         RExC_parse--;
16728                                         vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character");
16729                                     }
16730                                     ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
16731                                     break; /* <value> contains the first code
16732                                               point. Drop out of the switch to
16733                                               process it */
16734                                 }
16735                                 else {
16736                                     SV * multi_char_N = newSVpvn(backslash_N_beg,
16737                                                  RExC_parse - backslash_N_beg);
16738                                     multi_char_matches
16739                                         = add_multi_match(multi_char_matches,
16740                                                           multi_char_N,
16741                                                           cp_count);
16742                                 }
16743                             }
16744                         } /* End of cp_count != 1 */
16745
16746                         /* This element should not be processed further in this
16747                          * class */
16748                         element_count--;
16749                         value = save_value;
16750                         prevvalue = save_prevvalue;
16751                         continue;   /* Back to top of loop to get next char */
16752                     }
16753
16754                     /* Here, is a single code point, and <value> contains it */
16755                     unicode_range = TRUE;   /* \N{} are Unicode */
16756                 }
16757                 break;
16758             case 'p':
16759             case 'P':
16760                 {
16761                 char *e;
16762                 char *i;
16763
16764                 /* We will handle any undefined properties ourselves */
16765                 U8 swash_init_flags = _CORE_SWASH_INIT_RETURN_IF_UNDEF
16766                                        /* And we actually would prefer to get
16767                                         * the straight inversion list of the
16768                                         * swash, since we will be accessing it
16769                                         * anyway, to save a little time */
16770                                       |_CORE_SWASH_INIT_ACCEPT_INVLIST;
16771
16772                 SvREFCNT_dec(swash); /* Free any left-overs */
16773
16774                 /* \p means they want Unicode semantics */
16775                 REQUIRE_UNI_RULES(flagp, 0);
16776
16777                 if (RExC_parse >= RExC_end)
16778                     vFAIL2("Empty \\%c", (U8)value);
16779                 if (*RExC_parse == '{') {
16780                     const U8 c = (U8)value;
16781                     e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
16782                     if (!e) {
16783                         RExC_parse++;
16784                         vFAIL2("Missing right brace on \\%c{}", c);
16785                     }
16786
16787                     RExC_parse++;
16788
16789                     /* White space is allowed adjacent to the braces and after
16790                      * any '^', even when not under /x */
16791                     while (isSPACE(*RExC_parse)) {
16792                          RExC_parse++;
16793                     }
16794
16795                     if (UCHARAT(RExC_parse) == '^') {
16796
16797                         /* toggle.  (The rhs xor gets the single bit that
16798                          * differs between P and p; the other xor inverts just
16799                          * that bit) */
16800                         value ^= 'P' ^ 'p';
16801
16802                         RExC_parse++;
16803                         while (isSPACE(*RExC_parse)) {
16804                             RExC_parse++;
16805                         }
16806                     }
16807
16808                     if (e == RExC_parse)
16809                         vFAIL2("Empty \\%c{}", c);
16810
16811                     n = e - RExC_parse;
16812                     while (isSPACE(*(RExC_parse + n - 1)))
16813                         n--;
16814
16815                 }   /* The \p isn't immediately followed by a '{' */
16816                 else if (! isALPHA(*RExC_parse)) {
16817                     RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16818                     vFAIL2("Character following \\%c must be '{' or a "
16819                            "single-character Unicode property name",
16820                            (U8) value);
16821                 }
16822                 else {
16823                     e = RExC_parse;
16824                     n = 1;
16825                 }
16826                 {
16827                     char* name = RExC_parse;
16828                     char* base_name;    /* name after any packages are stripped */
16829                     char* lookup_name = NULL;
16830                     const char * const colon_colon = "::";
16831                     bool invert;
16832
16833                     SV* invlist;
16834
16835                     /* Temporary workaround for [perl #133136].  For this
16836                     * precise input that is in the .t that is failing, load
16837                     * utf8.pm, which is what the test wants, so that that
16838                     * .t passes */
16839                     if (     memEQs(RExC_start, e + 1 - RExC_start,
16840                                     "foo\\p{Alnum}")
16841                         && ! hv_common(GvHVn(PL_incgv),
16842                                        NULL,
16843                                        "utf8.pm", sizeof("utf8.pm") - 1,
16844                                        0, HV_FETCH_ISEXISTS, NULL, 0))
16845                     {
16846                         require_pv("utf8.pm");
16847                     }
16848                     invlist = parse_uniprop_string(name, n, FOLD, &invert);
16849                     if (invlist) {
16850                         if (invert) {
16851                             value ^= 'P' ^ 'p';
16852                         }
16853                     }
16854                     else {
16855
16856                     /* Try to get the definition of the property into
16857                      * <invlist>.  If /i is in effect, the effective property
16858                      * will have its name be <__NAME_i>.  The design is
16859                      * discussed in commit
16860                      * 2f833f5208e26b208886e51e09e2c072b5eabb46 */
16861                     name = savepv(Perl_form(aTHX_ "%.*s", (int)n, RExC_parse));
16862                     SAVEFREEPV(name);
16863
16864                     for (i = RExC_parse; i < RExC_parse + n; i++) {
16865                         if (isCNTRL(*i) && *i != '\t') {
16866                             RExC_parse = e + 1;
16867                             vFAIL2("Can't find Unicode property definition \"%s\"", name);
16868                         }
16869                     }
16870
16871                     if (FOLD) {
16872                         lookup_name = savepv(Perl_form(aTHX_ "__%s_i", name));
16873
16874                         /* The function call just below that uses this can fail
16875                          * to return, leaking memory if we don't do this */
16876                         SAVEFREEPV(lookup_name);
16877                     }
16878
16879                     /* Look up the property name, and get its swash and
16880                      * inversion list, if the property is found  */
16881                     swash = _core_swash_init("utf8",
16882                                              (lookup_name)
16883                                               ? lookup_name
16884                                               : name,
16885                                              &PL_sv_undef,
16886                                              1, /* binary */
16887                                              0, /* not tr/// */
16888                                              NULL, /* No inversion list */
16889                                              &swash_init_flags
16890                                             );
16891                     if (! swash || ! (invlist = _get_swash_invlist(swash))) {
16892                         HV* curpkg = (IN_PERL_COMPILETIME)
16893                                       ? PL_curstash
16894                                       : CopSTASH(PL_curcop);
16895                         UV final_n = n;
16896                         bool has_pkg;
16897
16898                         if (swash) {    /* Got a swash but no inversion list.
16899                                            Something is likely wrong that will
16900                                            be sorted-out later */
16901                             SvREFCNT_dec_NN(swash);
16902                             swash = NULL;
16903                         }
16904
16905                         /* Here didn't find it.  It could be a an error (like a
16906                          * typo) in specifying a Unicode property, or it could
16907                          * be a user-defined property that will be available at
16908                          * run-time.  The names of these must begin with 'In'
16909                          * or 'Is' (after any packages are stripped off).  So
16910                          * if not one of those, or if we accept only
16911                          * compile-time properties, is an error; otherwise add
16912                          * it to the list for run-time look up. */
16913                         if ((base_name = rninstr(name, name + n,
16914                                                  colon_colon, colon_colon + 2)))
16915                         { /* Has ::.  We know this must be a user-defined
16916                              property */
16917                             base_name += 2;
16918                             final_n -= base_name - name;
16919                             has_pkg = TRUE;
16920                         }
16921                         else {
16922                             base_name = name;
16923                             has_pkg = FALSE;
16924                         }
16925
16926                         if (   final_n < 3
16927                             || base_name[0] != 'I'
16928                             || (base_name[1] != 's' && base_name[1] != 'n')
16929                             || ret_invlist)
16930                         {
16931                             const char * const msg
16932                                 = (has_pkg)
16933                                   ? "Illegal user-defined property name"
16934                                   : "Can't find Unicode property definition";
16935                             RExC_parse = e + 1;
16936
16937                             /* diag_listed_as: Can't find Unicode property definition "%s" */
16938                             vFAIL3utf8f("%s \"%" UTF8f "\"",
16939                                 msg, UTF8fARG(UTF, n, name));
16940                         }
16941
16942                         /* If the property name doesn't already have a package
16943                          * name, add the current one to it so that it can be
16944                          * referred to outside it. [perl #121777] */
16945                         if (! has_pkg && curpkg) {
16946                             char* pkgname = HvNAME(curpkg);
16947                             if (memNEs(pkgname, HvNAMELEN(curpkg), "main")) {
16948                                 char* full_name = Perl_form(aTHX_
16949                                                             "%s::%s",
16950                                                             pkgname,
16951                                                             name);
16952                                 n = strlen(full_name);
16953                                 name = savepvn(full_name, n);
16954                                 SAVEFREEPV(name);
16955                             }
16956                         }
16957                         Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%s%" UTF8f "%s\n",
16958                                         (value == 'p' ? '+' : '!'),
16959                                         (FOLD) ? "__" : "",
16960                                         UTF8fARG(UTF, n, name),
16961                                         (FOLD) ? "_i" : "");
16962                         has_user_defined_property = TRUE;
16963                         optimizable = FALSE;    /* Will have to leave this an
16964                                                    ANYOF node */
16965
16966                         /* We don't know yet what this matches, so have to flag
16967                          * it */
16968                         anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
16969                     }
16970                     else {
16971
16972                         /* Here, did get the swash and its inversion list.  If
16973                          * the swash is from a user-defined property, then this
16974                          * whole character class should be regarded as such */
16975                         if (swash_init_flags
16976                             & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)
16977                         {
16978                             has_user_defined_property = TRUE;
16979                         }
16980                     }
16981                     }
16982                     if (invlist) {
16983                         if (! has_user_defined_property &&
16984                             /* We warn on matching an above-Unicode code point
16985                              * if the match would return true, except don't
16986                              * warn for \p{All}, which has exactly one element
16987                              * = 0 */
16988                             (_invlist_contains_cp(invlist, 0x110000)
16989                                 && (! (_invlist_len(invlist) == 1
16990                                        && *invlist_array(invlist) == 0))))
16991                         {
16992                             warn_super = TRUE;
16993                         }
16994
16995                         /* Invert if asking for the complement */
16996                         if (value == 'P') {
16997                             _invlist_union_complement_2nd(properties,
16998                                                           invlist,
16999                                                           &properties);
17000
17001                             /* The swash can't be used as-is, because we've
17002                              * inverted things; delay removing it to here after
17003                              * have copied its invlist above */
17004                             if (! swash) {
17005                                 SvREFCNT_dec_NN(invlist);
17006                             }
17007                             SvREFCNT_dec(swash);
17008                             swash = NULL;
17009                         }
17010                         else {
17011                             _invlist_union(properties, invlist, &properties);
17012                             if (! swash) {
17013                                 SvREFCNT_dec_NN(invlist);
17014                             }
17015                         }
17016                     }
17017                 }
17018
17019                 RExC_parse = e + 1;
17020                 namedclass = ANYOF_UNIPROP;  /* no official name, but it's
17021                                                 named */
17022                 }
17023                 break;
17024             case 'n':   value = '\n';                   break;
17025             case 'r':   value = '\r';                   break;
17026             case 't':   value = '\t';                   break;
17027             case 'f':   value = '\f';                   break;
17028             case 'b':   value = '\b';                   break;
17029             case 'e':   value = ESC_NATIVE;             break;
17030             case 'a':   value = '\a';                   break;
17031             case 'o':
17032                 RExC_parse--;   /* function expects to be pointed at the 'o' */
17033                 {
17034                     const char* error_msg;
17035                     bool valid = grok_bslash_o(&RExC_parse,
17036                                                RExC_end,
17037                                                &value,
17038                                                &error_msg,
17039                                                TO_OUTPUT_WARNINGS(RExC_parse),
17040                                                strict,
17041                                                silence_non_portable,
17042                                                UTF);
17043                     if (! valid) {
17044                         vFAIL(error_msg);
17045                     }
17046                     UPDATE_WARNINGS_LOC(RExC_parse - 1);
17047                 }
17048                 non_portable_endpoint++;
17049                 break;
17050             case 'x':
17051                 RExC_parse--;   /* function expects to be pointed at the 'x' */
17052                 {
17053                     const char* error_msg;
17054                     bool valid = grok_bslash_x(&RExC_parse,
17055                                                RExC_end,
17056                                                &value,
17057                                                &error_msg,
17058                                                TO_OUTPUT_WARNINGS(RExC_parse),
17059                                                strict,
17060                                                silence_non_portable,
17061                                                UTF);
17062                     if (! valid) {
17063                         vFAIL(error_msg);
17064                     }
17065                     UPDATE_WARNINGS_LOC(RExC_parse - 1);
17066                 }
17067                 non_portable_endpoint++;
17068                 break;
17069             case 'c':
17070                 value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse));
17071                 UPDATE_WARNINGS_LOC(RExC_parse);
17072                 RExC_parse++;
17073                 non_portable_endpoint++;
17074                 break;
17075             case '0': case '1': case '2': case '3': case '4':
17076             case '5': case '6': case '7':
17077                 {
17078                     /* Take 1-3 octal digits */
17079                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
17080                     numlen = (strict) ? 4 : 3;
17081                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17082                     RExC_parse += numlen;
17083                     if (numlen != 3) {
17084                         if (strict) {
17085                             RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
17086                             vFAIL("Need exactly 3 octal digits");
17087                         }
17088                         else if (   numlen < 3 /* like \08, \178 */
17089                                  && RExC_parse < RExC_end
17090                                  && isDIGIT(*RExC_parse)
17091                                  && ckWARN(WARN_REGEXP))
17092                         {
17093                             reg_warn_non_literal_string(
17094                                  RExC_parse + 1,
17095                                  form_short_octal_warning(RExC_parse, numlen));
17096                         }
17097                     }
17098                     non_portable_endpoint++;
17099                     break;
17100                 }
17101             default:
17102                 /* Allow \_ to not give an error */
17103                 if (isWORDCHAR(value) && value != '_') {
17104                     if (strict) {
17105                         vFAIL2("Unrecognized escape \\%c in character class",
17106                                (int)value);
17107                     }
17108                     else {
17109                         ckWARN2reg(RExC_parse,
17110                             "Unrecognized escape \\%c in character class passed through",
17111                             (int)value);
17112                     }
17113                 }
17114                 break;
17115             }   /* End of switch on char following backslash */
17116         } /* end of handling backslash escape sequences */
17117
17118         /* Here, we have the current token in 'value' */
17119
17120         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
17121             U8 classnum;
17122
17123             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
17124              * literal, as is the character that began the false range, i.e.
17125              * the 'a' in the examples */
17126             if (range) {
17127                 const int w = (RExC_parse >= rangebegin)
17128                                 ? RExC_parse - rangebegin
17129                                 : 0;
17130                 if (strict) {
17131                     vFAIL2utf8f(
17132                         "False [] range \"%" UTF8f "\"",
17133                         UTF8fARG(UTF, w, rangebegin));
17134                 }
17135                 else {
17136                     ckWARN2reg(RExC_parse,
17137                         "False [] range \"%" UTF8f "\"",
17138                         UTF8fARG(UTF, w, rangebegin));
17139                     cp_list = add_cp_to_invlist(cp_list, '-');
17140                     cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
17141                                                             prevvalue);
17142                 }
17143
17144                 range = 0; /* this was not a true range */
17145                 element_count += 2; /* So counts for three values */
17146             }
17147
17148             classnum = namedclass_to_classnum(namedclass);
17149
17150             if (LOC && namedclass < ANYOF_POSIXL_MAX
17151 #ifndef HAS_ISASCII
17152                 && classnum != _CC_ASCII
17153 #endif
17154             ) {
17155                 SV* scratch_list = NULL;
17156
17157                 /* What the Posix classes (like \w, [:space:]) match in locale
17158                  * isn't knowable under locale until actual match time.  Room
17159                  * must be reserved (one time per outer bracketed class) to
17160                  * store such classes.  The space will contain a bit for each
17161                  * named class that is to be matched against.  This isn't
17162                  * needed for \p{} and pseudo-classes, as they are not affected
17163                  * by locale, and hence are dealt with separately */
17164                 if (! need_class) {
17165                     need_class = 1;
17166                     anyof_flags |= ANYOF_MATCHES_POSIXL;
17167
17168                     /* We can't change this into some other type of node
17169                      * (unless this is the only element, in which case there
17170                      * are nodes that mean exactly this) as has runtime
17171                      * dependencies */
17172                     optimizable = FALSE;
17173                 }
17174
17175                 /* Coverity thinks it is possible for this to be negative; both
17176                  * jhi and khw think it's not, but be safer */
17177                 assert(! (anyof_flags & ANYOF_MATCHES_POSIXL)
17178                        || (namedclass + ((namedclass % 2) ? -1 : 1)) >= 0);
17179
17180                 /* See if it already matches the complement of this POSIX
17181                  * class */
17182                 if (  (anyof_flags & ANYOF_MATCHES_POSIXL)
17183                     && POSIXL_TEST(posixl, namedclass + ((namedclass % 2)
17184                                                          ? -1
17185                                                          : 1)))
17186                 {
17187                     posixl_matches_all = TRUE;
17188                     break;  /* No need to continue.  Since it matches both
17189                                e.g., \w and \W, it matches everything, and the
17190                                bracketed class can be optimized into qr/./s */
17191                 }
17192
17193                 /* Add this class to those that should be checked at runtime */
17194                 POSIXL_SET(posixl, namedclass);
17195
17196                 /* The above-Latin1 characters are not subject to locale rules.
17197                  * Just add them to the unconditionally-matched list */
17198
17199                 /* Get the list of the above-Latin1 code points this matches */
17200                 _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
17201                                         PL_XPosix_ptrs[classnum],
17202
17203                                         /* Odd numbers are complements, like
17204                                         * NDIGIT, NASCII, ... */
17205                                         namedclass % 2 != 0,
17206                                         &scratch_list);
17207                 /* Checking if 'cp_list' is NULL first saves an extra clone.
17208                  * Its reference count will be decremented at the next union,
17209                  * etc, or if this is the only instance, at the end of the
17210                  * routine */
17211                 if (! cp_list) {
17212                     cp_list = scratch_list;
17213                 }
17214                 else {
17215                     _invlist_union(cp_list, scratch_list, &cp_list);
17216                     SvREFCNT_dec_NN(scratch_list);
17217                 }
17218                 continue;   /* Go get next character */
17219             }
17220             else {
17221
17222                 /* Here, is not /l, or is a POSIX class for which /l doesn't
17223                  * matter (or is a Unicode property, which is skipped here). */
17224                 if (namedclass >= ANYOF_POSIXL_MAX) {  /* If a special class */
17225                     if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
17226
17227                         /* Here, should be \h, \H, \v, or \V.  None of /d, /i
17228                          * nor /l make a difference in what these match,
17229                          * therefore we just add what they match to cp_list. */
17230                         if (classnum != _CC_VERTSPACE) {
17231                             assert(   namedclass == ANYOF_HORIZWS
17232                                    || namedclass == ANYOF_NHORIZWS);
17233
17234                             /* It turns out that \h is just a synonym for
17235                              * XPosixBlank */
17236                             classnum = _CC_BLANK;
17237                         }
17238
17239                         _invlist_union_maybe_complement_2nd(
17240                                 cp_list,
17241                                 PL_XPosix_ptrs[classnum],
17242                                 namedclass % 2 != 0,    /* Complement if odd
17243                                                           (NHORIZWS, NVERTWS)
17244                                                         */
17245                                 &cp_list);
17246                     }
17247                 }
17248                 else if (  UNI_SEMANTICS
17249                         || AT_LEAST_ASCII_RESTRICTED
17250                         || classnum == _CC_ASCII
17251                         || (DEPENDS_SEMANTICS && (   classnum == _CC_DIGIT
17252                                                   || classnum == _CC_XDIGIT)))
17253                 {
17254                     /* We usually have to worry about /d affecting what POSIX
17255                      * classes match, with special code needed because we won't
17256                      * know until runtime what all matches.  But there is no
17257                      * extra work needed under /u and /a; and [:ascii:] is
17258                      * unaffected by /d; and :digit: and :xdigit: don't have
17259                      * runtime differences under /d.  So we can special case
17260                      * these, and avoid some extra work below, and at runtime.
17261                      * */
17262                     _invlist_union_maybe_complement_2nd(
17263                                                      simple_posixes,
17264                                                       ((AT_LEAST_ASCII_RESTRICTED)
17265                                                        ? PL_Posix_ptrs[classnum]
17266                                                        : PL_XPosix_ptrs[classnum]),
17267                                                      namedclass % 2 != 0,
17268                                                      &simple_posixes);
17269                 }
17270                 else {  /* Garden variety class.  If is NUPPER, NALPHA, ...
17271                            complement and use nposixes */
17272                     SV** posixes_ptr = namedclass % 2 == 0
17273                                        ? &posixes
17274                                        : &nposixes;
17275                     _invlist_union_maybe_complement_2nd(
17276                                                      *posixes_ptr,
17277                                                      PL_XPosix_ptrs[classnum],
17278                                                      namedclass % 2 != 0,
17279                                                      posixes_ptr);
17280                 }
17281             }
17282         } /* end of namedclass \blah */
17283
17284         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17285
17286         /* If 'range' is set, 'value' is the ending of a range--check its
17287          * validity.  (If value isn't a single code point in the case of a
17288          * range, we should have figured that out above in the code that
17289          * catches false ranges).  Later, we will handle each individual code
17290          * point in the range.  If 'range' isn't set, this could be the
17291          * beginning of a range, so check for that by looking ahead to see if
17292          * the next real character to be processed is the range indicator--the
17293          * minus sign */
17294
17295         if (range) {
17296 #ifdef EBCDIC
17297             /* For unicode ranges, we have to test that the Unicode as opposed
17298              * to the native values are not decreasing.  (Above 255, there is
17299              * no difference between native and Unicode) */
17300             if (unicode_range && prevvalue < 255 && value < 255) {
17301                 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
17302                     goto backwards_range;
17303                 }
17304             }
17305             else
17306 #endif
17307             if (prevvalue > value) /* b-a */ {
17308                 int w;
17309 #ifdef EBCDIC
17310               backwards_range:
17311 #endif
17312                 w = RExC_parse - rangebegin;
17313                 vFAIL2utf8f(
17314                     "Invalid [] range \"%" UTF8f "\"",
17315                     UTF8fARG(UTF, w, rangebegin));
17316                 NOT_REACHED; /* NOTREACHED */
17317             }
17318         }
17319         else {
17320             prevvalue = value; /* save the beginning of the potential range */
17321             if (! stop_at_1     /* Can't be a range if parsing just one thing */
17322                 && *RExC_parse == '-')
17323             {
17324                 char* next_char_ptr = RExC_parse + 1;
17325
17326                 /* Get the next real char after the '-' */
17327                 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
17328
17329                 /* If the '-' is at the end of the class (just before the ']',
17330                  * it is a literal minus; otherwise it is a range */
17331                 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
17332                     RExC_parse = next_char_ptr;
17333
17334                     /* a bad range like \w-, [:word:]- ? */
17335                     if (namedclass > OOB_NAMEDCLASS) {
17336                         if (strict || ckWARN(WARN_REGEXP)) {
17337                             const int w = RExC_parse >= rangebegin
17338                                           ?  RExC_parse - rangebegin
17339                                           : 0;
17340                             if (strict) {
17341                                 vFAIL4("False [] range \"%*.*s\"",
17342                                     w, w, rangebegin);
17343                             }
17344                             else {
17345                                 vWARN4(RExC_parse,
17346                                     "False [] range \"%*.*s\"",
17347                                     w, w, rangebegin);
17348                             }
17349                         }
17350                         cp_list = add_cp_to_invlist(cp_list, '-');
17351                         element_count++;
17352                     } else
17353                         range = 1;      /* yeah, it's a range! */
17354                     continue;   /* but do it the next time */
17355                 }
17356             }
17357         }
17358
17359         if (namedclass > OOB_NAMEDCLASS) {
17360             continue;
17361         }
17362
17363         /* Here, we have a single value this time through the loop, and
17364          * <prevvalue> is the beginning of the range, if any; or <value> if
17365          * not. */
17366
17367         /* non-Latin1 code point implies unicode semantics. */
17368         if (value > 255) {
17369             REQUIRE_UNI_RULES(flagp, 0);
17370         }
17371
17372         /* Ready to process either the single value, or the completed range.
17373          * For single-valued non-inverted ranges, we consider the possibility
17374          * of multi-char folds.  (We made a conscious decision to not do this
17375          * for the other cases because it can often lead to non-intuitive
17376          * results.  For example, you have the peculiar case that:
17377          *  "s s" =~ /^[^\xDF]+$/i => Y
17378          *  "ss"  =~ /^[^\xDF]+$/i => N
17379          *
17380          * See [perl #89750] */
17381         if (FOLD && allow_multi_folds && value == prevvalue) {
17382             if (value == LATIN_SMALL_LETTER_SHARP_S
17383                 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
17384                                                         value)))
17385             {
17386                 /* Here <value> is indeed a multi-char fold.  Get what it is */
17387
17388                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17389                 STRLEN foldlen;
17390
17391                 UV folded = _to_uni_fold_flags(
17392                                 value,
17393                                 foldbuf,
17394                                 &foldlen,
17395                                 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
17396                                                    ? FOLD_FLAGS_NOMIX_ASCII
17397                                                    : 0)
17398                                 );
17399
17400                 /* Here, <folded> should be the first character of the
17401                  * multi-char fold of <value>, with <foldbuf> containing the
17402                  * whole thing.  But, if this fold is not allowed (because of
17403                  * the flags), <fold> will be the same as <value>, and should
17404                  * be processed like any other character, so skip the special
17405                  * handling */
17406                 if (folded != value) {
17407
17408                     /* Skip if we are recursed, currently parsing the class
17409                      * again.  Otherwise add this character to the list of
17410                      * multi-char folds. */
17411                     if (! RExC_in_multi_char_class) {
17412                         STRLEN cp_count = utf8_length(foldbuf,
17413                                                       foldbuf + foldlen);
17414                         SV* multi_fold = sv_2mortal(newSVpvs(""));
17415
17416                         Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
17417
17418                         multi_char_matches
17419                                         = add_multi_match(multi_char_matches,
17420                                                           multi_fold,
17421                                                           cp_count);
17422
17423                     }
17424
17425                     /* This element should not be processed further in this
17426                      * class */
17427                     element_count--;
17428                     value = save_value;
17429                     prevvalue = save_prevvalue;
17430                     continue;
17431                 }
17432             }
17433         }
17434
17435         if (strict && ckWARN(WARN_REGEXP)) {
17436             if (range) {
17437
17438                 /* If the range starts above 255, everything is portable and
17439                  * likely to be so for any forseeable character set, so don't
17440                  * warn. */
17441                 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
17442                     vWARN(RExC_parse, "Both or neither range ends should be Unicode");
17443                 }
17444                 else if (prevvalue != value) {
17445
17446                     /* Under strict, ranges that stop and/or end in an ASCII
17447                      * printable should have each end point be a portable value
17448                      * for it (preferably like 'A', but we don't warn if it is
17449                      * a (portable) Unicode name or code point), and the range
17450                      * must be be all digits or all letters of the same case.
17451                      * Otherwise, the range is non-portable and unclear as to
17452                      * what it contains */
17453                     if (             (isPRINT_A(prevvalue) || isPRINT_A(value))
17454                         && (          non_portable_endpoint
17455                             || ! (   (isDIGIT_A(prevvalue) && isDIGIT_A(value))
17456                                   || (isLOWER_A(prevvalue) && isLOWER_A(value))
17457                                   || (isUPPER_A(prevvalue) && isUPPER_A(value))
17458                     ))) {
17459                         vWARN(RExC_parse, "Ranges of ASCII printables should"
17460                                           " be some subset of \"0-9\","
17461                                           " \"A-Z\", or \"a-z\"");
17462                     }
17463                     else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
17464                         SSize_t index_start;
17465                         SSize_t index_final;
17466
17467                         /* But the nature of Unicode and languages mean we
17468                          * can't do the same checks for above-ASCII ranges,
17469                          * except in the case of digit ones.  These should
17470                          * contain only digits from the same group of 10.  The
17471                          * ASCII case is handled just above.  Hence here, the
17472                          * range could be a range of digits.  First some
17473                          * unlikely special cases.  Grandfather in that a range
17474                          * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
17475                          * if its starting value is one of the 10 digits prior
17476                          * to it.  This is because it is an alternate way of
17477                          * writing 19D1, and some people may expect it to be in
17478                          * that group.  But it is bad, because it won't give
17479                          * the expected results.  In Unicode 5.2 it was
17480                          * considered to be in that group (of 11, hence), but
17481                          * this was fixed in the next version */
17482
17483                         if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
17484                             goto warn_bad_digit_range;
17485                         }
17486                         else if (UNLIKELY(   prevvalue >= 0x1D7CE
17487                                           &&     value <= 0x1D7FF))
17488                         {
17489                             /* This is the only other case currently in Unicode
17490                              * where the algorithm below fails.  The code
17491                              * points just above are the end points of a single
17492                              * range containing only decimal digits.  It is 5
17493                              * different series of 0-9.  All other ranges of
17494                              * digits currently in Unicode are just a single
17495                              * series.  (And mktables will notify us if a later
17496                              * Unicode version breaks this.)
17497                              *
17498                              * If the range being checked is at most 9 long,
17499                              * and the digit values represented are in
17500                              * numerical order, they are from the same series.
17501                              * */
17502                             if (         value - prevvalue > 9
17503                                 ||    (((    value - 0x1D7CE) % 10)
17504                                      <= (prevvalue - 0x1D7CE) % 10))
17505                             {
17506                                 goto warn_bad_digit_range;
17507                             }
17508                         }
17509                         else {
17510
17511                             /* For all other ranges of digits in Unicode, the
17512                              * algorithm is just to check if both end points
17513                              * are in the same series, which is the same range.
17514                              * */
17515                             index_start = _invlist_search(
17516                                                     PL_XPosix_ptrs[_CC_DIGIT],
17517                                                     prevvalue);
17518
17519                             /* Warn if the range starts and ends with a digit,
17520                              * and they are not in the same group of 10. */
17521                             if (   index_start >= 0
17522                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
17523                                 && (index_final =
17524                                     _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
17525                                                     value)) != index_start
17526                                 && index_final >= 0
17527                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
17528                             {
17529                               warn_bad_digit_range:
17530                                 vWARN(RExC_parse, "Ranges of digits should be"
17531                                                   " from the same group of"
17532                                                   " 10");
17533                             }
17534                         }
17535                     }
17536                 }
17537             }
17538             if ((! range || prevvalue == value) && non_portable_endpoint) {
17539                 if (isPRINT_A(value)) {
17540                     char literal[3];
17541                     unsigned d = 0;
17542                     if (isBACKSLASHED_PUNCT(value)) {
17543                         literal[d++] = '\\';
17544                     }
17545                     literal[d++] = (char) value;
17546                     literal[d++] = '\0';
17547
17548                     vWARN4(RExC_parse,
17549                            "\"%.*s\" is more clearly written simply as \"%s\"",
17550                            (int) (RExC_parse - rangebegin),
17551                            rangebegin,
17552                            literal
17553                         );
17554                 }
17555                 else if isMNEMONIC_CNTRL(value) {
17556                     vWARN4(RExC_parse,
17557                            "\"%.*s\" is more clearly written simply as \"%s\"",
17558                            (int) (RExC_parse - rangebegin),
17559                            rangebegin,
17560                            cntrl_to_mnemonic((U8) value)
17561                         );
17562                 }
17563             }
17564         }
17565
17566         /* Deal with this element of the class */
17567
17568 #ifndef EBCDIC
17569         cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17570                                                     prevvalue, value);
17571 #else
17572         /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
17573          * that don't require special handling, we can just add the range like
17574          * we do for ASCII platforms */
17575         if ((UNLIKELY(prevvalue == 0) && value >= 255)
17576             || ! (prevvalue < 256
17577                     && (unicode_range
17578                         || (! non_portable_endpoint
17579                             && ((isLOWER_A(prevvalue) && isLOWER_A(value))
17580                                 || (isUPPER_A(prevvalue)
17581                                     && isUPPER_A(value)))))))
17582         {
17583             cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17584                                                         prevvalue, value);
17585         }
17586         else {
17587             /* Here, requires special handling.  This can be because it is a
17588              * range whose code points are considered to be Unicode, and so
17589              * must be individually translated into native, or because its a
17590              * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
17591              * EBCDIC, but we have defined them to include only the "expected"
17592              * upper or lower case ASCII alphabetics.  Subranges above 255 are
17593              * the same in native and Unicode, so can be added as a range */
17594             U8 start = NATIVE_TO_LATIN1(prevvalue);
17595             unsigned j;
17596             U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
17597             for (j = start; j <= end; j++) {
17598                 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
17599             }
17600             if (value > 255) {
17601                 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17602                                                             256, value);
17603             }
17604         }
17605 #endif
17606
17607         range = 0; /* this range (if it was one) is done now */
17608     } /* End of loop through all the text within the brackets */
17609
17610     if (   posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
17611         output_posix_warnings(pRExC_state, posix_warnings);
17612     }
17613
17614     /* If anything in the class expands to more than one character, we have to
17615      * deal with them by building up a substitute parse string, and recursively
17616      * calling reg() on it, instead of proceeding */
17617     if (multi_char_matches) {
17618         SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
17619         I32 cp_count;
17620         STRLEN len;
17621         char *save_end = RExC_end;
17622         char *save_parse = RExC_parse;
17623         char *save_start = RExC_start;
17624         Size_t constructed_prefix_len = 0; /* This gives the length of the
17625                                               constructed portion of the
17626                                               substitute parse. */
17627         bool first_time = TRUE;     /* First multi-char occurrence doesn't get
17628                                        a "|" */
17629         I32 reg_flags;
17630
17631         assert(! invert);
17632         /* Only one level of recursion allowed */
17633         assert(RExC_copy_start_in_constructed == RExC_precomp);
17634
17635 #if 0   /* Have decided not to deal with multi-char folds in inverted classes,
17636            because too confusing */
17637         if (invert) {
17638             sv_catpvs(substitute_parse, "(?:");
17639         }
17640 #endif
17641
17642         /* Look at the longest folds first */
17643         for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
17644                         cp_count > 0;
17645                         cp_count--)
17646         {
17647
17648             if (av_exists(multi_char_matches, cp_count)) {
17649                 AV** this_array_ptr;
17650                 SV* this_sequence;
17651
17652                 this_array_ptr = (AV**) av_fetch(multi_char_matches,
17653                                                  cp_count, FALSE);
17654                 while ((this_sequence = av_pop(*this_array_ptr)) !=
17655                                                                 &PL_sv_undef)
17656                 {
17657                     if (! first_time) {
17658                         sv_catpvs(substitute_parse, "|");
17659                     }
17660                     first_time = FALSE;
17661
17662                     sv_catpv(substitute_parse, SvPVX(this_sequence));
17663                 }
17664             }
17665         }
17666
17667         /* If the character class contains anything else besides these
17668          * multi-character folds, have to include it in recursive parsing */
17669         if (element_count) {
17670             sv_catpvs(substitute_parse, "|[");
17671             constructed_prefix_len = SvCUR(substitute_parse);
17672             sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
17673
17674             /* Put in a closing ']' only if not going off the end, as otherwise
17675              * we are adding something that really isn't there */
17676             if (RExC_parse < RExC_end) {
17677                 sv_catpvs(substitute_parse, "]");
17678             }
17679         }
17680
17681         sv_catpvs(substitute_parse, ")");
17682 #if 0
17683         if (invert) {
17684             /* This is a way to get the parse to skip forward a whole named
17685              * sequence instead of matching the 2nd character when it fails the
17686              * first */
17687             sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
17688         }
17689 #endif
17690
17691         /* Set up the data structure so that any errors will be properly
17692          * reported.  See the comments at the definition of
17693          * REPORT_LOCATION_ARGS for details */
17694         RExC_copy_start_in_input = (char *) orig_parse;
17695         RExC_start = RExC_parse = SvPV(substitute_parse, len);
17696         RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
17697         RExC_end = RExC_parse + len;
17698         RExC_in_multi_char_class = 1;
17699
17700         ret = reg(pRExC_state, 1, &reg_flags, depth+1);
17701
17702         *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
17703
17704         /* And restore so can parse the rest of the pattern */
17705         RExC_parse = save_parse;
17706         RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
17707         RExC_end = save_end;
17708         RExC_in_multi_char_class = 0;
17709         SvREFCNT_dec_NN(multi_char_matches);
17710         return ret;
17711     }
17712
17713     /* If folding, we calculate all characters that could fold to or from the
17714      * ones already on the list */
17715     if (cp_foldable_list) {
17716         if (FOLD) {
17717             UV start, end;      /* End points of code point ranges */
17718
17719             SV* fold_intersection = NULL;
17720             SV** use_list;
17721
17722             /* Our calculated list will be for Unicode rules.  For locale
17723              * matching, we have to keep a separate list that is consulted at
17724              * runtime only when the locale indicates Unicode rules.  For
17725              * non-locale, we just use the general list */
17726             if (LOC) {
17727                 use_list = &only_utf8_locale_list;
17728             }
17729             else {
17730                 use_list = &cp_list;
17731             }
17732
17733             /* Only the characters in this class that participate in folds need
17734              * be checked.  Get the intersection of this class and all the
17735              * possible characters that are foldable.  This can quickly narrow
17736              * down a large class */
17737             _invlist_intersection(PL_utf8_foldable, cp_foldable_list,
17738                                   &fold_intersection);
17739
17740             /* Now look at the foldable characters in this class individually */
17741             invlist_iterinit(fold_intersection);
17742             while (invlist_iternext(fold_intersection, &start, &end)) {
17743                 UV j;
17744                 UV folded;
17745
17746                 /* Look at every character in the range */
17747                 for (j = start; j <= end; j++) {
17748                     U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17749                     STRLEN foldlen;
17750                     unsigned int k;
17751                     Size_t folds_to_count;
17752                     unsigned int first_folds_to;
17753                     const unsigned int * remaining_folds_to_list;
17754
17755                     if (j < 256) {
17756
17757                         if (IS_IN_SOME_FOLD_L1(j)) {
17758
17759                             /* ASCII is always matched; non-ASCII is matched
17760                              * only under Unicode rules (which could happen
17761                              * under /l if the locale is a UTF-8 one */
17762                             if (isASCII(j) || ! DEPENDS_SEMANTICS) {
17763                                 *use_list = add_cp_to_invlist(*use_list,
17764                                                             PL_fold_latin1[j]);
17765                             }
17766                             else {
17767                                 has_upper_latin1_only_utf8_matches
17768                                     = add_cp_to_invlist(
17769                                             has_upper_latin1_only_utf8_matches,
17770                                             PL_fold_latin1[j]);
17771                             }
17772                         }
17773
17774                         if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
17775                             && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
17776                         {
17777                             add_above_Latin1_folds(pRExC_state,
17778                                                    (U8) j,
17779                                                    use_list);
17780                         }
17781                         continue;
17782                     }
17783
17784                     /* Here is an above Latin1 character.  We don't have the
17785                      * rules hard-coded for it.  First, get its fold.  This is
17786                      * the simple fold, as the multi-character folds have been
17787                      * handled earlier and separated out */
17788                     folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
17789                                                         (ASCII_FOLD_RESTRICTED)
17790                                                         ? FOLD_FLAGS_NOMIX_ASCII
17791                                                         : 0);
17792
17793                     /* Single character fold of above Latin1.  Add everything
17794                      * in its fold closure to the list that this node should
17795                      * match. */
17796                     folds_to_count = _inverse_folds(folded, &first_folds_to,
17797                                                     &remaining_folds_to_list);
17798                     for (k = 0; k <= folds_to_count; k++) {
17799                         UV c = (k == 0)     /* First time through use itself */
17800                                 ? folded
17801                                 : (k == 1)  /* 2nd time use, the first fold */
17802                                    ? first_folds_to
17803
17804                                      /* Then the remaining ones */
17805                                    : remaining_folds_to_list[k-2];
17806
17807                         /* /aa doesn't allow folds between ASCII and non- */
17808                         if ((   ASCII_FOLD_RESTRICTED
17809                             && (isASCII(c) != isASCII(j))))
17810                         {
17811                             continue;
17812                         }
17813
17814                         /* Folds under /l which cross the 255/256 boundary are
17815                          * added to a separate list.  (These are valid only
17816                          * when the locale is UTF-8.) */
17817                         if (c < 256 && LOC) {
17818                             *use_list = add_cp_to_invlist(*use_list, c);
17819                             continue;
17820                         }
17821
17822                         if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
17823                         {
17824                             cp_list = add_cp_to_invlist(cp_list, c);
17825                         }
17826                         else {
17827                             /* Similarly folds involving non-ascii Latin1
17828                              * characters under /d are added to their list */
17829                             has_upper_latin1_only_utf8_matches
17830                                 = add_cp_to_invlist(
17831                                             has_upper_latin1_only_utf8_matches,
17832                                             c);
17833                         }
17834                     }
17835                 }
17836             }
17837             SvREFCNT_dec_NN(fold_intersection);
17838         }
17839
17840         /* Now that we have finished adding all the folds, there is no reason
17841          * to keep the foldable list separate */
17842         _invlist_union(cp_list, cp_foldable_list, &cp_list);
17843         SvREFCNT_dec_NN(cp_foldable_list);
17844     }
17845
17846     /* And combine the result (if any) with any inversion lists from posix
17847      * classes.  The lists are kept separate up to now because we don't want to
17848      * fold the classes (folding of those is automatically handled by the swash
17849      * fetching code) */
17850     if (simple_posixes) {   /* These are the classes known to be unaffected by
17851                                /a, /aa, and /d */
17852         if (cp_list) {
17853             _invlist_union(cp_list, simple_posixes, &cp_list);
17854             SvREFCNT_dec_NN(simple_posixes);
17855         }
17856         else {
17857             cp_list = simple_posixes;
17858         }
17859     }
17860     if (posixes || nposixes) {
17861         if (! DEPENDS_SEMANTICS) {
17862
17863             /* For everything but /d, we can just add the current 'posixes' and
17864              * 'nposixes' to the main list */
17865             if (posixes) {
17866                 if (cp_list) {
17867                     _invlist_union(cp_list, posixes, &cp_list);
17868                     SvREFCNT_dec_NN(posixes);
17869                 }
17870                 else {
17871                     cp_list = posixes;
17872                 }
17873             }
17874             if (nposixes) {
17875                 if (cp_list) {
17876                     _invlist_union(cp_list, nposixes, &cp_list);
17877                     SvREFCNT_dec_NN(nposixes);
17878                 }
17879                 else {
17880                     cp_list = nposixes;
17881                 }
17882             }
17883         }
17884         else {
17885             /* Under /d, things like \w match upper Latin1 characters only if
17886              * the target string is in UTF-8.  But things like \W match all the
17887              * upper Latin1 characters if the target string is not in UTF-8.
17888              *
17889              * Handle the case where there something like \W separately */
17890             if (nposixes) {
17891                 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
17892
17893                 /* A complemented posix class matches all upper Latin1
17894                  * characters if not in UTF-8.  And it matches just certain
17895                  * ones when in UTF-8.  That means those certain ones are
17896                  * matched regardless, so can just be added to the
17897                  * unconditional list */
17898                 if (cp_list) {
17899                     _invlist_union(cp_list, nposixes, &cp_list);
17900                     SvREFCNT_dec_NN(nposixes);
17901                     nposixes = NULL;
17902                 }
17903                 else {
17904                     cp_list = nposixes;
17905                 }
17906
17907                 /* Likewise for 'posixes' */
17908                 _invlist_union(posixes, cp_list, &cp_list);
17909
17910                 /* Likewise for anything else in the range that matched only
17911                  * under UTF-8 */
17912                 if (has_upper_latin1_only_utf8_matches) {
17913                     _invlist_union(cp_list,
17914                                    has_upper_latin1_only_utf8_matches,
17915                                    &cp_list);
17916                     SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17917                     has_upper_latin1_only_utf8_matches = NULL;
17918                 }
17919
17920                 /* If we don't match all the upper Latin1 characters regardless
17921                  * of UTF-8ness, we have to set a flag to match the rest when
17922                  * not in UTF-8 */
17923                 _invlist_subtract(only_non_utf8_list, cp_list,
17924                                   &only_non_utf8_list);
17925                 if (_invlist_len(only_non_utf8_list) != 0) {
17926                     anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
17927                 }
17928                 SvREFCNT_dec_NN(only_non_utf8_list);
17929             }
17930             else {
17931                 /* Here there were no complemented posix classes.  That means
17932                  * the upper Latin1 characters in 'posixes' match only when the
17933                  * target string is in UTF-8.  So we have to add them to the
17934                  * list of those types of code points, while adding the
17935                  * remainder to the unconditional list.
17936                  *
17937                  * First calculate what they are */
17938                 SV* nonascii_but_latin1_properties = NULL;
17939                 _invlist_intersection(posixes, PL_UpperLatin1,
17940                                       &nonascii_but_latin1_properties);
17941
17942                 /* And add them to the final list of such characters. */
17943                 _invlist_union(has_upper_latin1_only_utf8_matches,
17944                                nonascii_but_latin1_properties,
17945                                &has_upper_latin1_only_utf8_matches);
17946
17947                 /* Remove them from what now becomes the unconditional list */
17948                 _invlist_subtract(posixes, nonascii_but_latin1_properties,
17949                                   &posixes);
17950
17951                 /* And add those unconditional ones to the final list */
17952                 if (cp_list) {
17953                     _invlist_union(cp_list, posixes, &cp_list);
17954                     SvREFCNT_dec_NN(posixes);
17955                     posixes = NULL;
17956                 }
17957                 else {
17958                     cp_list = posixes;
17959                 }
17960
17961                 SvREFCNT_dec(nonascii_but_latin1_properties);
17962
17963                 /* Get rid of any characters that we now know are matched
17964                  * unconditionally from the conditional list, which may make
17965                  * that list empty */
17966                 _invlist_subtract(has_upper_latin1_only_utf8_matches,
17967                                   cp_list,
17968                                   &has_upper_latin1_only_utf8_matches);
17969                 if (_invlist_len(has_upper_latin1_only_utf8_matches) == 0) {
17970                     SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17971                     has_upper_latin1_only_utf8_matches = NULL;
17972                 }
17973             }
17974         }
17975     }
17976
17977     /* And combine the result (if any) with any inversion list from properties.
17978      * The lists are kept separate up to now so that we can distinguish the two
17979      * in regards to matching above-Unicode.  A run-time warning is generated
17980      * if a Unicode property is matched against a non-Unicode code point. But,
17981      * we allow user-defined properties to match anything, without any warning,
17982      * and we also suppress the warning if there is a portion of the character
17983      * class that isn't a Unicode property, and which matches above Unicode, \W
17984      * or [\x{110000}] for example.
17985      * (Note that in this case, unlike the Posix one above, there is no
17986      * <has_upper_latin1_only_utf8_matches>, because having a Unicode property
17987      * forces Unicode semantics */
17988     if (properties) {
17989         if (cp_list) {
17990
17991             /* If it matters to the final outcome, see if a non-property
17992              * component of the class matches above Unicode.  If so, the
17993              * warning gets suppressed.  This is true even if just a single
17994              * such code point is specified, as, though not strictly correct if
17995              * another such code point is matched against, the fact that they
17996              * are using above-Unicode code points indicates they should know
17997              * the issues involved */
17998             if (warn_super) {
17999                 warn_super = ! (invert
18000                                ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
18001             }
18002
18003             _invlist_union(properties, cp_list, &cp_list);
18004             SvREFCNT_dec_NN(properties);
18005         }
18006         else {
18007             cp_list = properties;
18008         }
18009
18010         if (warn_super) {
18011             anyof_flags
18012              |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18013
18014             /* Because an ANYOF node is the only one that warns, this node
18015              * can't be optimized into something else */
18016             optimizable = FALSE;
18017         }
18018     }
18019
18020     /* Here, we have calculated what code points should be in the character
18021      * class.
18022      *
18023      * Now we can see about various optimizations.  Fold calculation (which we
18024      * did above) needs to take place before inversion.  Otherwise /[^k]/i
18025      * would invert to include K, which under /i would match k, which it
18026      * shouldn't.  Therefore we can't invert folded locale now, as it won't be
18027      * folded until runtime */
18028
18029     /* If we didn't do folding, it's because some information isn't available
18030      * until runtime; set the run-time fold flag for these.  (We don't have to
18031      * worry about properties folding, as that is taken care of by the swash
18032      * fetching).  We know to set the flag if we have a non-NULL list for UTF-8
18033      * locales, or the class matches at least one 0-255 range code point */
18034     if (LOC && FOLD) {
18035
18036         /* Some things on the list might be unconditionally included because of
18037          * other components.  Remove them, and clean up the list if it goes to
18038          * 0 elements */
18039         if (only_utf8_locale_list && cp_list) {
18040             _invlist_subtract(only_utf8_locale_list, cp_list,
18041                               &only_utf8_locale_list);
18042
18043             if (_invlist_len(only_utf8_locale_list) == 0) {
18044                 SvREFCNT_dec_NN(only_utf8_locale_list);
18045                 only_utf8_locale_list = NULL;
18046             }
18047         }
18048         if (only_utf8_locale_list) {
18049             anyof_flags
18050                  |= ANYOFL_FOLD
18051                  |  ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18052         }
18053         else if (cp_list) { /* Look to see if a 0-255 code point is in list */
18054             UV start, end;
18055             invlist_iterinit(cp_list);
18056             if (invlist_iternext(cp_list, &start, &end) && start < 256) {
18057                 anyof_flags |= ANYOFL_FOLD;
18058             }
18059             invlist_iterfinish(cp_list);
18060         }
18061     }
18062     else if (   DEPENDS_SEMANTICS
18063              && (    has_upper_latin1_only_utf8_matches
18064                  || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18065     {
18066         use_anyofd = TRUE;
18067         RExC_seen_d_op = TRUE;
18068         optimizable = FALSE;
18069     }
18070
18071     /* Optimize inverted simple patterns (e.g. [^a-z]) when everything is known
18072      * at compile time.  Besides not inverting folded locale now, we can't
18073      * invert if there are things such as \w, which aren't known until runtime
18074      * */
18075     if (     cp_list
18076         &&   invert
18077         && ! use_anyofd
18078         && ! (anyof_flags & (ANYOF_LOCALE_FLAGS))
18079         && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
18080     {
18081         _invlist_invert(cp_list);
18082
18083         /* Any swash can't be used as-is, because we've inverted things */
18084         if (swash) {
18085             SvREFCNT_dec_NN(swash);
18086             swash = NULL;
18087         }
18088
18089         /* Clear the invert flag since have just done it here */
18090         invert = FALSE;
18091     }
18092
18093     if (ret_invlist) {
18094         *ret_invlist = cp_list;
18095         SvREFCNT_dec(swash);
18096
18097         return RExC_emit;
18098     }
18099
18100     /* Some character classes are equivalent to other nodes.  Such nodes take
18101      * up less room and generally fewer operations to execute than ANYOF nodes.
18102      * */
18103
18104     if (optimizable) {
18105         int posix_class = -1;   /* Illegal value */
18106         const char * cur_parse= RExC_parse;
18107         U8 ANYOFM_mask = 0xFF;
18108         U32 anode_arg = 0;
18109         UV start, end;
18110
18111         if (UNLIKELY(posixl_matches_all)) {
18112             op = SANY;
18113         }
18114         else if (cp_list && ! invert) {
18115
18116             invlist_iterinit(cp_list);
18117             if (! invlist_iternext(cp_list, &start, &end)) {
18118
18119                 /* Here, the list is empty.  This happens, for example, when a
18120                  * Unicode property that doesn't match anything is the only
18121                  * element in the character class (perluniprops.pod notes such
18122                  * properties).  */
18123                 op = OPFAIL;
18124                 *flagp |= HASWIDTH|SIMPLE;
18125             }
18126             else if (start == end) {    /* The range is a single code point */
18127                 if (! invlist_iternext(cp_list, &start, &end)
18128
18129                         /* Don't do this optimization if it would require
18130                          * changing the pattern to UTF-8 */
18131                     && (start < 256 || UTF))
18132                 {
18133                     /* Here, the list contains a single code point.  Can
18134                      * optimize into an EXACTish node */
18135
18136                     value = start;
18137
18138                     if (! FOLD) {
18139                         op = (LOC)
18140                              ? EXACTL
18141                              : EXACT;
18142                     }
18143                     else if (LOC) {
18144
18145                         /* A locale node under folding with one code point can
18146                          * be an EXACTFL, as its fold won't be calculated until
18147                          * runtime */
18148                         op = EXACTFL;
18149                     }
18150                     else {
18151
18152                         /* Here, we are generally folding, but there is only
18153                          * one code point to match.  If we have to, we use an
18154                          * EXACT node, but it would be better for joining with
18155                          * adjacent nodes in the optimization phase if we used
18156                          * the same EXACTFish node that any such are likely to
18157                          * be.  We can do this iff the code point doesn't
18158                          * participate in any folds.  For example, an EXACTF of
18159                          * a colon is the same as an EXACT one, since nothing
18160                          * folds to or from a colon. */
18161                         if (value < 256) {
18162                             if (IS_IN_SOME_FOLD_L1(value)) {
18163                                 op = EXACT;
18164                             }
18165                         }
18166                         else {
18167                             if (_invlist_contains_cp(PL_utf8_foldable, value)) {
18168                                 op = EXACT;
18169                             }
18170                         }
18171
18172                         /* If we haven't found the node type, above, it means
18173                          * we can use the prevailing one */
18174                         if (op == END) {
18175                             op = compute_EXACTish(pRExC_state);
18176                         }
18177                     }
18178                 }
18179             }   /* End of first range contains just a single code point */
18180             else if (start == 0) {
18181                 if (end == UV_MAX) {
18182                     op = SANY;
18183                     *flagp |= HASWIDTH|SIMPLE;
18184                     MARK_NAUGHTY(1);
18185                 }
18186                 else if (end == '\n' - 1
18187                         && invlist_iternext(cp_list, &start, &end)
18188                         && start == '\n' + 1 && end == UV_MAX)
18189                 {
18190                     op = REG_ANY;
18191                     *flagp |= HASWIDTH|SIMPLE;
18192                     MARK_NAUGHTY(1);
18193                 }
18194             }
18195             invlist_iterfinish(cp_list);
18196
18197             if (op == END) {
18198
18199                 /* Here, didn't find an optimization.  See if this matches any
18200                  * of the POSIX classes.  First try ASCII */
18201
18202                 if (_invlistEQ(cp_list, PL_XPosix_ptrs[_CC_ASCII], 0)) {
18203                     op = ASCII;
18204                     *flagp |= HASWIDTH|SIMPLE;
18205                 }
18206                 else if (_invlistEQ(cp_list, PL_XPosix_ptrs[_CC_ASCII], 1)) {
18207                     op = NASCII;
18208                     *flagp |= HASWIDTH|SIMPLE;
18209                 }
18210                 else {
18211
18212                     /* Then try the other POSIX classes.  The POSIXA ones are
18213                      * about the same speed as ANYOF ops, but take less room;
18214                      * the ones that have above-Latin1 code point matches are
18215                      * somewhat faster than ANYOF. */
18216
18217                     for (posix_class = 0;
18218                          posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
18219                          posix_class++)
18220                     {
18221                         int try_inverted;
18222
18223                         for (try_inverted = 0; try_inverted < 2; try_inverted++)
18224                         {
18225
18226                             /* Check if matches POSIXA, normal or inverted */
18227                             if (PL_Posix_ptrs[posix_class]) {
18228                                 if (_invlistEQ(cp_list,
18229                                                PL_Posix_ptrs[posix_class],
18230                                                try_inverted))
18231                                 {
18232                                     op = (try_inverted)
18233                                         ? NPOSIXA
18234                                         : POSIXA;
18235                                     *flagp |= HASWIDTH|SIMPLE;
18236                                     goto found_posix;
18237                                 }
18238                             }
18239
18240                             /* Check if matches POSIXU, normal or inverted */
18241                             if (_invlistEQ(cp_list,
18242                                            PL_XPosix_ptrs[posix_class],
18243                                            try_inverted))
18244                             {
18245                                 op = (try_inverted)
18246                                      ? NPOSIXU
18247                                      : POSIXU;
18248                                 *flagp |= HASWIDTH|SIMPLE;
18249                                 goto found_posix;
18250                             }
18251                         }
18252                     }
18253                   found_posix: ;
18254                 }
18255
18256                 /* If it didn't match a POSIX class, it might be able to be
18257                  * turned into an ANYOFM node.  Compare two different bytes,
18258                  * bit-by-bit.  In some positions, the bits in each will be 1;
18259                  * and in other positions both will be 0; and in some positions
18260                  * the bit will be 1 in one byte, and 0 in the other.  Let 'n'
18261                  * be the number of positions where the bits differ.  We create
18262                  * a mask which has exactly 'n' 0 bits, each in a position
18263                  * where the two bytes differ.  Now take the set of all bytes
18264                  * that when ANDed with the mask yield the same result.  That
18265                  * set has 2**n elements, and is representable by just two 8
18266                  * bit numbers: the result and the mask.  Importantly, matching
18267                  * the set can be vectorized by creating a word full of the
18268                  * result bytes, and a word full of the mask bytes, yielding a
18269                  * significant speed up.  Here, see if this node matches such a
18270                  * set.  As a concrete example consider [01], and the byte
18271                  * representing '0' which is 0x30 on ASCII machines.  It has
18272                  * the bits 0011 0000.  Take the mask 1111 1110.  If we AND
18273                  * 0x31 and 0x30 with that mask we get 0x30.  Any other bytes
18274                  * ANDed yield something else.  So [01], which is a common
18275                  * usage, is optimizable into ANYOFM, and can benefit from the
18276                  * speed up.  We can only do this on UTF-8 invariant bytes,
18277                  * because the variance would throw this off.  */
18278                 if (op == END) {
18279                     PERL_UINT_FAST8_T inverted = 0;
18280 #ifdef EBCDIC
18281                     const PERL_UINT_FAST8_T max_permissible = 0xFF;
18282 #else
18283                     const PERL_UINT_FAST8_T max_permissible = 0x7F;
18284 #endif
18285                     if (invlist_highest(cp_list) > max_permissible) {
18286                         _invlist_invert(cp_list);
18287                         inverted = 1;
18288                     }
18289
18290                     if (invlist_highest(cp_list) <= max_permissible) {
18291                     Size_t cp_count = 0;
18292                     bool first_time = TRUE;
18293                     unsigned int lowest_cp = 0xFF;
18294                     U8 bits_differing = 0;
18295
18296                     /* Only needed on EBCDIC, as there, variants and non- are mixed
18297                      * together.  Could #ifdef it out on ASCII, but probably the
18298                      * compiler will optimize it out */
18299                     bool has_variant = FALSE;
18300
18301                     /* Go through the bytes and find the bit positions that differ */
18302                     invlist_iterinit(cp_list);
18303                     while (invlist_iternext(cp_list, &start, &end)) {
18304                         unsigned int i = start;
18305
18306                         cp_count += end - start + 1;
18307
18308                         if (first_time) {
18309                             if (! UVCHR_IS_INVARIANT(i)) {
18310                                 has_variant = TRUE;
18311                                 continue;
18312                             }
18313
18314                             first_time = FALSE;
18315                             lowest_cp = start;
18316
18317                             i++;
18318                         }
18319
18320                         /* Find the bit positions that differ from the lowest
18321                          * code point in the node.  Keep track of all such
18322                          * positions by OR'ing */
18323                         for (; i <= end; i++) {
18324                             if (! UVCHR_IS_INVARIANT(i)) {
18325                                 has_variant = TRUE;
18326                                 continue;
18327                             }
18328
18329                             bits_differing  |= i ^ lowest_cp;
18330                         }
18331                     }
18332                     invlist_iterfinish(cp_list);
18333
18334                     /* At the end of the loop, we count how many bits differ
18335                      * from the bits in lowest code point, call the count 'd'.
18336                      * If the set we found contains 2**d elements, it is the
18337                      * closure of all code points that differ only in those bit
18338                      * positions.  To convince yourself of that, first note
18339                      * that the number in the closure must be a power of 2,
18340                      * which we test for.  The only way we could have that
18341                      * count and it be some differing set, is if we got some
18342                      * code points that don't differ from the lowest code point
18343                      * in any position, but do differ from each other in some
18344                      * other position.  That means one code point has a 1 in
18345                      * that position, and another has a 0.  But that would mean
18346                      * that one of them differs from the lowest code point in
18347                      * that position, which possibility we've already excluded.
18348                      * */
18349                     if ( ! has_variant
18350                         && cp_count == 1U << PL_bitcount[bits_differing])
18351                     {
18352                         assert(inverted || cp_count > 1);
18353                         op = ANYOFM + inverted;;
18354
18355                         /* We need to make the bits that differ be 0's */
18356                         ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS
18357                                                          */
18358
18359                         /* The argument is the lowest code point */
18360                         anode_arg = lowest_cp;
18361                         *flagp |= HASWIDTH|SIMPLE;
18362                     }
18363                 }
18364                 if (inverted) {
18365                     _invlist_invert(cp_list);
18366                 }
18367             }
18368             }
18369         }
18370
18371         if (op != END) {
18372             RExC_parse = (char *)orig_parse;
18373             RExC_emit = orig_emit;
18374
18375             if (regarglen[op]) {
18376                 ret = reganode(pRExC_state, op, anode_arg);
18377             } else {
18378                 ret = reg_node(pRExC_state, op);
18379             }
18380
18381             RExC_parse = (char *)cur_parse;
18382
18383             if (PL_regkind[op] == EXACT) {
18384                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value,
18385                                            TRUE /* downgradable to EXACT */
18386                                           );
18387             }
18388             else if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
18389                 FLAGS(REGNODE_p(ret)) = posix_class;
18390             }
18391             else if (PL_regkind[op] == ANYOFM) {
18392                 FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
18393             }
18394
18395             SvREFCNT_dec_NN(cp_list);
18396             return ret;
18397         }
18398     }   /* End of seeing if can optimize it into a different node */
18399
18400     /* It's going to be an ANYOF node. */
18401     op = (use_anyofd)
18402          ? ANYOFD
18403          : ((posixl)
18404             ? ANYOFPOSIXL
18405             : ((LOC)
18406                ? ANYOFL
18407                : ANYOF));
18408     ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
18409     FILL_NODE(ret, op);        /* We set the argument later */
18410     RExC_emit += 1 + regarglen[op];
18411     ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
18412
18413     /* Here, <cp_list> contains all the code points we can determine at
18414      * compile time that match under all conditions.  Go through it, and
18415      * for things that belong in the bitmap, put them there, and delete from
18416      * <cp_list>.  While we are at it, see if everything above 255 is in the
18417      * list, and if so, set a flag to speed up execution */
18418
18419     populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
18420
18421     if (posixl) {
18422         ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
18423     }
18424
18425     if (invert) {
18426         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
18427     }
18428
18429     /* Here, the bitmap has been populated with all the Latin1 code points that
18430      * always match.  Can now add to the overall list those that match only
18431      * when the target string is UTF-8 (<has_upper_latin1_only_utf8_matches>).
18432      * */
18433     if (has_upper_latin1_only_utf8_matches) {
18434         if (cp_list) {
18435             _invlist_union(cp_list,
18436                            has_upper_latin1_only_utf8_matches,
18437                            &cp_list);
18438             SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
18439         }
18440         else {
18441             cp_list = has_upper_latin1_only_utf8_matches;
18442         }
18443         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
18444     }
18445
18446     /* If there is a swash and more than one element, we can't use the swash in
18447      * the optimization below. */
18448     if (swash && element_count > 1) {
18449         SvREFCNT_dec_NN(swash);
18450         swash = NULL;
18451     }
18452
18453     /* Note that the optimization of using 'swash' if it is the only thing in
18454      * the class doesn't have us change swash at all, so it can include things
18455      * that are also in the bitmap; otherwise we have purposely deleted that
18456      * duplicate information */
18457     set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
18458                   (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
18459                    ? listsv : NULL,
18460                   only_utf8_locale_list,
18461                   swash, has_user_defined_property);
18462
18463     *flagp |= HASWIDTH|SIMPLE;
18464
18465     if (ANYOF_FLAGS(REGNODE_p(ret)) & ANYOF_LOCALE_FLAGS) {
18466         RExC_contains_locale = 1;
18467     }
18468
18469     return ret;
18470 }
18471
18472 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
18473
18474 STATIC void
18475 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
18476                 regnode* const node,
18477                 SV* const cp_list,
18478                 SV* const runtime_defns,
18479                 SV* const only_utf8_locale_list,
18480                 SV* const swash,
18481                 const bool has_user_defined_property)
18482 {
18483     /* Sets the arg field of an ANYOF-type node 'node', using information about
18484      * the node passed-in.  If there is nothing outside the node's bitmap, the
18485      * arg is set to ANYOF_ONLY_HAS_BITMAP.  Otherwise, it sets the argument to
18486      * the count returned by add_data(), having allocated and stored an array,
18487      * av, that that count references, as follows:
18488      *  av[0] stores the character class description in its textual form.
18489      *        This is used later (regexec.c:Perl_regclass_swash()) to
18490      *        initialize the appropriate swash, and is also useful for dumping
18491      *        the regnode.  This is set to &PL_sv_undef if the textual
18492      *        description is not needed at run-time (as happens if the other
18493      *        elements completely define the class)
18494      *  av[1] if &PL_sv_undef, is a placeholder to later contain the swash
18495      *        computed from av[0].  But if no further computation need be done,
18496      *        the swash is stored here now (and av[0] is &PL_sv_undef).
18497      *  av[2] stores the inversion list of code points that match only if the
18498      *        current locale is UTF-8
18499      *  av[3] stores the cp_list inversion list for use in addition or instead
18500      *        of av[0]; used only if cp_list exists and av[1] is &PL_sv_undef.
18501      *        (Otherwise everything needed is already in av[0] and av[1])
18502      *  av[4] is set if any component of the class is from a user-defined
18503      *        property; used only if av[3] exists */
18504
18505     UV n;
18506
18507     PERL_ARGS_ASSERT_SET_ANYOF_ARG;
18508
18509     if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
18510         assert(! (ANYOF_FLAGS(node)
18511                 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
18512         ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
18513     }
18514     else {
18515         AV * const av = newAV();
18516         SV *rv;
18517
18518         av_store(av, 0, (runtime_defns)
18519                         ? SvREFCNT_inc(runtime_defns) : &PL_sv_undef);
18520         if (swash) {
18521             assert(cp_list);
18522             av_store(av, 1, swash);
18523             SvREFCNT_dec_NN(cp_list);
18524         }
18525         else {
18526             av_store(av, 1, &PL_sv_undef);
18527             if (cp_list) {
18528                 av_store(av, 3, cp_list);
18529                 av_store(av, 4, newSVuv(has_user_defined_property));
18530             }
18531         }
18532
18533         if (only_utf8_locale_list) {
18534             av_store(av, 2, only_utf8_locale_list);
18535         }
18536         else {
18537             av_store(av, 2, &PL_sv_undef);
18538         }
18539
18540         rv = newRV_noinc(MUTABLE_SV(av));
18541         n = add_data(pRExC_state, STR_WITH_LEN("s"));
18542         RExC_rxi->data->data[n] = (void*)rv;
18543         ARG_SET(node, n);
18544     }
18545 }
18546
18547 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
18548 SV *
18549 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
18550                                         const regnode* node,
18551                                         bool doinit,
18552                                         SV** listsvp,
18553                                         SV** only_utf8_locale_ptr,
18554                                         SV** output_invlist)
18555
18556 {
18557     /* For internal core use only.
18558      * Returns the swash for the input 'node' in the regex 'prog'.
18559      * If <doinit> is 'true', will attempt to create the swash if not already
18560      *    done.
18561      * If <listsvp> is non-null, will return the printable contents of the
18562      *    swash.  This can be used to get debugging information even before the
18563      *    swash exists, by calling this function with 'doinit' set to false, in
18564      *    which case the components that will be used to eventually create the
18565      *    swash are returned  (in a printable form).
18566      * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
18567      *    store an inversion list of code points that should match only if the
18568      *    execution-time locale is a UTF-8 one.
18569      * If <output_invlist> is not NULL, it is where this routine is to store an
18570      *    inversion list of the code points that would be instead returned in
18571      *    <listsvp> if this were NULL.  Thus, what gets output in <listsvp>
18572      *    when this parameter is used, is just the non-code point data that
18573      *    will go into creating the swash.  This currently should be just
18574      *    user-defined properties whose definitions were not known at compile
18575      *    time.  Using this parameter allows for easier manipulation of the
18576      *    swash's data by the caller.  It is illegal to call this function with
18577      *    this parameter set, but not <listsvp>
18578      *
18579      * Tied intimately to how S_set_ANYOF_arg sets up the data structure.  Note
18580      * that, in spite of this function's name, the swash it returns may include
18581      * the bitmap data as well */
18582
18583     SV *sw  = NULL;
18584     SV *si  = NULL;         /* Input swash initialization string */
18585     SV* invlist = NULL;
18586
18587     RXi_GET_DECL(prog, progi);
18588     const struct reg_data * const data = prog ? progi->data : NULL;
18589
18590     PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
18591     assert(! output_invlist || listsvp);
18592
18593     if (data && data->count) {
18594         const U32 n = ARG(node);
18595
18596         if (data->what[n] == 's') {
18597             SV * const rv = MUTABLE_SV(data->data[n]);
18598             AV * const av = MUTABLE_AV(SvRV(rv));
18599             SV **const ary = AvARRAY(av);
18600             U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
18601
18602             si = *ary;  /* ary[0] = the string to initialize the swash with */
18603
18604             if (av_tindex_skip_len_mg(av) >= 2) {
18605                 if (only_utf8_locale_ptr
18606                     && ary[2]
18607                     && ary[2] != &PL_sv_undef)
18608                 {
18609                     *only_utf8_locale_ptr = ary[2];
18610                 }
18611                 else {
18612                     assert(only_utf8_locale_ptr);
18613                     *only_utf8_locale_ptr = NULL;
18614                 }
18615
18616                 /* Elements 3 and 4 are either both present or both absent. [3]
18617                  * is any inversion list generated at compile time; [4]
18618                  * indicates if that inversion list has any user-defined
18619                  * properties in it. */
18620                 if (av_tindex_skip_len_mg(av) >= 3) {
18621                     invlist = ary[3];
18622                     if (SvUV(ary[4])) {
18623                         swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
18624                     }
18625                 }
18626                 else {
18627                     invlist = NULL;
18628                 }
18629             }
18630
18631             /* Element [1] is reserved for the set-up swash.  If already there,
18632              * return it; if not, create it and store it there */
18633             if (ary[1] && SvROK(ary[1])) {
18634                 sw = ary[1];
18635             }
18636             else if (doinit && ((si && si != &PL_sv_undef)
18637                                  || (invlist && invlist != &PL_sv_undef))) {
18638                 assert(si);
18639                 sw = _core_swash_init("utf8", /* the utf8 package */
18640                                       "", /* nameless */
18641                                       si,
18642                                       1, /* binary */
18643                                       0, /* not from tr/// */
18644                                       invlist,
18645                                       &swash_init_flags);
18646                 (void)av_store(av, 1, sw);
18647             }
18648         }
18649     }
18650
18651     /* If requested, return a printable version of what this swash matches */
18652     if (listsvp) {
18653         SV* matches_string = NULL;
18654
18655         /* The swash should be used, if possible, to get the data, as it
18656          * contains the resolved data.  But this function can be called at
18657          * compile-time, before everything gets resolved, in which case we
18658          * return the currently best available information, which is the string
18659          * that will eventually be used to do that resolving, 'si' */
18660         if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
18661             && (si && si != &PL_sv_undef))
18662         {
18663             /* Here, we only have 'si' (and possibly some passed-in data in
18664              * 'invlist', which is handled below)  If the caller only wants
18665              * 'si', use that.  */
18666             if (! output_invlist) {
18667                 matches_string = newSVsv(si);
18668             }
18669             else {
18670                 /* But if the caller wants an inversion list of the node, we
18671                  * need to parse 'si' and place as much as possible in the
18672                  * desired output inversion list, making 'matches_string' only
18673                  * contain the currently unresolvable things */
18674                 const char *si_string = SvPVX(si);
18675                 STRLEN remaining = SvCUR(si);
18676                 UV prev_cp = 0;
18677                 U8 count = 0;
18678
18679                 /* Ignore everything before the first new-line */
18680                 while (*si_string != '\n' && remaining > 0) {
18681                     si_string++;
18682                     remaining--;
18683                 }
18684                 assert(remaining > 0);
18685
18686                 si_string++;
18687                 remaining--;
18688
18689                 while (remaining > 0) {
18690
18691                     /* The data consists of just strings defining user-defined
18692                      * property names, but in prior incarnations, and perhaps
18693                      * somehow from pluggable regex engines, it could still
18694                      * hold hex code point definitions.  Each component of a
18695                      * range would be separated by a tab, and each range by a
18696                      * new-line.  If these are found, instead add them to the
18697                      * inversion list */
18698                     I32 grok_flags =  PERL_SCAN_SILENT_ILLDIGIT
18699                                      |PERL_SCAN_SILENT_NON_PORTABLE;
18700                     STRLEN len = remaining;
18701                     UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
18702
18703                     /* If the hex decode routine found something, it should go
18704                      * up to the next \n */
18705                     if (   *(si_string + len) == '\n') {
18706                         if (count) {    /* 2nd code point on line */
18707                             *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
18708                         }
18709                         else {
18710                             *output_invlist = add_cp_to_invlist(*output_invlist, cp);
18711                         }
18712                         count = 0;
18713                         goto prepare_for_next_iteration;
18714                     }
18715
18716                     /* If the hex decode was instead for the lower range limit,
18717                      * save it, and go parse the upper range limit */
18718                     if (*(si_string + len) == '\t') {
18719                         assert(count == 0);
18720
18721                         prev_cp = cp;
18722                         count = 1;
18723                       prepare_for_next_iteration:
18724                         si_string += len + 1;
18725                         remaining -= len + 1;
18726                         continue;
18727                     }
18728
18729                     /* Here, didn't find a legal hex number.  Just add it from
18730                      * here to the next \n */
18731
18732                     remaining -= len;
18733                     while (*(si_string + len) != '\n' && remaining > 0) {
18734                         remaining--;
18735                         len++;
18736                     }
18737                     if (*(si_string + len) == '\n') {
18738                         len++;
18739                         remaining--;
18740                     }
18741                     if (matches_string) {
18742                         sv_catpvn(matches_string, si_string, len - 1);
18743                     }
18744                     else {
18745                         matches_string = newSVpvn(si_string, len - 1);
18746                     }
18747                     si_string += len;
18748                     sv_catpvs(matches_string, " ");
18749                 } /* end of loop through the text */
18750
18751                 assert(matches_string);
18752                 if (SvCUR(matches_string)) {  /* Get rid of trailing blank */
18753                     SvCUR_set(matches_string, SvCUR(matches_string) - 1);
18754                 }
18755             } /* end of has an 'si' but no swash */
18756         }
18757
18758         /* If we have a swash in place, its equivalent inversion list was above
18759          * placed into 'invlist'.  If not, this variable may contain a stored
18760          * inversion list which is information beyond what is in 'si' */
18761         if (invlist) {
18762
18763             /* Again, if the caller doesn't want the output inversion list, put
18764              * everything in 'matches-string' */
18765             if (! output_invlist) {
18766                 if ( ! matches_string) {
18767                     matches_string = newSVpvs("\n");
18768                 }
18769                 sv_catsv(matches_string, invlist_contents(invlist,
18770                                                   TRUE /* traditional style */
18771                                                   ));
18772             }
18773             else if (! *output_invlist) {
18774                 *output_invlist = invlist_clone(invlist, NULL);
18775             }
18776             else {
18777                 _invlist_union(*output_invlist, invlist, output_invlist);
18778             }
18779         }
18780
18781         *listsvp = matches_string;
18782     }
18783
18784     return sw;
18785 }
18786 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
18787
18788 /* reg_skipcomment()
18789
18790    Absorbs an /x style # comment from the input stream,
18791    returning a pointer to the first character beyond the comment, or if the
18792    comment terminates the pattern without anything following it, this returns
18793    one past the final character of the pattern (in other words, RExC_end) and
18794    sets the REG_RUN_ON_COMMENT_SEEN flag.
18795
18796    Note it's the callers responsibility to ensure that we are
18797    actually in /x mode
18798
18799 */
18800
18801 PERL_STATIC_INLINE char*
18802 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
18803 {
18804     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
18805
18806     assert(*p == '#');
18807
18808     while (p < RExC_end) {
18809         if (*(++p) == '\n') {
18810             return p+1;
18811         }
18812     }
18813
18814     /* we ran off the end of the pattern without ending the comment, so we have
18815      * to add an \n when wrapping */
18816     RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
18817     return p;
18818 }
18819
18820 STATIC void
18821 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
18822                                 char ** p,
18823                                 const bool force_to_xmod
18824                          )
18825 {
18826     /* If the text at the current parse position '*p' is a '(?#...)' comment,
18827      * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
18828      * is /x whitespace, advance '*p' so that on exit it points to the first
18829      * byte past all such white space and comments */
18830
18831     const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
18832
18833     PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
18834
18835     assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
18836
18837     for (;;) {
18838         if (RExC_end - (*p) >= 3
18839             && *(*p)     == '('
18840             && *(*p + 1) == '?'
18841             && *(*p + 2) == '#')
18842         {
18843             while (*(*p) != ')') {
18844                 if ((*p) == RExC_end)
18845                     FAIL("Sequence (?#... not terminated");
18846                 (*p)++;
18847             }
18848             (*p)++;
18849             continue;
18850         }
18851
18852         if (use_xmod) {
18853             const char * save_p = *p;
18854             while ((*p) < RExC_end) {
18855                 STRLEN len;
18856                 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
18857                     (*p) += len;
18858                 }
18859                 else if (*(*p) == '#') {
18860                     (*p) = reg_skipcomment(pRExC_state, (*p));
18861                 }
18862                 else {
18863                     break;
18864                 }
18865             }
18866             if (*p != save_p) {
18867                 continue;
18868             }
18869         }
18870
18871         break;
18872     }
18873
18874     return;
18875 }
18876
18877 /* nextchar()
18878
18879    Advances the parse position by one byte, unless that byte is the beginning
18880    of a '(?#...)' style comment, or is /x whitespace and /x is in effect.  In
18881    those two cases, the parse position is advanced beyond all such comments and
18882    white space.
18883
18884    This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
18885 */
18886
18887 STATIC void
18888 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
18889 {
18890     PERL_ARGS_ASSERT_NEXTCHAR;
18891
18892     if (RExC_parse < RExC_end) {
18893         assert(   ! UTF
18894                || UTF8_IS_INVARIANT(*RExC_parse)
18895                || UTF8_IS_START(*RExC_parse));
18896
18897         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
18898
18899         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
18900                                 FALSE /* Don't force /x */ );
18901     }
18902 }
18903
18904 STATIC void
18905 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
18906 {
18907     PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
18908
18909     RExC_size += size;
18910
18911     Renewc(RExC_rxi,
18912            sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
18913                                                 /* +1 for REG_MAGIC */
18914            char,
18915            regexp_internal);
18916     if ( RExC_rxi == NULL )
18917         FAIL("Regexp out of space");
18918     RXi_SET(RExC_rx, RExC_rxi);
18919
18920     RExC_emit_start = RExC_rxi->program;
18921     if (size > 0) {
18922         Zero(REGNODE_p(RExC_emit), size, regnode);
18923     }
18924
18925 #ifdef RE_TRACK_PATTERN_OFFSETS
18926     Renew(RExC_offsets, 2*RExC_size+1, U32);
18927     if (size > 0) {
18928         Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
18929     }
18930     RExC_offsets[0] = RExC_size;
18931 #endif
18932 }
18933
18934 STATIC regnode_offset
18935 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
18936 {
18937     /* Allocate a regnode for 'op', with 'extra_size' extra space.  It aligns
18938      * and increments RExC_size and RExC_emit
18939      *
18940      * It returns the regnode's offset into the regex engine program */
18941
18942     const regnode_offset ret = RExC_emit;
18943
18944     GET_RE_DEBUG_FLAGS_DECL;
18945
18946     PERL_ARGS_ASSERT_REGNODE_GUTS;
18947
18948     SIZE_ALIGN(RExC_size);
18949     change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
18950     NODE_ALIGN_FILL(REGNODE_p(ret));
18951 #ifndef RE_TRACK_PATTERN_OFFSETS
18952     PERL_UNUSED_ARG(name);
18953     PERL_UNUSED_ARG(op);
18954 #else
18955     assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
18956
18957     if (RExC_offsets) {         /* MJD */
18958         MJD_OFFSET_DEBUG(
18959               ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
18960               name, __LINE__,
18961               PL_reg_name[op],
18962               (UV)(RExC_emit) > RExC_offsets[0]
18963                 ? "Overwriting end of array!\n" : "OK",
18964               (UV)(RExC_emit),
18965               (UV)(RExC_parse - RExC_start),
18966               (UV)RExC_offsets[0]));
18967         Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
18968     }
18969 #endif
18970     return(ret);
18971 }
18972
18973 /*
18974 - reg_node - emit a node
18975 */
18976 STATIC regnode_offset /* Location. */
18977 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
18978 {
18979     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
18980     regnode_offset ptr = ret;
18981
18982     PERL_ARGS_ASSERT_REG_NODE;
18983
18984     assert(regarglen[op] == 0);
18985
18986     FILL_ADVANCE_NODE(ptr, op);
18987     RExC_emit = ptr;
18988     return(ret);
18989 }
18990
18991 /*
18992 - reganode - emit a node with an argument
18993 */
18994 STATIC regnode_offset /* Location. */
18995 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
18996 {
18997     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
18998     regnode_offset ptr = ret;
18999
19000     PERL_ARGS_ASSERT_REGANODE;
19001
19002     /* ANYOF are special cased to allow non-length 1 args */
19003     assert(regarglen[op] == 1);
19004
19005     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
19006     RExC_emit = ptr;
19007     return(ret);
19008 }
19009
19010 STATIC regnode_offset
19011 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
19012 {
19013     /* emit a node with U32 and I32 arguments */
19014
19015     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
19016     regnode_offset ptr = ret;
19017
19018     PERL_ARGS_ASSERT_REG2LANODE;
19019
19020     assert(regarglen[op] == 2);
19021
19022     FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
19023     RExC_emit = ptr;
19024     return(ret);
19025 }
19026
19027 /*
19028 - reginsert - insert an operator in front of already-emitted operand
19029 *
19030 * That means that on exit 'operand' is the offset of the newly inserted
19031 * operator, and the original operand has been relocated.
19032 *
19033 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
19034 * set up NEXT_OFF() of the inserted node if needed. Something like this:
19035 *
19036 *   reginsert(pRExC, OPFAIL, orig_emit, depth+1);
19037 *   NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
19038 *
19039 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
19040 */
19041 STATIC void
19042 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
19043                   const regnode_offset operand, const U32 depth)
19044 {
19045     regnode *src;
19046     regnode *dst;
19047     regnode *place;
19048     const int offset = regarglen[(U8)op];
19049     const int size = NODE_STEP_REGNODE + offset;
19050     GET_RE_DEBUG_FLAGS_DECL;
19051
19052     PERL_ARGS_ASSERT_REGINSERT;
19053     PERL_UNUSED_CONTEXT;
19054     PERL_UNUSED_ARG(depth);
19055 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
19056     DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
19057     assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
19058                                     studying. If this is wrong then we need to adjust RExC_recurse
19059                                     below like we do with RExC_open_parens/RExC_close_parens. */
19060     change_engine_size(pRExC_state, (Ptrdiff_t) size);
19061     src = REGNODE_p(RExC_emit);
19062     RExC_emit += size;
19063     dst = REGNODE_p(RExC_emit);
19064     if (RExC_open_parens) {
19065         int paren;
19066         /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
19067         /* remember that RExC_npar is rex->nparens + 1,
19068          * iow it is 1 more than the number of parens seen in
19069          * the pattern so far. */
19070         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
19071             /* note, RExC_open_parens[0] is the start of the
19072              * regex, it can't move. RExC_close_parens[0] is the end
19073              * of the regex, it *can* move. */
19074             if ( paren && RExC_open_parens[paren] >= operand ) {
19075                 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
19076                 RExC_open_parens[paren] += size;
19077             } else {
19078                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
19079             }
19080             if ( RExC_close_parens[paren] >= operand ) {
19081                 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
19082                 RExC_close_parens[paren] += size;
19083             } else {
19084                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
19085             }
19086         }
19087     }
19088     if (RExC_end_op)
19089         RExC_end_op += size;
19090
19091     while (src > REGNODE_p(operand)) {
19092         StructCopy(--src, --dst, regnode);
19093 #ifdef RE_TRACK_PATTERN_OFFSETS
19094         if (RExC_offsets) {     /* MJD 20010112 */
19095             MJD_OFFSET_DEBUG(
19096                  ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
19097                   "reginsert",
19098                   __LINE__,
19099                   PL_reg_name[op],
19100                   (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
19101                     ? "Overwriting end of array!\n" : "OK",
19102                   (UV)REGNODE_OFFSET(src),
19103                   (UV)REGNODE_OFFSET(dst),
19104                   (UV)RExC_offsets[0]));
19105             Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
19106             Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
19107         }
19108 #endif
19109     }
19110
19111     place = REGNODE_p(operand); /* Op node, where operand used to be. */
19112 #ifdef RE_TRACK_PATTERN_OFFSETS
19113     if (RExC_offsets) {         /* MJD */
19114         MJD_OFFSET_DEBUG(
19115               ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
19116               "reginsert",
19117               __LINE__,
19118               PL_reg_name[op],
19119               (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
19120               ? "Overwriting end of array!\n" : "OK",
19121               (UV)REGNODE_OFFSET(place),
19122               (UV)(RExC_parse - RExC_start),
19123               (UV)RExC_offsets[0]));
19124         Set_Node_Offset(place, RExC_parse);
19125         Set_Node_Length(place, 1);
19126     }
19127 #endif
19128     src = NEXTOPER(place);
19129     FLAGS(place) = 0;
19130     FILL_NODE(operand, op);
19131
19132     /* Zero out any arguments in the new node */
19133     Zero(src, offset, regnode);
19134 }
19135
19136 /*
19137 - regtail - set the next-pointer at the end of a node chain of p to val.
19138 - SEE ALSO: regtail_study
19139 */
19140 STATIC void
19141 S_regtail(pTHX_ RExC_state_t * pRExC_state,
19142                 const regnode_offset p,
19143                 const regnode_offset val,
19144                 const U32 depth)
19145 {
19146     regnode_offset scan;
19147     GET_RE_DEBUG_FLAGS_DECL;
19148
19149     PERL_ARGS_ASSERT_REGTAIL;
19150 #ifndef DEBUGGING
19151     PERL_UNUSED_ARG(depth);
19152 #endif
19153
19154     /* Find last node. */
19155     scan = (regnode_offset) p;
19156     for (;;) {
19157         regnode * const temp = regnext(REGNODE_p(scan));
19158         DEBUG_PARSE_r({
19159             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
19160             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
19161             Perl_re_printf( aTHX_  "~ %s (%d) %s %s\n",
19162                 SvPV_nolen_const(RExC_mysv), REG_NODE_NUM(REGNODE_p(scan)),
19163                     (temp == NULL ? "->" : ""),
19164                     (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
19165             );
19166         });
19167         if (temp == NULL)
19168             break;
19169         scan = REGNODE_OFFSET(temp);
19170     }
19171
19172     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
19173         ARG_SET(REGNODE_p(scan), val - scan);
19174     }
19175     else {
19176         NEXT_OFF(REGNODE_p(scan)) = val - scan;
19177     }
19178 }
19179
19180 #ifdef DEBUGGING
19181 /*
19182 - regtail_study - set the next-pointer at the end of a node chain of p to val.
19183 - Look for optimizable sequences at the same time.
19184 - currently only looks for EXACT chains.
19185
19186 This is experimental code. The idea is to use this routine to perform
19187 in place optimizations on branches and groups as they are constructed,
19188 with the long term intention of removing optimization from study_chunk so
19189 that it is purely analytical.
19190
19191 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
19192 to control which is which.
19193
19194 */
19195 /* TODO: All four parms should be const */
19196
19197 STATIC U8
19198 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
19199                       const regnode_offset val, U32 depth)
19200 {
19201     regnode_offset scan;
19202     U8 exact = PSEUDO;
19203 #ifdef EXPERIMENTAL_INPLACESCAN
19204     I32 min = 0;
19205 #endif
19206     GET_RE_DEBUG_FLAGS_DECL;
19207
19208     PERL_ARGS_ASSERT_REGTAIL_STUDY;
19209
19210
19211     /* Find last node. */
19212
19213     scan = p;
19214     for (;;) {
19215         regnode * const temp = regnext(REGNODE_p(scan));
19216 #ifdef EXPERIMENTAL_INPLACESCAN
19217         if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
19218             bool unfolded_multi_char;   /* Unexamined in this routine */
19219             if (join_exact(pRExC_state, scan, &min,
19220                            &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
19221                 return EXACT;
19222         }
19223 #endif
19224         if ( exact ) {
19225             switch (OP(REGNODE_p(scan))) {
19226                 case EXACT:
19227                 case EXACTL:
19228                 case EXACTF:
19229                 case EXACTFAA_NO_TRIE:
19230                 case EXACTFAA:
19231                 case EXACTFU:
19232                 case EXACTFLU8:
19233                 case EXACTFU_SS:
19234                 case EXACTFL:
19235                         if( exact == PSEUDO )
19236                             exact= OP(REGNODE_p(scan));
19237                         else if ( exact != OP(REGNODE_p(scan)) )
19238                             exact= 0;
19239                 case NOTHING:
19240                     break;
19241                 default:
19242                     exact= 0;
19243             }
19244         }
19245         DEBUG_PARSE_r({
19246             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
19247             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
19248             Perl_re_printf( aTHX_  "~ %s (%d) -> %s\n",
19249                 SvPV_nolen_const(RExC_mysv),
19250                 REG_NODE_NUM(REGNODE_p(scan)),
19251                 PL_reg_name[exact]);
19252         });
19253         if (temp == NULL)
19254             break;
19255         scan = REGNODE_OFFSET(temp);
19256     }
19257     DEBUG_PARSE_r({
19258         DEBUG_PARSE_MSG("");
19259         regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
19260         Perl_re_printf( aTHX_
19261                       "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
19262                       SvPV_nolen_const(RExC_mysv),
19263                       (IV)REG_NODE_NUM(REGNODE_p(val)),
19264                       (IV)(val - scan)
19265         );
19266     });
19267     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
19268         ARG_SET(REGNODE_p(scan), val - scan);
19269     }
19270     else {
19271         NEXT_OFF(REGNODE_p(scan)) = val - scan;
19272     }
19273
19274     return exact;
19275 }
19276 #endif
19277
19278 STATIC SV*
19279 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
19280
19281     /* Returns an inversion list of all the code points matched by the
19282      * ANYOFM/NANYOFM node 'n' */
19283
19284     SV * cp_list = _new_invlist(-1);
19285     const U8 lowest = (U8) ARG(n);
19286     unsigned int i;
19287     U8 count = 0;
19288     U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
19289
19290     PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
19291
19292     /* Starting with the lowest code point, any code point that ANDed with the
19293      * mask yields the lowest code point is in the set */
19294     for (i = lowest; i <= 0xFF; i++) {
19295         if ((i & FLAGS(n)) == ARG(n)) {
19296             cp_list = add_cp_to_invlist(cp_list, i);
19297             count++;
19298
19299             /* We know how many code points (a power of two) that are in the
19300              * set.  No use looking once we've got that number */
19301             if (count >= needed) break;
19302         }
19303     }
19304
19305     if (OP(n) == NANYOFM) {
19306         _invlist_invert(cp_list);
19307     }
19308     return cp_list;
19309 }
19310
19311 /*
19312  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
19313  */
19314 #ifdef DEBUGGING
19315
19316 static void
19317 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
19318 {
19319     int bit;
19320     int set=0;
19321
19322     ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
19323
19324     for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
19325         if (flags & (1<<bit)) {
19326             if (!set++ && lead)
19327                 Perl_re_printf( aTHX_  "%s", lead);
19328             Perl_re_printf( aTHX_  "%s ", PL_reg_intflags_name[bit]);
19329         }
19330     }
19331     if (lead)  {
19332         if (set)
19333             Perl_re_printf( aTHX_  "\n");
19334         else
19335             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
19336     }
19337 }
19338
19339 static void
19340 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
19341 {
19342     int bit;
19343     int set=0;
19344     regex_charset cs;
19345
19346     ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
19347
19348     for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
19349         if (flags & (1<<bit)) {
19350             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
19351                 continue;
19352             }
19353             if (!set++ && lead)
19354                 Perl_re_printf( aTHX_  "%s", lead);
19355             Perl_re_printf( aTHX_  "%s ", PL_reg_extflags_name[bit]);
19356         }
19357     }
19358     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
19359             if (!set++ && lead) {
19360                 Perl_re_printf( aTHX_  "%s", lead);
19361             }
19362             switch (cs) {
19363                 case REGEX_UNICODE_CHARSET:
19364                     Perl_re_printf( aTHX_  "UNICODE");
19365                     break;
19366                 case REGEX_LOCALE_CHARSET:
19367                     Perl_re_printf( aTHX_  "LOCALE");
19368                     break;
19369                 case REGEX_ASCII_RESTRICTED_CHARSET:
19370                     Perl_re_printf( aTHX_  "ASCII-RESTRICTED");
19371                     break;
19372                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
19373                     Perl_re_printf( aTHX_  "ASCII-MORE_RESTRICTED");
19374                     break;
19375                 default:
19376                     Perl_re_printf( aTHX_  "UNKNOWN CHARACTER SET");
19377                     break;
19378             }
19379     }
19380     if (lead)  {
19381         if (set)
19382             Perl_re_printf( aTHX_  "\n");
19383         else
19384             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
19385     }
19386 }
19387 #endif
19388
19389 void
19390 Perl_regdump(pTHX_ const regexp *r)
19391 {
19392 #ifdef DEBUGGING
19393     int i;
19394     SV * const sv = sv_newmortal();
19395     SV *dsv= sv_newmortal();
19396     RXi_GET_DECL(r, ri);
19397     GET_RE_DEBUG_FLAGS_DECL;
19398
19399     PERL_ARGS_ASSERT_REGDUMP;
19400
19401     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
19402
19403     /* Header fields of interest. */
19404     for (i = 0; i < 2; i++) {
19405         if (r->substrs->data[i].substr) {
19406             RE_PV_QUOTED_DECL(s, 0, dsv,
19407                             SvPVX_const(r->substrs->data[i].substr),
19408                             RE_SV_DUMPLEN(r->substrs->data[i].substr),
19409                             PL_dump_re_max_len);
19410             Perl_re_printf( aTHX_
19411                           "%s %s%s at %" IVdf "..%" UVuf " ",
19412                           i ? "floating" : "anchored",
19413                           s,
19414                           RE_SV_TAIL(r->substrs->data[i].substr),
19415                           (IV)r->substrs->data[i].min_offset,
19416                           (UV)r->substrs->data[i].max_offset);
19417         }
19418         else if (r->substrs->data[i].utf8_substr) {
19419             RE_PV_QUOTED_DECL(s, 1, dsv,
19420                             SvPVX_const(r->substrs->data[i].utf8_substr),
19421                             RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
19422                             30);
19423             Perl_re_printf( aTHX_
19424                           "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
19425                           i ? "floating" : "anchored",
19426                           s,
19427                           RE_SV_TAIL(r->substrs->data[i].utf8_substr),
19428                           (IV)r->substrs->data[i].min_offset,
19429                           (UV)r->substrs->data[i].max_offset);
19430         }
19431     }
19432
19433     if (r->check_substr || r->check_utf8)
19434         Perl_re_printf( aTHX_
19435                       (const char *)
19436                       (   r->check_substr == r->substrs->data[1].substr
19437                        && r->check_utf8   == r->substrs->data[1].utf8_substr
19438                        ? "(checking floating" : "(checking anchored"));
19439     if (r->intflags & PREGf_NOSCAN)
19440         Perl_re_printf( aTHX_  " noscan");
19441     if (r->extflags & RXf_CHECK_ALL)
19442         Perl_re_printf( aTHX_  " isall");
19443     if (r->check_substr || r->check_utf8)
19444         Perl_re_printf( aTHX_  ") ");
19445
19446     if (ri->regstclass) {
19447         regprop(r, sv, ri->regstclass, NULL, NULL);
19448         Perl_re_printf( aTHX_  "stclass %s ", SvPVX_const(sv));
19449     }
19450     if (r->intflags & PREGf_ANCH) {
19451         Perl_re_printf( aTHX_  "anchored");
19452         if (r->intflags & PREGf_ANCH_MBOL)
19453             Perl_re_printf( aTHX_  "(MBOL)");
19454         if (r->intflags & PREGf_ANCH_SBOL)
19455             Perl_re_printf( aTHX_  "(SBOL)");
19456         if (r->intflags & PREGf_ANCH_GPOS)
19457             Perl_re_printf( aTHX_  "(GPOS)");
19458         Perl_re_printf( aTHX_ " ");
19459     }
19460     if (r->intflags & PREGf_GPOS_SEEN)
19461         Perl_re_printf( aTHX_  "GPOS:%" UVuf " ", (UV)r->gofs);
19462     if (r->intflags & PREGf_SKIP)
19463         Perl_re_printf( aTHX_  "plus ");
19464     if (r->intflags & PREGf_IMPLICIT)
19465         Perl_re_printf( aTHX_  "implicit ");
19466     Perl_re_printf( aTHX_  "minlen %" IVdf " ", (IV)r->minlen);
19467     if (r->extflags & RXf_EVAL_SEEN)
19468         Perl_re_printf( aTHX_  "with eval ");
19469     Perl_re_printf( aTHX_  "\n");
19470     DEBUG_FLAGS_r({
19471         regdump_extflags("r->extflags: ", r->extflags);
19472         regdump_intflags("r->intflags: ", r->intflags);
19473     });
19474 #else
19475     PERL_ARGS_ASSERT_REGDUMP;
19476     PERL_UNUSED_CONTEXT;
19477     PERL_UNUSED_ARG(r);
19478 #endif  /* DEBUGGING */
19479 }
19480
19481 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
19482 #ifdef DEBUGGING
19483
19484 #  if   _CC_WORDCHAR != 0 || _CC_DIGIT != 1        || _CC_ALPHA != 2    \
19485      || _CC_LOWER != 3    || _CC_UPPER != 4        || _CC_PUNCT != 5    \
19486      || _CC_PRINT != 6    || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8    \
19487      || _CC_CASED != 9    || _CC_SPACE != 10       || _CC_BLANK != 11   \
19488      || _CC_XDIGIT != 12  || _CC_CNTRL != 13       || _CC_ASCII != 14   \
19489      || _CC_VERTSPACE != 15
19490 #   error Need to adjust order of anyofs[]
19491 #  endif
19492 static const char * const anyofs[] = {
19493     "\\w",
19494     "\\W",
19495     "\\d",
19496     "\\D",
19497     "[:alpha:]",
19498     "[:^alpha:]",
19499     "[:lower:]",
19500     "[:^lower:]",
19501     "[:upper:]",
19502     "[:^upper:]",
19503     "[:punct:]",
19504     "[:^punct:]",
19505     "[:print:]",
19506     "[:^print:]",
19507     "[:alnum:]",
19508     "[:^alnum:]",
19509     "[:graph:]",
19510     "[:^graph:]",
19511     "[:cased:]",
19512     "[:^cased:]",
19513     "\\s",
19514     "\\S",
19515     "[:blank:]",
19516     "[:^blank:]",
19517     "[:xdigit:]",
19518     "[:^xdigit:]",
19519     "[:cntrl:]",
19520     "[:^cntrl:]",
19521     "[:ascii:]",
19522     "[:^ascii:]",
19523     "\\v",
19524     "\\V"
19525 };
19526 #endif
19527
19528 /*
19529 - regprop - printable representation of opcode, with run time support
19530 */
19531
19532 void
19533 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
19534 {
19535 #ifdef DEBUGGING
19536     int k;
19537     RXi_GET_DECL(prog, progi);
19538     GET_RE_DEBUG_FLAGS_DECL;
19539
19540     PERL_ARGS_ASSERT_REGPROP;
19541
19542     SvPVCLEAR(sv);
19543
19544     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
19545         /* It would be nice to FAIL() here, but this may be called from
19546            regexec.c, and it would be hard to supply pRExC_state. */
19547         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
19548                                               (int)OP(o), (int)REGNODE_MAX);
19549     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
19550
19551     k = PL_regkind[OP(o)];
19552
19553     if (k == EXACT) {
19554         sv_catpvs(sv, " ");
19555         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
19556          * is a crude hack but it may be the best for now since
19557          * we have no flag "this EXACTish node was UTF-8"
19558          * --jhi */
19559         pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
19560                   PL_colors[0], PL_colors[1],
19561                   PERL_PV_ESCAPE_UNI_DETECT |
19562                   PERL_PV_ESCAPE_NONASCII   |
19563                   PERL_PV_PRETTY_ELLIPSES   |
19564                   PERL_PV_PRETTY_LTGT       |
19565                   PERL_PV_PRETTY_NOCLEAR
19566                   );
19567     } else if (k == TRIE) {
19568         /* print the details of the trie in dumpuntil instead, as
19569          * progi->data isn't available here */
19570         const char op = OP(o);
19571         const U32 n = ARG(o);
19572         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
19573                (reg_ac_data *)progi->data->data[n] :
19574                NULL;
19575         const reg_trie_data * const trie
19576             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
19577
19578         Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
19579         DEBUG_TRIE_COMPILE_r({
19580           if (trie->jump)
19581             sv_catpvs(sv, "(JUMP)");
19582           Perl_sv_catpvf(aTHX_ sv,
19583             "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
19584             (UV)trie->startstate,
19585             (IV)trie->statecount-1, /* -1 because of the unused 0 element */
19586             (UV)trie->wordcount,
19587             (UV)trie->minlen,
19588             (UV)trie->maxlen,
19589             (UV)TRIE_CHARCOUNT(trie),
19590             (UV)trie->uniquecharcount
19591           );
19592         });
19593         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
19594             sv_catpvs(sv, "[");
19595             (void) put_charclass_bitmap_innards(sv,
19596                                                 ((IS_ANYOF_TRIE(op))
19597                                                  ? ANYOF_BITMAP(o)
19598                                                  : TRIE_BITMAP(trie)),
19599                                                 NULL,
19600                                                 NULL,
19601                                                 NULL,
19602                                                 FALSE
19603                                                );
19604             sv_catpvs(sv, "]");
19605         }
19606     } else if (k == CURLY) {
19607         U32 lo = ARG1(o), hi = ARG2(o);
19608         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
19609             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
19610         Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
19611         if (hi == REG_INFTY)
19612             sv_catpvs(sv, "INFTY");
19613         else
19614             Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
19615         sv_catpvs(sv, "}");
19616     }
19617     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
19618         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
19619     else if (k == REF || k == OPEN || k == CLOSE
19620              || k == GROUPP || OP(o)==ACCEPT)
19621     {
19622         AV *name_list= NULL;
19623         U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
19624         Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno);        /* Parenth number */
19625         if ( RXp_PAREN_NAMES(prog) ) {
19626             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
19627         } else if ( pRExC_state ) {
19628             name_list= RExC_paren_name_list;
19629         }
19630         if (name_list) {
19631             if ( k != REF || (OP(o) < NREF)) {
19632                 SV **name= av_fetch(name_list, parno, 0 );
19633                 if (name)
19634                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
19635             }
19636             else {
19637                 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
19638                 I32 *nums=(I32*)SvPVX(sv_dat);
19639                 SV **name= av_fetch(name_list, nums[0], 0 );
19640                 I32 n;
19641                 if (name) {
19642                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
19643                         Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
19644                                     (n ? "," : ""), (IV)nums[n]);
19645                     }
19646                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
19647                 }
19648             }
19649         }
19650         if ( k == REF && reginfo) {
19651             U32 n = ARG(o);  /* which paren pair */
19652             I32 ln = prog->offs[n].start;
19653             if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
19654                 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
19655             else if (ln == prog->offs[n].end)
19656                 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
19657             else {
19658                 const char *s = reginfo->strbeg + ln;
19659                 Perl_sv_catpvf(aTHX_ sv, ": ");
19660                 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
19661                     PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
19662             }
19663         }
19664     } else if (k == GOSUB) {
19665         AV *name_list= NULL;
19666         if ( RXp_PAREN_NAMES(prog) ) {
19667             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
19668         } else if ( pRExC_state ) {
19669             name_list= RExC_paren_name_list;
19670         }
19671
19672         /* Paren and offset */
19673         Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
19674                 (int)((o + (int)ARG2L(o)) - progi->program) );
19675         if (name_list) {
19676             SV **name= av_fetch(name_list, ARG(o), 0 );
19677             if (name)
19678                 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
19679         }
19680     }
19681     else if (k == LOGICAL)
19682         /* 2: embedded, otherwise 1 */
19683         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
19684     else if (k == ANYOF) {
19685         const U8 flags = ANYOF_FLAGS(o);
19686         bool do_sep = FALSE;    /* Do we need to separate various components of
19687                                    the output? */
19688         /* Set if there is still an unresolved user-defined property */
19689         SV *unresolved                = NULL;
19690
19691         /* Things that are ignored except when the runtime locale is UTF-8 */
19692         SV *only_utf8_locale_invlist = NULL;
19693
19694         /* Code points that don't fit in the bitmap */
19695         SV *nonbitmap_invlist = NULL;
19696
19697         /* And things that aren't in the bitmap, but are small enough to be */
19698         SV* bitmap_range_not_in_bitmap = NULL;
19699
19700         const bool inverted = flags & ANYOF_INVERT;
19701
19702         if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
19703             if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
19704                 sv_catpvs(sv, "{utf8-locale-reqd}");
19705             }
19706             if (flags & ANYOFL_FOLD) {
19707                 sv_catpvs(sv, "{i}");
19708             }
19709         }
19710
19711         /* If there is stuff outside the bitmap, get it */
19712         if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) {
19713             (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
19714                                                 &unresolved,
19715                                                 &only_utf8_locale_invlist,
19716                                                 &nonbitmap_invlist);
19717             /* The non-bitmap data may contain stuff that could fit in the
19718              * bitmap.  This could come from a user-defined property being
19719              * finally resolved when this call was done; or much more likely
19720              * because there are matches that require UTF-8 to be valid, and so
19721              * aren't in the bitmap.  This is teased apart later */
19722             _invlist_intersection(nonbitmap_invlist,
19723                                   PL_InBitmap,
19724                                   &bitmap_range_not_in_bitmap);
19725             /* Leave just the things that don't fit into the bitmap */
19726             _invlist_subtract(nonbitmap_invlist,
19727                               PL_InBitmap,
19728                               &nonbitmap_invlist);
19729         }
19730
19731         /* Obey this flag to add all above-the-bitmap code points */
19732         if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
19733             nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
19734                                                       NUM_ANYOF_CODE_POINTS,
19735                                                       UV_MAX);
19736         }
19737
19738         /* Ready to start outputting.  First, the initial left bracket */
19739         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
19740
19741         /* Then all the things that could fit in the bitmap */
19742         do_sep = put_charclass_bitmap_innards(sv,
19743                                               ANYOF_BITMAP(o),
19744                                               bitmap_range_not_in_bitmap,
19745                                               only_utf8_locale_invlist,
19746                                               o,
19747
19748                                               /* Can't try inverting for a
19749                                                * better display if there are
19750                                                * things that haven't been
19751                                                * resolved */
19752                                               unresolved != NULL);
19753         SvREFCNT_dec(bitmap_range_not_in_bitmap);
19754
19755         /* If there are user-defined properties which haven't been defined yet,
19756          * output them.  If the result is not to be inverted, it is clearest to
19757          * output them in a separate [] from the bitmap range stuff.  If the
19758          * result is to be complemented, we have to show everything in one [],
19759          * as the inversion applies to the whole thing.  Use {braces} to
19760          * separate them from anything in the bitmap and anything above the
19761          * bitmap. */
19762         if (unresolved) {
19763             if (inverted) {
19764                 if (! do_sep) { /* If didn't output anything in the bitmap */
19765                     sv_catpvs(sv, "^");
19766                 }
19767                 sv_catpvs(sv, "{");
19768             }
19769             else if (do_sep) {
19770                 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
19771             }
19772             sv_catsv(sv, unresolved);
19773             if (inverted) {
19774                 sv_catpvs(sv, "}");
19775             }
19776             do_sep = ! inverted;
19777         }
19778
19779         /* And, finally, add the above-the-bitmap stuff */
19780         if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
19781             SV* contents;
19782
19783             /* See if truncation size is overridden */
19784             const STRLEN dump_len = (PL_dump_re_max_len > 256)
19785                                     ? PL_dump_re_max_len
19786                                     : 256;
19787
19788             /* This is output in a separate [] */
19789             if (do_sep) {
19790                 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
19791             }
19792
19793             /* And, for easy of understanding, it is shown in the
19794              * uncomplemented form if possible.  The one exception being if
19795              * there are unresolved items, where the inversion has to be
19796              * delayed until runtime */
19797             if (inverted && ! unresolved) {
19798                 _invlist_invert(nonbitmap_invlist);
19799                 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
19800             }
19801
19802             contents = invlist_contents(nonbitmap_invlist,
19803                                         FALSE /* output suitable for catsv */
19804                                        );
19805
19806             /* If the output is shorter than the permissible maximum, just do it. */
19807             if (SvCUR(contents) <= dump_len) {
19808                 sv_catsv(sv, contents);
19809             }
19810             else {
19811                 const char * contents_string = SvPVX(contents);
19812                 STRLEN i = dump_len;
19813
19814                 /* Otherwise, start at the permissible max and work back to the
19815                  * first break possibility */
19816                 while (i > 0 && contents_string[i] != ' ') {
19817                     i--;
19818                 }
19819                 if (i == 0) {       /* Fail-safe.  Use the max if we couldn't
19820                                        find a legal break */
19821                     i = dump_len;
19822                 }
19823
19824                 sv_catpvn(sv, contents_string, i);
19825                 sv_catpvs(sv, "...");
19826             }
19827
19828             SvREFCNT_dec_NN(contents);
19829             SvREFCNT_dec_NN(nonbitmap_invlist);
19830         }
19831
19832         /* And finally the matching, closing ']' */
19833         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
19834
19835         SvREFCNT_dec(unresolved);
19836     }
19837     else if (k == ANYOFM) {
19838         SV * cp_list = get_ANYOFM_contents(o);
19839
19840         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
19841         if (OP(o) == NANYOFM) {
19842             _invlist_invert(cp_list);
19843         }
19844
19845         put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, TRUE);
19846         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
19847
19848         SvREFCNT_dec(cp_list);
19849     }
19850     else if (k == POSIXD || k == NPOSIXD) {
19851         U8 index = FLAGS(o) * 2;
19852         if (index < C_ARRAY_LENGTH(anyofs)) {
19853             if (*anyofs[index] != '[')  {
19854                 sv_catpvs(sv, "[");
19855             }
19856             sv_catpv(sv, anyofs[index]);
19857             if (*anyofs[index] != '[')  {
19858                 sv_catpvs(sv, "]");
19859             }
19860         }
19861         else {
19862             Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
19863         }
19864     }
19865     else if (k == BOUND || k == NBOUND) {
19866         /* Must be synced with order of 'bound_type' in regcomp.h */
19867         const char * const bounds[] = {
19868             "",      /* Traditional */
19869             "{gcb}",
19870             "{lb}",
19871             "{sb}",
19872             "{wb}"
19873         };
19874         assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
19875         sv_catpv(sv, bounds[FLAGS(o)]);
19876     }
19877     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
19878         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
19879     else if (OP(o) == SBOL)
19880         Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
19881
19882     /* add on the verb argument if there is one */
19883     if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
19884         if ( ARG(o) )
19885             Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
19886                        SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
19887         else
19888             sv_catpvs(sv, ":NULL");
19889     }
19890 #else
19891     PERL_UNUSED_CONTEXT;
19892     PERL_UNUSED_ARG(sv);
19893     PERL_UNUSED_ARG(o);
19894     PERL_UNUSED_ARG(prog);
19895     PERL_UNUSED_ARG(reginfo);
19896     PERL_UNUSED_ARG(pRExC_state);
19897 #endif  /* DEBUGGING */
19898 }
19899
19900
19901
19902 SV *
19903 Perl_re_intuit_string(pTHX_ REGEXP * const r)
19904 {                               /* Assume that RE_INTUIT is set */
19905     struct regexp *const prog = ReANY(r);
19906     GET_RE_DEBUG_FLAGS_DECL;
19907
19908     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
19909     PERL_UNUSED_CONTEXT;
19910
19911     DEBUG_COMPILE_r(
19912         {
19913             const char * const s = SvPV_nolen_const(RX_UTF8(r)
19914                       ? prog->check_utf8 : prog->check_substr);
19915
19916             if (!PL_colorset) reginitcolors();
19917             Perl_re_printf( aTHX_
19918                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
19919                       PL_colors[4],
19920                       RX_UTF8(r) ? "utf8 " : "",
19921                       PL_colors[5], PL_colors[0],
19922                       s,
19923                       PL_colors[1],
19924                       (strlen(s) > PL_dump_re_max_len ? "..." : ""));
19925         } );
19926
19927     /* use UTF8 check substring if regexp pattern itself is in UTF8 */
19928     return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
19929 }
19930
19931 /*
19932    pregfree()
19933
19934    handles refcounting and freeing the perl core regexp structure. When
19935    it is necessary to actually free the structure the first thing it
19936    does is call the 'free' method of the regexp_engine associated to
19937    the regexp, allowing the handling of the void *pprivate; member
19938    first. (This routine is not overridable by extensions, which is why
19939    the extensions free is called first.)
19940
19941    See regdupe and regdupe_internal if you change anything here.
19942 */
19943 #ifndef PERL_IN_XSUB_RE
19944 void
19945 Perl_pregfree(pTHX_ REGEXP *r)
19946 {
19947     SvREFCNT_dec(r);
19948 }
19949
19950 void
19951 Perl_pregfree2(pTHX_ REGEXP *rx)
19952 {
19953     struct regexp *const r = ReANY(rx);
19954     GET_RE_DEBUG_FLAGS_DECL;
19955
19956     PERL_ARGS_ASSERT_PREGFREE2;
19957
19958     if (! r)
19959         return;
19960
19961     if (r->mother_re) {
19962         ReREFCNT_dec(r->mother_re);
19963     } else {
19964         CALLREGFREE_PVT(rx); /* free the private data */
19965         SvREFCNT_dec(RXp_PAREN_NAMES(r));
19966     }
19967     if (r->substrs) {
19968         int i;
19969         for (i = 0; i < 2; i++) {
19970             SvREFCNT_dec(r->substrs->data[i].substr);
19971             SvREFCNT_dec(r->substrs->data[i].utf8_substr);
19972         }
19973         Safefree(r->substrs);
19974     }
19975     RX_MATCH_COPY_FREE(rx);
19976 #ifdef PERL_ANY_COW
19977     SvREFCNT_dec(r->saved_copy);
19978 #endif
19979     Safefree(r->offs);
19980     SvREFCNT_dec(r->qr_anoncv);
19981     if (r->recurse_locinput)
19982         Safefree(r->recurse_locinput);
19983 }
19984
19985
19986 /*  reg_temp_copy()
19987
19988     Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
19989     except that dsv will be created if NULL.
19990
19991     This function is used in two main ways. First to implement
19992         $r = qr/....; $s = $$r;
19993
19994     Secondly, it is used as a hacky workaround to the structural issue of
19995     match results
19996     being stored in the regexp structure which is in turn stored in
19997     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
19998     could be PL_curpm in multiple contexts, and could require multiple
19999     result sets being associated with the pattern simultaneously, such
20000     as when doing a recursive match with (??{$qr})
20001
20002     The solution is to make a lightweight copy of the regexp structure
20003     when a qr// is returned from the code executed by (??{$qr}) this
20004     lightweight copy doesn't actually own any of its data except for
20005     the starp/end and the actual regexp structure itself.
20006
20007 */
20008
20009
20010 REGEXP *
20011 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
20012 {
20013     struct regexp *drx;
20014     struct regexp *const srx = ReANY(ssv);
20015     const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
20016
20017     PERL_ARGS_ASSERT_REG_TEMP_COPY;
20018
20019     if (!dsv)
20020         dsv = (REGEXP*) newSV_type(SVt_REGEXP);
20021     else {
20022         SvOK_off((SV *)dsv);
20023         if (islv) {
20024             /* For PVLVs, the head (sv_any) points to an XPVLV, while
20025              * the LV's xpvlenu_rx will point to a regexp body, which
20026              * we allocate here */
20027             REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
20028             assert(!SvPVX(dsv));
20029             ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
20030             temp->sv_any = NULL;
20031             SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
20032             SvREFCNT_dec_NN(temp);
20033             /* SvCUR still resides in the xpvlv struct, so the regexp copy-
20034                ing below will not set it. */
20035             SvCUR_set(dsv, SvCUR(ssv));
20036         }
20037     }
20038     /* This ensures that SvTHINKFIRST(sv) is true, and hence that
20039        sv_force_normal(sv) is called.  */
20040     SvFAKE_on(dsv);
20041     drx = ReANY(dsv);
20042
20043     SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
20044     SvPV_set(dsv, RX_WRAPPED(ssv));
20045     /* We share the same string buffer as the original regexp, on which we
20046        hold a reference count, incremented when mother_re is set below.
20047        The string pointer is copied here, being part of the regexp struct.
20048      */
20049     memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
20050            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
20051     if (!islv)
20052         SvLEN_set(dsv, 0);
20053     if (srx->offs) {
20054         const I32 npar = srx->nparens+1;
20055         Newx(drx->offs, npar, regexp_paren_pair);
20056         Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
20057     }
20058     if (srx->substrs) {
20059         int i;
20060         Newx(drx->substrs, 1, struct reg_substr_data);
20061         StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
20062
20063         for (i = 0; i < 2; i++) {
20064             SvREFCNT_inc_void(drx->substrs->data[i].substr);
20065             SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
20066         }
20067
20068         /* check_substr and check_utf8, if non-NULL, point to either their
20069            anchored or float namesakes, and don't hold a second reference.  */
20070     }
20071     RX_MATCH_COPIED_off(dsv);
20072 #ifdef PERL_ANY_COW
20073     drx->saved_copy = NULL;
20074 #endif
20075     drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
20076     SvREFCNT_inc_void(drx->qr_anoncv);
20077     if (srx->recurse_locinput)
20078         Newx(drx->recurse_locinput, srx->nparens + 1, char *);
20079
20080     return dsv;
20081 }
20082 #endif
20083
20084
20085 /* regfree_internal()
20086
20087    Free the private data in a regexp. This is overloadable by
20088    extensions. Perl takes care of the regexp structure in pregfree(),
20089    this covers the *pprivate pointer which technically perl doesn't
20090    know about, however of course we have to handle the
20091    regexp_internal structure when no extension is in use.
20092
20093    Note this is called before freeing anything in the regexp
20094    structure.
20095  */
20096
20097 void
20098 Perl_regfree_internal(pTHX_ REGEXP * const rx)
20099 {
20100     struct regexp *const r = ReANY(rx);
20101     RXi_GET_DECL(r, ri);
20102     GET_RE_DEBUG_FLAGS_DECL;
20103
20104     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
20105
20106     if (! ri) {
20107         return;
20108     }
20109
20110     DEBUG_COMPILE_r({
20111         if (!PL_colorset)
20112             reginitcolors();
20113         {
20114             SV *dsv= sv_newmortal();
20115             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
20116                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
20117             Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
20118                 PL_colors[4], PL_colors[5], s);
20119         }
20120     });
20121
20122 #ifdef RE_TRACK_PATTERN_OFFSETS
20123     if (ri->u.offsets)
20124         Safefree(ri->u.offsets);             /* 20010421 MJD */
20125 #endif
20126     if (ri->code_blocks)
20127         S_free_codeblocks(aTHX_ ri->code_blocks);
20128
20129     if (ri->data) {
20130         int n = ri->data->count;
20131
20132         while (--n >= 0) {
20133           /* If you add a ->what type here, update the comment in regcomp.h */
20134             switch (ri->data->what[n]) {
20135             case 'a':
20136             case 'r':
20137             case 's':
20138             case 'S':
20139             case 'u':
20140                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
20141                 break;
20142             case 'f':
20143                 Safefree(ri->data->data[n]);
20144                 break;
20145             case 'l':
20146             case 'L':
20147                 break;
20148             case 'T':
20149                 { /* Aho Corasick add-on structure for a trie node.
20150                      Used in stclass optimization only */
20151                     U32 refcount;
20152                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
20153 #ifdef USE_ITHREADS
20154                     dVAR;
20155 #endif
20156                     OP_REFCNT_LOCK;
20157                     refcount = --aho->refcount;
20158                     OP_REFCNT_UNLOCK;
20159                     if ( !refcount ) {
20160                         PerlMemShared_free(aho->states);
20161                         PerlMemShared_free(aho->fail);
20162                          /* do this last!!!! */
20163                         PerlMemShared_free(ri->data->data[n]);
20164                         /* we should only ever get called once, so
20165                          * assert as much, and also guard the free
20166                          * which /might/ happen twice. At the least
20167                          * it will make code anlyzers happy and it
20168                          * doesn't cost much. - Yves */
20169                         assert(ri->regstclass);
20170                         if (ri->regstclass) {
20171                             PerlMemShared_free(ri->regstclass);
20172                             ri->regstclass = 0;
20173                         }
20174                     }
20175                 }
20176                 break;
20177             case 't':
20178                 {
20179                     /* trie structure. */
20180                     U32 refcount;
20181                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
20182 #ifdef USE_ITHREADS
20183                     dVAR;
20184 #endif
20185                     OP_REFCNT_LOCK;
20186                     refcount = --trie->refcount;
20187                     OP_REFCNT_UNLOCK;
20188                     if ( !refcount ) {
20189                         PerlMemShared_free(trie->charmap);
20190                         PerlMemShared_free(trie->states);
20191                         PerlMemShared_free(trie->trans);
20192                         if (trie->bitmap)
20193                             PerlMemShared_free(trie->bitmap);
20194                         if (trie->jump)
20195                             PerlMemShared_free(trie->jump);
20196                         PerlMemShared_free(trie->wordinfo);
20197                         /* do this last!!!! */
20198                         PerlMemShared_free(ri->data->data[n]);
20199                     }
20200                 }
20201                 break;
20202             default:
20203                 Perl_croak(aTHX_ "panic: regfree data code '%c'",
20204                                                     ri->data->what[n]);
20205             }
20206         }
20207         Safefree(ri->data->what);
20208         Safefree(ri->data);
20209     }
20210
20211     Safefree(ri);
20212 }
20213
20214 #define av_dup_inc(s, t)        MUTABLE_AV(sv_dup_inc((const SV *)s, t))
20215 #define hv_dup_inc(s, t)        MUTABLE_HV(sv_dup_inc((const SV *)s, t))
20216 #define SAVEPVN(p, n)   ((p) ? savepvn(p, n) : NULL)
20217
20218 /*
20219    re_dup_guts - duplicate a regexp.
20220
20221    This routine is expected to clone a given regexp structure. It is only
20222    compiled under USE_ITHREADS.
20223
20224    After all of the core data stored in struct regexp is duplicated
20225    the regexp_engine.dupe method is used to copy any private data
20226    stored in the *pprivate pointer. This allows extensions to handle
20227    any duplication it needs to do.
20228
20229    See pregfree() and regfree_internal() if you change anything here.
20230 */
20231 #if defined(USE_ITHREADS)
20232 #ifndef PERL_IN_XSUB_RE
20233 void
20234 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
20235 {
20236     dVAR;
20237     I32 npar;
20238     const struct regexp *r = ReANY(sstr);
20239     struct regexp *ret = ReANY(dstr);
20240
20241     PERL_ARGS_ASSERT_RE_DUP_GUTS;
20242
20243     npar = r->nparens+1;
20244     Newx(ret->offs, npar, regexp_paren_pair);
20245     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
20246
20247     if (ret->substrs) {
20248         /* Do it this way to avoid reading from *r after the StructCopy().
20249            That way, if any of the sv_dup_inc()s dislodge *r from the L1
20250            cache, it doesn't matter.  */
20251         int i;
20252         const bool anchored = r->check_substr
20253             ? r->check_substr == r->substrs->data[0].substr
20254             : r->check_utf8   == r->substrs->data[0].utf8_substr;
20255         Newx(ret->substrs, 1, struct reg_substr_data);
20256         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
20257
20258         for (i = 0; i < 2; i++) {
20259             ret->substrs->data[i].substr =
20260                         sv_dup_inc(ret->substrs->data[i].substr, param);
20261             ret->substrs->data[i].utf8_substr =
20262                         sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
20263         }
20264
20265         /* check_substr and check_utf8, if non-NULL, point to either their
20266            anchored or float namesakes, and don't hold a second reference.  */
20267
20268         if (ret->check_substr) {
20269             if (anchored) {
20270                 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
20271
20272                 ret->check_substr = ret->substrs->data[0].substr;
20273                 ret->check_utf8   = ret->substrs->data[0].utf8_substr;
20274             } else {
20275                 assert(r->check_substr == r->substrs->data[1].substr);
20276                 assert(r->check_utf8   == r->substrs->data[1].utf8_substr);
20277
20278                 ret->check_substr = ret->substrs->data[1].substr;
20279                 ret->check_utf8   = ret->substrs->data[1].utf8_substr;
20280             }
20281         } else if (ret->check_utf8) {
20282             if (anchored) {
20283                 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
20284             } else {
20285                 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
20286             }
20287         }
20288     }
20289
20290     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
20291     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
20292     if (r->recurse_locinput)
20293         Newx(ret->recurse_locinput, r->nparens + 1, char *);
20294
20295     if (ret->pprivate)
20296         RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
20297
20298     if (RX_MATCH_COPIED(dstr))
20299         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
20300     else
20301         ret->subbeg = NULL;
20302 #ifdef PERL_ANY_COW
20303     ret->saved_copy = NULL;
20304 #endif
20305
20306     /* Whether mother_re be set or no, we need to copy the string.  We
20307        cannot refrain from copying it when the storage points directly to
20308        our mother regexp, because that's
20309                1: a buffer in a different thread
20310                2: something we no longer hold a reference on
20311                so we need to copy it locally.  */
20312     RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
20313     ret->mother_re   = NULL;
20314 }
20315 #endif /* PERL_IN_XSUB_RE */
20316
20317 /*
20318    regdupe_internal()
20319
20320    This is the internal complement to regdupe() which is used to copy
20321    the structure pointed to by the *pprivate pointer in the regexp.
20322    This is the core version of the extension overridable cloning hook.
20323    The regexp structure being duplicated will be copied by perl prior
20324    to this and will be provided as the regexp *r argument, however
20325    with the /old/ structures pprivate pointer value. Thus this routine
20326    may override any copying normally done by perl.
20327
20328    It returns a pointer to the new regexp_internal structure.
20329 */
20330
20331 void *
20332 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
20333 {
20334     dVAR;
20335     struct regexp *const r = ReANY(rx);
20336     regexp_internal *reti;
20337     int len;
20338     RXi_GET_DECL(r, ri);
20339
20340     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
20341
20342     len = ProgLen(ri);
20343
20344     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
20345           char, regexp_internal);
20346     Copy(ri->program, reti->program, len+1, regnode);
20347
20348
20349     if (ri->code_blocks) {
20350         int n;
20351         Newx(reti->code_blocks, 1, struct reg_code_blocks);
20352         Newx(reti->code_blocks->cb, ri->code_blocks->count,
20353                     struct reg_code_block);
20354         Copy(ri->code_blocks->cb, reti->code_blocks->cb,
20355              ri->code_blocks->count, struct reg_code_block);
20356         for (n = 0; n < ri->code_blocks->count; n++)
20357              reti->code_blocks->cb[n].src_regex = (REGEXP*)
20358                     sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
20359         reti->code_blocks->count = ri->code_blocks->count;
20360         reti->code_blocks->refcnt = 1;
20361     }
20362     else
20363         reti->code_blocks = NULL;
20364
20365     reti->regstclass = NULL;
20366
20367     if (ri->data) {
20368         struct reg_data *d;
20369         const int count = ri->data->count;
20370         int i;
20371
20372         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
20373                 char, struct reg_data);
20374         Newx(d->what, count, U8);
20375
20376         d->count = count;
20377         for (i = 0; i < count; i++) {
20378             d->what[i] = ri->data->what[i];
20379             switch (d->what[i]) {
20380                 /* see also regcomp.h and regfree_internal() */
20381             case 'a': /* actually an AV, but the dup function is identical.
20382                          values seem to be "plain sv's" generally. */
20383             case 'r': /* a compiled regex (but still just another SV) */
20384             case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
20385                          this use case should go away, the code could have used
20386                          'a' instead - see S_set_ANYOF_arg() for array contents. */
20387             case 'S': /* actually an SV, but the dup function is identical.  */
20388             case 'u': /* actually an HV, but the dup function is identical.
20389                          values are "plain sv's" */
20390                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
20391                 break;
20392             case 'f':
20393                 /* Synthetic Start Class - "Fake" charclass we generate to optimize
20394                  * patterns which could start with several different things. Pre-TRIE
20395                  * this was more important than it is now, however this still helps
20396                  * in some places, for instance /x?a+/ might produce a SSC equivalent
20397                  * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
20398                  * in regexec.c
20399                  */
20400                 /* This is cheating. */
20401                 Newx(d->data[i], 1, regnode_ssc);
20402                 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
20403                 reti->regstclass = (regnode*)d->data[i];
20404                 break;
20405             case 'T':
20406                 /* AHO-CORASICK fail table */
20407                 /* Trie stclasses are readonly and can thus be shared
20408                  * without duplication. We free the stclass in pregfree
20409                  * when the corresponding reg_ac_data struct is freed.
20410                  */
20411                 reti->regstclass= ri->regstclass;
20412                 /* FALLTHROUGH */
20413             case 't':
20414                 /* TRIE transition table */
20415                 OP_REFCNT_LOCK;
20416                 ((reg_trie_data*)ri->data->data[i])->refcount++;
20417                 OP_REFCNT_UNLOCK;
20418                 /* FALLTHROUGH */
20419             case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
20420             case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
20421                          is not from another regexp */
20422                 d->data[i] = ri->data->data[i];
20423                 break;
20424             default:
20425                 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
20426                                                            ri->data->what[i]);
20427             }
20428         }
20429
20430         reti->data = d;
20431     }
20432     else
20433         reti->data = NULL;
20434
20435     reti->name_list_idx = ri->name_list_idx;
20436
20437 #ifdef RE_TRACK_PATTERN_OFFSETS
20438     if (ri->u.offsets) {
20439         Newx(reti->u.offsets, 2*len+1, U32);
20440         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
20441     }
20442 #else
20443     SetProgLen(reti, len);
20444 #endif
20445
20446     return (void*)reti;
20447 }
20448
20449 #endif    /* USE_ITHREADS */
20450
20451 #ifndef PERL_IN_XSUB_RE
20452
20453 /*
20454  - regnext - dig the "next" pointer out of a node
20455  */
20456 regnode *
20457 Perl_regnext(pTHX_ regnode *p)
20458 {
20459     I32 offset;
20460
20461     if (!p)
20462         return(NULL);
20463
20464     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
20465         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
20466                                                 (int)OP(p), (int)REGNODE_MAX);
20467     }
20468
20469     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
20470     if (offset == 0)
20471         return(NULL);
20472
20473     return(p+offset);
20474 }
20475
20476 #endif
20477
20478 STATIC void
20479 S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...)
20480 {
20481     va_list args;
20482     STRLEN l1 = strlen(pat1);
20483     STRLEN l2 = strlen(pat2);
20484     char buf[512];
20485     SV *msv;
20486     const char *message;
20487
20488     PERL_ARGS_ASSERT_RE_CROAK2;
20489
20490     if (l1 > 510)
20491         l1 = 510;
20492     if (l1 + l2 > 510)
20493         l2 = 510 - l1;
20494     Copy(pat1, buf, l1 , char);
20495     Copy(pat2, buf + l1, l2 , char);
20496     buf[l1 + l2] = '\n';
20497     buf[l1 + l2 + 1] = '\0';
20498     va_start(args, pat2);
20499     msv = vmess(buf, &args);
20500     va_end(args);
20501     message = SvPV_const(msv, l1);
20502     if (l1 > 512)
20503         l1 = 512;
20504     Copy(message, buf, l1 , char);
20505     /* l1-1 to avoid \n */
20506     Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf));
20507 }
20508
20509 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
20510
20511 #ifndef PERL_IN_XSUB_RE
20512 void
20513 Perl_save_re_context(pTHX)
20514 {
20515     I32 nparens = -1;
20516     I32 i;
20517
20518     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
20519
20520     if (PL_curpm) {
20521         const REGEXP * const rx = PM_GETRE(PL_curpm);
20522         if (rx)
20523             nparens = RX_NPARENS(rx);
20524     }
20525
20526     /* RT #124109. This is a complete hack; in the SWASHNEW case we know
20527      * that PL_curpm will be null, but that utf8.pm and the modules it
20528      * loads will only use $1..$3.
20529      * The t/porting/re_context.t test file checks this assumption.
20530      */
20531     if (nparens == -1)
20532         nparens = 3;
20533
20534     for (i = 1; i <= nparens; i++) {
20535         char digits[TYPE_CHARS(long)];
20536         const STRLEN len = my_snprintf(digits, sizeof(digits),
20537                                        "%lu", (long)i);
20538         GV *const *const gvp
20539             = (GV**)hv_fetch(PL_defstash, digits, len, 0);
20540
20541         if (gvp) {
20542             GV * const gv = *gvp;
20543             if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
20544                 save_scalar(gv);
20545         }
20546     }
20547 }
20548 #endif
20549
20550 #ifdef DEBUGGING
20551
20552 STATIC void
20553 S_put_code_point(pTHX_ SV *sv, UV c)
20554 {
20555     PERL_ARGS_ASSERT_PUT_CODE_POINT;
20556
20557     if (c > 255) {
20558         Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
20559     }
20560     else if (isPRINT(c)) {
20561         const char string = (char) c;
20562
20563         /* We use {phrase} as metanotation in the class, so also escape literal
20564          * braces */
20565         if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
20566             sv_catpvs(sv, "\\");
20567         sv_catpvn(sv, &string, 1);
20568     }
20569     else if (isMNEMONIC_CNTRL(c)) {
20570         Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
20571     }
20572     else {
20573         Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
20574     }
20575 }
20576
20577 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
20578
20579 STATIC void
20580 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
20581 {
20582     /* Appends to 'sv' a displayable version of the range of code points from
20583      * 'start' to 'end'.  Mnemonics (like '\r') are used for the few controls
20584      * that have them, when they occur at the beginning or end of the range.
20585      * It uses hex to output the remaining code points, unless 'allow_literals'
20586      * is true, in which case the printable ASCII ones are output as-is (though
20587      * some of these will be escaped by put_code_point()).
20588      *
20589      * NOTE:  This is designed only for printing ranges of code points that fit
20590      *        inside an ANYOF bitmap.  Higher code points are simply suppressed
20591      */
20592
20593     const unsigned int min_range_count = 3;
20594
20595     assert(start <= end);
20596
20597     PERL_ARGS_ASSERT_PUT_RANGE;
20598
20599     while (start <= end) {
20600         UV this_end;
20601         const char * format;
20602
20603         if (end - start < min_range_count) {
20604
20605             /* Output chars individually when they occur in short ranges */
20606             for (; start <= end; start++) {
20607                 put_code_point(sv, start);
20608             }
20609             break;
20610         }
20611
20612         /* If permitted by the input options, and there is a possibility that
20613          * this range contains a printable literal, look to see if there is
20614          * one. */
20615         if (allow_literals && start <= MAX_PRINT_A) {
20616
20617             /* If the character at the beginning of the range isn't an ASCII
20618              * printable, effectively split the range into two parts:
20619              *  1) the portion before the first such printable,
20620              *  2) the rest
20621              * and output them separately. */
20622             if (! isPRINT_A(start)) {
20623                 UV temp_end = start + 1;
20624
20625                 /* There is no point looking beyond the final possible
20626                  * printable, in MAX_PRINT_A */
20627                 UV max = MIN(end, MAX_PRINT_A);
20628
20629                 while (temp_end <= max && ! isPRINT_A(temp_end)) {
20630                     temp_end++;
20631                 }
20632
20633                 /* Here, temp_end points to one beyond the first printable if
20634                  * found, or to one beyond 'max' if not.  If none found, make
20635                  * sure that we use the entire range */
20636                 if (temp_end > MAX_PRINT_A) {
20637                     temp_end = end + 1;
20638                 }
20639
20640                 /* Output the first part of the split range: the part that
20641                  * doesn't have printables, with the parameter set to not look
20642                  * for literals (otherwise we would infinitely recurse) */
20643                 put_range(sv, start, temp_end - 1, FALSE);
20644
20645                 /* The 2nd part of the range (if any) starts here. */
20646                 start = temp_end;
20647
20648                 /* We do a continue, instead of dropping down, because even if
20649                  * the 2nd part is non-empty, it could be so short that we want
20650                  * to output it as individual characters, as tested for at the
20651                  * top of this loop.  */
20652                 continue;
20653             }
20654
20655             /* Here, 'start' is a printable ASCII.  If it is an alphanumeric,
20656              * output a sub-range of just the digits or letters, then process
20657              * the remaining portion as usual. */
20658             if (isALPHANUMERIC_A(start)) {
20659                 UV mask = (isDIGIT_A(start))
20660                            ? _CC_DIGIT
20661                              : isUPPER_A(start)
20662                                ? _CC_UPPER
20663                                : _CC_LOWER;
20664                 UV temp_end = start + 1;
20665
20666                 /* Find the end of the sub-range that includes just the
20667                  * characters in the same class as the first character in it */
20668                 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
20669                     temp_end++;
20670                 }
20671                 temp_end--;
20672
20673                 /* For short ranges, don't duplicate the code above to output
20674                  * them; just call recursively */
20675                 if (temp_end - start < min_range_count) {
20676                     put_range(sv, start, temp_end, FALSE);
20677                 }
20678                 else {  /* Output as a range */
20679                     put_code_point(sv, start);
20680                     sv_catpvs(sv, "-");
20681                     put_code_point(sv, temp_end);
20682                 }
20683                 start = temp_end + 1;
20684                 continue;
20685             }
20686
20687             /* We output any other printables as individual characters */
20688             if (isPUNCT_A(start) || isSPACE_A(start)) {
20689                 while (start <= end && (isPUNCT_A(start)
20690                                         || isSPACE_A(start)))
20691                 {
20692                     put_code_point(sv, start);
20693                     start++;
20694                 }
20695                 continue;
20696             }
20697         } /* End of looking for literals */
20698
20699         /* Here is not to output as a literal.  Some control characters have
20700          * mnemonic names.  Split off any of those at the beginning and end of
20701          * the range to print mnemonically.  It isn't possible for many of
20702          * these to be in a row, so this won't overwhelm with output */
20703         if (   start <= end
20704             && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
20705         {
20706             while (isMNEMONIC_CNTRL(start) && start <= end) {
20707                 put_code_point(sv, start);
20708                 start++;
20709             }
20710
20711             /* If this didn't take care of the whole range ... */
20712             if (start <= end) {
20713
20714                 /* Look backwards from the end to find the final non-mnemonic
20715                  * */
20716                 UV temp_end = end;
20717                 while (isMNEMONIC_CNTRL(temp_end)) {
20718                     temp_end--;
20719                 }
20720
20721                 /* And separately output the interior range that doesn't start
20722                  * or end with mnemonics */
20723                 put_range(sv, start, temp_end, FALSE);
20724
20725                 /* Then output the mnemonic trailing controls */
20726                 start = temp_end + 1;
20727                 while (start <= end) {
20728                     put_code_point(sv, start);
20729                     start++;
20730                 }
20731                 break;
20732             }
20733         }
20734
20735         /* As a final resort, output the range or subrange as hex. */
20736
20737         this_end = (end < NUM_ANYOF_CODE_POINTS)
20738                     ? end
20739                     : NUM_ANYOF_CODE_POINTS - 1;
20740 #if NUM_ANYOF_CODE_POINTS > 256
20741         format = (this_end < 256)
20742                  ? "\\x%02" UVXf "-\\x%02" UVXf
20743                  : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
20744 #else
20745         format = "\\x%02" UVXf "-\\x%02" UVXf;
20746 #endif
20747         GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
20748         Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
20749         GCC_DIAG_RESTORE_STMT;
20750         break;
20751     }
20752 }
20753
20754 STATIC void
20755 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
20756 {
20757     /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
20758      * 'invlist' */
20759
20760     UV start, end;
20761     bool allow_literals = TRUE;
20762
20763     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
20764
20765     /* Generally, it is more readable if printable characters are output as
20766      * literals, but if a range (nearly) spans all of them, it's best to output
20767      * it as a single range.  This code will use a single range if all but 2
20768      * ASCII printables are in it */
20769     invlist_iterinit(invlist);
20770     while (invlist_iternext(invlist, &start, &end)) {
20771
20772         /* If the range starts beyond the final printable, it doesn't have any
20773          * in it */
20774         if (start > MAX_PRINT_A) {
20775             break;
20776         }
20777
20778         /* In both ASCII and EBCDIC, a SPACE is the lowest printable.  To span
20779          * all but two, the range must start and end no later than 2 from
20780          * either end */
20781         if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
20782             if (end > MAX_PRINT_A) {
20783                 end = MAX_PRINT_A;
20784             }
20785             if (start < ' ') {
20786                 start = ' ';
20787             }
20788             if (end - start >= MAX_PRINT_A - ' ' - 2) {
20789                 allow_literals = FALSE;
20790             }
20791             break;
20792         }
20793     }
20794     invlist_iterfinish(invlist);
20795
20796     /* Here we have figured things out.  Output each range */
20797     invlist_iterinit(invlist);
20798     while (invlist_iternext(invlist, &start, &end)) {
20799         if (start >= NUM_ANYOF_CODE_POINTS) {
20800             break;
20801         }
20802         put_range(sv, start, end, allow_literals);
20803     }
20804     invlist_iterfinish(invlist);
20805
20806     return;
20807 }
20808
20809 STATIC SV*
20810 S_put_charclass_bitmap_innards_common(pTHX_
20811         SV* invlist,            /* The bitmap */
20812         SV* posixes,            /* Under /l, things like [:word:], \S */
20813         SV* only_utf8,          /* Under /d, matches iff the target is UTF-8 */
20814         SV* not_utf8,           /* /d, matches iff the target isn't UTF-8 */
20815         SV* only_utf8_locale,   /* Under /l, matches if the locale is UTF-8 */
20816         const bool invert       /* Is the result to be inverted? */
20817 )
20818 {
20819     /* Create and return an SV containing a displayable version of the bitmap
20820      * and associated information determined by the input parameters.  If the
20821      * output would have been only the inversion indicator '^', NULL is instead
20822      * returned. */
20823
20824     SV * output;
20825
20826     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
20827
20828     if (invert) {
20829         output = newSVpvs("^");
20830     }
20831     else {
20832         output = newSVpvs("");
20833     }
20834
20835     /* First, the code points in the bitmap that are unconditionally there */
20836     put_charclass_bitmap_innards_invlist(output, invlist);
20837
20838     /* Traditionally, these have been placed after the main code points */
20839     if (posixes) {
20840         sv_catsv(output, posixes);
20841     }
20842
20843     if (only_utf8 && _invlist_len(only_utf8)) {
20844         Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
20845         put_charclass_bitmap_innards_invlist(output, only_utf8);
20846     }
20847
20848     if (not_utf8 && _invlist_len(not_utf8)) {
20849         Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
20850         put_charclass_bitmap_innards_invlist(output, not_utf8);
20851     }
20852
20853     if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
20854         Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
20855         put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
20856
20857         /* This is the only list in this routine that can legally contain code
20858          * points outside the bitmap range.  The call just above to
20859          * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
20860          * output them here.  There's about a half-dozen possible, and none in
20861          * contiguous ranges longer than 2 */
20862         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
20863             UV start, end;
20864             SV* above_bitmap = NULL;
20865
20866             _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
20867
20868             invlist_iterinit(above_bitmap);
20869             while (invlist_iternext(above_bitmap, &start, &end)) {
20870                 UV i;
20871
20872                 for (i = start; i <= end; i++) {
20873                     put_code_point(output, i);
20874                 }
20875             }
20876             invlist_iterfinish(above_bitmap);
20877             SvREFCNT_dec_NN(above_bitmap);
20878         }
20879     }
20880
20881     if (invert && SvCUR(output) == 1) {
20882         return NULL;
20883     }
20884
20885     return output;
20886 }
20887
20888 STATIC bool
20889 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
20890                                      char *bitmap,
20891                                      SV *nonbitmap_invlist,
20892                                      SV *only_utf8_locale_invlist,
20893                                      const regnode * const node,
20894                                      const bool force_as_is_display)
20895 {
20896     /* Appends to 'sv' a displayable version of the innards of the bracketed
20897      * character class defined by the other arguments:
20898      *  'bitmap' points to the bitmap, or NULL if to ignore that.
20899      *  'nonbitmap_invlist' is an inversion list of the code points that are in
20900      *      the bitmap range, but for some reason aren't in the bitmap; NULL if
20901      *      none.  The reasons for this could be that they require some
20902      *      condition such as the target string being or not being in UTF-8
20903      *      (under /d), or because they came from a user-defined property that
20904      *      was not resolved at the time of the regex compilation (under /u)
20905      *  'only_utf8_locale_invlist' is an inversion list of the code points that
20906      *      are valid only if the runtime locale is a UTF-8 one; NULL if none
20907      *  'node' is the regex pattern ANYOF node.  It is needed only when the
20908      *      above two parameters are not null, and is passed so that this
20909      *      routine can tease apart the various reasons for them.
20910      *  'force_as_is_display' is TRUE if this routine should definitely NOT try
20911      *      to invert things to see if that leads to a cleaner display.  If
20912      *      FALSE, this routine is free to use its judgment about doing this.
20913      *
20914      * It returns TRUE if there was actually something output.  (It may be that
20915      * the bitmap, etc is empty.)
20916      *
20917      * When called for outputting the bitmap of a non-ANYOF node, just pass the
20918      * bitmap, with the succeeding parameters set to NULL, and the final one to
20919      * FALSE.
20920      */
20921
20922     /* In general, it tries to display the 'cleanest' representation of the
20923      * innards, choosing whether to display them inverted or not, regardless of
20924      * whether the class itself is to be inverted.  However,  there are some
20925      * cases where it can't try inverting, as what actually matches isn't known
20926      * until runtime, and hence the inversion isn't either. */
20927     bool inverting_allowed = ! force_as_is_display;
20928
20929     int i;
20930     STRLEN orig_sv_cur = SvCUR(sv);
20931
20932     SV* invlist;            /* Inversion list we accumulate of code points that
20933                                are unconditionally matched */
20934     SV* only_utf8 = NULL;   /* Under /d, list of matches iff the target is
20935                                UTF-8 */
20936     SV* not_utf8 =  NULL;   /* /d, list of matches iff the target isn't UTF-8
20937                              */
20938     SV* posixes = NULL;     /* Under /l, string of things like [:word:], \D */
20939     SV* only_utf8_locale = NULL;    /* Under /l, list of matches if the locale
20940                                        is UTF-8 */
20941
20942     SV* as_is_display;      /* The output string when we take the inputs
20943                                literally */
20944     SV* inverted_display;   /* The output string when we invert the inputs */
20945
20946     U8 flags = (node) ? ANYOF_FLAGS(node) : 0;
20947
20948     bool invert = cBOOL(flags & ANYOF_INVERT);  /* Is the input to be inverted
20949                                                    to match? */
20950     /* We are biased in favor of displaying things without them being inverted,
20951      * as that is generally easier to understand */
20952     const int bias = 5;
20953
20954     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
20955
20956     /* Start off with whatever code points are passed in.  (We clone, so we
20957      * don't change the caller's list) */
20958     if (nonbitmap_invlist) {
20959         assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
20960         invlist = invlist_clone(nonbitmap_invlist, NULL);
20961     }
20962     else {  /* Worst case size is every other code point is matched */
20963         invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
20964     }
20965
20966     if (flags) {
20967         if (OP(node) == ANYOFD) {
20968
20969             /* This flag indicates that the code points below 0x100 in the
20970              * nonbitmap list are precisely the ones that match only when the
20971              * target is UTF-8 (they should all be non-ASCII). */
20972             if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
20973             {
20974                 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
20975                 _invlist_subtract(invlist, only_utf8, &invlist);
20976             }
20977
20978             /* And this flag for matching all non-ASCII 0xFF and below */
20979             if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
20980             {
20981                 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
20982             }
20983         }
20984         else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
20985
20986             /* If either of these flags are set, what matches isn't
20987              * determinable except during execution, so don't know enough here
20988              * to invert */
20989             if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
20990                 inverting_allowed = FALSE;
20991             }
20992
20993             /* What the posix classes match also varies at runtime, so these
20994              * will be output symbolically. */
20995             if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
20996                 int i;
20997
20998                 posixes = newSVpvs("");
20999                 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
21000                     if (ANYOF_POSIXL_TEST(node, i)) {
21001                         sv_catpv(posixes, anyofs[i]);
21002                     }
21003                 }
21004             }
21005         }
21006     }
21007
21008     /* Accumulate the bit map into the unconditional match list */
21009     if (bitmap) {
21010         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
21011             if (BITMAP_TEST(bitmap, i)) {
21012                 int start = i++;
21013                 for (;
21014                      i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
21015                      i++)
21016                 { /* empty */ }
21017                 invlist = _add_range_to_invlist(invlist, start, i-1);
21018             }
21019         }
21020     }
21021
21022     /* Make sure that the conditional match lists don't have anything in them
21023      * that match unconditionally; otherwise the output is quite confusing.
21024      * This could happen if the code that populates these misses some
21025      * duplication. */
21026     if (only_utf8) {
21027         _invlist_subtract(only_utf8, invlist, &only_utf8);
21028     }
21029     if (not_utf8) {
21030         _invlist_subtract(not_utf8, invlist, &not_utf8);
21031     }
21032
21033     if (only_utf8_locale_invlist) {
21034
21035         /* Since this list is passed in, we have to make a copy before
21036          * modifying it */
21037         only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
21038
21039         _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
21040
21041         /* And, it can get really weird for us to try outputting an inverted
21042          * form of this list when it has things above the bitmap, so don't even
21043          * try */
21044         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
21045             inverting_allowed = FALSE;
21046         }
21047     }
21048
21049     /* Calculate what the output would be if we take the input as-is */
21050     as_is_display = put_charclass_bitmap_innards_common(invlist,
21051                                                     posixes,
21052                                                     only_utf8,
21053                                                     not_utf8,
21054                                                     only_utf8_locale,
21055                                                     invert);
21056
21057     /* If have to take the output as-is, just do that */
21058     if (! inverting_allowed) {
21059         if (as_is_display) {
21060             sv_catsv(sv, as_is_display);
21061             SvREFCNT_dec_NN(as_is_display);
21062         }
21063     }
21064     else { /* But otherwise, create the output again on the inverted input, and
21065               use whichever version is shorter */
21066
21067         int inverted_bias, as_is_bias;
21068
21069         /* We will apply our bias to whichever of the the results doesn't have
21070          * the '^' */
21071         if (invert) {
21072             invert = FALSE;
21073             as_is_bias = bias;
21074             inverted_bias = 0;
21075         }
21076         else {
21077             invert = TRUE;
21078             as_is_bias = 0;
21079             inverted_bias = bias;
21080         }
21081
21082         /* Now invert each of the lists that contribute to the output,
21083          * excluding from the result things outside the possible range */
21084
21085         /* For the unconditional inversion list, we have to add in all the
21086          * conditional code points, so that when inverted, they will be gone
21087          * from it */
21088         _invlist_union(only_utf8, invlist, &invlist);
21089         _invlist_union(not_utf8, invlist, &invlist);
21090         _invlist_union(only_utf8_locale, invlist, &invlist);
21091         _invlist_invert(invlist);
21092         _invlist_intersection(invlist, PL_InBitmap, &invlist);
21093
21094         if (only_utf8) {
21095             _invlist_invert(only_utf8);
21096             _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
21097         }
21098         else if (not_utf8) {
21099
21100             /* If a code point matches iff the target string is not in UTF-8,
21101              * then complementing the result has it not match iff not in UTF-8,
21102              * which is the same thing as matching iff it is UTF-8. */
21103             only_utf8 = not_utf8;
21104             not_utf8 = NULL;
21105         }
21106
21107         if (only_utf8_locale) {
21108             _invlist_invert(only_utf8_locale);
21109             _invlist_intersection(only_utf8_locale,
21110                                   PL_InBitmap,
21111                                   &only_utf8_locale);
21112         }
21113
21114         inverted_display = put_charclass_bitmap_innards_common(
21115                                             invlist,
21116                                             posixes,
21117                                             only_utf8,
21118                                             not_utf8,
21119                                             only_utf8_locale, invert);
21120
21121         /* Use the shortest representation, taking into account our bias
21122          * against showing it inverted */
21123         if (   inverted_display
21124             && (   ! as_is_display
21125                 || (  SvCUR(inverted_display) + inverted_bias
21126                     < SvCUR(as_is_display)    + as_is_bias)))
21127         {
21128             sv_catsv(sv, inverted_display);
21129         }
21130         else if (as_is_display) {
21131             sv_catsv(sv, as_is_display);
21132         }
21133
21134         SvREFCNT_dec(as_is_display);
21135         SvREFCNT_dec(inverted_display);
21136     }
21137
21138     SvREFCNT_dec_NN(invlist);
21139     SvREFCNT_dec(only_utf8);
21140     SvREFCNT_dec(not_utf8);
21141     SvREFCNT_dec(posixes);
21142     SvREFCNT_dec(only_utf8_locale);
21143
21144     return SvCUR(sv) > orig_sv_cur;
21145 }
21146
21147 #define CLEAR_OPTSTART                                                       \
21148     if (optstart) STMT_START {                                               \
21149         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_                                           \
21150                               " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
21151         optstart=NULL;                                                       \
21152     } STMT_END
21153
21154 #define DUMPUNTIL(b,e)                                                       \
21155                     CLEAR_OPTSTART;                                          \
21156                     node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
21157
21158 STATIC const regnode *
21159 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
21160             const regnode *last, const regnode *plast,
21161             SV* sv, I32 indent, U32 depth)
21162 {
21163     U8 op = PSEUDO;     /* Arbitrary non-END op. */
21164     const regnode *next;
21165     const regnode *optstart= NULL;
21166
21167     RXi_GET_DECL(r, ri);
21168     GET_RE_DEBUG_FLAGS_DECL;
21169
21170     PERL_ARGS_ASSERT_DUMPUNTIL;
21171
21172 #ifdef DEBUG_DUMPUNTIL
21173     Perl_re_printf( aTHX_  "--- %d : %d - %d - %d\n", indent, node-start,
21174         last ? last-start : 0, plast ? plast-start : 0);
21175 #endif
21176
21177     if (plast && plast < last)
21178         last= plast;
21179
21180     while (PL_regkind[op] != END && (!last || node < last)) {
21181         assert(node);
21182         /* While that wasn't END last time... */
21183         NODE_ALIGN(node);
21184         op = OP(node);
21185         if (op == CLOSE || op == SRCLOSE || op == WHILEM)
21186             indent--;
21187         next = regnext((regnode *)node);
21188
21189         /* Where, what. */
21190         if (OP(node) == OPTIMIZED) {
21191             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
21192                 optstart = node;
21193             else
21194                 goto after_print;
21195         } else
21196             CLEAR_OPTSTART;
21197
21198         regprop(r, sv, node, NULL, NULL);
21199         Perl_re_printf( aTHX_  "%4" IVdf ":%*s%s", (IV)(node - start),
21200                       (int)(2*indent + 1), "", SvPVX_const(sv));
21201
21202         if (OP(node) != OPTIMIZED) {
21203             if (next == NULL)           /* Next ptr. */
21204                 Perl_re_printf( aTHX_  " (0)");
21205             else if (PL_regkind[(U8)op] == BRANCH
21206                      && PL_regkind[OP(next)] != BRANCH )
21207                 Perl_re_printf( aTHX_  " (FAIL)");
21208             else
21209                 Perl_re_printf( aTHX_  " (%" IVdf ")", (IV)(next - start));
21210             Perl_re_printf( aTHX_ "\n");
21211         }
21212
21213       after_print:
21214         if (PL_regkind[(U8)op] == BRANCHJ) {
21215             assert(next);
21216             {
21217                 const regnode *nnode = (OP(next) == LONGJMP
21218                                        ? regnext((regnode *)next)
21219                                        : next);
21220                 if (last && nnode > last)
21221                     nnode = last;
21222                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
21223             }
21224         }
21225         else if (PL_regkind[(U8)op] == BRANCH) {
21226             assert(next);
21227             DUMPUNTIL(NEXTOPER(node), next);
21228         }
21229         else if ( PL_regkind[(U8)op]  == TRIE ) {
21230             const regnode *this_trie = node;
21231             const char op = OP(node);
21232             const U32 n = ARG(node);
21233             const reg_ac_data * const ac = op>=AHOCORASICK ?
21234                (reg_ac_data *)ri->data->data[n] :
21235                NULL;
21236             const reg_trie_data * const trie =
21237                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
21238 #ifdef DEBUGGING
21239             AV *const trie_words
21240                            = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
21241 #endif
21242             const regnode *nextbranch= NULL;
21243             I32 word_idx;
21244             SvPVCLEAR(sv);
21245             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
21246                 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
21247
21248                 Perl_re_indentf( aTHX_  "%s ",
21249                     indent+3,
21250                     elem_ptr
21251                     ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
21252                                 SvCUR(*elem_ptr), PL_dump_re_max_len,
21253                                 PL_colors[0], PL_colors[1],
21254                                 (SvUTF8(*elem_ptr)
21255                                  ? PERL_PV_ESCAPE_UNI
21256                                  : 0)
21257                                 | PERL_PV_PRETTY_ELLIPSES
21258                                 | PERL_PV_PRETTY_LTGT
21259                             )
21260                     : "???"
21261                 );
21262                 if (trie->jump) {
21263                     U16 dist= trie->jump[word_idx+1];
21264                     Perl_re_printf( aTHX_  "(%" UVuf ")\n",
21265                                (UV)((dist ? this_trie + dist : next) - start));
21266                     if (dist) {
21267                         if (!nextbranch)
21268                             nextbranch= this_trie + trie->jump[0];
21269                         DUMPUNTIL(this_trie + dist, nextbranch);
21270                     }
21271                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
21272                         nextbranch= regnext((regnode *)nextbranch);
21273                 } else {
21274                     Perl_re_printf( aTHX_  "\n");
21275                 }
21276             }
21277             if (last && next > last)
21278                 node= last;
21279             else
21280                 node= next;
21281         }
21282         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
21283             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
21284                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
21285         }
21286         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
21287             assert(next);
21288             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
21289         }
21290         else if ( op == PLUS || op == STAR) {
21291             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
21292         }
21293         else if (PL_regkind[(U8)op] == EXACT) {
21294             /* Literal string, where present. */
21295             node += NODE_SZ_STR(node) - 1;
21296             node = NEXTOPER(node);
21297         }
21298         else {
21299             node = NEXTOPER(node);
21300             node += regarglen[(U8)op];
21301         }
21302         if (op == CURLYX || op == OPEN || op == SROPEN)
21303             indent++;
21304     }
21305     CLEAR_OPTSTART;
21306 #ifdef DEBUG_DUMPUNTIL
21307     Perl_re_printf( aTHX_  "--- %d\n", (int)indent);
21308 #endif
21309     return node;
21310 }
21311
21312 #endif  /* DEBUGGING */
21313
21314 #ifndef PERL_IN_XSUB_RE
21315
21316 #include "uni_keywords.h"
21317
21318 void
21319 Perl_init_uniprops(pTHX)
21320 {
21321     /* Set up the inversion list global variables */
21322
21323     PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
21324     PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
21325     PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
21326     PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
21327     PL_XPosix_ptrs[_CC_CASED] =  _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
21328     PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
21329     PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
21330     PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
21331     PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
21332     PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
21333     PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
21334     PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
21335     PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
21336     PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
21337     PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
21338     PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
21339
21340     PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
21341     PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
21342     PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
21343     PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
21344     PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
21345     PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
21346     PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
21347     PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
21348     PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
21349     PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
21350     PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
21351     PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
21352     PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
21353     PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
21354     PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
21355     PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
21356
21357     PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
21358     PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
21359     PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
21360     PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
21361     PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
21362
21363     PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
21364     PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
21365     PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
21366
21367     PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
21368
21369     PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
21370     PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
21371
21372     PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
21373     PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
21374
21375     PL_utf8_foldable = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
21376     PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
21377                                             UNI__PERL_FOLDS_TO_MULTI_CHAR]);
21378     PL_NonL1NonFinalFold = _new_invlist_C_array(
21379                                             NonL1_Perl_Non_Final_Folds_invlist);
21380
21381     PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
21382     PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
21383     PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
21384     PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
21385     PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
21386     PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
21387     PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
21388
21389     /* The below are used only by deprecated functions.  They could be removed */
21390     PL_utf8_xidcont  = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
21391     PL_utf8_idcont   = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
21392     PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
21393 }
21394
21395 SV *
21396 Perl_parse_uniprop_string(pTHX_ const char * const name, const Size_t name_len,
21397                                 const bool to_fold, bool * invert)
21398 {
21399     /* Parse the interior meat of \p{} passed to this in 'name' with length
21400      * 'name_len', and return an inversion list if a property with 'name' is
21401      * found, or NULL if not.  'name' point to the input with leading and
21402      * trailing space trimmed.  'to_fold' indicates if /i is in effect.
21403      *
21404      * When the return is an inversion list, '*invert' will be set to a boolean
21405      * indicating if it should be inverted or not
21406      *
21407      * This currently doesn't handle all cases.  A NULL return indicates the
21408      * caller should try a different approach
21409      */
21410
21411     char* lookup_name;
21412     bool stricter = FALSE;
21413     bool is_nv_type = FALSE;         /* nv= or numeric_value=, or possibly one
21414                                         of the cjk numeric properties (though
21415                                         it requires extra effort to compile
21416                                         them) */
21417     unsigned int i;
21418     unsigned int j = 0, lookup_len;
21419     int equals_pos = -1;        /* Where the '=' is found, or negative if none */
21420     int slash_pos = -1;        /* Where the '/' is found, or negative if none */
21421     int table_index = 0;
21422     bool starts_with_In_or_Is = FALSE;
21423     Size_t lookup_offset = 0;
21424
21425     PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
21426
21427     /* The input will be modified into 'lookup_name' */
21428     Newx(lookup_name, name_len, char);
21429     SAVEFREEPV(lookup_name);
21430
21431     /* Parse the input. */
21432     for (i = 0; i < name_len; i++) {
21433         char cur = name[i];
21434
21435         /* These characters can be freely ignored in most situations.  Later it
21436          * may turn out we shouldn't have ignored them, and we have to reparse,
21437          * but we don't have enough information yet to make that decision */
21438         if (cur == '-' || cur == '_' || isSPACE_A(cur)) {
21439             continue;
21440         }
21441
21442         /* Case differences are also ignored.  Our lookup routine assumes
21443          * everything is lowercase */
21444         if (isUPPER_A(cur)) {
21445             lookup_name[j++] = toLOWER(cur);
21446             continue;
21447         }
21448
21449         /* A double colon is either an error, or a package qualifier to a
21450          * subroutine user-defined property; neither of which do we currently
21451          * handle
21452          *
21453          * But a single colon is a synonym for '=' */
21454         if (cur == ':') {
21455             if (i < name_len - 1 && name[i+1] == ':') {
21456                 return NULL;
21457             }
21458             cur = '=';
21459         }
21460
21461         /* Otherwise, this character is part of the name. */
21462         lookup_name[j++] = cur;
21463
21464         /* Only the equals sign needs further processing */
21465         if (cur == '=') {
21466             equals_pos = j; /* Note where it occurred in the input */
21467             break;
21468         }
21469     }
21470
21471     /* Here, we are either done with the whole property name, if it was simple;
21472      * or are positioned just after the '=' if it is compound. */
21473
21474     if (equals_pos >= 0) {
21475         assert(! stricter); /* We shouldn't have set this yet */
21476
21477         /* Space immediately after the '=' is ignored */
21478         i++;
21479         for (; i < name_len; i++) {
21480             if (! isSPACE_A(name[i])) {
21481                 break;
21482             }
21483         }
21484
21485         /* Certain properties need special handling.  They may optionally be
21486          * prefixed by 'is'.  Ignore that prefix for the purposes of checking
21487          * if this is one of those properties */
21488         if (memBEGINPs(lookup_name, name_len, "is")) {
21489             lookup_offset = 2;
21490         }
21491
21492         /* Then check if it is one of these properties.  This is hard-coded
21493          * because easier this way, and the list is unlikely to change.  There
21494          * are several properties like this in the Unihan DB, which is unlikely
21495          * to be compiled, and they all end with 'numeric'.  The interiors
21496          * aren't checked for the precise property.  This would stop working if
21497          * a cjk property were to be created that ended with 'numeric' and
21498          * wasn't a numeric type */
21499         is_nv_type = memEQs(lookup_name + lookup_offset,
21500                        j - 1 - lookup_offset, "numericvalue")
21501                   || memEQs(lookup_name + lookup_offset,
21502                       j - 1 - lookup_offset, "nv")
21503                   || (   memENDPs(lookup_name + lookup_offset,
21504                             j - 1 - lookup_offset, "numeric")
21505                       && (   memBEGINPs(lookup_name + lookup_offset,
21506                                       j - 1 - lookup_offset, "cjk")
21507                           || memBEGINPs(lookup_name + lookup_offset,
21508                                       j - 1 - lookup_offset, "k")));
21509         if (   is_nv_type
21510             || memEQs(lookup_name + lookup_offset,
21511                       j - 1 - lookup_offset, "canonicalcombiningclass")
21512             || memEQs(lookup_name + lookup_offset,
21513                       j - 1 - lookup_offset, "ccc")
21514             || memEQs(lookup_name + lookup_offset,
21515                       j - 1 - lookup_offset, "age")
21516             || memEQs(lookup_name + lookup_offset,
21517                       j - 1 - lookup_offset, "in")
21518             || memEQs(lookup_name + lookup_offset,
21519                       j - 1 - lookup_offset, "presentin"))
21520         {
21521             unsigned int k;
21522
21523             /* What makes these properties special is that the stuff after the
21524              * '=' is a number.  Therefore, we can't throw away '-'
21525              * willy-nilly, as those could be a minus sign.  Other stricter
21526              * rules also apply.  However, these properties all can have the
21527              * rhs not be a number, in which case they contain at least one
21528              * alphabetic.  In those cases, the stricter rules don't apply.
21529              * But the numeric type properties can have the alphas [Ee] to
21530              * signify an exponent, and it is still a number with stricter
21531              * rules.  So look for an alpha that signifys not-strict */
21532             stricter = TRUE;
21533             for (k = i; k < name_len; k++) {
21534                 if (   isALPHA_A(name[k])
21535                     && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
21536                 {
21537                     stricter = FALSE;
21538                     break;
21539                 }
21540             }
21541         }
21542
21543         if (stricter) {
21544
21545             /* A number may have a leading '+' or '-'.  The latter is retained
21546              * */
21547             if (name[i] == '+') {
21548                 i++;
21549             }
21550             else if (name[i] == '-') {
21551                 lookup_name[j++] = '-';
21552                 i++;
21553             }
21554
21555             /* Skip leading zeros including single underscores separating the
21556              * zeros, or between the final leading zero and the first other
21557              * digit */
21558             for (; i < name_len - 1; i++) {
21559                 if (   name[i] != '0'
21560                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
21561                 {
21562                     break;
21563                 }
21564             }
21565         }
21566     }
21567     else {  /* No '=' */
21568
21569        /* We are now in a position to determine if this property should have
21570         * been parsed using stricter rules.  Only a few are like that, and
21571         * unlikely to change. */
21572         if (   memBEGINPs(lookup_name, j, "perl")
21573             && memNEs(lookup_name + 4, j - 4, "space")
21574             && memNEs(lookup_name + 4, j - 4, "word"))
21575         {
21576             stricter = TRUE;
21577
21578             /* We set the inputs back to 0 and the code below will reparse,
21579              * using strict */
21580             i = j = 0;
21581         }
21582     }
21583
21584     /* Here, we have either finished the property, or are positioned to parse
21585      * the remainder, and we know if stricter rules apply.  Finish out, if not
21586      * already done */
21587     for (; i < name_len; i++) {
21588         char cur = name[i];
21589
21590         /* In all instances, case differences are ignored, and we normalize to
21591          * lowercase */
21592         if (isUPPER_A(cur)) {
21593             lookup_name[j++] = toLOWER(cur);
21594             continue;
21595         }
21596
21597         /* An underscore is skipped, but not under strict rules unless it
21598          * separates two digits */
21599         if (cur == '_') {
21600             if (    stricter
21601                 && (     i == 0 || (int) i == equals_pos || i == name_len- 1
21602                     || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
21603             {
21604                 lookup_name[j++] = '_';
21605             }
21606             continue;
21607         }
21608
21609         /* Hyphens are skipped except under strict */
21610         if (cur == '-' && ! stricter) {
21611             continue;
21612         }
21613
21614         /* XXX Bug in documentation.  It says white space skipped adjacent to
21615          * non-word char.  Maybe we should, but shouldn't skip it next to a dot
21616          * in a number */
21617         if (isSPACE_A(cur) && ! stricter) {
21618             continue;
21619         }
21620
21621         lookup_name[j++] = cur;
21622
21623         /* Unless this is a non-trailing slash, we are done with it */
21624         if (i >= name_len - 1 || cur != '/') {
21625             continue;
21626         }
21627
21628         slash_pos = j;
21629
21630         /* A slash in the 'numeric value' property indicates that what follows
21631          * is a denominator.  It can have a leading '+' and '0's that should be
21632          * skipped.  But we have never allowed a negative denominator, so treat
21633          * a minus like every other character.  (No need to rule out a second
21634          * '/', as that won't match anything anyway */
21635         if (is_nv_type) {
21636             i++;
21637             if (i < name_len && name[i] == '+') {
21638                 i++;
21639             }
21640
21641             /* Skip leading zeros including underscores separating digits */
21642             for (; i < name_len - 1; i++) {
21643                 if (   name[i] != '0'
21644                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
21645                 {
21646                     break;
21647                 }
21648             }
21649
21650             /* Store the first real character in the denominator */
21651             lookup_name[j++] = name[i];
21652         }
21653     }
21654
21655     /* Here are completely done parsing the input 'name', and 'lookup_name'
21656      * contains a copy, normalized.
21657      *
21658      * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
21659      * different from without the underscores.  */
21660     if (  (   UNLIKELY(memEQs(lookup_name, j, "l"))
21661            || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
21662         && UNLIKELY(name[name_len-1] == '_'))
21663     {
21664         lookup_name[j++] = '&';
21665     }
21666     else if (name_len > 2 && name[0] == 'I' && (   name[1] == 'n'
21667                                                 || name[1] == 's'))
21668     {
21669
21670         /* Also, if the original input began with 'In' or 'Is', it could be a
21671          * subroutine call instead of a property names, which currently isn't
21672          * handled by this function.  Subroutine calls can't happen if there is
21673          * an '=' in the name */
21674         if (equals_pos < 0 && get_cvn_flags(name, name_len, GV_NOTQUAL) != NULL)
21675         {
21676             return NULL;
21677         }
21678
21679         starts_with_In_or_Is = TRUE;
21680     }
21681
21682     lookup_len = j;     /* Use a more mnemonic name starting here */
21683
21684     /* Get the index into our pointer table of the inversion list corresponding
21685      * to the property */
21686     table_index = match_uniprop((U8 *) lookup_name, lookup_len);
21687
21688     /* If it didn't find the property */
21689     if (table_index == 0) {
21690
21691         /* If didn't find the property, we try again stripping off any initial
21692          * 'In' or 'Is' */
21693         if (starts_with_In_or_Is) {
21694             lookup_name += 2;
21695             lookup_len -= 2;
21696             equals_pos -= 2;
21697             slash_pos -= 2;
21698
21699             table_index = match_uniprop((U8 *) lookup_name, lookup_len);
21700         }
21701
21702         if (table_index == 0) {
21703             char * canonical;
21704
21705             /* If not found, and not a numeric type property, isn't a legal
21706              * property */
21707             if (! is_nv_type) {
21708                 return NULL;
21709             }
21710
21711             /* But the numeric type properties need more work to decide.  What
21712              * we do is make sure we have the number in canonical form and look
21713              * that up. */
21714
21715             if (slash_pos < 0) {    /* No slash */
21716
21717                 /* When it isn't a rational, take the input, convert it to a
21718                  * NV, then create a canonical string representation of that
21719                  * NV. */
21720
21721                 NV value;
21722
21723                 /* Get the value */
21724                 if (my_atof3(lookup_name + equals_pos, &value,
21725                              lookup_len - equals_pos)
21726                           != lookup_name + lookup_len)
21727                 {
21728                     return NULL;
21729                 }
21730
21731                 /* If the value is an integer, the canonical value is integral */
21732                 if (Perl_ceil(value) == value) {
21733                     canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
21734                                                 equals_pos, lookup_name, value);
21735                 }
21736                 else {  /* Otherwise, it is %e with a known precision */
21737                     char * exp_ptr;
21738
21739                     canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
21740                                                 equals_pos, lookup_name,
21741                                                 PL_E_FORMAT_PRECISION, value);
21742
21743                     /* The exponent generated is expecting two digits, whereas
21744                      * %e on some systems will generate three.  Remove leading
21745                      * zeros in excess of 2 from the exponent.  We start
21746                      * looking for them after the '=' */
21747                     exp_ptr = strchr(canonical + equals_pos, 'e');
21748                     if (exp_ptr) {
21749                         char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
21750                         SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
21751
21752                         assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
21753
21754                         if (excess_exponent_len > 0) {
21755                             SSize_t leading_zeros = strspn(cur_ptr, "0");
21756                             SSize_t excess_leading_zeros
21757                                     = MIN(leading_zeros, excess_exponent_len);
21758                             if (excess_leading_zeros > 0) {
21759                                 Move(cur_ptr + excess_leading_zeros,
21760                                      cur_ptr,
21761                                      strlen(cur_ptr) - excess_leading_zeros
21762                                        + 1,  /* Copy the NUL as well */
21763                                      char);
21764                             }
21765                         }
21766                     }
21767                 }
21768             }
21769             else {  /* Has a slash.  Create a rational in canonical form  */
21770                 UV numerator, denominator, gcd, trial;
21771                 const char * end_ptr;
21772                 const char * sign = "";
21773
21774                 /* We can't just find the numerator, denominator, and do the
21775                  * division, then use the method above, because that is
21776                  * inexact.  And the input could be a rational that is within
21777                  * epsilon (given our precision) of a valid rational, and would
21778                  * then incorrectly compare valid.
21779                  *
21780                  * We're only interested in the part after the '=' */
21781                 const char * this_lookup_name = lookup_name + equals_pos;
21782                 lookup_len -= equals_pos;
21783                 slash_pos -= equals_pos;
21784
21785                 /* Handle any leading minus */
21786                 if (this_lookup_name[0] == '-') {
21787                     sign = "-";
21788                     this_lookup_name++;
21789                     lookup_len--;
21790                     slash_pos--;
21791                 }
21792
21793                 /* Convert the numerator to numeric */
21794                 end_ptr = this_lookup_name + slash_pos;
21795                 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
21796                     return NULL;
21797                 }
21798
21799                 /* It better have included all characters before the slash */
21800                 if (*end_ptr != '/') {
21801                     return NULL;
21802                 }
21803
21804                 /* Set to look at just the denominator */
21805                 this_lookup_name += slash_pos;
21806                 lookup_len -= slash_pos;
21807                 end_ptr = this_lookup_name + lookup_len;
21808
21809                 /* Convert the denominator to numeric */
21810                 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
21811                     return NULL;
21812                 }
21813
21814                 /* It better be the rest of the characters, and don't divide by
21815                  * 0 */
21816                 if (   end_ptr != this_lookup_name + lookup_len
21817                     || denominator == 0)
21818                 {
21819                     return NULL;
21820                 }
21821
21822                 /* Get the greatest common denominator using
21823                    http://en.wikipedia.org/wiki/Euclidean_algorithm */
21824                 gcd = numerator;
21825                 trial = denominator;
21826                 while (trial != 0) {
21827                     UV temp = trial;
21828                     trial = gcd % trial;
21829                     gcd = temp;
21830                 }
21831
21832                 /* If already in lowest possible terms, we have already tried
21833                  * looking this up */
21834                 if (gcd == 1) {
21835                     return NULL;
21836                 }
21837
21838                 /* Reduce the rational, which should put it in canonical form.
21839                  * Then look it up */
21840                 numerator /= gcd;
21841                 denominator /= gcd;
21842
21843                 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
21844                         equals_pos, lookup_name, sign, numerator, denominator);
21845             }
21846
21847             /* Here, we have the number in canonical form.  Try that */
21848             table_index = match_uniprop((U8 *) canonical, strlen(canonical));
21849             if (table_index == 0) {
21850                 return NULL;
21851             }
21852         }
21853     }
21854
21855     /* The return is an index into a table of ptrs.  A negative return
21856      * signifies that the real index is the absolute value, but the result
21857      * needs to be inverted */
21858     if (table_index < 0) {
21859         *invert = TRUE;
21860         table_index = -table_index;
21861     }
21862     else {
21863         *invert = FALSE;
21864     }
21865
21866     /* Out-of band indices indicate a deprecated property.  The proper index is
21867      * modulo it with the table size.  And dividing by the table size yields
21868      * an offset into a table constructed to contain the corresponding warning
21869      * message */
21870     if (table_index > MAX_UNI_KEYWORD_INDEX) {
21871         Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
21872         table_index %= MAX_UNI_KEYWORD_INDEX;
21873         Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
21874                 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
21875                 (int) name_len, name, deprecated_property_msgs[warning_offset]);
21876     }
21877
21878     /* In a few properties, a different property is used under /i.  These are
21879      * unlikely to change, so are hard-coded here. */
21880     if (to_fold) {
21881         if (   table_index == UNI_XPOSIXUPPER
21882             || table_index == UNI_XPOSIXLOWER
21883             || table_index == UNI_TITLE)
21884         {
21885             table_index = UNI_CASED;
21886         }
21887         else if (   table_index == UNI_UPPERCASELETTER
21888                  || table_index == UNI_LOWERCASELETTER
21889 #  ifdef UNI_TITLECASELETTER   /* Missing from early Unicodes */
21890                  || table_index == UNI_TITLECASELETTER
21891 #  endif
21892         ) {
21893             table_index = UNI_CASEDLETTER;
21894         }
21895         else if (  table_index == UNI_POSIXUPPER
21896                 || table_index == UNI_POSIXLOWER)
21897         {
21898             table_index = UNI_POSIXALPHA;
21899         }
21900     }
21901
21902     /* Create and return the inversion list */
21903     return _new_invlist_C_array(uni_prop_ptrs[table_index]);
21904 }
21905
21906 #endif
21907
21908 /*
21909  * ex: set ts=8 sts=4 sw=4 et:
21910  */