This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
locale.c: Fix grammar in comment
[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 #define REG_COMP_C
78 #ifdef PERL_IN_XSUB_RE
79 #  include "re_comp.h"
80 EXTERN_C const struct regexp_engine my_reg_engine;
81 #else
82 #  include "regcomp.h"
83 #endif
84
85 #include "dquote_inline.h"
86 #include "invlist_inline.h"
87 #include "unicode_constants.h"
88
89 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
90  _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
91 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
92  _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
93 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
94 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
95
96 #ifndef STATIC
97 #define STATIC  static
98 #endif
99
100 /* this is a chain of data about sub patterns we are processing that
101    need to be handled separately/specially in study_chunk. Its so
102    we can simulate recursion without losing state.  */
103 struct scan_frame;
104 typedef struct scan_frame {
105     regnode *last_regnode;      /* last node to process in this frame */
106     regnode *next_regnode;      /* next node to process when last is reached */
107     U32 prev_recursed_depth;
108     I32 stopparen;              /* what stopparen do we use */
109
110     struct scan_frame *this_prev_frame; /* this previous frame */
111     struct scan_frame *prev_frame;      /* previous frame */
112     struct scan_frame *next_frame;      /* next frame */
113 } scan_frame;
114
115 /* Certain characters are output as a sequence with the first being a
116  * backslash. */
117 #define isBACKSLASHED_PUNCT(c)  strchr("-[]\\^", c)
118
119
120 struct RExC_state_t {
121     U32         flags;                  /* RXf_* are we folding, multilining? */
122     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
123     char        *precomp;               /* uncompiled string. */
124     char        *precomp_end;           /* pointer to end of uncompiled string. */
125     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
126     regexp      *rx;                    /* perl core regexp structure */
127     regexp_internal     *rxi;           /* internal data for regexp object
128                                            pprivate field */
129     char        *start;                 /* Start of input for compile */
130     char        *end;                   /* End of input for compile */
131     char        *parse;                 /* Input-scan pointer. */
132     char        *copy_start;            /* start of copy of input within
133                                            constructed parse string */
134     char        *copy_start_in_input;   /* Position in input string
135                                            corresponding to copy_start */
136     SSize_t     whilem_seen;            /* number of WHILEM in this expr */
137     regnode     *emit_start;            /* Start of emitted-code area */
138     regnode_offset emit;                /* Code-emit pointer */
139     I32         naughty;                /* How bad is this pattern? */
140     I32         sawback;                /* Did we see \1, ...? */
141     U32         seen;
142     SSize_t     size;                   /* Number of regnode equivalents in
143                                            pattern */
144
145     /* position beyond 'precomp' of the warning message furthest away from
146      * 'precomp'.  During the parse, no warnings are raised for any problems
147      * earlier in the parse than this position.  This works if warnings are
148      * raised the first time a given spot is parsed, and if only one
149      * independent warning is raised for any given spot */
150     Size_t      latest_warn_offset;
151
152     I32         npar;                   /* Capture buffer count so far in the
153                                            parse, (OPEN) plus one. ("par" 0 is
154                                            the whole pattern)*/
155     I32         total_par;              /* During initial parse, is either 0,
156                                            or -1; the latter indicating a
157                                            reparse is needed.  After that pass,
158                                            it is what 'npar' became after the
159                                            pass.  Hence, it being > 0 indicates
160                                            we are in a reparse situation */
161     I32         nestroot;               /* root parens we are in - used by
162                                            accept */
163     I32         seen_zerolen;
164     regnode_offset *open_parens;        /* offsets to open parens */
165     regnode_offset *close_parens;       /* offsets to close parens */
166     regnode     *end_op;                /* END node in program */
167     I32         utf8;           /* whether the pattern is utf8 or not */
168     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
169                                 /* XXX use this for future optimisation of case
170                                  * where pattern must be upgraded to utf8. */
171     I32         uni_semantics;  /* If a d charset modifier should use unicode
172                                    rules, even if the pattern is not in
173                                    utf8 */
174     HV          *paren_names;           /* Paren names */
175
176     regnode     **recurse;              /* Recurse regops */
177     I32         recurse_count;          /* Number of recurse regops we have generated */
178     U8          *study_chunk_recursed;  /* bitmap of which subs we have moved
179                                            through */
180     U32         study_chunk_recursed_bytes;  /* bytes in bitmap */
181     I32         in_lookbehind;
182     I32         contains_locale;
183     I32         override_recoding;
184 #ifdef EBCDIC
185     I32         recode_x_to_native;
186 #endif
187     I32         in_multi_char_class;
188     struct reg_code_blocks *code_blocks;/* positions of literal (?{})
189                                             within pattern */
190     int         code_index;             /* next code_blocks[] slot */
191     SSize_t     maxlen;                        /* mininum possible number of chars in string to match */
192     scan_frame *frame_head;
193     scan_frame *frame_last;
194     U32         frame_count;
195     AV         *warn_text;
196 #ifdef ADD_TO_REGEXEC
197     char        *starttry;              /* -Dr: where regtry was called. */
198 #define RExC_starttry   (pRExC_state->starttry)
199 #endif
200     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
201 #ifdef DEBUGGING
202     const char  *lastparse;
203     I32         lastnum;
204     AV          *paren_name_list;       /* idx -> name */
205     U32         study_chunk_recursed_count;
206     SV          *mysv1;
207     SV          *mysv2;
208
209 #define RExC_lastparse  (pRExC_state->lastparse)
210 #define RExC_lastnum    (pRExC_state->lastnum)
211 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
212 #define RExC_study_chunk_recursed_count    (pRExC_state->study_chunk_recursed_count)
213 #define RExC_mysv       (pRExC_state->mysv1)
214 #define RExC_mysv1      (pRExC_state->mysv1)
215 #define RExC_mysv2      (pRExC_state->mysv2)
216
217 #endif
218     bool        seen_d_op;
219     bool        strict;
220     bool        study_started;
221     bool        in_script_run;
222     bool        use_BRANCHJ;
223 };
224
225 #define RExC_flags      (pRExC_state->flags)
226 #define RExC_pm_flags   (pRExC_state->pm_flags)
227 #define RExC_precomp    (pRExC_state->precomp)
228 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
229 #define RExC_copy_start_in_constructed  (pRExC_state->copy_start)
230 #define RExC_precomp_end (pRExC_state->precomp_end)
231 #define RExC_rx_sv      (pRExC_state->rx_sv)
232 #define RExC_rx         (pRExC_state->rx)
233 #define RExC_rxi        (pRExC_state->rxi)
234 #define RExC_start      (pRExC_state->start)
235 #define RExC_end        (pRExC_state->end)
236 #define RExC_parse      (pRExC_state->parse)
237 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
238 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
239 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
240                                                    under /d from /u ? */
241
242
243 #ifdef RE_TRACK_PATTERN_OFFSETS
244 #  define RExC_offsets  (RExC_rxi->u.offsets) /* I am not like the
245                                                          others */
246 #endif
247 #define RExC_emit       (pRExC_state->emit)
248 #define RExC_emit_start (pRExC_state->emit_start)
249 #define RExC_sawback    (pRExC_state->sawback)
250 #define RExC_seen       (pRExC_state->seen)
251 #define RExC_size       (pRExC_state->size)
252 #define RExC_maxlen        (pRExC_state->maxlen)
253 #define RExC_npar       (pRExC_state->npar)
254 #define RExC_total_parens       (pRExC_state->total_par)
255 #define RExC_nestroot   (pRExC_state->nestroot)
256 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
257 #define RExC_utf8       (pRExC_state->utf8)
258 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
259 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
260 #define RExC_open_parens        (pRExC_state->open_parens)
261 #define RExC_close_parens       (pRExC_state->close_parens)
262 #define RExC_end_op     (pRExC_state->end_op)
263 #define RExC_paren_names        (pRExC_state->paren_names)
264 #define RExC_recurse    (pRExC_state->recurse)
265 #define RExC_recurse_count      (pRExC_state->recurse_count)
266 #define RExC_study_chunk_recursed        (pRExC_state->study_chunk_recursed)
267 #define RExC_study_chunk_recursed_bytes  \
268                                    (pRExC_state->study_chunk_recursed_bytes)
269 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
270 #define RExC_contains_locale    (pRExC_state->contains_locale)
271 #ifdef EBCDIC
272 #   define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
273 #endif
274 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
275 #define RExC_frame_head (pRExC_state->frame_head)
276 #define RExC_frame_last (pRExC_state->frame_last)
277 #define RExC_frame_count (pRExC_state->frame_count)
278 #define RExC_strict (pRExC_state->strict)
279 #define RExC_study_started      (pRExC_state->study_started)
280 #define RExC_warn_text (pRExC_state->warn_text)
281 #define RExC_in_script_run      (pRExC_state->in_script_run)
282 #define RExC_use_BRANCHJ        (pRExC_state->use_BRANCHJ)
283
284 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
285  * a flag to disable back-off on the fixed/floating substrings - if it's
286  * a high complexity pattern we assume the benefit of avoiding a full match
287  * is worth the cost of checking for the substrings even if they rarely help.
288  */
289 #define RExC_naughty    (pRExC_state->naughty)
290 #define TOO_NAUGHTY (10)
291 #define MARK_NAUGHTY(add) \
292     if (RExC_naughty < TOO_NAUGHTY) \
293         RExC_naughty += (add)
294 #define MARK_NAUGHTY_EXP(exp, add) \
295     if (RExC_naughty < TOO_NAUGHTY) \
296         RExC_naughty += RExC_naughty / (exp) + (add)
297
298 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
299 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
300         ((*s) == '{' && regcurly(s)))
301
302 /*
303  * Flags to be passed up and down.
304  */
305 #define WORST           0       /* Worst case. */
306 #define HASWIDTH        0x01    /* Known to not match null strings, could match
307                                    non-null ones. */
308
309 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
310  * character.  (There needs to be a case: in the switch statement in regexec.c
311  * for any node marked SIMPLE.)  Note that this is not the same thing as
312  * REGNODE_SIMPLE */
313 #define SIMPLE          0x02
314 #define SPSTART         0x04    /* Starts with * or + */
315 #define POSTPONED       0x08    /* (?1),(?&name), (??{...}) or similar */
316 #define TRYAGAIN        0x10    /* Weeded out a declaration. */
317 #define RESTART_PARSE   0x20    /* Need to redo the parse */
318 #define NEED_UTF8       0x40    /* In conjunction with RESTART_PARSE, need to
319                                    calcuate sizes as UTF-8 */
320
321 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
322
323 /* whether trie related optimizations are enabled */
324 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
325 #define TRIE_STUDY_OPT
326 #define FULL_TRIE_STUDY
327 #define TRIE_STCLASS
328 #endif
329
330
331
332 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
333 #define PBITVAL(paren) (1 << ((paren) & 7))
334 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
335 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
336 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
337
338 #define REQUIRE_UTF8(flagp) STMT_START {                                   \
339                                      if (!UTF) {                           \
340                                          *flagp = RESTART_PARSE|NEED_UTF8; \
341                                          return 0;                         \
342                                      }                                     \
343                              } STMT_END
344
345 /* Change from /d into /u rules, and restart the parse.  RExC_uni_semantics is
346  * a flag that indicates we need to override /d with /u as a result of
347  * something in the pattern.  It should only be used in regards to calling
348  * set_regex_charset() or get_regex_charse() */
349 #define REQUIRE_UNI_RULES(flagp, restart_retval)                            \
350     STMT_START {                                                            \
351             if (DEPENDS_SEMANTICS) {                                        \
352                 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);      \
353                 RExC_uni_semantics = 1;                                     \
354                 if (RExC_seen_d_op && LIKELY(RExC_total_parens >= 0)) {     \
355                     /* No need to restart the parse if we haven't seen      \
356                      * anything that differs between /u and /d, and no need \
357                      * to restart immediately if we're going to reparse     \
358                      * anyway to count parens */                            \
359                     *flagp |= RESTART_PARSE;                                \
360                     return restart_retval;                                  \
361                 }                                                           \
362             }                                                               \
363     } STMT_END
364
365 #define BRANCH_MAX_OFFSET   U16_MAX
366 #define REQUIRE_BRANCHJ(flagp, restart_retval)                              \
367     STMT_START {                                                            \
368                 RExC_use_BRANCHJ = 1;                                       \
369                 if (LIKELY(RExC_total_parens >= 0)) {                       \
370                     /* No need to restart the parse immediately if we're    \
371                      * going to reparse anyway to count parens */           \
372                     *flagp |= RESTART_PARSE;                                \
373                     return restart_retval;                                  \
374                 }                                                           \
375     } STMT_END
376
377 #define REQUIRE_PARENS_PASS                                                 \
378     STMT_START {                                                            \
379                     if (RExC_total_parens == 0) RExC_total_parens = -1;     \
380     } STMT_END
381
382 /* This is used to return failure (zero) early from the calling function if
383  * various flags in 'flags' are set.  Two flags always cause a return:
384  * 'RESTART_PARSE' and 'NEED_UTF8'.   'extra' can be used to specify any
385  * additional flags that should cause a return; 0 if none.  If the return will
386  * be done, '*flagp' is first set to be all of the flags that caused the
387  * return. */
388 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra)                  \
389     STMT_START {                                                            \
390             if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) {              \
391                 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra));     \
392                 return 0;                                                   \
393             }                                                               \
394     } STMT_END
395
396 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
397
398 #define RETURN_FAIL_ON_RESTART(flags,flagp)                                 \
399                         RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
400 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp)                                 \
401                                     if (MUST_RESTART(*(flagp))) return 0
402
403 /* This converts the named class defined in regcomp.h to its equivalent class
404  * number defined in handy.h. */
405 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
406 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
407
408 #define _invlist_union_complement_2nd(a, b, output) \
409                         _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
410 #define _invlist_intersection_complement_2nd(a, b, output) \
411                  _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
412
413 /* About scan_data_t.
414
415   During optimisation we recurse through the regexp program performing
416   various inplace (keyhole style) optimisations. In addition study_chunk
417   and scan_commit populate this data structure with information about
418   what strings MUST appear in the pattern. We look for the longest
419   string that must appear at a fixed location, and we look for the
420   longest string that may appear at a floating location. So for instance
421   in the pattern:
422
423     /FOO[xX]A.*B[xX]BAR/
424
425   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
426   strings (because they follow a .* construct). study_chunk will identify
427   both FOO and BAR as being the longest fixed and floating strings respectively.
428
429   The strings can be composites, for instance
430
431      /(f)(o)(o)/
432
433   will result in a composite fixed substring 'foo'.
434
435   For each string some basic information is maintained:
436
437   - min_offset
438     This is the position the string must appear at, or not before.
439     It also implicitly (when combined with minlenp) tells us how many
440     characters must match before the string we are searching for.
441     Likewise when combined with minlenp and the length of the string it
442     tells us how many characters must appear after the string we have
443     found.
444
445   - max_offset
446     Only used for floating strings. This is the rightmost point that
447     the string can appear at. If set to SSize_t_MAX it indicates that the
448     string can occur infinitely far to the right.
449     For fixed strings, it is equal to min_offset.
450
451   - minlenp
452     A pointer to the minimum number of characters of the pattern that the
453     string was found inside. This is important as in the case of positive
454     lookahead or positive lookbehind we can have multiple patterns
455     involved. Consider
456
457     /(?=FOO).*F/
458
459     The minimum length of the pattern overall is 3, the minimum length
460     of the lookahead part is 3, but the minimum length of the part that
461     will actually match is 1. So 'FOO's minimum length is 3, but the
462     minimum length for the F is 1. This is important as the minimum length
463     is used to determine offsets in front of and behind the string being
464     looked for.  Since strings can be composites this is the length of the
465     pattern at the time it was committed with a scan_commit. Note that
466     the length is calculated by study_chunk, so that the minimum lengths
467     are not known until the full pattern has been compiled, thus the
468     pointer to the value.
469
470   - lookbehind
471
472     In the case of lookbehind the string being searched for can be
473     offset past the start point of the final matching string.
474     If this value was just blithely removed from the min_offset it would
475     invalidate some of the calculations for how many chars must match
476     before or after (as they are derived from min_offset and minlen and
477     the length of the string being searched for).
478     When the final pattern is compiled and the data is moved from the
479     scan_data_t structure into the regexp structure the information
480     about lookbehind is factored in, with the information that would
481     have been lost precalculated in the end_shift field for the
482     associated string.
483
484   The fields pos_min and pos_delta are used to store the minimum offset
485   and the delta to the maximum offset at the current point in the pattern.
486
487 */
488
489 struct scan_data_substrs {
490     SV      *str;       /* longest substring found in pattern */
491     SSize_t min_offset; /* earliest point in string it can appear */
492     SSize_t max_offset; /* latest point in string it can appear */
493     SSize_t *minlenp;   /* pointer to the minlen relevant to the string */
494     SSize_t lookbehind; /* is the pos of the string modified by LB */
495     I32 flags;          /* per substring SF_* and SCF_* flags */
496 };
497
498 typedef struct scan_data_t {
499     /*I32 len_min;      unused */
500     /*I32 len_delta;    unused */
501     SSize_t pos_min;
502     SSize_t pos_delta;
503     SV *last_found;
504     SSize_t last_end;       /* min value, <0 unless valid. */
505     SSize_t last_start_min;
506     SSize_t last_start_max;
507     U8      cur_is_floating; /* whether the last_* values should be set as
508                               * the next fixed (0) or floating (1)
509                               * substring */
510
511     /* [0] is longest fixed substring so far, [1] is longest float so far */
512     struct scan_data_substrs  substrs[2];
513
514     I32 flags;             /* common SF_* and SCF_* flags */
515     I32 whilem_c;
516     SSize_t *last_closep;
517     regnode_ssc *start_class;
518 } scan_data_t;
519
520 /*
521  * Forward declarations for pregcomp()'s friends.
522  */
523
524 static const scan_data_t zero_scan_data = {
525     0, 0, NULL, 0, 0, 0, 0,
526     {
527         { NULL, 0, 0, 0, 0, 0 },
528         { NULL, 0, 0, 0, 0, 0 },
529     },
530     0, 0, NULL, NULL
531 };
532
533 /* study flags */
534
535 #define SF_BEFORE_SEOL          0x0001
536 #define SF_BEFORE_MEOL          0x0002
537 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
538
539 #define SF_IS_INF               0x0040
540 #define SF_HAS_PAR              0x0080
541 #define SF_IN_PAR               0x0100
542 #define SF_HAS_EVAL             0x0200
543
544
545 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
546  * longest substring in the pattern. When it is not set the optimiser keeps
547  * track of position, but does not keep track of the actual strings seen,
548  *
549  * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
550  * /foo/i will not.
551  *
552  * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
553  * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
554  * turned off because of the alternation (BRANCH). */
555 #define SCF_DO_SUBSTR           0x0400
556
557 #define SCF_DO_STCLASS_AND      0x0800
558 #define SCF_DO_STCLASS_OR       0x1000
559 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
560 #define SCF_WHILEM_VISITED_POS  0x2000
561
562 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
563 #define SCF_SEEN_ACCEPT         0x8000
564 #define SCF_TRIE_DOING_RESTUDY 0x10000
565 #define SCF_IN_DEFINE          0x20000
566
567
568
569
570 #define UTF cBOOL(RExC_utf8)
571
572 /* The enums for all these are ordered so things work out correctly */
573 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
574 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags)                    \
575                                                      == REGEX_DEPENDS_CHARSET)
576 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
577 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags)                \
578                                                      >= REGEX_UNICODE_CHARSET)
579 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags)                      \
580                                             == REGEX_ASCII_RESTRICTED_CHARSET)
581 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags)             \
582                                             >= REGEX_ASCII_RESTRICTED_CHARSET)
583 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags)                 \
584                                         == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
585
586 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
587
588 /* For programs that want to be strictly Unicode compatible by dying if any
589  * attempt is made to match a non-Unicode code point against a Unicode
590  * property.  */
591 #define ALWAYS_WARN_SUPER  ckDEAD(packWARN(WARN_NON_UNICODE))
592
593 #define OOB_NAMEDCLASS          -1
594
595 /* There is no code point that is out-of-bounds, so this is problematic.  But
596  * its only current use is to initialize a variable that is always set before
597  * looked at. */
598 #define OOB_UNICODE             0xDEADBEEF
599
600 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
601
602
603 /* length of regex to show in messages that don't mark a position within */
604 #define RegexLengthToShowInErrorMessages 127
605
606 /*
607  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
608  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
609  * op/pragma/warn/regcomp.
610  */
611 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
612 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
613
614 #define REPORT_LOCATION " in regex; marked by " MARKER1    \
615                         " in m/%" UTF8f MARKER2 "%" UTF8f "/"
616
617 /* The code in this file in places uses one level of recursion with parsing
618  * rebased to an alternate string constructed by us in memory.  This can take
619  * the form of something that is completely different from the input, or
620  * something that uses the input as part of the alternate.  In the first case,
621  * there should be no possibility of an error, as we are in complete control of
622  * the alternate string.  But in the second case we don't completely control
623  * the input portion, so there may be errors in that.  Here's an example:
624  *      /[abc\x{DF}def]/ui
625  * is handled specially because \x{df} folds to a sequence of more than one
626  * character: 'ss'.  What is done is to create and parse an alternate string,
627  * which looks like this:
628  *      /(?:\x{DF}|[abc\x{DF}def])/ui
629  * where it uses the input unchanged in the middle of something it constructs,
630  * which is a branch for the DF outside the character class, and clustering
631  * parens around the whole thing. (It knows enough to skip the DF inside the
632  * class while in this substitute parse.) 'abc' and 'def' may have errors that
633  * need to be reported.  The general situation looks like this:
634  *
635  *                                       |<------- identical ------>|
636  *              sI                       tI               xI       eI
637  * Input:       ---------------------------------------------------------------
638  * Constructed:         ---------------------------------------------------
639  *                      sC               tC               xC       eC     EC
640  *                                       |<------- identical ------>|
641  *
642  * sI..eI   is the portion of the input pattern we are concerned with here.
643  * sC..EC   is the constructed substitute parse string.
644  *  sC..tC  is constructed by us
645  *  tC..eC  is an exact duplicate of the portion of the input pattern tI..eI.
646  *          In the diagram, these are vertically aligned.
647  *  eC..EC  is also constructed by us.
648  * xC       is the position in the substitute parse string where we found a
649  *          problem.
650  * xI       is the position in the original pattern corresponding to xC.
651  *
652  * We want to display a message showing the real input string.  Thus we need to
653  * translate from xC to xI.  We know that xC >= tC, since the portion of the
654  * string sC..tC has been constructed by us, and so shouldn't have errors.  We
655  * get:
656  *      xI = tI + (xC - tC)
657  *
658  * When the substitute parse is constructed, the code needs to set:
659  *      RExC_start (sC)
660  *      RExC_end (eC)
661  *      RExC_copy_start_in_input  (tI)
662  *      RExC_copy_start_in_constructed (tC)
663  * and restore them when done.
664  *
665  * During normal processing of the input pattern, both
666  * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
667  * sI, so that xC equals xI.
668  */
669
670 #define sI              RExC_precomp
671 #define eI              RExC_precomp_end
672 #define sC              RExC_start
673 #define eC              RExC_end
674 #define tI              RExC_copy_start_in_input
675 #define tC              RExC_copy_start_in_constructed
676 #define xI(xC)          (tI + (xC - tC))
677 #define xI_offset(xC)   (xI(xC) - sI)
678
679 #define REPORT_LOCATION_ARGS(xC)                                            \
680     UTF8fARG(UTF,                                                           \
681              (xI(xC) > eI) /* Don't run off end */                          \
682               ? eI - sI   /* Length before the <--HERE */                   \
683               : ((xI_offset(xC) >= 0)                                       \
684                  ? xI_offset(xC)                                            \
685                  : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %"    \
686                                     IVdf " trying to output message for "   \
687                                     " pattern %.*s",                        \
688                                     __FILE__, __LINE__, (IV) xI_offset(xC), \
689                                     ((int) (eC - sC)), sC), 0)),            \
690              sI),         /* The input pattern printed up to the <--HERE */ \
691     UTF8fARG(UTF,                                                           \
692              (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */    \
693              (xI(xC) > eI) ? eI : xI(xC))     /* pattern after <--HERE */
694
695 /* Used to point after bad bytes for an error message, but avoid skipping
696  * past a nul byte. */
697 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
698
699 /* Set up to clean up after our imminent demise */
700 #define PREPARE_TO_DIE                                                      \
701     STMT_START {                                                            \
702         if (RExC_rx_sv)                                                     \
703             SAVEFREESV(RExC_rx_sv);                                         \
704         if (RExC_open_parens)                                               \
705             SAVEFREEPV(RExC_open_parens);                                   \
706         if (RExC_close_parens)                                              \
707             SAVEFREEPV(RExC_close_parens);                                  \
708     } STMT_END
709
710 /*
711  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
712  * arg. Show regex, up to a maximum length. If it's too long, chop and add
713  * "...".
714  */
715 #define _FAIL(code) STMT_START {                                        \
716     const char *ellipses = "";                                          \
717     IV len = RExC_precomp_end - RExC_precomp;                           \
718                                                                         \
719     PREPARE_TO_DIE;                                                     \
720     if (len > RegexLengthToShowInErrorMessages) {                       \
721         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
722         len = RegexLengthToShowInErrorMessages - 10;                    \
723         ellipses = "...";                                               \
724     }                                                                   \
725     code;                                                               \
726 } STMT_END
727
728 #define FAIL(msg) _FAIL(                            \
729     Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/",         \
730             msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
731
732 #define FAIL2(msg,arg) _FAIL(                       \
733     Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/",       \
734             arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
735
736 /*
737  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
738  */
739 #define Simple_vFAIL(m) STMT_START {                                    \
740     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
741             m, REPORT_LOCATION_ARGS(RExC_parse));                       \
742 } STMT_END
743
744 /*
745  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
746  */
747 #define vFAIL(m) STMT_START {                           \
748     PREPARE_TO_DIE;                                     \
749     Simple_vFAIL(m);                                    \
750 } STMT_END
751
752 /*
753  * Like Simple_vFAIL(), but accepts two arguments.
754  */
755 #define Simple_vFAIL2(m,a1) STMT_START {                        \
756     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,              \
757                       REPORT_LOCATION_ARGS(RExC_parse));        \
758 } STMT_END
759
760 /*
761  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
762  */
763 #define vFAIL2(m,a1) STMT_START {                       \
764     PREPARE_TO_DIE;                                     \
765     Simple_vFAIL2(m, a1);                               \
766 } STMT_END
767
768
769 /*
770  * Like Simple_vFAIL(), but accepts three arguments.
771  */
772 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
773     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,          \
774             REPORT_LOCATION_ARGS(RExC_parse));                  \
775 } STMT_END
776
777 /*
778  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
779  */
780 #define vFAIL3(m,a1,a2) STMT_START {                    \
781     PREPARE_TO_DIE;                                     \
782     Simple_vFAIL3(m, a1, a2);                           \
783 } STMT_END
784
785 /*
786  * Like Simple_vFAIL(), but accepts four arguments.
787  */
788 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
789     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3,      \
790             REPORT_LOCATION_ARGS(RExC_parse));                  \
791 } STMT_END
792
793 #define vFAIL4(m,a1,a2,a3) STMT_START {                 \
794     PREPARE_TO_DIE;                                     \
795     Simple_vFAIL4(m, a1, a2, a3);                       \
796 } STMT_END
797
798 /* A specialized version of vFAIL2 that works with UTF8f */
799 #define vFAIL2utf8f(m, a1) STMT_START {             \
800     PREPARE_TO_DIE;                                 \
801     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,  \
802             REPORT_LOCATION_ARGS(RExC_parse));      \
803 } STMT_END
804
805 #define vFAIL3utf8f(m, a1, a2) STMT_START {             \
806     PREPARE_TO_DIE;                                     \
807     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,  \
808             REPORT_LOCATION_ARGS(RExC_parse));          \
809 } STMT_END
810
811 /* Setting this to NULL is a signal to not output warnings */
812 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE RExC_copy_start_in_constructed = NULL
813 #define RESTORE_WARNINGS RExC_copy_start_in_constructed = RExC_precomp
814
815 /* Since a warning can be generated multiple times as the input is reparsed, we
816  * output it the first time we come to that point in the parse, but suppress it
817  * otherwise.  'RExC_copy_start_in_constructed' being NULL is a flag to not
818  * generate any warnings */
819 #define TO_OUTPUT_WARNINGS(loc)                                         \
820   (   RExC_copy_start_in_constructed                                    \
821    && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
822
823 /* After we've emitted a warning, we save the position in the input so we don't
824  * output it again */
825 #define UPDATE_WARNINGS_LOC(loc)                                        \
826     STMT_START {                                                        \
827         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
828             RExC_latest_warn_offset = (xI(loc)) - RExC_precomp;         \
829         }                                                               \
830     } STMT_END
831
832 /* 'warns' is the output of the packWARNx macro used in 'code' */
833 #define _WARN_HELPER(loc, warns, code)                                  \
834     STMT_START {                                                        \
835         if (! RExC_copy_start_in_constructed) {                         \
836             Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none"  \
837                               " expected at '%s'",                      \
838                               __FILE__, __LINE__, loc);                 \
839         }                                                               \
840         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
841             if (ckDEAD(warns))                                          \
842                 PREPARE_TO_DIE;                                         \
843             code;                                                       \
844             UPDATE_WARNINGS_LOC(loc);                                   \
845         }                                                               \
846     } STMT_END
847
848 /* m is not necessarily a "literal string", in this macro */
849 #define reg_warn_non_literal_string(loc, m)                             \
850     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
851                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
852                                        "%s" REPORT_LOCATION,            \
853                                   m, REPORT_LOCATION_ARGS(loc)))
854
855 #define ckWARNreg(loc,m)                                                \
856     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
857                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
858                                           m REPORT_LOCATION,            \
859                                           REPORT_LOCATION_ARGS(loc)))
860
861 #define vWARN(loc, m)                                                   \
862     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
863                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
864                                        m REPORT_LOCATION,               \
865                                        REPORT_LOCATION_ARGS(loc)))      \
866
867 #define vWARN_dep(loc, m)                                               \
868     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
869                       Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),      \
870                                        m REPORT_LOCATION,               \
871                                        REPORT_LOCATION_ARGS(loc)))
872
873 #define ckWARNdep(loc,m)                                                \
874     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
875                       Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
876                                             m REPORT_LOCATION,          \
877                                             REPORT_LOCATION_ARGS(loc)))
878
879 #define ckWARNregdep(loc,m)                                                 \
880     _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP),              \
881                       Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED,     \
882                                                       WARN_REGEXP),         \
883                                              m REPORT_LOCATION,             \
884                                              REPORT_LOCATION_ARGS(loc)))
885
886 #define ckWARN2reg_d(loc,m, a1)                                             \
887     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
888                       Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP),         \
889                                             m REPORT_LOCATION,              \
890                                             a1, REPORT_LOCATION_ARGS(loc)))
891
892 #define ckWARN2reg(loc, m, a1)                                              \
893     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
894                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
895                                           m REPORT_LOCATION,                \
896                                           a1, REPORT_LOCATION_ARGS(loc)))
897
898 #define vWARN3(loc, m, a1, a2)                                              \
899     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
900                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),              \
901                                        m REPORT_LOCATION,                   \
902                                        a1, a2, REPORT_LOCATION_ARGS(loc)))
903
904 #define ckWARN3reg(loc, m, a1, a2)                                          \
905     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
906                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
907                                           m REPORT_LOCATION,                \
908                                           a1, a2,                           \
909                                           REPORT_LOCATION_ARGS(loc)))
910
911 #define vWARN4(loc, m, a1, a2, a3)                                      \
912     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
913                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
914                                        m REPORT_LOCATION,               \
915                                        a1, a2, a3,                      \
916                                        REPORT_LOCATION_ARGS(loc)))
917
918 #define ckWARN4reg(loc, m, a1, a2, a3)                                  \
919     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
920                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
921                                           m REPORT_LOCATION,            \
922                                           a1, a2, a3,                   \
923                                           REPORT_LOCATION_ARGS(loc)))
924
925 #define vWARN5(loc, m, a1, a2, a3, a4)                                  \
926     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
927                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
928                                        m REPORT_LOCATION,               \
929                                        a1, a2, a3, a4,                  \
930                                        REPORT_LOCATION_ARGS(loc)))
931
932 #define ckWARNexperimental(loc, class, m)                               \
933     _WARN_HELPER(loc, packWARN(class),                                  \
934                       Perl_ck_warner_d(aTHX_ packWARN(class),           \
935                                             m REPORT_LOCATION,          \
936                                             REPORT_LOCATION_ARGS(loc)))
937
938 /* Convert between a pointer to a node and its offset from the beginning of the
939  * program */
940 #define REGNODE_p(offset)    (RExC_emit_start + (offset))
941 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
942
943 /* Macros for recording node offsets.   20001227 mjd@plover.com
944  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
945  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
946  * Element 0 holds the number n.
947  * Position is 1 indexed.
948  */
949 #ifndef RE_TRACK_PATTERN_OFFSETS
950 #define Set_Node_Offset_To_R(offset,byte)
951 #define Set_Node_Offset(node,byte)
952 #define Set_Cur_Node_Offset
953 #define Set_Node_Length_To_R(node,len)
954 #define Set_Node_Length(node,len)
955 #define Set_Node_Cur_Length(node,start)
956 #define Node_Offset(n)
957 #define Node_Length(n)
958 #define Set_Node_Offset_Length(node,offset,len)
959 #define ProgLen(ri) ri->u.proglen
960 #define SetProgLen(ri,x) ri->u.proglen = x
961 #define Track_Code(code)
962 #else
963 #define ProgLen(ri) ri->u.offsets[0]
964 #define SetProgLen(ri,x) ri->u.offsets[0] = x
965 #define Set_Node_Offset_To_R(offset,byte) STMT_START {                  \
966         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
967                     __LINE__, (int)(offset), (int)(byte)));             \
968         if((offset) < 0) {                                              \
969             Perl_croak(aTHX_ "value of node is %d in Offset macro",     \
970                                          (int)(offset));                \
971         } else {                                                        \
972             RExC_offsets[2*(offset)-1] = (byte);                        \
973         }                                                               \
974 } STMT_END
975
976 #define Set_Node_Offset(node,byte)                                      \
977     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
978 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
979
980 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
981         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
982                 __LINE__, (int)(node), (int)(len)));                    \
983         if((node) < 0) {                                                \
984             Perl_croak(aTHX_ "value of node is %d in Length macro",     \
985                                          (int)(node));                  \
986         } else {                                                        \
987             RExC_offsets[2*(node)] = (len);                             \
988         }                                                               \
989 } STMT_END
990
991 #define Set_Node_Length(node,len) \
992     Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
993 #define Set_Node_Cur_Length(node, start)                \
994     Set_Node_Length(node, RExC_parse - start)
995
996 /* Get offsets and lengths */
997 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
998 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
999
1000 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
1001     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset));       \
1002     Set_Node_Length_To_R(REGNODE_OFFSET(node), (len));  \
1003 } STMT_END
1004
1005 #define Track_Code(code) STMT_START { code } STMT_END
1006 #endif
1007
1008 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1009 #define EXPERIMENTAL_INPLACESCAN
1010 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1011
1012 #ifdef DEBUGGING
1013 int
1014 Perl_re_printf(pTHX_ const char *fmt, ...)
1015 {
1016     va_list ap;
1017     int result;
1018     PerlIO *f= Perl_debug_log;
1019     PERL_ARGS_ASSERT_RE_PRINTF;
1020     va_start(ap, fmt);
1021     result = PerlIO_vprintf(f, fmt, ap);
1022     va_end(ap);
1023     return result;
1024 }
1025
1026 int
1027 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1028 {
1029     va_list ap;
1030     int result;
1031     PerlIO *f= Perl_debug_log;
1032     PERL_ARGS_ASSERT_RE_INDENTF;
1033     va_start(ap, depth);
1034     PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1035     result = PerlIO_vprintf(f, fmt, ap);
1036     va_end(ap);
1037     return result;
1038 }
1039 #endif /* DEBUGGING */
1040
1041 #define DEBUG_RExC_seen()                                                   \
1042         DEBUG_OPTIMISE_MORE_r({                                             \
1043             Perl_re_printf( aTHX_ "RExC_seen: ");                           \
1044                                                                             \
1045             if (RExC_seen & REG_ZERO_LEN_SEEN)                              \
1046                 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN ");                \
1047                                                                             \
1048             if (RExC_seen & REG_LOOKBEHIND_SEEN)                            \
1049                 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN ");              \
1050                                                                             \
1051             if (RExC_seen & REG_GPOS_SEEN)                                  \
1052                 Perl_re_printf( aTHX_ "REG_GPOS_SEEN ");                    \
1053                                                                             \
1054             if (RExC_seen & REG_RECURSE_SEEN)                               \
1055                 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN ");                 \
1056                                                                             \
1057             if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)                    \
1058                 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN ");      \
1059                                                                             \
1060             if (RExC_seen & REG_VERBARG_SEEN)                               \
1061                 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN ");                 \
1062                                                                             \
1063             if (RExC_seen & REG_CUTGROUP_SEEN)                              \
1064                 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN ");                \
1065                                                                             \
1066             if (RExC_seen & REG_RUN_ON_COMMENT_SEEN)                        \
1067                 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN ");          \
1068                                                                             \
1069             if (RExC_seen & REG_UNFOLDED_MULTI_SEEN)                        \
1070                 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN ");          \
1071                                                                             \
1072             if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)                  \
1073                 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN ");    \
1074                                                                             \
1075             Perl_re_printf( aTHX_ "\n");                                    \
1076         });
1077
1078 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1079   if ((flags) & flag) Perl_re_printf( aTHX_  "%s ", #flag)
1080
1081
1082 #ifdef DEBUGGING
1083 static void
1084 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1085                                     const char *close_str)
1086 {
1087     if (!flags)
1088         return;
1089
1090     Perl_re_printf( aTHX_  "%s", open_str);
1091     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1092     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1093     DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1094     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1095     DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1096     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1097     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1098     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1099     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1100     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1101     DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1102     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1103     DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1104     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1105     DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1106     Perl_re_printf( aTHX_  "%s", close_str);
1107 }
1108
1109
1110 static void
1111 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1112                     U32 depth, int is_inf)
1113 {
1114     GET_RE_DEBUG_FLAGS_DECL;
1115
1116     DEBUG_OPTIMISE_MORE_r({
1117         if (!data)
1118             return;
1119         Perl_re_indentf(aTHX_  "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1120             depth,
1121             where,
1122             (IV)data->pos_min,
1123             (IV)data->pos_delta,
1124             (UV)data->flags
1125         );
1126
1127         S_debug_show_study_flags(aTHX_ data->flags," [","]");
1128
1129         Perl_re_printf( aTHX_
1130             " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1131             (IV)data->whilem_c,
1132             (IV)(data->last_closep ? *((data)->last_closep) : -1),
1133             is_inf ? "INF " : ""
1134         );
1135
1136         if (data->last_found) {
1137             int i;
1138             Perl_re_printf(aTHX_
1139                 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1140                     SvPVX_const(data->last_found),
1141                     (IV)data->last_end,
1142                     (IV)data->last_start_min,
1143                     (IV)data->last_start_max
1144             );
1145
1146             for (i = 0; i < 2; i++) {
1147                 Perl_re_printf(aTHX_
1148                     " %s%s: '%s' @ %" IVdf "/%" IVdf,
1149                     data->cur_is_floating == i ? "*" : "",
1150                     i ? "Float" : "Fixed",
1151                     SvPVX_const(data->substrs[i].str),
1152                     (IV)data->substrs[i].min_offset,
1153                     (IV)data->substrs[i].max_offset
1154                 );
1155                 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1156             }
1157         }
1158
1159         Perl_re_printf( aTHX_ "\n");
1160     });
1161 }
1162
1163
1164 static void
1165 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1166                 regnode *scan, U32 depth, U32 flags)
1167 {
1168     GET_RE_DEBUG_FLAGS_DECL;
1169
1170     DEBUG_OPTIMISE_r({
1171         regnode *Next;
1172
1173         if (!scan)
1174             return;
1175         Next = regnext(scan);
1176         regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1177         Perl_re_indentf( aTHX_   "%s>%3d: %s (%d)",
1178             depth,
1179             str,
1180             REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1181             Next ? (REG_NODE_NUM(Next)) : 0 );
1182         S_debug_show_study_flags(aTHX_ flags," [ ","]");
1183         Perl_re_printf( aTHX_  "\n");
1184    });
1185 }
1186
1187
1188 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1189                     S_debug_studydata(aTHX_ where, data, depth, is_inf)
1190
1191 #  define DEBUG_PEEP(str, scan, depth, flags)   \
1192                     S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1193
1194 #else
1195 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1196 #  define DEBUG_PEEP(str, scan, depth, flags)         NOOP
1197 #endif
1198
1199
1200 /* =========================================================
1201  * BEGIN edit_distance stuff.
1202  *
1203  * This calculates how many single character changes of any type are needed to
1204  * transform a string into another one.  It is taken from version 3.1 of
1205  *
1206  * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1207  */
1208
1209 /* Our unsorted dictionary linked list.   */
1210 /* Note we use UVs, not chars. */
1211
1212 struct dictionary{
1213   UV key;
1214   UV value;
1215   struct dictionary* next;
1216 };
1217 typedef struct dictionary item;
1218
1219
1220 PERL_STATIC_INLINE item*
1221 push(UV key, item* curr)
1222 {
1223     item* head;
1224     Newx(head, 1, item);
1225     head->key = key;
1226     head->value = 0;
1227     head->next = curr;
1228     return head;
1229 }
1230
1231
1232 PERL_STATIC_INLINE item*
1233 find(item* head, UV key)
1234 {
1235     item* iterator = head;
1236     while (iterator){
1237         if (iterator->key == key){
1238             return iterator;
1239         }
1240         iterator = iterator->next;
1241     }
1242
1243     return NULL;
1244 }
1245
1246 PERL_STATIC_INLINE item*
1247 uniquePush(item* head, UV key)
1248 {
1249     item* iterator = head;
1250
1251     while (iterator){
1252         if (iterator->key == key) {
1253             return head;
1254         }
1255         iterator = iterator->next;
1256     }
1257
1258     return push(key, head);
1259 }
1260
1261 PERL_STATIC_INLINE void
1262 dict_free(item* head)
1263 {
1264     item* iterator = head;
1265
1266     while (iterator) {
1267         item* temp = iterator;
1268         iterator = iterator->next;
1269         Safefree(temp);
1270     }
1271
1272     head = NULL;
1273 }
1274
1275 /* End of Dictionary Stuff */
1276
1277 /* All calculations/work are done here */
1278 STATIC int
1279 S_edit_distance(const UV* src,
1280                 const UV* tgt,
1281                 const STRLEN x,             /* length of src[] */
1282                 const STRLEN y,             /* length of tgt[] */
1283                 const SSize_t maxDistance
1284 )
1285 {
1286     item *head = NULL;
1287     UV swapCount, swapScore, targetCharCount, i, j;
1288     UV *scores;
1289     UV score_ceil = x + y;
1290
1291     PERL_ARGS_ASSERT_EDIT_DISTANCE;
1292
1293     /* intialize matrix start values */
1294     Newx(scores, ( (x + 2) * (y + 2)), UV);
1295     scores[0] = score_ceil;
1296     scores[1 * (y + 2) + 0] = score_ceil;
1297     scores[0 * (y + 2) + 1] = score_ceil;
1298     scores[1 * (y + 2) + 1] = 0;
1299     head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1300
1301     /* work loops    */
1302     /* i = src index */
1303     /* j = tgt index */
1304     for (i=1;i<=x;i++) {
1305         if (i < x)
1306             head = uniquePush(head, src[i]);
1307         scores[(i+1) * (y + 2) + 1] = i;
1308         scores[(i+1) * (y + 2) + 0] = score_ceil;
1309         swapCount = 0;
1310
1311         for (j=1;j<=y;j++) {
1312             if (i == 1) {
1313                 if(j < y)
1314                 head = uniquePush(head, tgt[j]);
1315                 scores[1 * (y + 2) + (j + 1)] = j;
1316                 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1317             }
1318
1319             targetCharCount = find(head, tgt[j-1])->value;
1320             swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1321
1322             if (src[i-1] != tgt[j-1]){
1323                 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));
1324             }
1325             else {
1326                 swapCount = j;
1327                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1328             }
1329         }
1330
1331         find(head, src[i-1])->value = i;
1332     }
1333
1334     {
1335         IV score = scores[(x+1) * (y + 2) + (y + 1)];
1336         dict_free(head);
1337         Safefree(scores);
1338         return (maxDistance != 0 && maxDistance < score)?(-1):score;
1339     }
1340 }
1341
1342 /* END of edit_distance() stuff
1343  * ========================================================= */
1344
1345 /* is c a control character for which we have a mnemonic? */
1346 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1347
1348 STATIC const char *
1349 S_cntrl_to_mnemonic(const U8 c)
1350 {
1351     /* Returns the mnemonic string that represents character 'c', if one
1352      * exists; NULL otherwise.  The only ones that exist for the purposes of
1353      * this routine are a few control characters */
1354
1355     switch (c) {
1356         case '\a':       return "\\a";
1357         case '\b':       return "\\b";
1358         case ESC_NATIVE: return "\\e";
1359         case '\f':       return "\\f";
1360         case '\n':       return "\\n";
1361         case '\r':       return "\\r";
1362         case '\t':       return "\\t";
1363     }
1364
1365     return NULL;
1366 }
1367
1368 /* Mark that we cannot extend a found fixed substring at this point.
1369    Update the longest found anchored substring or the longest found
1370    floating substrings if needed. */
1371
1372 STATIC void
1373 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1374                     SSize_t *minlenp, int is_inf)
1375 {
1376     const STRLEN l = CHR_SVLEN(data->last_found);
1377     SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1378     const STRLEN old_l = CHR_SVLEN(longest_sv);
1379     GET_RE_DEBUG_FLAGS_DECL;
1380
1381     PERL_ARGS_ASSERT_SCAN_COMMIT;
1382
1383     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1384         const U8 i = data->cur_is_floating;
1385         SvSetMagicSV(longest_sv, data->last_found);
1386         data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1387
1388         if (!i) /* fixed */
1389             data->substrs[0].max_offset = data->substrs[0].min_offset;
1390         else { /* float */
1391             data->substrs[1].max_offset = (l
1392                           ? data->last_start_max
1393                           : (data->pos_delta > SSize_t_MAX - data->pos_min
1394                                          ? SSize_t_MAX
1395                                          : data->pos_min + data->pos_delta));
1396             if (is_inf
1397                  || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1398                 data->substrs[1].max_offset = SSize_t_MAX;
1399         }
1400
1401         if (data->flags & SF_BEFORE_EOL)
1402             data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1403         else
1404             data->substrs[i].flags &= ~SF_BEFORE_EOL;
1405         data->substrs[i].minlenp = minlenp;
1406         data->substrs[i].lookbehind = 0;
1407     }
1408
1409     SvCUR_set(data->last_found, 0);
1410     {
1411         SV * const sv = data->last_found;
1412         if (SvUTF8(sv) && SvMAGICAL(sv)) {
1413             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1414             if (mg)
1415                 mg->mg_len = 0;
1416         }
1417     }
1418     data->last_end = -1;
1419     data->flags &= ~SF_BEFORE_EOL;
1420     DEBUG_STUDYDATA("commit", data, 0, is_inf);
1421 }
1422
1423 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1424  * list that describes which code points it matches */
1425
1426 STATIC void
1427 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1428 {
1429     /* Set the SSC 'ssc' to match an empty string or any code point */
1430
1431     PERL_ARGS_ASSERT_SSC_ANYTHING;
1432
1433     assert(is_ANYOF_SYNTHETIC(ssc));
1434
1435     /* mortalize so won't leak */
1436     ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1437     ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING;  /* Plus matches empty */
1438 }
1439
1440 STATIC int
1441 S_ssc_is_anything(const regnode_ssc *ssc)
1442 {
1443     /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1444      * point; FALSE otherwise.  Thus, this is used to see if using 'ssc' buys
1445      * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1446      * in any way, so there's no point in using it */
1447
1448     UV start, end;
1449     bool ret;
1450
1451     PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1452
1453     assert(is_ANYOF_SYNTHETIC(ssc));
1454
1455     if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1456         return FALSE;
1457     }
1458
1459     /* See if the list consists solely of the range 0 - Infinity */
1460     invlist_iterinit(ssc->invlist);
1461     ret = invlist_iternext(ssc->invlist, &start, &end)
1462           && start == 0
1463           && end == UV_MAX;
1464
1465     invlist_iterfinish(ssc->invlist);
1466
1467     if (ret) {
1468         return TRUE;
1469     }
1470
1471     /* If e.g., both \w and \W are set, matches everything */
1472     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1473         int i;
1474         for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1475             if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1476                 return TRUE;
1477             }
1478         }
1479     }
1480
1481     return FALSE;
1482 }
1483
1484 STATIC void
1485 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1486 {
1487     /* Initializes the SSC 'ssc'.  This includes setting it to match an empty
1488      * string, any code point, or any posix class under locale */
1489
1490     PERL_ARGS_ASSERT_SSC_INIT;
1491
1492     Zero(ssc, 1, regnode_ssc);
1493     set_ANYOF_SYNTHETIC(ssc);
1494     ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1495     ssc_anything(ssc);
1496
1497     /* If any portion of the regex is to operate under locale rules that aren't
1498      * fully known at compile time, initialization includes it.  The reason
1499      * this isn't done for all regexes is that the optimizer was written under
1500      * the assumption that locale was all-or-nothing.  Given the complexity and
1501      * lack of documentation in the optimizer, and that there are inadequate
1502      * test cases for locale, many parts of it may not work properly, it is
1503      * safest to avoid locale unless necessary. */
1504     if (RExC_contains_locale) {
1505         ANYOF_POSIXL_SETALL(ssc);
1506     }
1507     else {
1508         ANYOF_POSIXL_ZERO(ssc);
1509     }
1510 }
1511
1512 STATIC int
1513 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1514                         const regnode_ssc *ssc)
1515 {
1516     /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1517      * to the list of code points matched, and locale posix classes; hence does
1518      * not check its flags) */
1519
1520     UV start, end;
1521     bool ret;
1522
1523     PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1524
1525     assert(is_ANYOF_SYNTHETIC(ssc));
1526
1527     invlist_iterinit(ssc->invlist);
1528     ret = invlist_iternext(ssc->invlist, &start, &end)
1529           && start == 0
1530           && end == UV_MAX;
1531
1532     invlist_iterfinish(ssc->invlist);
1533
1534     if (! ret) {
1535         return FALSE;
1536     }
1537
1538     if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1539         return FALSE;
1540     }
1541
1542     return TRUE;
1543 }
1544
1545 #define INVLIST_INDEX 0
1546 #define ONLY_LOCALE_MATCHES_INDEX 1
1547 #define DEFERRED_USER_DEFINED_INDEX 2
1548
1549 STATIC SV*
1550 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1551                                const regnode_charclass* const node)
1552 {
1553     /* Returns a mortal inversion list defining which code points are matched
1554      * by 'node', which is of type ANYOF.  Handles complementing the result if
1555      * appropriate.  If some code points aren't knowable at this time, the
1556      * returned list must, and will, contain every code point that is a
1557      * possibility. */
1558
1559     dVAR;
1560     SV* invlist = NULL;
1561     SV* only_utf8_locale_invlist = NULL;
1562     unsigned int i;
1563     const U32 n = ARG(node);
1564     bool new_node_has_latin1 = FALSE;
1565
1566     PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1567
1568     /* Look at the data structure created by S_set_ANYOF_arg() */
1569     if (n != ANYOF_ONLY_HAS_BITMAP) {
1570         SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1571         AV * const av = MUTABLE_AV(SvRV(rv));
1572         SV **const ary = AvARRAY(av);
1573         assert(RExC_rxi->data->what[n] == 's');
1574
1575         if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1576
1577             /* Here there are things that won't be known until runtime -- we
1578              * have to assume it could be anything */
1579             invlist = sv_2mortal(_new_invlist(1));
1580             return _add_range_to_invlist(invlist, 0, UV_MAX);
1581         }
1582         else if (ary[INVLIST_INDEX]) {
1583
1584             /* Use the node's inversion list */
1585             invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1586         }
1587
1588         /* Get the code points valid only under UTF-8 locales */
1589         if (   (ANYOF_FLAGS(node) & ANYOFL_FOLD)
1590             &&  av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1591         {
1592             only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
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     if (OP(node) != ANYOFH) {
1618         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1619             if (ANYOF_BITMAP_TEST(node, i)) {
1620                 unsigned int start = i++;
1621
1622                 for (;    i < NUM_ANYOF_CODE_POINTS
1623                        && ANYOF_BITMAP_TEST(node, i); ++i)
1624                 {
1625                     /* empty */
1626                 }
1627                 invlist = _add_range_to_invlist(invlist, start, i-1);
1628                 new_node_has_latin1 = TRUE;
1629             }
1630         }
1631     }
1632
1633     /* If this can match all upper Latin1 code points, have to add them
1634      * as well.  But don't add them if inverting, as when that gets done below,
1635      * it would exclude all these characters, including the ones it shouldn't
1636      * that were added just above */
1637     if (! (ANYOF_FLAGS(node) & ANYOF_INVERT) && OP(node) == ANYOFD
1638         && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1639     {
1640         _invlist_union(invlist, PL_UpperLatin1, &invlist);
1641     }
1642
1643     /* Similarly for these */
1644     if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1645         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1646     }
1647
1648     if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1649         _invlist_invert(invlist);
1650     }
1651     else if (ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1652         if (new_node_has_latin1) {
1653
1654             /* Under /li, any 0-255 could fold to any other 0-255, depending on
1655              * the locale.  We can skip this if there are no 0-255 at all. */
1656             _invlist_union(invlist, PL_Latin1, &invlist);
1657
1658             invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1659             invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1660         }
1661         else {
1662             if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1663                 invlist = add_cp_to_invlist(invlist, 'I');
1664             }
1665             if (_invlist_contains_cp(invlist,
1666                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1667             {
1668                 invlist = add_cp_to_invlist(invlist, 'i');
1669             }
1670         }
1671     }
1672
1673     /* Similarly add the UTF-8 locale possible matches.  These have to be
1674      * deferred until after the non-UTF-8 locale ones are taken care of just
1675      * above, or it leads to wrong results under ANYOF_INVERT */
1676     if (only_utf8_locale_invlist) {
1677         _invlist_union_maybe_complement_2nd(invlist,
1678                                             only_utf8_locale_invlist,
1679                                             ANYOF_FLAGS(node) & ANYOF_INVERT,
1680                                             &invlist);
1681     }
1682
1683     return invlist;
1684 }
1685
1686 /* These two functions currently do the exact same thing */
1687 #define ssc_init_zero           ssc_init
1688
1689 #define ssc_add_cp(ssc, cp)   ssc_add_range((ssc), (cp), (cp))
1690 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1691
1692 /* 'AND' a given class with another one.  Can create false positives.  'ssc'
1693  * should not be inverted.  'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1694  * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1695
1696 STATIC void
1697 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1698                 const regnode_charclass *and_with)
1699 {
1700     /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1701      * another SSC or a regular ANYOF class.  Can create false positives. */
1702
1703     SV* anded_cp_list;
1704     U8  anded_flags;
1705
1706     PERL_ARGS_ASSERT_SSC_AND;
1707
1708     assert(is_ANYOF_SYNTHETIC(ssc));
1709
1710     /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1711      * the code point inversion list and just the relevant flags */
1712     if (is_ANYOF_SYNTHETIC(and_with)) {
1713         anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1714         anded_flags = ANYOF_FLAGS(and_with);
1715
1716         /* XXX This is a kludge around what appears to be deficiencies in the
1717          * optimizer.  If we make S_ssc_anything() add in the WARN_SUPER flag,
1718          * there are paths through the optimizer where it doesn't get weeded
1719          * out when it should.  And if we don't make some extra provision for
1720          * it like the code just below, it doesn't get added when it should.
1721          * This solution is to add it only when AND'ing, which is here, and
1722          * only when what is being AND'ed is the pristine, original node
1723          * matching anything.  Thus it is like adding it to ssc_anything() but
1724          * only when the result is to be AND'ed.  Probably the same solution
1725          * could be adopted for the same problem we have with /l matching,
1726          * which is solved differently in S_ssc_init(), and that would lead to
1727          * fewer false positives than that solution has.  But if this solution
1728          * creates bugs, the consequences are only that a warning isn't raised
1729          * that should be; while the consequences for having /l bugs is
1730          * incorrect matches */
1731         if (ssc_is_anything((regnode_ssc *)and_with)) {
1732             anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1733         }
1734     }
1735     else {
1736         anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1737         if (OP(and_with) == ANYOFD) {
1738             anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1739         }
1740         else {
1741             anded_flags = ANYOF_FLAGS(and_with)
1742             &( ANYOF_COMMON_FLAGS
1743               |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1744               |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1745             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1746                 anded_flags &=
1747                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1748             }
1749         }
1750     }
1751
1752     ANYOF_FLAGS(ssc) &= anded_flags;
1753
1754     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1755      * C2 is the list of code points in 'and-with'; P2, its posix classes.
1756      * 'and_with' may be inverted.  When not inverted, we have the situation of
1757      * computing:
1758      *  (C1 | P1) & (C2 | P2)
1759      *                     =  (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1760      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1761      *                    <=  ((C1 & C2) |       P2)) | ( P1       | (P1 & P2))
1762      *                    <=  ((C1 & C2) | P1 | P2)
1763      * Alternatively, the last few steps could be:
1764      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1765      *                    <=  ((C1 & C2) |  C1      ) | (      C2  | (P1 & P2))
1766      *                    <=  (C1 | C2 | (P1 & P2))
1767      * We favor the second approach if either P1 or P2 is non-empty.  This is
1768      * because these components are a barrier to doing optimizations, as what
1769      * they match cannot be known until the moment of matching as they are
1770      * dependent on the current locale, 'AND"ing them likely will reduce or
1771      * eliminate them.
1772      * But we can do better if we know that C1,P1 are in their initial state (a
1773      * frequent occurrence), each matching everything:
1774      *  (<everything>) & (C2 | P2) =  C2 | P2
1775      * Similarly, if C2,P2 are in their initial state (again a frequent
1776      * occurrence), the result is a no-op
1777      *  (C1 | P1) & (<everything>) =  C1 | P1
1778      *
1779      * Inverted, we have
1780      *  (C1 | P1) & ~(C2 | P2)  =  (C1 | P1) & (~C2 & ~P2)
1781      *                          =  (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1782      *                         <=  (C1 & ~C2) | (P1 & ~P2)
1783      * */
1784
1785     if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1786         && ! is_ANYOF_SYNTHETIC(and_with))
1787     {
1788         unsigned int i;
1789
1790         ssc_intersection(ssc,
1791                          anded_cp_list,
1792                          FALSE /* Has already been inverted */
1793                          );
1794
1795         /* If either P1 or P2 is empty, the intersection will be also; can skip
1796          * the loop */
1797         if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1798             ANYOF_POSIXL_ZERO(ssc);
1799         }
1800         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1801
1802             /* Note that the Posix class component P from 'and_with' actually
1803              * looks like:
1804              *      P = Pa | Pb | ... | Pn
1805              * where each component is one posix class, such as in [\w\s].
1806              * Thus
1807              *      ~P = ~(Pa | Pb | ... | Pn)
1808              *         = ~Pa & ~Pb & ... & ~Pn
1809              *        <= ~Pa | ~Pb | ... | ~Pn
1810              * The last is something we can easily calculate, but unfortunately
1811              * is likely to have many false positives.  We could do better
1812              * in some (but certainly not all) instances if two classes in
1813              * P have known relationships.  For example
1814              *      :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1815              * So
1816              *      :lower: & :print: = :lower:
1817              * And similarly for classes that must be disjoint.  For example,
1818              * since \s and \w can have no elements in common based on rules in
1819              * the POSIX standard,
1820              *      \w & ^\S = nothing
1821              * Unfortunately, some vendor locales do not meet the Posix
1822              * standard, in particular almost everything by Microsoft.
1823              * The loop below just changes e.g., \w into \W and vice versa */
1824
1825             regnode_charclass_posixl temp;
1826             int add = 1;    /* To calculate the index of the complement */
1827
1828             Zero(&temp, 1, regnode_charclass_posixl);
1829             ANYOF_POSIXL_ZERO(&temp);
1830             for (i = 0; i < ANYOF_MAX; i++) {
1831                 assert(i % 2 != 0
1832                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1833                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1834
1835                 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1836                     ANYOF_POSIXL_SET(&temp, i + add);
1837                 }
1838                 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1839             }
1840             ANYOF_POSIXL_AND(&temp, ssc);
1841
1842         } /* else ssc already has no posixes */
1843     } /* else: Not inverted.  This routine is a no-op if 'and_with' is an SSC
1844          in its initial state */
1845     else if (! is_ANYOF_SYNTHETIC(and_with)
1846              || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1847     {
1848         /* But if 'ssc' is in its initial state, the result is just 'and_with';
1849          * copy it over 'ssc' */
1850         if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1851             if (is_ANYOF_SYNTHETIC(and_with)) {
1852                 StructCopy(and_with, ssc, regnode_ssc);
1853             }
1854             else {
1855                 ssc->invlist = anded_cp_list;
1856                 ANYOF_POSIXL_ZERO(ssc);
1857                 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1858                     ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1859                 }
1860             }
1861         }
1862         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1863                  || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1864         {
1865             /* One or the other of P1, P2 is non-empty. */
1866             if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1867                 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1868             }
1869             ssc_union(ssc, anded_cp_list, FALSE);
1870         }
1871         else { /* P1 = P2 = empty */
1872             ssc_intersection(ssc, anded_cp_list, FALSE);
1873         }
1874     }
1875 }
1876
1877 STATIC void
1878 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1879                const regnode_charclass *or_with)
1880 {
1881     /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1882      * another SSC or a regular ANYOF class.  Can create false positives if
1883      * 'or_with' is to be inverted. */
1884
1885     SV* ored_cp_list;
1886     U8 ored_flags;
1887
1888     PERL_ARGS_ASSERT_SSC_OR;
1889
1890     assert(is_ANYOF_SYNTHETIC(ssc));
1891
1892     /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1893      * the code point inversion list and just the relevant flags */
1894     if (is_ANYOF_SYNTHETIC(or_with)) {
1895         ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1896         ored_flags = ANYOF_FLAGS(or_with);
1897     }
1898     else {
1899         ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1900         ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1901         if (OP(or_with) != ANYOFD) {
1902             ored_flags
1903             |= ANYOF_FLAGS(or_with)
1904              & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1905                 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1906             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1907                 ored_flags |=
1908                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1909             }
1910         }
1911     }
1912
1913     ANYOF_FLAGS(ssc) |= ored_flags;
1914
1915     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1916      * C2 is the list of code points in 'or-with'; P2, its posix classes.
1917      * 'or_with' may be inverted.  When not inverted, we have the simple
1918      * situation of computing:
1919      *  (C1 | P1) | (C2 | P2)  =  (C1 | C2) | (P1 | P2)
1920      * If P1|P2 yields a situation with both a class and its complement are
1921      * set, like having both \w and \W, this matches all code points, and we
1922      * can delete these from the P component of the ssc going forward.  XXX We
1923      * might be able to delete all the P components, but I (khw) am not certain
1924      * about this, and it is better to be safe.
1925      *
1926      * Inverted, we have
1927      *  (C1 | P1) | ~(C2 | P2)  =  (C1 | P1) | (~C2 & ~P2)
1928      *                         <=  (C1 | P1) | ~C2
1929      *                         <=  (C1 | ~C2) | P1
1930      * (which results in actually simpler code than the non-inverted case)
1931      * */
1932
1933     if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1934         && ! is_ANYOF_SYNTHETIC(or_with))
1935     {
1936         /* We ignore P2, leaving P1 going forward */
1937     }   /* else  Not inverted */
1938     else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1939         ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1940         if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1941             unsigned int i;
1942             for (i = 0; i < ANYOF_MAX; i += 2) {
1943                 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1944                 {
1945                     ssc_match_all_cp(ssc);
1946                     ANYOF_POSIXL_CLEAR(ssc, i);
1947                     ANYOF_POSIXL_CLEAR(ssc, i+1);
1948                 }
1949             }
1950         }
1951     }
1952
1953     ssc_union(ssc,
1954               ored_cp_list,
1955               FALSE /* Already has been inverted */
1956               );
1957 }
1958
1959 PERL_STATIC_INLINE void
1960 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1961 {
1962     PERL_ARGS_ASSERT_SSC_UNION;
1963
1964     assert(is_ANYOF_SYNTHETIC(ssc));
1965
1966     _invlist_union_maybe_complement_2nd(ssc->invlist,
1967                                         invlist,
1968                                         invert2nd,
1969                                         &ssc->invlist);
1970 }
1971
1972 PERL_STATIC_INLINE void
1973 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1974                          SV* const invlist,
1975                          const bool invert2nd)
1976 {
1977     PERL_ARGS_ASSERT_SSC_INTERSECTION;
1978
1979     assert(is_ANYOF_SYNTHETIC(ssc));
1980
1981     _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1982                                                invlist,
1983                                                invert2nd,
1984                                                &ssc->invlist);
1985 }
1986
1987 PERL_STATIC_INLINE void
1988 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1989 {
1990     PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1991
1992     assert(is_ANYOF_SYNTHETIC(ssc));
1993
1994     ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1995 }
1996
1997 PERL_STATIC_INLINE void
1998 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1999 {
2000     /* AND just the single code point 'cp' into the SSC 'ssc' */
2001
2002     SV* cp_list = _new_invlist(2);
2003
2004     PERL_ARGS_ASSERT_SSC_CP_AND;
2005
2006     assert(is_ANYOF_SYNTHETIC(ssc));
2007
2008     cp_list = add_cp_to_invlist(cp_list, cp);
2009     ssc_intersection(ssc, cp_list,
2010                      FALSE /* Not inverted */
2011                      );
2012     SvREFCNT_dec_NN(cp_list);
2013 }
2014
2015 PERL_STATIC_INLINE void
2016 S_ssc_clear_locale(regnode_ssc *ssc)
2017 {
2018     /* Set the SSC 'ssc' to not match any locale things */
2019     PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2020
2021     assert(is_ANYOF_SYNTHETIC(ssc));
2022
2023     ANYOF_POSIXL_ZERO(ssc);
2024     ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2025 }
2026
2027 #define NON_OTHER_COUNT   NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2028
2029 STATIC bool
2030 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2031 {
2032     /* The synthetic start class is used to hopefully quickly winnow down
2033      * places where a pattern could start a match in the target string.  If it
2034      * doesn't really narrow things down that much, there isn't much point to
2035      * having the overhead of using it.  This function uses some very crude
2036      * heuristics to decide if to use the ssc or not.
2037      *
2038      * It returns TRUE if 'ssc' rules out more than half what it considers to
2039      * be the "likely" possible matches, but of course it doesn't know what the
2040      * actual things being matched are going to be; these are only guesses
2041      *
2042      * For /l matches, it assumes that the only likely matches are going to be
2043      *      in the 0-255 range, uniformly distributed, so half of that is 127
2044      * For /a and /d matches, it assumes that the likely matches will be just
2045      *      the ASCII range, so half of that is 63
2046      * For /u and there isn't anything matching above the Latin1 range, it
2047      *      assumes that that is the only range likely to be matched, and uses
2048      *      half that as the cut-off: 127.  If anything matches above Latin1,
2049      *      it assumes that all of Unicode could match (uniformly), except for
2050      *      non-Unicode code points and things in the General Category "Other"
2051      *      (unassigned, private use, surrogates, controls and formats).  This
2052      *      is a much large number. */
2053
2054     U32 count = 0;      /* Running total of number of code points matched by
2055                            'ssc' */
2056     UV start, end;      /* Start and end points of current range in inversion
2057                            XXX outdated.  UTF-8 locales are common, what about invert? list */
2058     const U32 max_code_points = (LOC)
2059                                 ?  256
2060                                 : ((  ! UNI_SEMANTICS
2061                                     ||  invlist_highest(ssc->invlist) < 256)
2062                                   ? 128
2063                                   : NON_OTHER_COUNT);
2064     const U32 max_match = max_code_points / 2;
2065
2066     PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2067
2068     invlist_iterinit(ssc->invlist);
2069     while (invlist_iternext(ssc->invlist, &start, &end)) {
2070         if (start >= max_code_points) {
2071             break;
2072         }
2073         end = MIN(end, max_code_points - 1);
2074         count += end - start + 1;
2075         if (count >= max_match) {
2076             invlist_iterfinish(ssc->invlist);
2077             return FALSE;
2078         }
2079     }
2080
2081     return TRUE;
2082 }
2083
2084
2085 STATIC void
2086 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2087 {
2088     /* The inversion list in the SSC is marked mortal; now we need a more
2089      * permanent copy, which is stored the same way that is done in a regular
2090      * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2091      * map */
2092
2093     SV* invlist = invlist_clone(ssc->invlist, NULL);
2094
2095     PERL_ARGS_ASSERT_SSC_FINALIZE;
2096
2097     assert(is_ANYOF_SYNTHETIC(ssc));
2098
2099     /* The code in this file assumes that all but these flags aren't relevant
2100      * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2101      * by the time we reach here */
2102     assert(! (ANYOF_FLAGS(ssc)
2103         & ~( ANYOF_COMMON_FLAGS
2104             |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2105             |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2106
2107     populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2108
2109     set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2110
2111     /* Make sure is clone-safe */
2112     ssc->invlist = NULL;
2113
2114     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2115         ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2116         OP(ssc) = ANYOFPOSIXL;
2117     }
2118     else if (RExC_contains_locale) {
2119         OP(ssc) = ANYOFL;
2120     }
2121
2122     assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2123 }
2124
2125 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2126 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
2127 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2128 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list         \
2129                                ? (TRIE_LIST_CUR( idx ) - 1)           \
2130                                : 0 )
2131
2132
2133 #ifdef DEBUGGING
2134 /*
2135    dump_trie(trie,widecharmap,revcharmap)
2136    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2137    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2138
2139    These routines dump out a trie in a somewhat readable format.
2140    The _interim_ variants are used for debugging the interim
2141    tables that are used to generate the final compressed
2142    representation which is what dump_trie expects.
2143
2144    Part of the reason for their existence is to provide a form
2145    of documentation as to how the different representations function.
2146
2147 */
2148
2149 /*
2150   Dumps the final compressed table form of the trie to Perl_debug_log.
2151   Used for debugging make_trie().
2152 */
2153
2154 STATIC void
2155 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2156             AV *revcharmap, U32 depth)
2157 {
2158     U32 state;
2159     SV *sv=sv_newmortal();
2160     int colwidth= widecharmap ? 6 : 4;
2161     U16 word;
2162     GET_RE_DEBUG_FLAGS_DECL;
2163
2164     PERL_ARGS_ASSERT_DUMP_TRIE;
2165
2166     Perl_re_indentf( aTHX_  "Char : %-6s%-6s%-4s ",
2167         depth+1, "Match","Base","Ofs" );
2168
2169     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2170         SV ** const tmp = av_fetch( revcharmap, state, 0);
2171         if ( tmp ) {
2172             Perl_re_printf( aTHX_  "%*s",
2173                 colwidth,
2174                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2175                             PL_colors[0], PL_colors[1],
2176                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2177                             PERL_PV_ESCAPE_FIRSTCHAR
2178                 )
2179             );
2180         }
2181     }
2182     Perl_re_printf( aTHX_  "\n");
2183     Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2184
2185     for( state = 0 ; state < trie->uniquecharcount ; state++ )
2186         Perl_re_printf( aTHX_  "%.*s", colwidth, "--------");
2187     Perl_re_printf( aTHX_  "\n");
2188
2189     for( state = 1 ; state < trie->statecount ; state++ ) {
2190         const U32 base = trie->states[ state ].trans.base;
2191
2192         Perl_re_indentf( aTHX_  "#%4" UVXf "|", depth+1, (UV)state);
2193
2194         if ( trie->states[ state ].wordnum ) {
2195             Perl_re_printf( aTHX_  " W%4X", trie->states[ state ].wordnum );
2196         } else {
2197             Perl_re_printf( aTHX_  "%6s", "" );
2198         }
2199
2200         Perl_re_printf( aTHX_  " @%4" UVXf " ", (UV)base );
2201
2202         if ( base ) {
2203             U32 ofs = 0;
2204
2205             while( ( base + ofs  < trie->uniquecharcount ) ||
2206                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
2207                      && trie->trans[ base + ofs - trie->uniquecharcount ].check
2208                                                                     != state))
2209                     ofs++;
2210
2211             Perl_re_printf( aTHX_  "+%2" UVXf "[ ", (UV)ofs);
2212
2213             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2214                 if ( ( base + ofs >= trie->uniquecharcount )
2215                         && ( base + ofs - trie->uniquecharcount
2216                                                         < trie->lasttrans )
2217                         && trie->trans[ base + ofs
2218                                     - trie->uniquecharcount ].check == state )
2219                 {
2220                    Perl_re_printf( aTHX_  "%*" UVXf, colwidth,
2221                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2222                    );
2223                 } else {
2224                     Perl_re_printf( aTHX_  "%*s", colwidth,"   ." );
2225                 }
2226             }
2227
2228             Perl_re_printf( aTHX_  "]");
2229
2230         }
2231         Perl_re_printf( aTHX_  "\n" );
2232     }
2233     Perl_re_indentf( aTHX_  "word_info N:(prev,len)=",
2234                                 depth);
2235     for (word=1; word <= trie->wordcount; word++) {
2236         Perl_re_printf( aTHX_  " %d:(%d,%d)",
2237             (int)word, (int)(trie->wordinfo[word].prev),
2238             (int)(trie->wordinfo[word].len));
2239     }
2240     Perl_re_printf( aTHX_  "\n" );
2241 }
2242 /*
2243   Dumps a fully constructed but uncompressed trie in list form.
2244   List tries normally only are used for construction when the number of
2245   possible chars (trie->uniquecharcount) is very high.
2246   Used for debugging make_trie().
2247 */
2248 STATIC void
2249 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2250                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
2251                          U32 depth)
2252 {
2253     U32 state;
2254     SV *sv=sv_newmortal();
2255     int colwidth= widecharmap ? 6 : 4;
2256     GET_RE_DEBUG_FLAGS_DECL;
2257
2258     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2259
2260     /* print out the table precompression.  */
2261     Perl_re_indentf( aTHX_  "State :Word | Transition Data\n",
2262             depth+1 );
2263     Perl_re_indentf( aTHX_  "%s",
2264             depth+1, "------:-----+-----------------\n" );
2265
2266     for( state=1 ; state < next_alloc ; state ++ ) {
2267         U16 charid;
2268
2269         Perl_re_indentf( aTHX_  " %4" UVXf " :",
2270             depth+1, (UV)state  );
2271         if ( ! trie->states[ state ].wordnum ) {
2272             Perl_re_printf( aTHX_  "%5s| ","");
2273         } else {
2274             Perl_re_printf( aTHX_  "W%4x| ",
2275                 trie->states[ state ].wordnum
2276             );
2277         }
2278         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2279             SV ** const tmp = av_fetch( revcharmap,
2280                                         TRIE_LIST_ITEM(state, charid).forid, 0);
2281             if ( tmp ) {
2282                 Perl_re_printf( aTHX_  "%*s:%3X=%4" UVXf " | ",
2283                     colwidth,
2284                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2285                               colwidth,
2286                               PL_colors[0], PL_colors[1],
2287                               (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2288                               | PERL_PV_ESCAPE_FIRSTCHAR
2289                     ) ,
2290                     TRIE_LIST_ITEM(state, charid).forid,
2291                     (UV)TRIE_LIST_ITEM(state, charid).newstate
2292                 );
2293                 if (!(charid % 10))
2294                     Perl_re_printf( aTHX_  "\n%*s| ",
2295                         (int)((depth * 2) + 14), "");
2296             }
2297         }
2298         Perl_re_printf( aTHX_  "\n");
2299     }
2300 }
2301
2302 /*
2303   Dumps a fully constructed but uncompressed trie in table form.
2304   This is the normal DFA style state transition table, with a few
2305   twists to facilitate compression later.
2306   Used for debugging make_trie().
2307 */
2308 STATIC void
2309 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2310                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
2311                           U32 depth)
2312 {
2313     U32 state;
2314     U16 charid;
2315     SV *sv=sv_newmortal();
2316     int colwidth= widecharmap ? 6 : 4;
2317     GET_RE_DEBUG_FLAGS_DECL;
2318
2319     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2320
2321     /*
2322        print out the table precompression so that we can do a visual check
2323        that they are identical.
2324      */
2325
2326     Perl_re_indentf( aTHX_  "Char : ", depth+1 );
2327
2328     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2329         SV ** const tmp = av_fetch( revcharmap, charid, 0);
2330         if ( tmp ) {
2331             Perl_re_printf( aTHX_  "%*s",
2332                 colwidth,
2333                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2334                             PL_colors[0], PL_colors[1],
2335                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2336                             PERL_PV_ESCAPE_FIRSTCHAR
2337                 )
2338             );
2339         }
2340     }
2341
2342     Perl_re_printf( aTHX_ "\n");
2343     Perl_re_indentf( aTHX_  "State+-", depth+1 );
2344
2345     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2346         Perl_re_printf( aTHX_  "%.*s", colwidth,"--------");
2347     }
2348
2349     Perl_re_printf( aTHX_  "\n" );
2350
2351     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2352
2353         Perl_re_indentf( aTHX_  "%4" UVXf " : ",
2354             depth+1,
2355             (UV)TRIE_NODENUM( state ) );
2356
2357         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2358             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2359             if (v)
2360                 Perl_re_printf( aTHX_  "%*" UVXf, colwidth, v );
2361             else
2362                 Perl_re_printf( aTHX_  "%*s", colwidth, "." );
2363         }
2364         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2365             Perl_re_printf( aTHX_  " (%4" UVXf ")\n",
2366                                             (UV)trie->trans[ state ].check );
2367         } else {
2368             Perl_re_printf( aTHX_  " (%4" UVXf ") W%4X\n",
2369                                             (UV)trie->trans[ state ].check,
2370             trie->states[ TRIE_NODENUM( state ) ].wordnum );
2371         }
2372     }
2373 }
2374
2375 #endif
2376
2377
2378 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2379   startbranch: the first branch in the whole branch sequence
2380   first      : start branch of sequence of branch-exact nodes.
2381                May be the same as startbranch
2382   last       : Thing following the last branch.
2383                May be the same as tail.
2384   tail       : item following the branch sequence
2385   count      : words in the sequence
2386   flags      : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2387   depth      : indent depth
2388
2389 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2390
2391 A trie is an N'ary tree where the branches are determined by digital
2392 decomposition of the key. IE, at the root node you look up the 1st character and
2393 follow that branch repeat until you find the end of the branches. Nodes can be
2394 marked as "accepting" meaning they represent a complete word. Eg:
2395
2396   /he|she|his|hers/
2397
2398 would convert into the following structure. Numbers represent states, letters
2399 following numbers represent valid transitions on the letter from that state, if
2400 the number is in square brackets it represents an accepting state, otherwise it
2401 will be in parenthesis.
2402
2403       +-h->+-e->[3]-+-r->(8)-+-s->[9]
2404       |    |
2405       |   (2)
2406       |    |
2407      (1)   +-i->(6)-+-s->[7]
2408       |
2409       +-s->(3)-+-h->(4)-+-e->[5]
2410
2411       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2412
2413 This shows that when matching against the string 'hers' we will begin at state 1
2414 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2415 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2416 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2417 single traverse. We store a mapping from accepting to state to which word was
2418 matched, and then when we have multiple possibilities we try to complete the
2419 rest of the regex in the order in which they occurred in the alternation.
2420
2421 The only prior NFA like behaviour that would be changed by the TRIE support is
2422 the silent ignoring of duplicate alternations which are of the form:
2423
2424  / (DUPE|DUPE) X? (?{ ... }) Y /x
2425
2426 Thus EVAL blocks following a trie may be called a different number of times with
2427 and without the optimisation. With the optimisations dupes will be silently
2428 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2429 the following demonstrates:
2430
2431  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2432
2433 which prints out 'word' three times, but
2434
2435  'words'=~/(word|word|word)(?{ print $1 })S/
2436
2437 which doesnt print it out at all. This is due to other optimisations kicking in.
2438
2439 Example of what happens on a structural level:
2440
2441 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2442
2443    1: CURLYM[1] {1,32767}(18)
2444    5:   BRANCH(8)
2445    6:     EXACT <ac>(16)
2446    8:   BRANCH(11)
2447    9:     EXACT <ad>(16)
2448   11:   BRANCH(14)
2449   12:     EXACT <ab>(16)
2450   16:   SUCCEED(0)
2451   17:   NOTHING(18)
2452   18: END(0)
2453
2454 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2455 and should turn into:
2456
2457    1: CURLYM[1] {1,32767}(18)
2458    5:   TRIE(16)
2459         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2460           <ac>
2461           <ad>
2462           <ab>
2463   16:   SUCCEED(0)
2464   17:   NOTHING(18)
2465   18: END(0)
2466
2467 Cases where tail != last would be like /(?foo|bar)baz/:
2468
2469    1: BRANCH(4)
2470    2:   EXACT <foo>(8)
2471    4: BRANCH(7)
2472    5:   EXACT <bar>(8)
2473    7: TAIL(8)
2474    8: EXACT <baz>(10)
2475   10: END(0)
2476
2477 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2478 and would end up looking like:
2479
2480     1: TRIE(8)
2481       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2482         <foo>
2483         <bar>
2484    7: TAIL(8)
2485    8: EXACT <baz>(10)
2486   10: END(0)
2487
2488     d = uvchr_to_utf8_flags(d, uv, 0);
2489
2490 is the recommended Unicode-aware way of saying
2491
2492     *(d++) = uv;
2493 */
2494
2495 #define TRIE_STORE_REVCHAR(val)                                            \
2496     STMT_START {                                                           \
2497         if (UTF) {                                                         \
2498             SV *zlopp = newSV(UTF8_MAXBYTES);                              \
2499             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
2500             unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2501             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
2502             SvPOK_on(zlopp);                                               \
2503             SvUTF8_on(zlopp);                                              \
2504             av_push(revcharmap, zlopp);                                    \
2505         } else {                                                           \
2506             char ooooff = (char)val;                                           \
2507             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
2508         }                                                                  \
2509         } STMT_END
2510
2511 /* This gets the next character from the input, folding it if not already
2512  * folded. */
2513 #define TRIE_READ_CHAR STMT_START {                                           \
2514     wordlen++;                                                                \
2515     if ( UTF ) {                                                              \
2516         /* if it is UTF then it is either already folded, or does not need    \
2517          * folding */                                                         \
2518         uvc = valid_utf8_to_uvchr( (const U8*) uc, &len);                     \
2519     }                                                                         \
2520     else if (folder == PL_fold_latin1) {                                      \
2521         /* This folder implies Unicode rules, which in the range expressible  \
2522          *  by not UTF is the lower case, with the two exceptions, one of     \
2523          *  which should have been taken care of before calling this */       \
2524         assert(*uc != LATIN_SMALL_LETTER_SHARP_S);                            \
2525         uvc = toLOWER_L1(*uc);                                                \
2526         if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU;         \
2527         len = 1;                                                              \
2528     } else {                                                                  \
2529         /* raw data, will be folded later if needed */                        \
2530         uvc = (U32)*uc;                                                       \
2531         len = 1;                                                              \
2532     }                                                                         \
2533 } STMT_END
2534
2535
2536
2537 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
2538     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
2539         U32 ging = TRIE_LIST_LEN( state ) * 2;                  \
2540         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2541         TRIE_LIST_LEN( state ) = ging;                          \
2542     }                                                           \
2543     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
2544     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
2545     TRIE_LIST_CUR( state )++;                                   \
2546 } STMT_END
2547
2548 #define TRIE_LIST_NEW(state) STMT_START {                       \
2549     Newx( trie->states[ state ].trans.list,                     \
2550         4, reg_trie_trans_le );                                 \
2551      TRIE_LIST_CUR( state ) = 1;                                \
2552      TRIE_LIST_LEN( state ) = 4;                                \
2553 } STMT_END
2554
2555 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
2556     U16 dupe= trie->states[ state ].wordnum;                    \
2557     regnode * const noper_next = regnext( noper );              \
2558                                                                 \
2559     DEBUG_r({                                                   \
2560         /* store the word for dumping */                        \
2561         SV* tmp;                                                \
2562         if (OP(noper) != NOTHING)                               \
2563             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
2564         else                                                    \
2565             tmp = newSVpvn_utf8( "", 0, UTF );                  \
2566         av_push( trie_words, tmp );                             \
2567     });                                                         \
2568                                                                 \
2569     curword++;                                                  \
2570     trie->wordinfo[curword].prev   = 0;                         \
2571     trie->wordinfo[curword].len    = wordlen;                   \
2572     trie->wordinfo[curword].accept = state;                     \
2573                                                                 \
2574     if ( noper_next < tail ) {                                  \
2575         if (!trie->jump)                                        \
2576             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2577                                                  sizeof(U16) ); \
2578         trie->jump[curword] = (U16)(noper_next - convert);      \
2579         if (!jumper)                                            \
2580             jumper = noper_next;                                \
2581         if (!nextbranch)                                        \
2582             nextbranch= regnext(cur);                           \
2583     }                                                           \
2584                                                                 \
2585     if ( dupe ) {                                               \
2586         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
2587         /* chain, so that when the bits of chain are later    */\
2588         /* linked together, the dups appear in the chain      */\
2589         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2590         trie->wordinfo[dupe].prev = curword;                    \
2591     } else {                                                    \
2592         /* we haven't inserted this word yet.                */ \
2593         trie->states[ state ].wordnum = curword;                \
2594     }                                                           \
2595 } STMT_END
2596
2597
2598 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
2599      ( ( base + charid >=  ucharcount                                   \
2600          && base + charid < ubound                                      \
2601          && state == trie->trans[ base - ucharcount + charid ].check    \
2602          && trie->trans[ base - ucharcount + charid ].next )            \
2603            ? trie->trans[ base - ucharcount + charid ].next             \
2604            : ( state==1 ? special : 0 )                                 \
2605       )
2606
2607 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder)           \
2608 STMT_START {                                                \
2609     TRIE_BITMAP_SET(trie, uvc);                             \
2610     /* store the folded codepoint */                        \
2611     if ( folder )                                           \
2612         TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);           \
2613                                                             \
2614     if ( !UTF ) {                                           \
2615         /* store first byte of utf8 representation of */    \
2616         /* variant codepoints */                            \
2617         if (! UVCHR_IS_INVARIANT(uvc)) {                    \
2618             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));   \
2619         }                                                   \
2620     }                                                       \
2621 } STMT_END
2622 #define MADE_TRIE       1
2623 #define MADE_JUMP_TRIE  2
2624 #define MADE_EXACT_TRIE 4
2625
2626 STATIC I32
2627 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2628                   regnode *first, regnode *last, regnode *tail,
2629                   U32 word_count, U32 flags, U32 depth)
2630 {
2631     /* first pass, loop through and scan words */
2632     reg_trie_data *trie;
2633     HV *widecharmap = NULL;
2634     AV *revcharmap = newAV();
2635     regnode *cur;
2636     STRLEN len = 0;
2637     UV uvc = 0;
2638     U16 curword = 0;
2639     U32 next_alloc = 0;
2640     regnode *jumper = NULL;
2641     regnode *nextbranch = NULL;
2642     regnode *convert = NULL;
2643     U32 *prev_states; /* temp array mapping each state to previous one */
2644     /* we just use folder as a flag in utf8 */
2645     const U8 * folder = NULL;
2646
2647     /* in the below add_data call we are storing either 'tu' or 'tuaa'
2648      * which stands for one trie structure, one hash, optionally followed
2649      * by two arrays */
2650 #ifdef DEBUGGING
2651     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2652     AV *trie_words = NULL;
2653     /* along with revcharmap, this only used during construction but both are
2654      * useful during debugging so we store them in the struct when debugging.
2655      */
2656 #else
2657     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2658     STRLEN trie_charcount=0;
2659 #endif
2660     SV *re_trie_maxbuff;
2661     GET_RE_DEBUG_FLAGS_DECL;
2662
2663     PERL_ARGS_ASSERT_MAKE_TRIE;
2664 #ifndef DEBUGGING
2665     PERL_UNUSED_ARG(depth);
2666 #endif
2667
2668     switch (flags) {
2669         case EXACT: case EXACT_ONLY8: case EXACTL: break;
2670         case EXACTFAA:
2671         case EXACTFUP:
2672         case EXACTFU:
2673         case EXACTFLU8: folder = PL_fold_latin1; break;
2674         case EXACTF:  folder = PL_fold; break;
2675         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2676     }
2677
2678     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2679     trie->refcount = 1;
2680     trie->startstate = 1;
2681     trie->wordcount = word_count;
2682     RExC_rxi->data->data[ data_slot ] = (void*)trie;
2683     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2684     if (flags == EXACT || flags == EXACT_ONLY8 || flags == EXACTL)
2685         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2686     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2687                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
2688
2689     DEBUG_r({
2690         trie_words = newAV();
2691     });
2692
2693     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2694     assert(re_trie_maxbuff);
2695     if (!SvIOK(re_trie_maxbuff)) {
2696         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2697     }
2698     DEBUG_TRIE_COMPILE_r({
2699         Perl_re_indentf( aTHX_
2700           "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2701           depth+1,
2702           REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2703           REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2704     });
2705
2706    /* Find the node we are going to overwrite */
2707     if ( first == startbranch && OP( last ) != BRANCH ) {
2708         /* whole branch chain */
2709         convert = first;
2710     } else {
2711         /* branch sub-chain */
2712         convert = NEXTOPER( first );
2713     }
2714
2715     /*  -- First loop and Setup --
2716
2717        We first traverse the branches and scan each word to determine if it
2718        contains widechars, and how many unique chars there are, this is
2719        important as we have to build a table with at least as many columns as we
2720        have unique chars.
2721
2722        We use an array of integers to represent the character codes 0..255
2723        (trie->charmap) and we use a an HV* to store Unicode characters. We use
2724        the native representation of the character value as the key and IV's for
2725        the coded index.
2726
2727        *TODO* If we keep track of how many times each character is used we can
2728        remap the columns so that the table compression later on is more
2729        efficient in terms of memory by ensuring the most common value is in the
2730        middle and the least common are on the outside.  IMO this would be better
2731        than a most to least common mapping as theres a decent chance the most
2732        common letter will share a node with the least common, meaning the node
2733        will not be compressible. With a middle is most common approach the worst
2734        case is when we have the least common nodes twice.
2735
2736      */
2737
2738     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2739         regnode *noper = NEXTOPER( cur );
2740         const U8 *uc;
2741         const U8 *e;
2742         int foldlen = 0;
2743         U32 wordlen      = 0;         /* required init */
2744         STRLEN minchars = 0;
2745         STRLEN maxchars = 0;
2746         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2747                                                bitmap?*/
2748
2749         if (OP(noper) == NOTHING) {
2750             /* skip past a NOTHING at the start of an alternation
2751              * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2752              */
2753             regnode *noper_next= regnext(noper);
2754             if (noper_next < tail)
2755                 noper= noper_next;
2756         }
2757
2758         if (    noper < tail
2759             && (    OP(noper) == flags
2760                 || (flags == EXACT && OP(noper) == EXACT_ONLY8)
2761                 || (flags == EXACTFU && (   OP(noper) == EXACTFU_ONLY8
2762                                          || OP(noper) == EXACTFUP))))
2763         {
2764             uc= (U8*)STRING(noper);
2765             e= uc + STR_LEN(noper);
2766         } else {
2767             trie->minlen= 0;
2768             continue;
2769         }
2770
2771
2772         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2773             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2774                                           regardless of encoding */
2775             if (OP( noper ) == EXACTFUP) {
2776                 /* false positives are ok, so just set this */
2777                 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2778             }
2779         }
2780
2781         for ( ; uc < e ; uc += len ) {  /* Look at each char in the current
2782                                            branch */
2783             TRIE_CHARCOUNT(trie)++;
2784             TRIE_READ_CHAR;
2785
2786             /* TRIE_READ_CHAR returns the current character, or its fold if /i
2787              * is in effect.  Under /i, this character can match itself, or
2788              * anything that folds to it.  If not under /i, it can match just
2789              * itself.  Most folds are 1-1, for example k, K, and KELVIN SIGN
2790              * all fold to k, and all are single characters.   But some folds
2791              * expand to more than one character, so for example LATIN SMALL
2792              * LIGATURE FFI folds to the three character sequence 'ffi'.  If
2793              * the string beginning at 'uc' is 'ffi', it could be matched by
2794              * three characters, or just by the one ligature character. (It
2795              * could also be matched by two characters: LATIN SMALL LIGATURE FF
2796              * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2797              * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2798              * match.)  The trie needs to know the minimum and maximum number
2799              * of characters that could match so that it can use size alone to
2800              * quickly reject many match attempts.  The max is simple: it is
2801              * the number of folded characters in this branch (since a fold is
2802              * never shorter than what folds to it. */
2803
2804             maxchars++;
2805
2806             /* And the min is equal to the max if not under /i (indicated by
2807              * 'folder' being NULL), or there are no multi-character folds.  If
2808              * there is a multi-character fold, the min is incremented just
2809              * once, for the character that folds to the sequence.  Each
2810              * character in the sequence needs to be added to the list below of
2811              * characters in the trie, but we count only the first towards the
2812              * min number of characters needed.  This is done through the
2813              * variable 'foldlen', which is returned by the macros that look
2814              * for these sequences as the number of bytes the sequence
2815              * occupies.  Each time through the loop, we decrement 'foldlen' by
2816              * how many bytes the current char occupies.  Only when it reaches
2817              * 0 do we increment 'minchars' or look for another multi-character
2818              * sequence. */
2819             if (folder == NULL) {
2820                 minchars++;
2821             }
2822             else if (foldlen > 0) {
2823                 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2824             }
2825             else {
2826                 minchars++;
2827
2828                 /* See if *uc is the beginning of a multi-character fold.  If
2829                  * so, we decrement the length remaining to look at, to account
2830                  * for the current character this iteration.  (We can use 'uc'
2831                  * instead of the fold returned by TRIE_READ_CHAR because for
2832                  * non-UTF, the latin1_safe macro is smart enough to account
2833                  * for all the unfolded characters, and because for UTF, the
2834                  * string will already have been folded earlier in the
2835                  * compilation process */
2836                 if (UTF) {
2837                     if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2838                         foldlen -= UTF8SKIP(uc);
2839                     }
2840                 }
2841                 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2842                     foldlen--;
2843                 }
2844             }
2845
2846             /* The current character (and any potential folds) should be added
2847              * to the possible matching characters for this position in this
2848              * branch */
2849             if ( uvc < 256 ) {
2850                 if ( folder ) {
2851                     U8 folded= folder[ (U8) uvc ];
2852                     if ( !trie->charmap[ folded ] ) {
2853                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
2854                         TRIE_STORE_REVCHAR( folded );
2855                     }
2856                 }
2857                 if ( !trie->charmap[ uvc ] ) {
2858                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2859                     TRIE_STORE_REVCHAR( uvc );
2860                 }
2861                 if ( set_bit ) {
2862                     /* store the codepoint in the bitmap, and its folded
2863                      * equivalent. */
2864                     TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2865                     set_bit = 0; /* We've done our bit :-) */
2866                 }
2867             } else {
2868
2869                 /* XXX We could come up with the list of code points that fold
2870                  * to this using PL_utf8_foldclosures, except not for
2871                  * multi-char folds, as there may be multiple combinations
2872                  * there that could work, which needs to wait until runtime to
2873                  * resolve (The comment about LIGATURE FFI above is such an
2874                  * example */
2875
2876                 SV** svpp;
2877                 if ( !widecharmap )
2878                     widecharmap = newHV();
2879
2880                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2881
2882                 if ( !svpp )
2883                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2884
2885                 if ( !SvTRUE( *svpp ) ) {
2886                     sv_setiv( *svpp, ++trie->uniquecharcount );
2887                     TRIE_STORE_REVCHAR(uvc);
2888                 }
2889             }
2890         } /* end loop through characters in this branch of the trie */
2891
2892         /* We take the min and max for this branch and combine to find the min
2893          * and max for all branches processed so far */
2894         if( cur == first ) {
2895             trie->minlen = minchars;
2896             trie->maxlen = maxchars;
2897         } else if (minchars < trie->minlen) {
2898             trie->minlen = minchars;
2899         } else if (maxchars > trie->maxlen) {
2900             trie->maxlen = maxchars;
2901         }
2902     } /* end first pass */
2903     DEBUG_TRIE_COMPILE_r(
2904         Perl_re_indentf( aTHX_
2905                 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2906                 depth+1,
2907                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2908                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2909                 (int)trie->minlen, (int)trie->maxlen )
2910     );
2911
2912     /*
2913         We now know what we are dealing with in terms of unique chars and
2914         string sizes so we can calculate how much memory a naive
2915         representation using a flat table  will take. If it's over a reasonable
2916         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2917         conservative but potentially much slower representation using an array
2918         of lists.
2919
2920         At the end we convert both representations into the same compressed
2921         form that will be used in regexec.c for matching with. The latter
2922         is a form that cannot be used to construct with but has memory
2923         properties similar to the list form and access properties similar
2924         to the table form making it both suitable for fast searches and
2925         small enough that its feasable to store for the duration of a program.
2926
2927         See the comment in the code where the compressed table is produced
2928         inplace from the flat tabe representation for an explanation of how
2929         the compression works.
2930
2931     */
2932
2933
2934     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2935     prev_states[1] = 0;
2936
2937     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2938                                                     > SvIV(re_trie_maxbuff) )
2939     {
2940         /*
2941             Second Pass -- Array Of Lists Representation
2942
2943             Each state will be represented by a list of charid:state records
2944             (reg_trie_trans_le) the first such element holds the CUR and LEN
2945             points of the allocated array. (See defines above).
2946
2947             We build the initial structure using the lists, and then convert
2948             it into the compressed table form which allows faster lookups
2949             (but cant be modified once converted).
2950         */
2951
2952         STRLEN transcount = 1;
2953
2954         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using list compiler\n",
2955             depth+1));
2956
2957         trie->states = (reg_trie_state *)
2958             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2959                                   sizeof(reg_trie_state) );
2960         TRIE_LIST_NEW(1);
2961         next_alloc = 2;
2962
2963         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2964
2965             regnode *noper   = NEXTOPER( cur );
2966             U32 state        = 1;         /* required init */
2967             U16 charid       = 0;         /* sanity init */
2968             U32 wordlen      = 0;         /* required init */
2969
2970             if (OP(noper) == NOTHING) {
2971                 regnode *noper_next= regnext(noper);
2972                 if (noper_next < tail)
2973                     noper= noper_next;
2974             }
2975
2976             if (    noper < tail
2977                 && (    OP(noper) == flags
2978                     || (flags == EXACT && OP(noper) == EXACT_ONLY8)
2979                     || (flags == EXACTFU && (   OP(noper) == EXACTFU_ONLY8
2980                                              || OP(noper) == EXACTFUP))))
2981             {
2982                 const U8 *uc= (U8*)STRING(noper);
2983                 const U8 *e= uc + STR_LEN(noper);
2984
2985                 for ( ; uc < e ; uc += len ) {
2986
2987                     TRIE_READ_CHAR;
2988
2989                     if ( uvc < 256 ) {
2990                         charid = trie->charmap[ uvc ];
2991                     } else {
2992                         SV** const svpp = hv_fetch( widecharmap,
2993                                                     (char*)&uvc,
2994                                                     sizeof( UV ),
2995                                                     0);
2996                         if ( !svpp ) {
2997                             charid = 0;
2998                         } else {
2999                             charid=(U16)SvIV( *svpp );
3000                         }
3001                     }
3002                     /* charid is now 0 if we dont know the char read, or
3003                      * nonzero if we do */
3004                     if ( charid ) {
3005
3006                         U16 check;
3007                         U32 newstate = 0;
3008
3009                         charid--;
3010                         if ( !trie->states[ state ].trans.list ) {
3011                             TRIE_LIST_NEW( state );
3012                         }
3013                         for ( check = 1;
3014                               check <= TRIE_LIST_USED( state );
3015                               check++ )
3016                         {
3017                             if ( TRIE_LIST_ITEM( state, check ).forid
3018                                                                     == charid )
3019                             {
3020                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3021                                 break;
3022                             }
3023                         }
3024                         if ( ! newstate ) {
3025                             newstate = next_alloc++;
3026                             prev_states[newstate] = state;
3027                             TRIE_LIST_PUSH( state, charid, newstate );
3028                             transcount++;
3029                         }
3030                         state = newstate;
3031                     } else {
3032                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3033                     }
3034                 }
3035             }
3036             TRIE_HANDLE_WORD(state);
3037
3038         } /* end second pass */
3039
3040         /* next alloc is the NEXT state to be allocated */
3041         trie->statecount = next_alloc;
3042         trie->states = (reg_trie_state *)
3043             PerlMemShared_realloc( trie->states,
3044                                    next_alloc
3045                                    * sizeof(reg_trie_state) );
3046
3047         /* and now dump it out before we compress it */
3048         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3049                                                          revcharmap, next_alloc,
3050                                                          depth+1)
3051         );
3052
3053         trie->trans = (reg_trie_trans *)
3054             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3055         {
3056             U32 state;
3057             U32 tp = 0;
3058             U32 zp = 0;
3059
3060
3061             for( state=1 ; state < next_alloc ; state ++ ) {
3062                 U32 base=0;
3063
3064                 /*
3065                 DEBUG_TRIE_COMPILE_MORE_r(
3066                     Perl_re_printf( aTHX_  "tp: %d zp: %d ",tp,zp)
3067                 );
3068                 */
3069
3070                 if (trie->states[state].trans.list) {
3071                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3072                     U16 maxid=minid;
3073                     U16 idx;
3074
3075                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3076                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3077                         if ( forid < minid ) {
3078                             minid=forid;
3079                         } else if ( forid > maxid ) {
3080                             maxid=forid;
3081                         }
3082                     }
3083                     if ( transcount < tp + maxid - minid + 1) {
3084                         transcount *= 2;
3085                         trie->trans = (reg_trie_trans *)
3086                             PerlMemShared_realloc( trie->trans,
3087                                                      transcount
3088                                                      * sizeof(reg_trie_trans) );
3089                         Zero( trie->trans + (transcount / 2),
3090                               transcount / 2,
3091                               reg_trie_trans );
3092                     }
3093                     base = trie->uniquecharcount + tp - minid;
3094                     if ( maxid == minid ) {
3095                         U32 set = 0;
3096                         for ( ; zp < tp ; zp++ ) {
3097                             if ( ! trie->trans[ zp ].next ) {
3098                                 base = trie->uniquecharcount + zp - minid;
3099                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3100                                                                    1).newstate;
3101                                 trie->trans[ zp ].check = state;
3102                                 set = 1;
3103                                 break;
3104                             }
3105                         }
3106                         if ( !set ) {
3107                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3108                                                                    1).newstate;
3109                             trie->trans[ tp ].check = state;
3110                             tp++;
3111                             zp = tp;
3112                         }
3113                     } else {
3114                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3115                             const U32 tid = base
3116                                            - trie->uniquecharcount
3117                                            + TRIE_LIST_ITEM( state, idx ).forid;
3118                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3119                                                                 idx ).newstate;
3120                             trie->trans[ tid ].check = state;
3121                         }
3122                         tp += ( maxid - minid + 1 );
3123                     }
3124                     Safefree(trie->states[ state ].trans.list);
3125                 }
3126                 /*
3127                 DEBUG_TRIE_COMPILE_MORE_r(
3128                     Perl_re_printf( aTHX_  " base: %d\n",base);
3129                 );
3130                 */
3131                 trie->states[ state ].trans.base=base;
3132             }
3133             trie->lasttrans = tp + 1;
3134         }
3135     } else {
3136         /*
3137            Second Pass -- Flat Table Representation.
3138
3139            we dont use the 0 slot of either trans[] or states[] so we add 1 to
3140            each.  We know that we will need Charcount+1 trans at most to store
3141            the data (one row per char at worst case) So we preallocate both
3142            structures assuming worst case.
3143
3144            We then construct the trie using only the .next slots of the entry
3145            structs.
3146
3147            We use the .check field of the first entry of the node temporarily
3148            to make compression both faster and easier by keeping track of how
3149            many non zero fields are in the node.
3150
3151            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3152            transition.
3153
3154            There are two terms at use here: state as a TRIE_NODEIDX() which is
3155            a number representing the first entry of the node, and state as a
3156            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3157            and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3158            if there are 2 entrys per node. eg:
3159
3160              A B       A B
3161           1. 2 4    1. 3 7
3162           2. 0 3    3. 0 5
3163           3. 0 0    5. 0 0
3164           4. 0 0    7. 0 0
3165
3166            The table is internally in the right hand, idx form. However as we
3167            also have to deal with the states array which is indexed by nodenum
3168            we have to use TRIE_NODENUM() to convert.
3169
3170         */
3171         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using table compiler\n",
3172             depth+1));
3173
3174         trie->trans = (reg_trie_trans *)
3175             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3176                                   * trie->uniquecharcount + 1,
3177                                   sizeof(reg_trie_trans) );
3178         trie->states = (reg_trie_state *)
3179             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3180                                   sizeof(reg_trie_state) );
3181         next_alloc = trie->uniquecharcount + 1;
3182
3183
3184         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3185
3186             regnode *noper   = NEXTOPER( cur );
3187
3188             U32 state        = 1;         /* required init */
3189
3190             U16 charid       = 0;         /* sanity init */
3191             U32 accept_state = 0;         /* sanity init */
3192
3193             U32 wordlen      = 0;         /* required init */
3194
3195             if (OP(noper) == NOTHING) {
3196                 regnode *noper_next= regnext(noper);
3197                 if (noper_next < tail)
3198                     noper= noper_next;
3199             }
3200
3201             if (    noper < tail
3202                 && (    OP(noper) == flags
3203                     || (flags == EXACT && OP(noper) == EXACT_ONLY8)
3204                     || (flags == EXACTFU && (   OP(noper) == EXACTFU_ONLY8
3205                                              || OP(noper) == EXACTFUP))))
3206             {
3207                 const U8 *uc= (U8*)STRING(noper);
3208                 const U8 *e= uc + STR_LEN(noper);
3209
3210                 for ( ; uc < e ; uc += len ) {
3211
3212                     TRIE_READ_CHAR;
3213
3214                     if ( uvc < 256 ) {
3215                         charid = trie->charmap[ uvc ];
3216                     } else {
3217                         SV* const * const svpp = hv_fetch( widecharmap,
3218                                                            (char*)&uvc,
3219                                                            sizeof( UV ),
3220                                                            0);
3221                         charid = svpp ? (U16)SvIV(*svpp) : 0;
3222                     }
3223                     if ( charid ) {
3224                         charid--;
3225                         if ( !trie->trans[ state + charid ].next ) {
3226                             trie->trans[ state + charid ].next = next_alloc;
3227                             trie->trans[ state ].check++;
3228                             prev_states[TRIE_NODENUM(next_alloc)]
3229                                     = TRIE_NODENUM(state);
3230                             next_alloc += trie->uniquecharcount;
3231                         }
3232                         state = trie->trans[ state + charid ].next;
3233                     } else {
3234                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3235                     }
3236                     /* charid is now 0 if we dont know the char read, or
3237                      * nonzero if we do */
3238                 }
3239             }
3240             accept_state = TRIE_NODENUM( state );
3241             TRIE_HANDLE_WORD(accept_state);
3242
3243         } /* end second pass */
3244
3245         /* and now dump it out before we compress it */
3246         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3247                                                           revcharmap,
3248                                                           next_alloc, depth+1));
3249
3250         {
3251         /*
3252            * Inplace compress the table.*
3253
3254            For sparse data sets the table constructed by the trie algorithm will
3255            be mostly 0/FAIL transitions or to put it another way mostly empty.
3256            (Note that leaf nodes will not contain any transitions.)
3257
3258            This algorithm compresses the tables by eliminating most such
3259            transitions, at the cost of a modest bit of extra work during lookup:
3260
3261            - Each states[] entry contains a .base field which indicates the
3262            index in the state[] array wheres its transition data is stored.
3263
3264            - If .base is 0 there are no valid transitions from that node.
3265
3266            - If .base is nonzero then charid is added to it to find an entry in
3267            the trans array.
3268
3269            -If trans[states[state].base+charid].check!=state then the
3270            transition is taken to be a 0/Fail transition. Thus if there are fail
3271            transitions at the front of the node then the .base offset will point
3272            somewhere inside the previous nodes data (or maybe even into a node
3273            even earlier), but the .check field determines if the transition is
3274            valid.
3275
3276            XXX - wrong maybe?
3277            The following process inplace converts the table to the compressed
3278            table: We first do not compress the root node 1,and mark all its
3279            .check pointers as 1 and set its .base pointer as 1 as well. This
3280            allows us to do a DFA construction from the compressed table later,
3281            and ensures that any .base pointers we calculate later are greater
3282            than 0.
3283
3284            - We set 'pos' to indicate the first entry of the second node.
3285
3286            - We then iterate over the columns of the node, finding the first and
3287            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3288            and set the .check pointers accordingly, and advance pos
3289            appropriately and repreat for the next node. Note that when we copy
3290            the next pointers we have to convert them from the original
3291            NODEIDX form to NODENUM form as the former is not valid post
3292            compression.
3293
3294            - If a node has no transitions used we mark its base as 0 and do not
3295            advance the pos pointer.
3296
3297            - If a node only has one transition we use a second pointer into the
3298            structure to fill in allocated fail transitions from other states.
3299            This pointer is independent of the main pointer and scans forward
3300            looking for null transitions that are allocated to a state. When it
3301            finds one it writes the single transition into the "hole".  If the
3302            pointer doesnt find one the single transition is appended as normal.
3303
3304            - Once compressed we can Renew/realloc the structures to release the
3305            excess space.
3306
3307            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3308            specifically Fig 3.47 and the associated pseudocode.
3309
3310            demq
3311         */
3312         const U32 laststate = TRIE_NODENUM( next_alloc );
3313         U32 state, charid;
3314         U32 pos = 0, zp=0;
3315         trie->statecount = laststate;
3316
3317         for ( state = 1 ; state < laststate ; state++ ) {
3318             U8 flag = 0;
3319             const U32 stateidx = TRIE_NODEIDX( state );
3320             const U32 o_used = trie->trans[ stateidx ].check;
3321             U32 used = trie->trans[ stateidx ].check;
3322             trie->trans[ stateidx ].check = 0;
3323
3324             for ( charid = 0;
3325                   used && charid < trie->uniquecharcount;
3326                   charid++ )
3327             {
3328                 if ( flag || trie->trans[ stateidx + charid ].next ) {
3329                     if ( trie->trans[ stateidx + charid ].next ) {
3330                         if (o_used == 1) {
3331                             for ( ; zp < pos ; zp++ ) {
3332                                 if ( ! trie->trans[ zp ].next ) {
3333                                     break;
3334                                 }
3335                             }
3336                             trie->states[ state ].trans.base
3337                                                     = zp
3338                                                       + trie->uniquecharcount
3339                                                       - charid ;
3340                             trie->trans[ zp ].next
3341                                 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3342                                                              + charid ].next );
3343                             trie->trans[ zp ].check = state;
3344                             if ( ++zp > pos ) pos = zp;
3345                             break;
3346                         }
3347                         used--;
3348                     }
3349                     if ( !flag ) {
3350                         flag = 1;
3351                         trie->states[ state ].trans.base
3352                                        = pos + trie->uniquecharcount - charid ;
3353                     }
3354                     trie->trans[ pos ].next
3355                         = SAFE_TRIE_NODENUM(
3356                                        trie->trans[ stateidx + charid ].next );
3357                     trie->trans[ pos ].check = state;
3358                     pos++;
3359                 }
3360             }
3361         }
3362         trie->lasttrans = pos + 1;
3363         trie->states = (reg_trie_state *)
3364             PerlMemShared_realloc( trie->states, laststate
3365                                    * sizeof(reg_trie_state) );
3366         DEBUG_TRIE_COMPILE_MORE_r(
3367             Perl_re_indentf( aTHX_  "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3368                 depth+1,
3369                 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3370                        + 1 ),
3371                 (IV)next_alloc,
3372                 (IV)pos,
3373                 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3374             );
3375
3376         } /* end table compress */
3377     }
3378     DEBUG_TRIE_COMPILE_MORE_r(
3379             Perl_re_indentf( aTHX_  "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3380                 depth+1,
3381                 (UV)trie->statecount,
3382                 (UV)trie->lasttrans)
3383     );
3384     /* resize the trans array to remove unused space */
3385     trie->trans = (reg_trie_trans *)
3386         PerlMemShared_realloc( trie->trans, trie->lasttrans
3387                                * sizeof(reg_trie_trans) );
3388
3389     {   /* Modify the program and insert the new TRIE node */
3390         U8 nodetype =(U8)(flags & 0xFF);
3391         char *str=NULL;
3392
3393 #ifdef DEBUGGING
3394         regnode *optimize = NULL;
3395 #ifdef RE_TRACK_PATTERN_OFFSETS
3396
3397         U32 mjd_offset = 0;
3398         U32 mjd_nodelen = 0;
3399 #endif /* RE_TRACK_PATTERN_OFFSETS */
3400 #endif /* DEBUGGING */
3401         /*
3402            This means we convert either the first branch or the first Exact,
3403            depending on whether the thing following (in 'last') is a branch
3404            or not and whther first is the startbranch (ie is it a sub part of
3405            the alternation or is it the whole thing.)
3406            Assuming its a sub part we convert the EXACT otherwise we convert
3407            the whole branch sequence, including the first.
3408          */
3409         /* Find the node we are going to overwrite */
3410         if ( first != startbranch || OP( last ) == BRANCH ) {
3411             /* branch sub-chain */
3412             NEXT_OFF( first ) = (U16)(last - first);
3413 #ifdef RE_TRACK_PATTERN_OFFSETS
3414             DEBUG_r({
3415                 mjd_offset= Node_Offset((convert));
3416                 mjd_nodelen= Node_Length((convert));
3417             });
3418 #endif
3419             /* whole branch chain */
3420         }
3421 #ifdef RE_TRACK_PATTERN_OFFSETS
3422         else {
3423             DEBUG_r({
3424                 const  regnode *nop = NEXTOPER( convert );
3425                 mjd_offset= Node_Offset((nop));
3426                 mjd_nodelen= Node_Length((nop));
3427             });
3428         }
3429         DEBUG_OPTIMISE_r(
3430             Perl_re_indentf( aTHX_  "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3431                 depth+1,
3432                 (UV)mjd_offset, (UV)mjd_nodelen)
3433         );
3434 #endif
3435         /* But first we check to see if there is a common prefix we can
3436            split out as an EXACT and put in front of the TRIE node.  */
3437         trie->startstate= 1;
3438         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
3439             /* we want to find the first state that has more than
3440              * one transition, if that state is not the first state
3441              * then we have a common prefix which we can remove.
3442              */
3443             U32 state;
3444             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3445                 U32 ofs = 0;
3446                 I32 first_ofs = -1; /* keeps track of the ofs of the first
3447                                        transition, -1 means none */
3448                 U32 count = 0;
3449                 const U32 base = trie->states[ state ].trans.base;
3450
3451                 /* does this state terminate an alternation? */
3452                 if ( trie->states[state].wordnum )
3453                         count = 1;
3454
3455                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3456                     if ( ( base + ofs >= trie->uniquecharcount ) &&
3457                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3458                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3459                     {
3460                         if ( ++count > 1 ) {
3461                             /* we have more than one transition */
3462                             SV **tmp;
3463                             U8 *ch;
3464                             /* if this is the first state there is no common prefix
3465                              * to extract, so we can exit */
3466                             if ( state == 1 ) break;
3467                             tmp = av_fetch( revcharmap, ofs, 0);
3468                             ch = (U8*)SvPV_nolen_const( *tmp );
3469
3470                             /* if we are on count 2 then we need to initialize the
3471                              * bitmap, and store the previous char if there was one
3472                              * in it*/
3473                             if ( count == 2 ) {
3474                                 /* clear the bitmap */
3475                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3476                                 DEBUG_OPTIMISE_r(
3477                                     Perl_re_indentf( aTHX_  "New Start State=%" UVuf " Class: [",
3478                                         depth+1,
3479                                         (UV)state));
3480                                 if (first_ofs >= 0) {
3481                                     SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3482                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3483
3484                                     TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3485                                     DEBUG_OPTIMISE_r(
3486                                         Perl_re_printf( aTHX_  "%s", (char*)ch)
3487                                     );
3488                                 }
3489                             }
3490                             /* store the current firstchar in the bitmap */
3491                             TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3492                             DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3493                         }
3494                         first_ofs = ofs;
3495                     }
3496                 }
3497                 if ( count == 1 ) {
3498                     /* This state has only one transition, its transition is part
3499                      * of a common prefix - we need to concatenate the char it
3500                      * represents to what we have so far. */
3501                     SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3502                     STRLEN len;
3503                     char *ch = SvPV( *tmp, len );
3504                     DEBUG_OPTIMISE_r({
3505                         SV *sv=sv_newmortal();
3506                         Perl_re_indentf( aTHX_  "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3507                             depth+1,
3508                             (UV)state, (UV)first_ofs,
3509                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3510                                 PL_colors[0], PL_colors[1],
3511                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3512                                 PERL_PV_ESCAPE_FIRSTCHAR
3513                             )
3514                         );
3515                     });
3516                     if ( state==1 ) {
3517                         OP( convert ) = nodetype;
3518                         str=STRING(convert);
3519                         STR_LEN(convert)=0;
3520                     }
3521                     STR_LEN(convert) += len;
3522                     while (len--)
3523                         *str++ = *ch++;
3524                 } else {
3525 #ifdef DEBUGGING
3526                     if (state>1)
3527                         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3528 #endif
3529                     break;
3530                 }
3531             }
3532             trie->prefixlen = (state-1);
3533             if (str) {
3534                 regnode *n = convert+NODE_SZ_STR(convert);
3535                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3536                 trie->startstate = state;
3537                 trie->minlen -= (state - 1);
3538                 trie->maxlen -= (state - 1);
3539 #ifdef DEBUGGING
3540                /* At least the UNICOS C compiler choked on this
3541                 * being argument to DEBUG_r(), so let's just have
3542                 * it right here. */
3543                if (
3544 #ifdef PERL_EXT_RE_BUILD
3545                    1
3546 #else
3547                    DEBUG_r_TEST
3548 #endif
3549                    ) {
3550                    regnode *fix = convert;
3551                    U32 word = trie->wordcount;
3552 #ifdef RE_TRACK_PATTERN_OFFSETS
3553                    mjd_nodelen++;
3554 #endif
3555                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3556                    while( ++fix < n ) {
3557                        Set_Node_Offset_Length(fix, 0, 0);
3558                    }
3559                    while (word--) {
3560                        SV ** const tmp = av_fetch( trie_words, word, 0 );
3561                        if (tmp) {
3562                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
3563                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3564                            else
3565                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3566                        }
3567                    }
3568                }
3569 #endif
3570                 if (trie->maxlen) {
3571                     convert = n;
3572                 } else {
3573                     NEXT_OFF(convert) = (U16)(tail - convert);
3574                     DEBUG_r(optimize= n);
3575                 }
3576             }
3577         }
3578         if (!jumper)
3579             jumper = last;
3580         if ( trie->maxlen ) {
3581             NEXT_OFF( convert ) = (U16)(tail - convert);
3582             ARG_SET( convert, data_slot );
3583             /* Store the offset to the first unabsorbed branch in
3584                jump[0], which is otherwise unused by the jump logic.
3585                We use this when dumping a trie and during optimisation. */
3586             if (trie->jump)
3587                 trie->jump[0] = (U16)(nextbranch - convert);
3588
3589             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3590              *   and there is a bitmap
3591              *   and the first "jump target" node we found leaves enough room
3592              * then convert the TRIE node into a TRIEC node, with the bitmap
3593              * embedded inline in the opcode - this is hypothetically faster.
3594              */
3595             if ( !trie->states[trie->startstate].wordnum
3596                  && trie->bitmap
3597                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3598             {
3599                 OP( convert ) = TRIEC;
3600                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3601                 PerlMemShared_free(trie->bitmap);
3602                 trie->bitmap= NULL;
3603             } else
3604                 OP( convert ) = TRIE;
3605
3606             /* store the type in the flags */
3607             convert->flags = nodetype;
3608             DEBUG_r({
3609             optimize = convert
3610                       + NODE_STEP_REGNODE
3611                       + regarglen[ OP( convert ) ];
3612             });
3613             /* XXX We really should free up the resource in trie now,
3614                    as we won't use them - (which resources?) dmq */
3615         }
3616         /* needed for dumping*/
3617         DEBUG_r(if (optimize) {
3618             regnode *opt = convert;
3619
3620             while ( ++opt < optimize) {
3621                 Set_Node_Offset_Length(opt, 0, 0);
3622             }
3623             /*
3624                 Try to clean up some of the debris left after the
3625                 optimisation.
3626              */
3627             while( optimize < jumper ) {
3628                 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3629                 OP( optimize ) = OPTIMIZED;
3630                 Set_Node_Offset_Length(optimize, 0, 0);
3631                 optimize++;
3632             }
3633             Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3634         });
3635     } /* end node insert */
3636
3637     /*  Finish populating the prev field of the wordinfo array.  Walk back
3638      *  from each accept state until we find another accept state, and if
3639      *  so, point the first word's .prev field at the second word. If the
3640      *  second already has a .prev field set, stop now. This will be the
3641      *  case either if we've already processed that word's accept state,
3642      *  or that state had multiple words, and the overspill words were
3643      *  already linked up earlier.
3644      */
3645     {
3646         U16 word;
3647         U32 state;
3648         U16 prev;
3649
3650         for (word=1; word <= trie->wordcount; word++) {
3651             prev = 0;
3652             if (trie->wordinfo[word].prev)
3653                 continue;
3654             state = trie->wordinfo[word].accept;
3655             while (state) {
3656                 state = prev_states[state];
3657                 if (!state)
3658                     break;
3659                 prev = trie->states[state].wordnum;
3660                 if (prev)
3661                     break;
3662             }
3663             trie->wordinfo[word].prev = prev;
3664         }
3665         Safefree(prev_states);
3666     }
3667
3668
3669     /* and now dump out the compressed format */
3670     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3671
3672     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3673 #ifdef DEBUGGING
3674     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3675     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3676 #else
3677     SvREFCNT_dec_NN(revcharmap);
3678 #endif
3679     return trie->jump
3680            ? MADE_JUMP_TRIE
3681            : trie->startstate>1
3682              ? MADE_EXACT_TRIE
3683              : MADE_TRIE;
3684 }
3685
3686 STATIC regnode *
3687 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3688 {
3689 /* The Trie is constructed and compressed now so we can build a fail array if
3690  * it's needed
3691
3692    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3693    3.32 in the
3694    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3695    Ullman 1985/88
3696    ISBN 0-201-10088-6
3697
3698    We find the fail state for each state in the trie, this state is the longest
3699    proper suffix of the current state's 'word' that is also a proper prefix of
3700    another word in our trie. State 1 represents the word '' and is thus the
3701    default fail state. This allows the DFA not to have to restart after its
3702    tried and failed a word at a given point, it simply continues as though it
3703    had been matching the other word in the first place.
3704    Consider
3705       'abcdgu'=~/abcdefg|cdgu/
3706    When we get to 'd' we are still matching the first word, we would encounter
3707    'g' which would fail, which would bring us to the state representing 'd' in
3708    the second word where we would try 'g' and succeed, proceeding to match
3709    'cdgu'.
3710  */
3711  /* add a fail transition */
3712     const U32 trie_offset = ARG(source);
3713     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3714     U32 *q;
3715     const U32 ucharcount = trie->uniquecharcount;
3716     const U32 numstates = trie->statecount;
3717     const U32 ubound = trie->lasttrans + ucharcount;
3718     U32 q_read = 0;
3719     U32 q_write = 0;
3720     U32 charid;
3721     U32 base = trie->states[ 1 ].trans.base;
3722     U32 *fail;
3723     reg_ac_data *aho;
3724     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3725     regnode *stclass;
3726     GET_RE_DEBUG_FLAGS_DECL;
3727
3728     PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3729     PERL_UNUSED_CONTEXT;
3730 #ifndef DEBUGGING
3731     PERL_UNUSED_ARG(depth);
3732 #endif
3733
3734     if ( OP(source) == TRIE ) {
3735         struct regnode_1 *op = (struct regnode_1 *)
3736             PerlMemShared_calloc(1, sizeof(struct regnode_1));
3737         StructCopy(source, op, struct regnode_1);
3738         stclass = (regnode *)op;
3739     } else {
3740         struct regnode_charclass *op = (struct regnode_charclass *)
3741             PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3742         StructCopy(source, op, struct regnode_charclass);
3743         stclass = (regnode *)op;
3744     }
3745     OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3746
3747     ARG_SET( stclass, data_slot );
3748     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3749     RExC_rxi->data->data[ data_slot ] = (void*)aho;
3750     aho->trie=trie_offset;
3751     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3752     Copy( trie->states, aho->states, numstates, reg_trie_state );
3753     Newx( q, numstates, U32);
3754     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3755     aho->refcount = 1;
3756     fail = aho->fail;
3757     /* initialize fail[0..1] to be 1 so that we always have
3758        a valid final fail state */
3759     fail[ 0 ] = fail[ 1 ] = 1;
3760
3761     for ( charid = 0; charid < ucharcount ; charid++ ) {
3762         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3763         if ( newstate ) {
3764             q[ q_write ] = newstate;
3765             /* set to point at the root */
3766             fail[ q[ q_write++ ] ]=1;
3767         }
3768     }
3769     while ( q_read < q_write) {
3770         const U32 cur = q[ q_read++ % numstates ];
3771         base = trie->states[ cur ].trans.base;
3772
3773         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3774             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3775             if (ch_state) {
3776                 U32 fail_state = cur;
3777                 U32 fail_base;
3778                 do {
3779                     fail_state = fail[ fail_state ];
3780                     fail_base = aho->states[ fail_state ].trans.base;
3781                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3782
3783                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3784                 fail[ ch_state ] = fail_state;
3785                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3786                 {
3787                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
3788                 }
3789                 q[ q_write++ % numstates] = ch_state;
3790             }
3791         }
3792     }
3793     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3794        when we fail in state 1, this allows us to use the
3795        charclass scan to find a valid start char. This is based on the principle
3796        that theres a good chance the string being searched contains lots of stuff
3797        that cant be a start char.
3798      */
3799     fail[ 0 ] = fail[ 1 ] = 0;
3800     DEBUG_TRIE_COMPILE_r({
3801         Perl_re_indentf( aTHX_  "Stclass Failtable (%" UVuf " states): 0",
3802                       depth, (UV)numstates
3803         );
3804         for( q_read=1; q_read<numstates; q_read++ ) {
3805             Perl_re_printf( aTHX_  ", %" UVuf, (UV)fail[q_read]);
3806         }
3807         Perl_re_printf( aTHX_  "\n");
3808     });
3809     Safefree(q);
3810     /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3811     return stclass;
3812 }
3813
3814
3815 /* The below joins as many adjacent EXACTish nodes as possible into a single
3816  * one.  The regop may be changed if the node(s) contain certain sequences that
3817  * require special handling.  The joining is only done if:
3818  * 1) there is room in the current conglomerated node to entirely contain the
3819  *    next one.
3820  * 2) they are compatible node types
3821  *
3822  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3823  * these get optimized out
3824  *
3825  * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3826  * as possible, even if that means splitting an existing node so that its first
3827  * part is moved to the preceeding node.  This would maximise the efficiency of
3828  * memEQ during matching.
3829  *
3830  * If a node is to match under /i (folded), the number of characters it matches
3831  * can be different than its character length if it contains a multi-character
3832  * fold.  *min_subtract is set to the total delta number of characters of the
3833  * input nodes.
3834  *
3835  * And *unfolded_multi_char is set to indicate whether or not the node contains
3836  * an unfolded multi-char fold.  This happens when it won't be known until
3837  * runtime whether the fold is valid or not; namely
3838  *  1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3839  *      target string being matched against turns out to be UTF-8 is that fold
3840  *      valid; or
3841  *  2) for EXACTFL nodes whose folding rules depend on the locale in force at
3842  *      runtime.
3843  * (Multi-char folds whose components are all above the Latin1 range are not
3844  * run-time locale dependent, and have already been folded by the time this
3845  * function is called.)
3846  *
3847  * This is as good a place as any to discuss the design of handling these
3848  * multi-character fold sequences.  It's been wrong in Perl for a very long
3849  * time.  There are three code points in Unicode whose multi-character folds
3850  * were long ago discovered to mess things up.  The previous designs for
3851  * dealing with these involved assigning a special node for them.  This
3852  * approach doesn't always work, as evidenced by this example:
3853  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
3854  * Both sides fold to "sss", but if the pattern is parsed to create a node that
3855  * would match just the \xDF, it won't be able to handle the case where a
3856  * successful match would have to cross the node's boundary.  The new approach
3857  * that hopefully generally solves the problem generates an EXACTFUP node
3858  * that is "sss" in this case.
3859  *
3860  * It turns out that there are problems with all multi-character folds, and not
3861  * just these three.  Now the code is general, for all such cases.  The
3862  * approach taken is:
3863  * 1)   This routine examines each EXACTFish node that could contain multi-
3864  *      character folded sequences.  Since a single character can fold into
3865  *      such a sequence, the minimum match length for this node is less than
3866  *      the number of characters in the node.  This routine returns in
3867  *      *min_subtract how many characters to subtract from the the actual
3868  *      length of the string to get a real minimum match length; it is 0 if
3869  *      there are no multi-char foldeds.  This delta is used by the caller to
3870  *      adjust the min length of the match, and the delta between min and max,
3871  *      so that the optimizer doesn't reject these possibilities based on size
3872  *      constraints.
3873  *
3874  * 2)   For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
3875  *      under /u, we fold it to 'ss' in regatom(), and in this routine, after
3876  *      joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
3877  *      EXACTFU nodes.  The node type of such nodes is then changed to
3878  *      EXACTFUP, indicating it is problematic, and needs careful handling.
3879  *      (The procedures in step 1) above are sufficient to handle this case in
3880  *      UTF-8 encoded nodes.)  The reason this is problematic is that this is
3881  *      the only case where there is a possible fold length change in non-UTF-8
3882  *      patterns.  By reserving a special node type for problematic cases, the
3883  *      far more common regular EXACTFU nodes can be processed faster.
3884  *      regexec.c takes advantage of this.
3885  *
3886  *      EXACTFUP has been created as a grab-bag for (hopefully uncommon)
3887  *      problematic cases.   These all only occur when the pattern is not
3888  *      UTF-8.  In addition to the 'ss' sequence where there is a possible fold
3889  *      length change, it handles the situation where the string cannot be
3890  *      entirely folded.  The strings in an EXACTFish node are folded as much
3891  *      as possible during compilation in regcomp.c.  This saves effort in
3892  *      regex matching.  By using an EXACTFUP node when it is not possible to
3893  *      fully fold at compile time, regexec.c can know that everything in an
3894  *      EXACTFU node is folded, so folding can be skipped at runtime.  The only
3895  *      case where folding in EXACTFU nodes can't be done at compile time is
3896  *      the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8.  This
3897  *      is because its fold requires UTF-8 to represent.  Thus EXACTFUP nodes
3898  *      handle two very different cases.  Alternatively, there could have been
3899  *      a node type where there are length changes, one for unfolded, and one
3900  *      for both.  If yet another special case needed to be created, the number
3901  *      of required node types would have to go to 7.  khw figures that even
3902  *      though there are plenty of node types to spare, that the maintenance
3903  *      cost wasn't worth the small speedup of doing it that way, especially
3904  *      since he thinks the MICRO SIGN is rarely encountered in practice.
3905  *
3906  *      There are other cases where folding isn't done at compile time, but
3907  *      none of them are under /u, and hence not for EXACTFU nodes.  The folds
3908  *      in EXACTFL nodes aren't known until runtime, and vary as the locale
3909  *      changes.  Some folds in EXACTF depend on if the runtime target string
3910  *      is UTF-8 or not.  (regatom() will create an EXACTFU node even under /di
3911  *      when no fold in it depends on the UTF-8ness of the target string.)
3912  *
3913  * 3)   A problem remains for unfolded multi-char folds. (These occur when the
3914  *      validity of the fold won't be known until runtime, and so must remain
3915  *      unfolded for now.  This happens for the sharp s in EXACTF and EXACTFAA
3916  *      nodes when the pattern isn't in UTF-8.  (Note, BTW, that there cannot
3917  *      be an EXACTF node with a UTF-8 pattern.)  They also occur for various
3918  *      folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3919  *      The reason this is a problem is that the optimizer part of regexec.c
3920  *      (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3921  *      that a character in the pattern corresponds to at most a single
3922  *      character in the target string.  (And I do mean character, and not byte
3923  *      here, unlike other parts of the documentation that have never been
3924  *      updated to account for multibyte Unicode.)  Sharp s in EXACTF and
3925  *      EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
3926  *      nodes it can match "\x{17F}\x{17F}".  These, along with other ones in
3927  *      EXACTFL nodes, violate the assumption, and they are the only instances
3928  *      where it is violated.  I'm reluctant to try to change the assumption,
3929  *      as the code involved is impenetrable to me (khw), so instead the code
3930  *      here punts.  This routine examines EXACTFL nodes, and (when the pattern
3931  *      isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
3932  *      boolean indicating whether or not the node contains such a fold.  When
3933  *      it is true, the caller sets a flag that later causes the optimizer in
3934  *      this file to not set values for the floating and fixed string lengths,
3935  *      and thus avoids the optimizer code in regexec.c that makes the invalid
3936  *      assumption.  Thus, there is no optimization based on string lengths for
3937  *      EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3938  *      EXACTF and EXACTFAA nodes that contain the sharp s.  (The reason the
3939  *      assumption is wrong only in these cases is that all other non-UTF-8
3940  *      folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3941  *      their expanded versions.  (Again, we can't prefold sharp s to 'ss' in
3942  *      EXACTF nodes because we don't know at compile time if it actually
3943  *      matches 'ss' or not.  For EXACTF nodes it will match iff the target
3944  *      string is in UTF-8.  This is in contrast to EXACTFU nodes, where it
3945  *      always matches; and EXACTFAA where it never does.  In an EXACTFAA node
3946  *      in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3947  *      problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3948  *      string would require the pattern to be forced into UTF-8, the overhead
3949  *      of which we want to avoid.  Similarly the unfolded multi-char folds in
3950  *      EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3951  *      locale.)
3952  *
3953  *      Similarly, the code that generates tries doesn't currently handle
3954  *      not-already-folded multi-char folds, and it looks like a pain to change
3955  *      that.  Therefore, trie generation of EXACTFAA nodes with the sharp s
3956  *      doesn't work.  Instead, such an EXACTFAA is turned into a new regnode,
3957  *      EXACTFAA_NO_TRIE, which the trie code knows not to handle.  Most people
3958  *      using /iaa matching will be doing so almost entirely with ASCII
3959  *      strings, so this should rarely be encountered in practice */
3960
3961 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3962     if (PL_regkind[OP(scan)] == EXACT) \
3963         join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
3964
3965 STATIC U32
3966 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3967                    UV *min_subtract, bool *unfolded_multi_char,
3968                    U32 flags, regnode *val, U32 depth)
3969 {
3970     /* Merge several consecutive EXACTish nodes into one. */
3971
3972     regnode *n = regnext(scan);
3973     U32 stringok = 1;
3974     regnode *next = scan + NODE_SZ_STR(scan);
3975     U32 merged = 0;
3976     U32 stopnow = 0;
3977 #ifdef DEBUGGING
3978     regnode *stop = scan;
3979     GET_RE_DEBUG_FLAGS_DECL;
3980 #else
3981     PERL_UNUSED_ARG(depth);
3982 #endif
3983
3984     PERL_ARGS_ASSERT_JOIN_EXACT;
3985 #ifndef EXPERIMENTAL_INPLACESCAN
3986     PERL_UNUSED_ARG(flags);
3987     PERL_UNUSED_ARG(val);
3988 #endif
3989     DEBUG_PEEP("join", scan, depth, 0);
3990
3991     assert(PL_regkind[OP(scan)] == EXACT);
3992
3993     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
3994      * EXACT ones that are mergeable to the current one. */
3995     while (    n
3996            && (    PL_regkind[OP(n)] == NOTHING
3997                || (stringok && PL_regkind[OP(n)] == EXACT))
3998            && NEXT_OFF(n)
3999            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
4000     {
4001
4002         if (OP(n) == TAIL || n > next)
4003             stringok = 0;
4004         if (PL_regkind[OP(n)] == NOTHING) {
4005             DEBUG_PEEP("skip:", n, depth, 0);
4006             NEXT_OFF(scan) += NEXT_OFF(n);
4007             next = n + NODE_STEP_REGNODE;
4008 #ifdef DEBUGGING
4009             if (stringok)
4010                 stop = n;
4011 #endif
4012             n = regnext(n);
4013         }
4014         else if (stringok) {
4015             const unsigned int oldl = STR_LEN(scan);
4016             regnode * const nnext = regnext(n);
4017
4018             /* XXX I (khw) kind of doubt that this works on platforms (should
4019              * Perl ever run on one) where U8_MAX is above 255 because of lots
4020              * of other assumptions */
4021             /* Don't join if the sum can't fit into a single node */
4022             if (oldl + STR_LEN(n) > U8_MAX)
4023                 break;
4024
4025             /* Joining something that requires UTF-8 with something that
4026              * doesn't, means the result requires UTF-8. */
4027             if (OP(scan) == EXACT && (OP(n) == EXACT_ONLY8)) {
4028                 OP(scan) = EXACT_ONLY8;
4029             }
4030             else if (OP(scan) == EXACT_ONLY8 && (OP(n) == EXACT)) {
4031                 ;   /* join is compatible, no need to change OP */
4032             }
4033             else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_ONLY8)) {
4034                 OP(scan) = EXACTFU_ONLY8;
4035             }
4036             else if ((OP(scan) == EXACTFU_ONLY8) && (OP(n) == EXACTFU)) {
4037                 ;   /* join is compatible, no need to change OP */
4038             }
4039             else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
4040                 ;   /* join is compatible, no need to change OP */
4041             }
4042             else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
4043
4044                  /* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
4045                   * which can join with EXACTFU ones.  We check for this case
4046                   * here.  These need to be resolved to either EXACTFU or
4047                   * EXACTF at joining time.  They have nothing in them that
4048                   * would forbid them from being the more desirable EXACTFU
4049                   * nodes except that they begin and/or end with a single [Ss].
4050                   * The reason this is problematic is because they could be
4051                   * joined in this loop with an adjacent node that ends and/or
4052                   * begins with [Ss] which would then form the sequence 'ss',
4053                   * which matches differently under /di than /ui, in which case
4054                   * EXACTFU can't be used.  If the 'ss' sequence doesn't get
4055                   * formed, the nodes get absorbed into any adjacent EXACTFU
4056                   * node.  And if the only adjacent node is EXACTF, they get
4057                   * absorbed into that, under the theory that a longer node is
4058                   * better than two shorter ones, even if one is EXACTFU.  Note
4059                   * that EXACTFU_ONLY8 is generated only for UTF-8 patterns,
4060                   * and the EXACTFU_S_EDGE ones only for non-UTF-8.  */
4061
4062                 if (STRING(n)[STR_LEN(n)-1] == 's') {
4063
4064                     /* Here the joined node would end with 's'.  If the node
4065                      * following the combination is an EXACTF one, it's better to
4066                      * join this trailing edge 's' node with that one, leaving the
4067                      * current one in 'scan' be the more desirable EXACTFU */
4068                     if (OP(nnext) == EXACTF) {
4069                         break;
4070                     }
4071
4072                     OP(scan) = EXACTFU_S_EDGE;
4073
4074                 }   /* Otherwise, the beginning 's' of the 2nd node just
4075                        becomes an interior 's' in 'scan' */
4076             }
4077             else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
4078                 ;   /* join is compatible, no need to change OP */
4079             }
4080             else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
4081
4082                 /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
4083                  * nodes.  But the latter nodes can be also joined with EXACTFU
4084                  * ones, and that is a better outcome, so if the node following
4085                  * 'n' is EXACTFU, quit now so that those two can be joined
4086                  * later */
4087                 if (OP(nnext) == EXACTFU) {
4088                     break;
4089                 }
4090
4091                 /* The join is compatible, and the combined node will be
4092                  * EXACTF.  (These don't care if they begin or end with 's' */
4093             }
4094             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
4095                 if (   STRING(scan)[STR_LEN(scan)-1] == 's'
4096                     && STRING(n)[0] == 's')
4097                 {
4098                     /* When combined, we have the sequence 'ss', which means we
4099                      * have to remain /di */
4100                     OP(scan) = EXACTF;
4101                 }
4102             }
4103             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
4104                 if (STRING(n)[0] == 's') {
4105                     ;   /* Here the join is compatible and the combined node
4106                            starts with 's', no need to change OP */
4107                 }
4108                 else {  /* Now the trailing 's' is in the interior */
4109                     OP(scan) = EXACTFU;
4110                 }
4111             }
4112             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
4113
4114                 /* The join is compatible, and the combined node will be
4115                  * EXACTF.  (These don't care if they begin or end with 's' */
4116                 OP(scan) = EXACTF;
4117             }
4118             else if (OP(scan) != OP(n)) {
4119
4120                 /* The only other compatible joinings are the same node type */
4121                 break;
4122             }
4123
4124             DEBUG_PEEP("merg", n, depth, 0);
4125             merged++;
4126
4127             NEXT_OFF(scan) += NEXT_OFF(n);
4128             STR_LEN(scan) += STR_LEN(n);
4129             next = n + NODE_SZ_STR(n);
4130             /* Now we can overwrite *n : */
4131             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
4132 #ifdef DEBUGGING
4133             stop = next - 1;
4134 #endif
4135             n = nnext;
4136             if (stopnow) break;
4137         }
4138
4139 #ifdef EXPERIMENTAL_INPLACESCAN
4140         if (flags && !NEXT_OFF(n)) {
4141             DEBUG_PEEP("atch", val, depth, 0);
4142             if (reg_off_by_arg[OP(n)]) {
4143                 ARG_SET(n, val - n);
4144             }
4145             else {
4146                 NEXT_OFF(n) = val - n;
4147             }
4148             stopnow = 1;
4149         }
4150 #endif
4151     }
4152
4153     /* This temporary node can now be turned into EXACTFU, and must, as
4154      * regexec.c doesn't handle it */
4155     if (OP(scan) == EXACTFU_S_EDGE) {
4156         OP(scan) = EXACTFU;
4157     }
4158
4159     *min_subtract = 0;
4160     *unfolded_multi_char = FALSE;
4161
4162     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
4163      * can now analyze for sequences of problematic code points.  (Prior to
4164      * this final joining, sequences could have been split over boundaries, and
4165      * hence missed).  The sequences only happen in folding, hence for any
4166      * non-EXACT EXACTish node */
4167     if (OP(scan) != EXACT && OP(scan) != EXACT_ONLY8 && OP(scan) != EXACTL) {
4168         U8* s0 = (U8*) STRING(scan);
4169         U8* s = s0;
4170         U8* s_end = s0 + STR_LEN(scan);
4171
4172         int total_count_delta = 0;  /* Total delta number of characters that
4173                                        multi-char folds expand to */
4174
4175         /* One pass is made over the node's string looking for all the
4176          * possibilities.  To avoid some tests in the loop, there are two main
4177          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4178          * non-UTF-8 */
4179         if (UTF) {
4180             U8* folded = NULL;
4181
4182             if (OP(scan) == EXACTFL) {
4183                 U8 *d;
4184
4185                 /* An EXACTFL node would already have been changed to another
4186                  * node type unless there is at least one character in it that
4187                  * is problematic; likely a character whose fold definition
4188                  * won't be known until runtime, and so has yet to be folded.
4189                  * For all but the UTF-8 locale, folds are 1-1 in length, but
4190                  * to handle the UTF-8 case, we need to create a temporary
4191                  * folded copy using UTF-8 locale rules in order to analyze it.
4192                  * This is because our macros that look to see if a sequence is
4193                  * a multi-char fold assume everything is folded (otherwise the
4194                  * tests in those macros would be too complicated and slow).
4195                  * Note that here, the non-problematic folds will have already
4196                  * been done, so we can just copy such characters.  We actually
4197                  * don't completely fold the EXACTFL string.  We skip the
4198                  * unfolded multi-char folds, as that would just create work
4199                  * below to figure out the size they already are */
4200
4201                 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4202                 d = folded;
4203                 while (s < s_end) {
4204                     STRLEN s_len = UTF8SKIP(s);
4205                     if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4206                         Copy(s, d, s_len, U8);
4207                         d += s_len;
4208                     }
4209                     else if (is_FOLDS_TO_MULTI_utf8(s)) {
4210                         *unfolded_multi_char = TRUE;
4211                         Copy(s, d, s_len, U8);
4212                         d += s_len;
4213                     }
4214                     else if (isASCII(*s)) {
4215                         *(d++) = toFOLD(*s);
4216                     }
4217                     else {
4218                         STRLEN len;
4219                         _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4220                         d += len;
4221                     }
4222                     s += s_len;
4223                 }
4224
4225                 /* Point the remainder of the routine to look at our temporary
4226                  * folded copy */
4227                 s = folded;
4228                 s_end = d;
4229             } /* End of creating folded copy of EXACTFL string */
4230
4231             /* Examine the string for a multi-character fold sequence.  UTF-8
4232              * patterns have all characters pre-folded by the time this code is
4233              * executed */
4234             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4235                                      length sequence we are looking for is 2 */
4236             {
4237                 int count = 0;  /* How many characters in a multi-char fold */
4238                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4239                 if (! len) {    /* Not a multi-char fold: get next char */
4240                     s += UTF8SKIP(s);
4241                     continue;
4242                 }
4243
4244                 { /* Here is a generic multi-char fold. */
4245                     U8* multi_end  = s + len;
4246
4247                     /* Count how many characters are in it.  In the case of
4248                      * /aa, no folds which contain ASCII code points are
4249                      * allowed, so check for those, and skip if found. */
4250                     if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4251                         count = utf8_length(s, multi_end);
4252                         s = multi_end;
4253                     }
4254                     else {
4255                         while (s < multi_end) {
4256                             if (isASCII(*s)) {
4257                                 s++;
4258                                 goto next_iteration;
4259                             }
4260                             else {
4261                                 s += UTF8SKIP(s);
4262                             }
4263                             count++;
4264                         }
4265                     }
4266                 }
4267
4268                 /* The delta is how long the sequence is minus 1 (1 is how long
4269                  * the character that folds to the sequence is) */
4270                 total_count_delta += count - 1;
4271               next_iteration: ;
4272             }
4273
4274             /* We created a temporary folded copy of the string in EXACTFL
4275              * nodes.  Therefore we need to be sure it doesn't go below zero,
4276              * as the real string could be shorter */
4277             if (OP(scan) == EXACTFL) {
4278                 int total_chars = utf8_length((U8*) STRING(scan),
4279                                            (U8*) STRING(scan) + STR_LEN(scan));
4280                 if (total_count_delta > total_chars) {
4281                     total_count_delta = total_chars;
4282                 }
4283             }
4284
4285             *min_subtract += total_count_delta;
4286             Safefree(folded);
4287         }
4288         else if (OP(scan) == EXACTFAA) {
4289
4290             /* Non-UTF-8 pattern, EXACTFAA node.  There can't be a multi-char
4291              * fold to the ASCII range (and there are no existing ones in the
4292              * upper latin1 range).  But, as outlined in the comments preceding
4293              * this function, we need to flag any occurrences of the sharp s.
4294              * This character forbids trie formation (because of added
4295              * complexity) */
4296 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
4297    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
4298                                       || UNICODE_DOT_DOT_VERSION > 0)
4299             while (s < s_end) {
4300                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4301                     OP(scan) = EXACTFAA_NO_TRIE;
4302                     *unfolded_multi_char = TRUE;
4303                     break;
4304                 }
4305                 s++;
4306             }
4307         }
4308         else {
4309
4310             /* Non-UTF-8 pattern, not EXACTFAA node.  Look for the multi-char
4311              * folds that are all Latin1.  As explained in the comments
4312              * preceding this function, we look also for the sharp s in EXACTF
4313              * and EXACTFL nodes; it can be in the final position.  Otherwise
4314              * we can stop looking 1 byte earlier because have to find at least
4315              * two characters for a multi-fold */
4316             const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4317                               ? s_end
4318                               : s_end -1;
4319
4320             while (s < upper) {
4321                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4322                 if (! len) {    /* Not a multi-char fold. */
4323                     if (*s == LATIN_SMALL_LETTER_SHARP_S
4324                         && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4325                     {
4326                         *unfolded_multi_char = TRUE;
4327                     }
4328                     s++;
4329                     continue;
4330                 }
4331
4332                 if (len == 2
4333                     && isALPHA_FOLD_EQ(*s, 's')
4334                     && isALPHA_FOLD_EQ(*(s+1), 's'))
4335                 {
4336
4337                     /* EXACTF nodes need to know that the minimum length
4338                      * changed so that a sharp s in the string can match this
4339                      * ss in the pattern, but they remain EXACTF nodes, as they
4340                      * won't match this unless the target string is is UTF-8,
4341                      * which we don't know until runtime.  EXACTFL nodes can't
4342                      * transform into EXACTFU nodes */
4343                     if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4344                         OP(scan) = EXACTFUP;
4345                     }
4346                 }
4347
4348                 *min_subtract += len - 1;
4349                 s += len;
4350             }
4351 #endif
4352         }
4353
4354         if (     STR_LEN(scan) == 1
4355             &&   isALPHA_A(* STRING(scan))
4356             &&  (         OP(scan) == EXACTFAA
4357                  || (     OP(scan) == EXACTFU
4358                      && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(scan)))))
4359         {
4360             U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
4361
4362             /* Replace a length 1 ASCII fold pair node with an ANYOFM node,
4363              * with the mask set to the complement of the bit that differs
4364              * between upper and lower case, and the lowest code point of the
4365              * pair (which the '&' forces) */
4366             OP(scan) = ANYOFM;
4367             ARG_SET(scan, *STRING(scan) & mask);
4368             FLAGS(scan) = mask;
4369         }
4370     }
4371
4372 #ifdef DEBUGGING
4373     /* Allow dumping but overwriting the collection of skipped
4374      * ops and/or strings with fake optimized ops */
4375     n = scan + NODE_SZ_STR(scan);
4376     while (n <= stop) {
4377         OP(n) = OPTIMIZED;
4378         FLAGS(n) = 0;
4379         NEXT_OFF(n) = 0;
4380         n++;
4381     }
4382 #endif
4383     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4384     return stopnow;
4385 }
4386
4387 /* REx optimizer.  Converts nodes into quicker variants "in place".
4388    Finds fixed substrings.  */
4389
4390 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4391    to the position after last scanned or to NULL. */
4392
4393 #define INIT_AND_WITHP \
4394     assert(!and_withp); \
4395     Newx(and_withp, 1, regnode_ssc); \
4396     SAVEFREEPV(and_withp)
4397
4398
4399 static void
4400 S_unwind_scan_frames(pTHX_ const void *p)
4401 {
4402     scan_frame *f= (scan_frame *)p;
4403     do {
4404         scan_frame *n= f->next_frame;
4405         Safefree(f);
4406         f= n;
4407     } while (f);
4408 }
4409
4410 /* the return from this sub is the minimum length that could possibly match */
4411 STATIC SSize_t
4412 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4413                         SSize_t *minlenp, SSize_t *deltap,
4414                         regnode *last,
4415                         scan_data_t *data,
4416                         I32 stopparen,
4417                         U32 recursed_depth,
4418                         regnode_ssc *and_withp,
4419                         U32 flags, U32 depth)
4420                         /* scanp: Start here (read-write). */
4421                         /* deltap: Write maxlen-minlen here. */
4422                         /* last: Stop before this one. */
4423                         /* data: string data about the pattern */
4424                         /* stopparen: treat close N as END */
4425                         /* recursed: which subroutines have we recursed into */
4426                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4427 {
4428     dVAR;
4429     /* There must be at least this number of characters to match */
4430     SSize_t min = 0;
4431     I32 pars = 0, code;
4432     regnode *scan = *scanp, *next;
4433     SSize_t delta = 0;
4434     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4435     int is_inf_internal = 0;            /* The studied chunk is infinite */
4436     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4437     scan_data_t data_fake;
4438     SV *re_trie_maxbuff = NULL;
4439     regnode *first_non_open = scan;
4440     SSize_t stopmin = SSize_t_MAX;
4441     scan_frame *frame = NULL;
4442     GET_RE_DEBUG_FLAGS_DECL;
4443
4444     PERL_ARGS_ASSERT_STUDY_CHUNK;
4445     RExC_study_started= 1;
4446
4447     Zero(&data_fake, 1, scan_data_t);
4448
4449     if ( depth == 0 ) {
4450         while (first_non_open && OP(first_non_open) == OPEN)
4451             first_non_open=regnext(first_non_open);
4452     }
4453
4454
4455   fake_study_recurse:
4456     DEBUG_r(
4457         RExC_study_chunk_recursed_count++;
4458     );
4459     DEBUG_OPTIMISE_MORE_r(
4460     {
4461         Perl_re_indentf( aTHX_  "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4462             depth, (long)stopparen,
4463             (unsigned long)RExC_study_chunk_recursed_count,
4464             (unsigned long)depth, (unsigned long)recursed_depth,
4465             scan,
4466             last);
4467         if (recursed_depth) {
4468             U32 i;
4469             U32 j;
4470             for ( j = 0 ; j < recursed_depth ; j++ ) {
4471                 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4472                     if (
4473                         PAREN_TEST(RExC_study_chunk_recursed +
4474                                    ( j * RExC_study_chunk_recursed_bytes), i )
4475                         && (
4476                             !j ||
4477                             !PAREN_TEST(RExC_study_chunk_recursed +
4478                                    (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
4479                         )
4480                     ) {
4481                         Perl_re_printf( aTHX_ " %d",(int)i);
4482                         break;
4483                     }
4484                 }
4485                 if ( j + 1 < recursed_depth ) {
4486                     Perl_re_printf( aTHX_  ",");
4487                 }
4488             }
4489         }
4490         Perl_re_printf( aTHX_ "\n");
4491     }
4492     );
4493     while ( scan && OP(scan) != END && scan < last ){
4494         UV min_subtract = 0;    /* How mmany chars to subtract from the minimum
4495                                    node length to get a real minimum (because
4496                                    the folded version may be shorter) */
4497         bool unfolded_multi_char = FALSE;
4498         /* Peephole optimizer: */
4499         DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4500         DEBUG_PEEP("Peep", scan, depth, flags);
4501
4502
4503         /* The reason we do this here is that we need to deal with things like
4504          * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4505          * parsing code, as each (?:..) is handled by a different invocation of
4506          * reg() -- Yves
4507          */
4508         JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
4509
4510         /* Follow the next-chain of the current node and optimize
4511            away all the NOTHINGs from it.  */
4512         if (OP(scan) != CURLYX) {
4513             const int max = (reg_off_by_arg[OP(scan)]
4514                        ? I32_MAX
4515                        /* I32 may be smaller than U16 on CRAYs! */
4516                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4517             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4518             int noff;
4519             regnode *n = scan;
4520
4521             /* Skip NOTHING and LONGJMP. */
4522             while ((n = regnext(n))
4523                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4524                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4525                    && off + noff < max)
4526                 off += noff;
4527             if (reg_off_by_arg[OP(scan)])
4528                 ARG(scan) = off;
4529             else
4530                 NEXT_OFF(scan) = off;
4531         }
4532
4533         /* The principal pseudo-switch.  Cannot be a switch, since we
4534            look into several different things.  */
4535         if ( OP(scan) == DEFINEP ) {
4536             SSize_t minlen = 0;
4537             SSize_t deltanext = 0;
4538             SSize_t fake_last_close = 0;
4539             I32 f = SCF_IN_DEFINE;
4540
4541             StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4542             scan = regnext(scan);
4543             assert( OP(scan) == IFTHEN );
4544             DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4545
4546             data_fake.last_closep= &fake_last_close;
4547             minlen = *minlenp;
4548             next = regnext(scan);
4549             scan = NEXTOPER(NEXTOPER(scan));
4550             DEBUG_PEEP("scan", scan, depth, flags);
4551             DEBUG_PEEP("next", next, depth, flags);
4552
4553             /* we suppose the run is continuous, last=next...
4554              * NOTE we dont use the return here! */
4555             /* DEFINEP study_chunk() recursion */
4556             (void)study_chunk(pRExC_state, &scan, &minlen,
4557                               &deltanext, next, &data_fake, stopparen,
4558                               recursed_depth, NULL, f, depth+1);
4559
4560             scan = next;
4561         } else
4562         if (
4563             OP(scan) == BRANCH  ||
4564             OP(scan) == BRANCHJ ||
4565             OP(scan) == IFTHEN
4566         ) {
4567             next = regnext(scan);
4568             code = OP(scan);
4569
4570             /* The op(next)==code check below is to see if we
4571              * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4572              * IFTHEN is special as it might not appear in pairs.
4573              * Not sure whether BRANCH-BRANCHJ is possible, regardless
4574              * we dont handle it cleanly. */
4575             if (OP(next) == code || code == IFTHEN) {
4576                 /* NOTE - There is similar code to this block below for
4577                  * handling TRIE nodes on a re-study.  If you change stuff here
4578                  * check there too. */
4579                 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
4580                 regnode_ssc accum;
4581                 regnode * const startbranch=scan;
4582
4583                 if (flags & SCF_DO_SUBSTR) {
4584                     /* Cannot merge strings after this. */
4585                     scan_commit(pRExC_state, data, minlenp, is_inf);
4586                 }
4587
4588                 if (flags & SCF_DO_STCLASS)
4589                     ssc_init_zero(pRExC_state, &accum);
4590
4591                 while (OP(scan) == code) {
4592                     SSize_t deltanext, minnext, fake;
4593                     I32 f = 0;
4594                     regnode_ssc this_class;
4595
4596                     DEBUG_PEEP("Branch", scan, depth, flags);
4597
4598                     num++;
4599                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4600                     if (data) {
4601                         data_fake.whilem_c = data->whilem_c;
4602                         data_fake.last_closep = data->last_closep;
4603                     }
4604                     else
4605                         data_fake.last_closep = &fake;
4606
4607                     data_fake.pos_delta = delta;
4608                     next = regnext(scan);
4609
4610                     scan = NEXTOPER(scan); /* everything */
4611                     if (code != BRANCH)    /* everything but BRANCH */
4612                         scan = NEXTOPER(scan);
4613
4614                     if (flags & SCF_DO_STCLASS) {
4615                         ssc_init(pRExC_state, &this_class);
4616                         data_fake.start_class = &this_class;
4617                         f = SCF_DO_STCLASS_AND;
4618                     }
4619                     if (flags & SCF_WHILEM_VISITED_POS)
4620                         f |= SCF_WHILEM_VISITED_POS;
4621
4622                     /* we suppose the run is continuous, last=next...*/
4623                     /* recurse study_chunk() for each BRANCH in an alternation */
4624                     minnext = study_chunk(pRExC_state, &scan, minlenp,
4625                                       &deltanext, next, &data_fake, stopparen,
4626                                       recursed_depth, NULL, f, depth+1);
4627
4628                     if (min1 > minnext)
4629                         min1 = minnext;
4630                     if (deltanext == SSize_t_MAX) {
4631                         is_inf = is_inf_internal = 1;
4632                         max1 = SSize_t_MAX;
4633                     } else if (max1 < minnext + deltanext)
4634                         max1 = minnext + deltanext;
4635                     scan = next;
4636                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4637                         pars++;
4638                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4639                         if ( stopmin > minnext)
4640                             stopmin = min + min1;
4641                         flags &= ~SCF_DO_SUBSTR;
4642                         if (data)
4643                             data->flags |= SCF_SEEN_ACCEPT;
4644                     }
4645                     if (data) {
4646                         if (data_fake.flags & SF_HAS_EVAL)
4647                             data->flags |= SF_HAS_EVAL;
4648                         data->whilem_c = data_fake.whilem_c;
4649                     }
4650                     if (flags & SCF_DO_STCLASS)
4651                         ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4652                 }
4653                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4654                     min1 = 0;
4655                 if (flags & SCF_DO_SUBSTR) {
4656                     data->pos_min += min1;
4657                     if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
4658                         data->pos_delta = SSize_t_MAX;
4659                     else
4660                         data->pos_delta += max1 - min1;
4661                     if (max1 != min1 || is_inf)
4662                         data->cur_is_floating = 1;
4663                 }
4664                 min += min1;
4665                 if (delta == SSize_t_MAX
4666                  || SSize_t_MAX - delta - (max1 - min1) < 0)
4667                     delta = SSize_t_MAX;
4668                 else
4669                     delta += max1 - min1;
4670                 if (flags & SCF_DO_STCLASS_OR) {
4671                     ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4672                     if (min1) {
4673                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4674                         flags &= ~SCF_DO_STCLASS;
4675                     }
4676                 }
4677                 else if (flags & SCF_DO_STCLASS_AND) {
4678                     if (min1) {
4679                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4680                         flags &= ~SCF_DO_STCLASS;
4681                     }
4682                     else {
4683                         /* Switch to OR mode: cache the old value of
4684                          * data->start_class */
4685                         INIT_AND_WITHP;
4686                         StructCopy(data->start_class, and_withp, regnode_ssc);
4687                         flags &= ~SCF_DO_STCLASS_AND;
4688                         StructCopy(&accum, data->start_class, regnode_ssc);
4689                         flags |= SCF_DO_STCLASS_OR;
4690                     }
4691                 }
4692
4693                 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4694                         OP( startbranch ) == BRANCH )
4695                 {
4696                 /* demq.
4697
4698                    Assuming this was/is a branch we are dealing with: 'scan'
4699                    now points at the item that follows the branch sequence,
4700                    whatever it is. We now start at the beginning of the
4701                    sequence and look for subsequences of
4702
4703                    BRANCH->EXACT=>x1
4704                    BRANCH->EXACT=>x2
4705                    tail
4706
4707                    which would be constructed from a pattern like
4708                    /A|LIST|OF|WORDS/
4709
4710                    If we can find such a subsequence we need to turn the first
4711                    element into a trie and then add the subsequent branch exact
4712                    strings to the trie.
4713
4714                    We have two cases
4715
4716                      1. patterns where the whole set of branches can be
4717                         converted.
4718
4719                      2. patterns where only a subset can be converted.
4720
4721                    In case 1 we can replace the whole set with a single regop
4722                    for the trie. In case 2 we need to keep the start and end
4723                    branches so
4724
4725                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4726                      becomes BRANCH TRIE; BRANCH X;
4727
4728                   There is an additional case, that being where there is a
4729                   common prefix, which gets split out into an EXACT like node
4730                   preceding the TRIE node.
4731
4732                   If x(1..n)==tail then we can do a simple trie, if not we make
4733                   a "jump" trie, such that when we match the appropriate word
4734                   we "jump" to the appropriate tail node. Essentially we turn
4735                   a nested if into a case structure of sorts.
4736
4737                 */
4738
4739                     int made=0;
4740                     if (!re_trie_maxbuff) {
4741                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4742                         if (!SvIOK(re_trie_maxbuff))
4743                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4744                     }
4745                     if ( SvIV(re_trie_maxbuff)>=0  ) {
4746                         regnode *cur;
4747                         regnode *first = (regnode *)NULL;
4748                         regnode *last = (regnode *)NULL;
4749                         regnode *tail = scan;
4750                         U8 trietype = 0;
4751                         U32 count=0;
4752
4753                         /* var tail is used because there may be a TAIL
4754                            regop in the way. Ie, the exacts will point to the
4755                            thing following the TAIL, but the last branch will
4756                            point at the TAIL. So we advance tail. If we
4757                            have nested (?:) we may have to move through several
4758                            tails.
4759                          */
4760
4761                         while ( OP( tail ) == TAIL ) {
4762                             /* this is the TAIL generated by (?:) */
4763                             tail = regnext( tail );
4764                         }
4765
4766
4767                         DEBUG_TRIE_COMPILE_r({
4768                             regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4769                             Perl_re_indentf( aTHX_  "%s %" UVuf ":%s\n",
4770                               depth+1,
4771                               "Looking for TRIE'able sequences. Tail node is ",
4772                               (UV) REGNODE_OFFSET(tail),
4773                               SvPV_nolen_const( RExC_mysv )
4774                             );
4775                         });
4776
4777                         /*
4778
4779                             Step through the branches
4780                                 cur represents each branch,
4781                                 noper is the first thing to be matched as part
4782                                       of that branch
4783                                 noper_next is the regnext() of that node.
4784
4785                             We normally handle a case like this
4786                             /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4787                             support building with NOJUMPTRIE, which restricts
4788                             the trie logic to structures like /FOO|BAR/.
4789
4790                             If noper is a trieable nodetype then the branch is
4791                             a possible optimization target. If we are building
4792                             under NOJUMPTRIE then we require that noper_next is
4793                             the same as scan (our current position in the regex
4794                             program).
4795
4796                             Once we have two or more consecutive such branches
4797                             we can create a trie of the EXACT's contents and
4798                             stitch it in place into the program.
4799
4800                             If the sequence represents all of the branches in
4801                             the alternation we replace the entire thing with a
4802                             single TRIE node.
4803
4804                             Otherwise when it is a subsequence we need to
4805                             stitch it in place and replace only the relevant
4806                             branches. This means the first branch has to remain
4807                             as it is used by the alternation logic, and its
4808                             next pointer, and needs to be repointed at the item
4809                             on the branch chain following the last branch we
4810                             have optimized away.
4811
4812                             This could be either a BRANCH, in which case the
4813                             subsequence is internal, or it could be the item
4814                             following the branch sequence in which case the
4815                             subsequence is at the end (which does not
4816                             necessarily mean the first node is the start of the
4817                             alternation).
4818
4819                             TRIE_TYPE(X) is a define which maps the optype to a
4820                             trietype.
4821
4822                                 optype          |  trietype
4823                                 ----------------+-----------
4824                                 NOTHING         | NOTHING
4825                                 EXACT           | EXACT
4826                                 EXACT_ONLY8     | EXACT
4827                                 EXACTFU         | EXACTFU
4828                                 EXACTFU_ONLY8   | EXACTFU
4829                                 EXACTFUP        | EXACTFU
4830                                 EXACTFAA        | EXACTFAA
4831                                 EXACTL          | EXACTL
4832                                 EXACTFLU8       | EXACTFLU8
4833
4834
4835                         */
4836 #define TRIE_TYPE(X) ( ( NOTHING == (X) )                                   \
4837                        ? NOTHING                                            \
4838                        : ( EXACT == (X) || EXACT_ONLY8 == (X) )             \
4839                          ? EXACT                                            \
4840                          : (     EXACTFU == (X)                             \
4841                               || EXACTFU_ONLY8 == (X)                       \
4842                               || EXACTFUP == (X) )                          \
4843                            ? EXACTFU                                        \
4844                            : ( EXACTFAA == (X) )                            \
4845                              ? EXACTFAA                                     \
4846                              : ( EXACTL == (X) )                            \
4847                                ? EXACTL                                     \
4848                                : ( EXACTFLU8 == (X) )                       \
4849                                  ? EXACTFLU8                                \
4850                                  : 0 )
4851
4852                         /* dont use tail as the end marker for this traverse */
4853                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4854                             regnode * const noper = NEXTOPER( cur );
4855                             U8 noper_type = OP( noper );
4856                             U8 noper_trietype = TRIE_TYPE( noper_type );
4857 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4858                             regnode * const noper_next = regnext( noper );
4859                             U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4860                             U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
4861 #endif
4862
4863                             DEBUG_TRIE_COMPILE_r({
4864                                 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4865                                 Perl_re_indentf( aTHX_  "- %d:%s (%d)",
4866                                    depth+1,
4867                                    REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4868
4869                                 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4870                                 Perl_re_printf( aTHX_  " -> %d:%s",
4871                                     REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
4872
4873                                 if ( noper_next ) {
4874                                   regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4875                                   Perl_re_printf( aTHX_ "\t=> %d:%s\t",
4876                                     REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
4877                                 }
4878                                 Perl_re_printf( aTHX_  "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
4879                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4880                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4881                                 );
4882                             });
4883
4884                             /* Is noper a trieable nodetype that can be merged
4885                              * with the current trie (if there is one)? */
4886                             if ( noper_trietype
4887                                   &&
4888                                   (
4889                                         ( noper_trietype == NOTHING )
4890                                         || ( trietype == NOTHING )
4891                                         || ( trietype == noper_trietype )
4892                                   )
4893 #ifdef NOJUMPTRIE
4894                                   && noper_next >= tail
4895 #endif
4896                                   && count < U16_MAX)
4897                             {
4898                                 /* Handle mergable triable node Either we are
4899                                  * the first node in a new trieable sequence,
4900                                  * in which case we do some bookkeeping,
4901                                  * otherwise we update the end pointer. */
4902                                 if ( !first ) {
4903                                     first = cur;
4904                                     if ( noper_trietype == NOTHING ) {
4905 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4906                                         regnode * const noper_next = regnext( noper );
4907                                         U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4908                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4909 #endif
4910
4911                                         if ( noper_next_trietype ) {
4912                                             trietype = noper_next_trietype;
4913                                         } else if (noper_next_type)  {
4914                                             /* a NOTHING regop is 1 regop wide.
4915                                              * We need at least two for a trie
4916                                              * so we can't merge this in */
4917                                             first = NULL;
4918                                         }
4919                                     } else {
4920                                         trietype = noper_trietype;
4921                                     }
4922                                 } else {
4923                                     if ( trietype == NOTHING )
4924                                         trietype = noper_trietype;
4925                                     last = cur;
4926                                 }
4927                                 if (first)
4928                                     count++;
4929                             } /* end handle mergable triable node */
4930                             else {
4931                                 /* handle unmergable node -
4932                                  * noper may either be a triable node which can
4933                                  * not be tried together with the current trie,
4934                                  * or a non triable node */
4935                                 if ( last ) {
4936                                     /* If last is set and trietype is not
4937                                      * NOTHING then we have found at least two
4938                                      * triable branch sequences in a row of a
4939                                      * similar trietype so we can turn them
4940                                      * into a trie. If/when we allow NOTHING to
4941                                      * start a trie sequence this condition
4942                                      * will be required, and it isn't expensive
4943                                      * so we leave it in for now. */
4944                                     if ( trietype && trietype != NOTHING )
4945                                         make_trie( pRExC_state,
4946                                                 startbranch, first, cur, tail,
4947                                                 count, trietype, depth+1 );
4948                                     last = NULL; /* note: we clear/update
4949                                                     first, trietype etc below,
4950                                                     so we dont do it here */
4951                                 }
4952                                 if ( noper_trietype
4953 #ifdef NOJUMPTRIE
4954                                      && noper_next >= tail
4955 #endif
4956                                 ){
4957                                     /* noper is triable, so we can start a new
4958                                      * trie sequence */
4959                                     count = 1;
4960                                     first = cur;
4961                                     trietype = noper_trietype;
4962                                 } else if (first) {
4963                                     /* if we already saw a first but the
4964                                      * current node is not triable then we have
4965                                      * to reset the first information. */
4966                                     count = 0;
4967                                     first = NULL;
4968                                     trietype = 0;
4969                                 }
4970                             } /* end handle unmergable node */
4971                         } /* loop over branches */
4972                         DEBUG_TRIE_COMPILE_r({
4973                             regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4974                             Perl_re_indentf( aTHX_  "- %s (%d) <SCAN FINISHED> ",
4975                               depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
4976                             Perl_re_printf( aTHX_  "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
4977                                REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4978                                PL_reg_name[trietype]
4979                             );
4980
4981                         });
4982                         if ( last && trietype ) {
4983                             if ( trietype != NOTHING ) {
4984                                 /* the last branch of the sequence was part of
4985                                  * a trie, so we have to construct it here
4986                                  * outside of the loop */
4987                                 made= make_trie( pRExC_state, startbranch,
4988                                                  first, scan, tail, count,
4989                                                  trietype, depth+1 );
4990 #ifdef TRIE_STUDY_OPT
4991                                 if ( ((made == MADE_EXACT_TRIE &&
4992                                      startbranch == first)
4993                                      || ( first_non_open == first )) &&
4994                                      depth==0 ) {
4995                                     flags |= SCF_TRIE_RESTUDY;
4996                                     if ( startbranch == first
4997                                          && scan >= tail )
4998                                     {
4999                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
5000                                     }
5001                                 }
5002 #endif
5003                             } else {
5004                                 /* at this point we know whatever we have is a
5005                                  * NOTHING sequence/branch AND if 'startbranch'
5006                                  * is 'first' then we can turn the whole thing
5007                                  * into a NOTHING
5008                                  */
5009                                 if ( startbranch == first ) {
5010                                     regnode *opt;
5011                                     /* the entire thing is a NOTHING sequence,
5012                                      * something like this: (?:|) So we can
5013                                      * turn it into a plain NOTHING op. */
5014                                     DEBUG_TRIE_COMPILE_r({
5015                                         regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5016                                         Perl_re_indentf( aTHX_  "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
5017                                           depth+1,
5018                                           SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5019
5020                                     });
5021                                     OP(startbranch)= NOTHING;
5022                                     NEXT_OFF(startbranch)= tail - startbranch;
5023                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
5024                                         OP(opt)= OPTIMIZED;
5025                                 }
5026                             }
5027                         } /* end if ( last) */
5028                     } /* TRIE_MAXBUF is non zero */
5029
5030                 } /* do trie */
5031
5032             }
5033             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
5034                 scan = NEXTOPER(NEXTOPER(scan));
5035             } else                      /* single branch is optimized. */
5036                 scan = NEXTOPER(scan);
5037             continue;
5038         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
5039             I32 paren = 0;
5040             regnode *start = NULL;
5041             regnode *end = NULL;
5042             U32 my_recursed_depth= recursed_depth;
5043
5044             if (OP(scan) != SUSPEND) { /* GOSUB */
5045                 /* Do setup, note this code has side effects beyond
5046                  * the rest of this block. Specifically setting
5047                  * RExC_recurse[] must happen at least once during
5048                  * study_chunk(). */
5049                 paren = ARG(scan);
5050                 RExC_recurse[ARG2L(scan)] = scan;
5051                 start = REGNODE_p(RExC_open_parens[paren]);
5052                 end   = REGNODE_p(RExC_close_parens[paren]);
5053
5054                 /* NOTE we MUST always execute the above code, even
5055                  * if we do nothing with a GOSUB */
5056                 if (
5057                     ( flags & SCF_IN_DEFINE )
5058                     ||
5059                     (
5060                         (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
5061                         &&
5062                         ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
5063                     )
5064                 ) {
5065                     /* no need to do anything here if we are in a define. */
5066                     /* or we are after some kind of infinite construct
5067                      * so we can skip recursing into this item.
5068                      * Since it is infinite we will not change the maxlen
5069                      * or delta, and if we miss something that might raise
5070                      * the minlen it will merely pessimise a little.
5071                      *
5072                      * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
5073                      * might result in a minlen of 1 and not of 4,
5074                      * but this doesn't make us mismatch, just try a bit
5075                      * harder than we should.
5076                      * */
5077                     scan= regnext(scan);
5078                     continue;
5079                 }
5080
5081                 if (
5082                     !recursed_depth
5083                     ||
5084                     !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
5085                 ) {
5086                     /* it is quite possible that there are more efficient ways
5087                      * to do this. We maintain a bitmap per level of recursion
5088                      * of which patterns we have entered so we can detect if a
5089                      * pattern creates a possible infinite loop. When we
5090                      * recurse down a level we copy the previous levels bitmap
5091                      * down. When we are at recursion level 0 we zero the top
5092                      * level bitmap. It would be nice to implement a different
5093                      * more efficient way of doing this. In particular the top
5094                      * level bitmap may be unnecessary.
5095                      */
5096                     if (!recursed_depth) {
5097                         Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
5098                     } else {
5099                         Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
5100                              RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
5101                              RExC_study_chunk_recursed_bytes, U8);
5102                     }
5103                     /* we havent recursed into this paren yet, so recurse into it */
5104                     DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
5105                     PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
5106                     my_recursed_depth= recursed_depth + 1;
5107                 } else {
5108                     DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
5109                     /* some form of infinite recursion, assume infinite length
5110                      * */
5111                     if (flags & SCF_DO_SUBSTR) {
5112                         scan_commit(pRExC_state, data, minlenp, is_inf);
5113                         data->cur_is_floating = 1;
5114                     }
5115                     is_inf = is_inf_internal = 1;
5116                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5117                         ssc_anything(data->start_class);
5118                     flags &= ~SCF_DO_STCLASS;
5119
5120                     start= NULL; /* reset start so we dont recurse later on. */
5121                 }
5122             } else {
5123                 paren = stopparen;
5124                 start = scan + 2;
5125                 end = regnext(scan);
5126             }
5127             if (start) {
5128                 scan_frame *newframe;
5129                 assert(end);
5130                 if (!RExC_frame_last) {
5131                     Newxz(newframe, 1, scan_frame);
5132                     SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
5133                     RExC_frame_head= newframe;
5134                     RExC_frame_count++;
5135                 } else if (!RExC_frame_last->next_frame) {
5136                     Newxz(newframe, 1, scan_frame);
5137                     RExC_frame_last->next_frame= newframe;
5138                     newframe->prev_frame= RExC_frame_last;
5139                     RExC_frame_count++;
5140                 } else {
5141                     newframe= RExC_frame_last->next_frame;
5142                 }
5143                 RExC_frame_last= newframe;
5144
5145                 newframe->next_regnode = regnext(scan);
5146                 newframe->last_regnode = last;
5147                 newframe->stopparen = stopparen;
5148                 newframe->prev_recursed_depth = recursed_depth;
5149                 newframe->this_prev_frame= frame;
5150
5151                 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
5152                 DEBUG_PEEP("fnew", scan, depth, flags);
5153
5154                 frame = newframe;
5155                 scan =  start;
5156                 stopparen = paren;
5157                 last = end;
5158                 depth = depth + 1;
5159                 recursed_depth= my_recursed_depth;
5160
5161                 continue;
5162             }
5163         }
5164         else if (   OP(scan) == EXACT
5165                  || OP(scan) == EXACT_ONLY8
5166                  || OP(scan) == EXACTL)
5167         {
5168             SSize_t l = STR_LEN(scan);
5169             UV uc;
5170             assert(l);
5171             if (UTF) {
5172                 const U8 * const s = (U8*)STRING(scan);
5173                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
5174                 l = utf8_length(s, s + l);
5175             } else {
5176                 uc = *((U8*)STRING(scan));
5177             }
5178             min += l;
5179             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5180                 /* The code below prefers earlier match for fixed
5181                    offset, later match for variable offset.  */
5182                 if (data->last_end == -1) { /* Update the start info. */
5183                     data->last_start_min = data->pos_min;
5184                     data->last_start_max = is_inf
5185                         ? SSize_t_MAX : data->pos_min + data->pos_delta;
5186                 }
5187                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
5188                 if (UTF)
5189                     SvUTF8_on(data->last_found);
5190                 {
5191                     SV * const sv = data->last_found;
5192                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5193                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5194                     if (mg && mg->mg_len >= 0)
5195                         mg->mg_len += utf8_length((U8*)STRING(scan),
5196                                               (U8*)STRING(scan)+STR_LEN(scan));
5197                 }
5198                 data->last_end = data->pos_min + l;
5199                 data->pos_min += l; /* As in the first entry. */
5200                 data->flags &= ~SF_BEFORE_EOL;
5201             }
5202
5203             /* ANDing the code point leaves at most it, and not in locale, and
5204              * can't match null string */
5205             if (flags & SCF_DO_STCLASS_AND) {
5206                 ssc_cp_and(data->start_class, uc);
5207                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5208                 ssc_clear_locale(data->start_class);
5209             }
5210             else if (flags & SCF_DO_STCLASS_OR) {
5211                 ssc_add_cp(data->start_class, uc);
5212                 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5213
5214                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5215                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5216             }
5217             flags &= ~SCF_DO_STCLASS;
5218         }
5219         else if (PL_regkind[OP(scan)] == EXACT) {
5220             /* But OP != EXACT!, so is EXACTFish */
5221             SSize_t l = STR_LEN(scan);
5222             const U8 * s = (U8*)STRING(scan);
5223
5224             /* Search for fixed substrings supports EXACT only. */
5225             if (flags & SCF_DO_SUBSTR) {
5226                 assert(data);
5227                 scan_commit(pRExC_state, data, minlenp, is_inf);
5228             }
5229             if (UTF) {
5230                 l = utf8_length(s, s + l);
5231             }
5232             if (unfolded_multi_char) {
5233                 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5234             }
5235             min += l - min_subtract;
5236             assert (min >= 0);
5237             delta += min_subtract;
5238             if (flags & SCF_DO_SUBSTR) {
5239                 data->pos_min += l - min_subtract;
5240                 if (data->pos_min < 0) {
5241                     data->pos_min = 0;
5242                 }
5243                 data->pos_delta += min_subtract;
5244                 if (min_subtract) {
5245                     data->cur_is_floating = 1; /* float */
5246                 }
5247             }
5248
5249             if (flags & SCF_DO_STCLASS) {
5250                 SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);
5251
5252                 assert(EXACTF_invlist);
5253                 if (flags & SCF_DO_STCLASS_AND) {
5254                     if (OP(scan) != EXACTFL)
5255                         ssc_clear_locale(data->start_class);
5256                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5257                     ANYOF_POSIXL_ZERO(data->start_class);
5258                     ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5259                 }
5260                 else {  /* SCF_DO_STCLASS_OR */
5261                     ssc_union(data->start_class, EXACTF_invlist, FALSE);
5262                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5263
5264                     /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5265                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5266                 }
5267                 flags &= ~SCF_DO_STCLASS;
5268                 SvREFCNT_dec(EXACTF_invlist);
5269             }
5270         }
5271         else if (REGNODE_VARIES(OP(scan))) {
5272             SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5273             I32 fl = 0, f = flags;
5274             regnode * const oscan = scan;
5275             regnode_ssc this_class;
5276             regnode_ssc *oclass = NULL;
5277             I32 next_is_eval = 0;
5278
5279             switch (PL_regkind[OP(scan)]) {
5280             case WHILEM:                /* End of (?:...)* . */
5281                 scan = NEXTOPER(scan);
5282                 goto finish;
5283             case PLUS:
5284                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5285                     next = NEXTOPER(scan);
5286                     if (   OP(next) == EXACT
5287                         || OP(next) == EXACT_ONLY8
5288                         || OP(next) == EXACTL
5289                         || (flags & SCF_DO_STCLASS))
5290                     {
5291                         mincount = 1;
5292                         maxcount = REG_INFTY;
5293                         next = regnext(scan);
5294                         scan = NEXTOPER(scan);
5295                         goto do_curly;
5296                     }
5297                 }
5298                 if (flags & SCF_DO_SUBSTR)
5299                     data->pos_min++;
5300                 min++;
5301                 /* FALLTHROUGH */
5302             case STAR:
5303                 next = NEXTOPER(scan);
5304
5305                 /* This temporary node can now be turned into EXACTFU, and
5306                  * must, as regexec.c doesn't handle it */
5307                 if (OP(next) == EXACTFU_S_EDGE) {
5308                     OP(next) = EXACTFU;
5309                 }
5310
5311                 if (     STR_LEN(next) == 1
5312                     &&   isALPHA_A(* STRING(next))
5313                     && (         OP(next) == EXACTFAA
5314                         || (     OP(next) == EXACTFU
5315                             && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next)))))
5316                 {
5317                     /* These differ in just one bit */
5318                     U8 mask = ~ ('A' ^ 'a');
5319
5320                     assert(isALPHA_A(* STRING(next)));
5321
5322                     /* Then replace it by an ANYOFM node, with
5323                     * the mask set to the complement of the
5324                     * bit that differs between upper and lower
5325                     * case, and the lowest code point of the
5326                     * pair (which the '&' forces) */
5327                     OP(next) = ANYOFM;
5328                     ARG_SET(next, *STRING(next) & mask);
5329                     FLAGS(next) = mask;
5330                 }
5331
5332                 if (flags & SCF_DO_STCLASS) {
5333                     mincount = 0;
5334                     maxcount = REG_INFTY;
5335                     next = regnext(scan);
5336                     scan = NEXTOPER(scan);
5337                     goto do_curly;
5338                 }
5339                 if (flags & SCF_DO_SUBSTR) {
5340                     scan_commit(pRExC_state, data, minlenp, is_inf);
5341                     /* Cannot extend fixed substrings */
5342                     data->cur_is_floating = 1; /* float */
5343                 }
5344                 is_inf = is_inf_internal = 1;
5345                 scan = regnext(scan);
5346                 goto optimize_curly_tail;
5347             case CURLY:
5348                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5349                     && (scan->flags == stopparen))
5350                 {
5351                     mincount = 1;
5352                     maxcount = 1;
5353                 } else {
5354                     mincount = ARG1(scan);
5355                     maxcount = ARG2(scan);
5356                 }
5357                 next = regnext(scan);
5358                 if (OP(scan) == CURLYX) {
5359                     I32 lp = (data ? *(data->last_closep) : 0);
5360                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5361                 }
5362                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5363                 next_is_eval = (OP(scan) == EVAL);
5364               do_curly:
5365                 if (flags & SCF_DO_SUBSTR) {
5366                     if (mincount == 0)
5367                         scan_commit(pRExC_state, data, minlenp, is_inf);
5368                     /* Cannot extend fixed substrings */
5369                     pos_before = data->pos_min;
5370                 }
5371                 if (data) {
5372                     fl = data->flags;
5373                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5374                     if (is_inf)
5375                         data->flags |= SF_IS_INF;
5376                 }
5377                 if (flags & SCF_DO_STCLASS) {
5378                     ssc_init(pRExC_state, &this_class);
5379                     oclass = data->start_class;
5380                     data->start_class = &this_class;
5381                     f |= SCF_DO_STCLASS_AND;
5382                     f &= ~SCF_DO_STCLASS_OR;
5383                 }
5384                 /* Exclude from super-linear cache processing any {n,m}
5385                    regops for which the combination of input pos and regex
5386                    pos is not enough information to determine if a match
5387                    will be possible.
5388
5389                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
5390                    regex pos at the \s*, the prospects for a match depend not
5391                    only on the input position but also on how many (bar\s*)
5392                    repeats into the {4,8} we are. */
5393                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5394                     f &= ~SCF_WHILEM_VISITED_POS;
5395
5396                 /* This will finish on WHILEM, setting scan, or on NULL: */
5397                 /* recurse study_chunk() on loop bodies */
5398                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5399                                   last, data, stopparen, recursed_depth, NULL,
5400                                   (mincount == 0
5401                                    ? (f & ~SCF_DO_SUBSTR)
5402                                    : f)
5403                                   ,depth+1);
5404
5405                 if (flags & SCF_DO_STCLASS)
5406                     data->start_class = oclass;
5407                 if (mincount == 0 || minnext == 0) {
5408                     if (flags & SCF_DO_STCLASS_OR) {
5409                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5410                     }
5411                     else if (flags & SCF_DO_STCLASS_AND) {
5412                         /* Switch to OR mode: cache the old value of
5413                          * data->start_class */
5414                         INIT_AND_WITHP;
5415                         StructCopy(data->start_class, and_withp, regnode_ssc);
5416                         flags &= ~SCF_DO_STCLASS_AND;
5417                         StructCopy(&this_class, data->start_class, regnode_ssc);
5418                         flags |= SCF_DO_STCLASS_OR;
5419                         ANYOF_FLAGS(data->start_class)
5420                                                 |= SSC_MATCHES_EMPTY_STRING;
5421                     }
5422                 } else {                /* Non-zero len */
5423                     if (flags & SCF_DO_STCLASS_OR) {
5424                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5425                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5426                     }
5427                     else if (flags & SCF_DO_STCLASS_AND)
5428                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5429                     flags &= ~SCF_DO_STCLASS;
5430                 }
5431                 if (!scan)              /* It was not CURLYX, but CURLY. */
5432                     scan = next;
5433                 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5434                     /* ? quantifier ok, except for (?{ ... }) */
5435                     && (next_is_eval || !(mincount == 0 && maxcount == 1))
5436                     && (minnext == 0) && (deltanext == 0)
5437                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5438                     && maxcount <= REG_INFTY/3) /* Complement check for big
5439                                                    count */
5440                 {
5441                     _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5442                         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5443                             "Quantifier unexpected on zero-length expression "
5444                             "in regex m/%" UTF8f "/",
5445                              UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5446                                   RExC_precomp)));
5447                 }
5448
5449                 min += minnext * mincount;
5450                 is_inf_internal |= deltanext == SSize_t_MAX
5451                          || (maxcount == REG_INFTY && minnext + deltanext > 0);
5452                 is_inf |= is_inf_internal;
5453                 if (is_inf) {
5454                     delta = SSize_t_MAX;
5455                 } else {
5456                     delta += (minnext + deltanext) * maxcount
5457                              - minnext * mincount;
5458                 }
5459                 /* Try powerful optimization CURLYX => CURLYN. */
5460                 if (  OP(oscan) == CURLYX && data
5461                       && data->flags & SF_IN_PAR
5462                       && !(data->flags & SF_HAS_EVAL)
5463                       && !deltanext && minnext == 1 ) {
5464                     /* Try to optimize to CURLYN.  */
5465                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5466                     regnode * const nxt1 = nxt;
5467 #ifdef DEBUGGING
5468                     regnode *nxt2;
5469 #endif
5470
5471                     /* Skip open. */
5472                     nxt = regnext(nxt);
5473                     if (!REGNODE_SIMPLE(OP(nxt))
5474                         && !(PL_regkind[OP(nxt)] == EXACT
5475                              && STR_LEN(nxt) == 1))
5476                         goto nogo;
5477 #ifdef DEBUGGING
5478                     nxt2 = nxt;
5479 #endif
5480                     nxt = regnext(nxt);
5481                     if (OP(nxt) != CLOSE)
5482                         goto nogo;
5483                     if (RExC_open_parens) {
5484
5485                         /*open->CURLYM*/
5486                         RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5487
5488                         /*close->while*/
5489                         RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5490                     }
5491                     /* Now we know that nxt2 is the only contents: */
5492                     oscan->flags = (U8)ARG(nxt);
5493                     OP(oscan) = CURLYN;
5494                     OP(nxt1) = NOTHING; /* was OPEN. */
5495
5496 #ifdef DEBUGGING
5497                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5498                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5499                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5500                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
5501                     OP(nxt + 1) = OPTIMIZED; /* was count. */
5502                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5503 #endif
5504                 }
5505               nogo:
5506
5507                 /* Try optimization CURLYX => CURLYM. */
5508                 if (  OP(oscan) == CURLYX && data
5509                       && !(data->flags & SF_HAS_PAR)
5510                       && !(data->flags & SF_HAS_EVAL)
5511                       && !deltanext     /* atom is fixed width */
5512                       && minnext != 0   /* CURLYM can't handle zero width */
5513
5514                          /* Nor characters whose fold at run-time may be
5515                           * multi-character */
5516                       && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5517                 ) {
5518                     /* XXXX How to optimize if data == 0? */
5519                     /* Optimize to a simpler form.  */
5520                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5521                     regnode *nxt2;
5522
5523                     OP(oscan) = CURLYM;
5524                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5525                             && (OP(nxt2) != WHILEM))
5526                         nxt = nxt2;
5527                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
5528                     /* Need to optimize away parenths. */
5529                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5530                         /* Set the parenth number.  */
5531                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5532
5533                         oscan->flags = (U8)ARG(nxt);
5534                         if (RExC_open_parens) {
5535                              /*open->CURLYM*/
5536                             RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5537
5538                             /*close->NOTHING*/
5539                             RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5540                                                          + 1;
5541                         }
5542                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
5543                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
5544
5545 #ifdef DEBUGGING
5546                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5547                         OP(nxt + 1) = OPTIMIZED; /* was count. */
5548                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5549                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5550 #endif
5551 #if 0
5552                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
5553                             regnode *nnxt = regnext(nxt1);
5554                             if (nnxt == nxt) {
5555                                 if (reg_off_by_arg[OP(nxt1)])
5556                                     ARG_SET(nxt1, nxt2 - nxt1);
5557                                 else if (nxt2 - nxt1 < U16_MAX)
5558                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
5559                                 else
5560                                     OP(nxt) = NOTHING;  /* Cannot beautify */
5561                             }
5562                             nxt1 = nnxt;
5563                         }
5564 #endif
5565                         /* Optimize again: */
5566                         /* recurse study_chunk() on optimised CURLYX => CURLYM */
5567                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5568                                     NULL, stopparen, recursed_depth, NULL, 0,
5569                                     depth+1);
5570                     }
5571                     else
5572                         oscan->flags = 0;
5573                 }
5574                 else if ((OP(oscan) == CURLYX)
5575                          && (flags & SCF_WHILEM_VISITED_POS)
5576                          /* See the comment on a similar expression above.
5577                             However, this time it's not a subexpression
5578                             we care about, but the expression itself. */
5579                          && (maxcount == REG_INFTY)
5580                          && data) {
5581                     /* This stays as CURLYX, we can put the count/of pair. */
5582                     /* Find WHILEM (as in regexec.c) */
5583                     regnode *nxt = oscan + NEXT_OFF(oscan);
5584
5585                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5586                         nxt += ARG(nxt);
5587                     nxt = PREVOPER(nxt);
5588                     if (nxt->flags & 0xf) {
5589                         /* we've already set whilem count on this node */
5590                     } else if (++data->whilem_c < 16) {
5591                         assert(data->whilem_c <= RExC_whilem_seen);
5592                         nxt->flags = (U8)(data->whilem_c
5593                             | (RExC_whilem_seen << 4)); /* On WHILEM */
5594                     }
5595                 }
5596                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5597                     pars++;
5598                 if (flags & SCF_DO_SUBSTR) {
5599                     SV *last_str = NULL;
5600                     STRLEN last_chrs = 0;
5601                     int counted = mincount != 0;
5602
5603                     if (data->last_end > 0 && mincount != 0) { /* Ends with a
5604                                                                   string. */
5605                         SSize_t b = pos_before >= data->last_start_min
5606                             ? pos_before : data->last_start_min;
5607                         STRLEN l;
5608                         const char * const s = SvPV_const(data->last_found, l);
5609                         SSize_t old = b - data->last_start_min;
5610
5611                         if (UTF)
5612                             old = utf8_hop((U8*)s, old) - (U8*)s;
5613                         l -= old;
5614                         /* Get the added string: */
5615                         last_str = newSVpvn_utf8(s  + old, l, UTF);
5616                         last_chrs = UTF ? utf8_length((U8*)(s + old),
5617                                             (U8*)(s + old + l)) : l;
5618                         if (deltanext == 0 && pos_before == b) {
5619                             /* What was added is a constant string */
5620                             if (mincount > 1) {
5621
5622                                 SvGROW(last_str, (mincount * l) + 1);
5623                                 repeatcpy(SvPVX(last_str) + l,
5624                                           SvPVX_const(last_str), l,
5625                                           mincount - 1);
5626                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5627                                 /* Add additional parts. */
5628                                 SvCUR_set(data->last_found,
5629                                           SvCUR(data->last_found) - l);
5630                                 sv_catsv(data->last_found, last_str);
5631                                 {
5632                                     SV * sv = data->last_found;
5633                                     MAGIC *mg =
5634                                         SvUTF8(sv) && SvMAGICAL(sv) ?
5635                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5636                                     if (mg && mg->mg_len >= 0)
5637                                         mg->mg_len += last_chrs * (mincount-1);
5638                                 }
5639                                 last_chrs *= mincount;
5640                                 data->last_end += l * (mincount - 1);
5641                             }
5642                         } else {
5643                             /* start offset must point into the last copy */
5644                             data->last_start_min += minnext * (mincount - 1);
5645                             data->last_start_max =
5646                               is_inf
5647                                ? SSize_t_MAX
5648                                : data->last_start_max +
5649                                  (maxcount - 1) * (minnext + data->pos_delta);
5650                         }
5651                     }
5652                     /* It is counted once already... */
5653                     data->pos_min += minnext * (mincount - counted);
5654 #if 0
5655 Perl_re_printf( aTHX_  "counted=%" UVuf " deltanext=%" UVuf
5656                               " SSize_t_MAX=%" UVuf " minnext=%" UVuf
5657                               " maxcount=%" UVuf " mincount=%" UVuf "\n",
5658     (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
5659     (UV)mincount);
5660 if (deltanext != SSize_t_MAX)
5661 Perl_re_printf( aTHX_  "LHS=%" UVuf " RHS=%" UVuf "\n",
5662     (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5663           - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
5664 #endif
5665                     if (deltanext == SSize_t_MAX
5666                         || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
5667                         data->pos_delta = SSize_t_MAX;
5668                     else
5669                         data->pos_delta += - counted * deltanext +
5670                         (minnext + deltanext) * maxcount - minnext * mincount;
5671                     if (mincount != maxcount) {
5672                          /* Cannot extend fixed substrings found inside
5673                             the group.  */
5674                         scan_commit(pRExC_state, data, minlenp, is_inf);
5675                         if (mincount && last_str) {
5676                             SV * const sv = data->last_found;
5677                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5678                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5679
5680                             if (mg)
5681                                 mg->mg_len = -1;
5682                             sv_setsv(sv, last_str);
5683                             data->last_end = data->pos_min;
5684                             data->last_start_min = data->pos_min - last_chrs;
5685                             data->last_start_max = is_inf
5686                                 ? SSize_t_MAX
5687                                 : data->pos_min + data->pos_delta - last_chrs;
5688                         }
5689                         data->cur_is_floating = 1; /* float */
5690                     }
5691                     SvREFCNT_dec(last_str);
5692                 }
5693                 if (data && (fl & SF_HAS_EVAL))
5694                     data->flags |= SF_HAS_EVAL;
5695               optimize_curly_tail:
5696                 if (OP(oscan) != CURLYX) {
5697                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5698                            && NEXT_OFF(next))
5699                         NEXT_OFF(oscan) += NEXT_OFF(next);
5700                 }
5701                 continue;
5702
5703             default:
5704 #ifdef DEBUGGING
5705                 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5706                                                                     OP(scan));
5707 #endif
5708             case REF:
5709             case CLUMP:
5710                 if (flags & SCF_DO_SUBSTR) {
5711                     /* Cannot expect anything... */
5712                     scan_commit(pRExC_state, data, minlenp, is_inf);
5713                     data->cur_is_floating = 1; /* float */
5714                 }
5715                 is_inf = is_inf_internal = 1;
5716                 if (flags & SCF_DO_STCLASS_OR) {
5717                     if (OP(scan) == CLUMP) {
5718                         /* Actually is any start char, but very few code points
5719                          * aren't start characters */
5720                         ssc_match_all_cp(data->start_class);
5721                     }
5722                     else {
5723                         ssc_anything(data->start_class);
5724                     }
5725                 }
5726                 flags &= ~SCF_DO_STCLASS;
5727                 break;
5728             }
5729         }
5730         else if (OP(scan) == LNBREAK) {
5731             if (flags & SCF_DO_STCLASS) {
5732                 if (flags & SCF_DO_STCLASS_AND) {
5733                     ssc_intersection(data->start_class,
5734                                     PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5735                     ssc_clear_locale(data->start_class);
5736                     ANYOF_FLAGS(data->start_class)
5737                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5738                 }
5739                 else if (flags & SCF_DO_STCLASS_OR) {
5740                     ssc_union(data->start_class,
5741                               PL_XPosix_ptrs[_CC_VERTSPACE],
5742                               FALSE);
5743                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5744
5745                     /* See commit msg for
5746                      * 749e076fceedeb708a624933726e7989f2302f6a */
5747                     ANYOF_FLAGS(data->start_class)
5748                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5749                 }
5750                 flags &= ~SCF_DO_STCLASS;
5751             }
5752             min++;
5753             if (delta != SSize_t_MAX)
5754                 delta++;    /* Because of the 2 char string cr-lf */
5755             if (flags & SCF_DO_SUBSTR) {
5756                 /* Cannot expect anything... */
5757                 scan_commit(pRExC_state, data, minlenp, is_inf);
5758                 data->pos_min += 1;
5759                 if (data->pos_delta != SSize_t_MAX) {
5760                     data->pos_delta += 1;
5761                 }
5762                 data->cur_is_floating = 1; /* float */
5763             }
5764         }
5765         else if (REGNODE_SIMPLE(OP(scan))) {
5766
5767             if (flags & SCF_DO_SUBSTR) {
5768                 scan_commit(pRExC_state, data, minlenp, is_inf);
5769                 data->pos_min++;
5770             }
5771             min++;
5772             if (flags & SCF_DO_STCLASS) {
5773                 bool invert = 0;
5774                 SV* my_invlist = NULL;
5775                 U8 namedclass;
5776
5777                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5778                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5779
5780                 /* Some of the logic below assumes that switching
5781                    locale on will only add false positives. */
5782                 switch (OP(scan)) {
5783
5784                 default:
5785 #ifdef DEBUGGING
5786                    Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5787                                                                      OP(scan));
5788 #endif
5789                 case SANY:
5790                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5791                         ssc_match_all_cp(data->start_class);
5792                     break;
5793
5794                 case REG_ANY:
5795                     {
5796                         SV* REG_ANY_invlist = _new_invlist(2);
5797                         REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5798                                                             '\n');
5799                         if (flags & SCF_DO_STCLASS_OR) {
5800                             ssc_union(data->start_class,
5801                                       REG_ANY_invlist,
5802                                       TRUE /* TRUE => invert, hence all but \n
5803                                             */
5804                                       );
5805                         }
5806                         else if (flags & SCF_DO_STCLASS_AND) {
5807                             ssc_intersection(data->start_class,
5808                                              REG_ANY_invlist,
5809                                              TRUE  /* TRUE => invert */
5810                                              );
5811                             ssc_clear_locale(data->start_class);
5812                         }
5813                         SvREFCNT_dec_NN(REG_ANY_invlist);
5814                     }
5815                     break;
5816
5817                 case ANYOFD:
5818                 case ANYOFL:
5819                 case ANYOFPOSIXL:
5820                 case ANYOFH:
5821                 case ANYOF:
5822                     if (flags & SCF_DO_STCLASS_AND)
5823                         ssc_and(pRExC_state, data->start_class,
5824                                 (regnode_charclass *) scan);
5825                     else
5826                         ssc_or(pRExC_state, data->start_class,
5827                                                           (regnode_charclass *) scan);
5828                     break;
5829
5830                 case NANYOFM:
5831                 case ANYOFM:
5832                   {
5833                     SV* cp_list = get_ANYOFM_contents(scan);
5834
5835                     if (flags & SCF_DO_STCLASS_OR) {
5836                         ssc_union(data->start_class, cp_list, invert);
5837                     }
5838                     else if (flags & SCF_DO_STCLASS_AND) {
5839                         ssc_intersection(data->start_class, cp_list, invert);
5840                     }
5841
5842                     SvREFCNT_dec_NN(cp_list);
5843                     break;
5844                   }
5845
5846                 case NPOSIXL:
5847                     invert = 1;
5848                     /* FALLTHROUGH */
5849
5850                 case POSIXL:
5851                     namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5852                     if (flags & SCF_DO_STCLASS_AND) {
5853                         bool was_there = cBOOL(
5854                                           ANYOF_POSIXL_TEST(data->start_class,
5855                                                                  namedclass));
5856                         ANYOF_POSIXL_ZERO(data->start_class);
5857                         if (was_there) {    /* Do an AND */
5858                             ANYOF_POSIXL_SET(data->start_class, namedclass);
5859                         }
5860                         /* No individual code points can now match */
5861                         data->start_class->invlist
5862                                                 = sv_2mortal(_new_invlist(0));
5863                     }
5864                     else {
5865                         int complement = namedclass + ((invert) ? -1 : 1);
5866
5867                         assert(flags & SCF_DO_STCLASS_OR);
5868
5869                         /* If the complement of this class was already there,
5870                          * the result is that they match all code points,
5871                          * (\d + \D == everything).  Remove the classes from
5872                          * future consideration.  Locale is not relevant in
5873                          * this case */
5874                         if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5875                             ssc_match_all_cp(data->start_class);
5876                             ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5877                             ANYOF_POSIXL_CLEAR(data->start_class, complement);
5878                         }
5879                         else {  /* The usual case; just add this class to the
5880                                    existing set */
5881                             ANYOF_POSIXL_SET(data->start_class, namedclass);
5882                         }
5883                     }
5884                     break;
5885
5886                 case NPOSIXA:   /* For these, we always know the exact set of
5887                                    what's matched */
5888                     invert = 1;
5889                     /* FALLTHROUGH */
5890                 case POSIXA:
5891                     my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
5892                     goto join_posix_and_ascii;
5893
5894                 case NPOSIXD:
5895                 case NPOSIXU:
5896                     invert = 1;
5897                     /* FALLTHROUGH */
5898                 case POSIXD:
5899                 case POSIXU:
5900                     my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
5901
5902                     /* NPOSIXD matches all upper Latin1 code points unless the
5903                      * target string being matched is UTF-8, which is
5904                      * unknowable until match time.  Since we are going to
5905                      * invert, we want to get rid of all of them so that the
5906                      * inversion will match all */
5907                     if (OP(scan) == NPOSIXD) {
5908                         _invlist_subtract(my_invlist, PL_UpperLatin1,
5909                                           &my_invlist);
5910                     }
5911
5912                   join_posix_and_ascii:
5913
5914                     if (flags & SCF_DO_STCLASS_AND) {
5915                         ssc_intersection(data->start_class, my_invlist, invert);
5916                         ssc_clear_locale(data->start_class);
5917                     }
5918                     else {
5919                         assert(flags & SCF_DO_STCLASS_OR);
5920                         ssc_union(data->start_class, my_invlist, invert);
5921                     }
5922                     SvREFCNT_dec(my_invlist);
5923                 }
5924                 if (flags & SCF_DO_STCLASS_OR)
5925                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5926                 flags &= ~SCF_DO_STCLASS;
5927             }
5928         }
5929         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
5930             data->flags |= (OP(scan) == MEOL
5931                             ? SF_BEFORE_MEOL
5932                             : SF_BEFORE_SEOL);
5933             scan_commit(pRExC_state, data, minlenp, is_inf);
5934
5935         }
5936         else if (  PL_regkind[OP(scan)] == BRANCHJ
5937                  /* Lookbehind, or need to calculate parens/evals/stclass: */
5938                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
5939                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
5940         {
5941             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5942                 || OP(scan) == UNLESSM )
5943             {
5944                 /* Negative Lookahead/lookbehind
5945                    In this case we can't do fixed string optimisation.
5946                 */
5947
5948                 SSize_t deltanext, minnext, fake = 0;
5949                 regnode *nscan;
5950                 regnode_ssc intrnl;
5951                 int f = 0;
5952
5953                 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
5954                 if (data) {
5955                     data_fake.whilem_c = data->whilem_c;
5956                     data_fake.last_closep = data->last_closep;
5957                 }
5958                 else
5959                     data_fake.last_closep = &fake;
5960                 data_fake.pos_delta = delta;
5961                 if ( flags & SCF_DO_STCLASS && !scan->flags
5962                      && OP(scan) == IFMATCH ) { /* Lookahead */
5963                     ssc_init(pRExC_state, &intrnl);
5964                     data_fake.start_class = &intrnl;
5965                     f |= SCF_DO_STCLASS_AND;
5966                 }
5967                 if (flags & SCF_WHILEM_VISITED_POS)
5968                     f |= SCF_WHILEM_VISITED_POS;
5969                 next = regnext(scan);
5970                 nscan = NEXTOPER(NEXTOPER(scan));
5971
5972                 /* recurse study_chunk() for lookahead body */
5973                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
5974                                       last, &data_fake, stopparen,
5975                                       recursed_depth, NULL, f, depth+1);
5976                 if (scan->flags) {
5977                     if (deltanext) {
5978                         FAIL("Variable length lookbehind not implemented");
5979                     }
5980                     else if (minnext > (I32)U8_MAX) {
5981                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
5982                               (UV)U8_MAX);
5983                     }
5984                     scan->flags = (U8)minnext;
5985                 }
5986                 if (data) {
5987                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5988                         pars++;
5989                     if (data_fake.flags & SF_HAS_EVAL)
5990                         data->flags |= SF_HAS_EVAL;
5991                     data->whilem_c = data_fake.whilem_c;
5992                 }
5993                 if (f & SCF_DO_STCLASS_AND) {
5994                     if (flags & SCF_DO_STCLASS_OR) {
5995                         /* OR before, AND after: ideally we would recurse with
5996                          * data_fake to get the AND applied by study of the
5997                          * remainder of the pattern, and then derecurse;
5998                          * *** HACK *** for now just treat as "no information".
5999                          * See [perl #56690].
6000                          */
6001                         ssc_init(pRExC_state, data->start_class);
6002                     }  else {
6003                         /* AND before and after: combine and continue.  These
6004                          * assertions are zero-length, so can match an EMPTY
6005                          * string */
6006                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6007                         ANYOF_FLAGS(data->start_class)
6008                                                    |= SSC_MATCHES_EMPTY_STRING;
6009                     }
6010                 }
6011             }
6012 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6013             else {
6014                 /* Positive Lookahead/lookbehind
6015                    In this case we can do fixed string optimisation,
6016                    but we must be careful about it. Note in the case of
6017                    lookbehind the positions will be offset by the minimum
6018                    length of the pattern, something we won't know about
6019                    until after the recurse.
6020                 */
6021                 SSize_t deltanext, fake = 0;
6022                 regnode *nscan;
6023                 regnode_ssc intrnl;
6024                 int f = 0;
6025                 /* We use SAVEFREEPV so that when the full compile
6026                     is finished perl will clean up the allocated
6027                     minlens when it's all done. This way we don't
6028                     have to worry about freeing them when we know
6029                     they wont be used, which would be a pain.
6030                  */
6031                 SSize_t *minnextp;
6032                 Newx( minnextp, 1, SSize_t );
6033                 SAVEFREEPV(minnextp);
6034
6035                 if (data) {
6036                     StructCopy(data, &data_fake, scan_data_t);
6037                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
6038                         f |= SCF_DO_SUBSTR;
6039                         if (scan->flags)
6040                             scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
6041                         data_fake.last_found=newSVsv(data->last_found);
6042                     }
6043                 }
6044                 else
6045                     data_fake.last_closep = &fake;
6046                 data_fake.flags = 0;
6047                 data_fake.substrs[0].flags = 0;
6048                 data_fake.substrs[1].flags = 0;
6049                 data_fake.pos_delta = delta;
6050                 if (is_inf)
6051                     data_fake.flags |= SF_IS_INF;
6052                 if ( flags & SCF_DO_STCLASS && !scan->flags
6053                      && OP(scan) == IFMATCH ) { /* Lookahead */
6054                     ssc_init(pRExC_state, &intrnl);
6055                     data_fake.start_class = &intrnl;
6056                     f |= SCF_DO_STCLASS_AND;
6057                 }
6058                 if (flags & SCF_WHILEM_VISITED_POS)
6059                     f |= SCF_WHILEM_VISITED_POS;
6060                 next = regnext(scan);
6061                 nscan = NEXTOPER(NEXTOPER(scan));
6062
6063                 /* positive lookahead study_chunk() recursion */
6064                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
6065                                         &deltanext, last, &data_fake,
6066                                         stopparen, recursed_depth, NULL,
6067                                         f, depth+1);
6068                 if (scan->flags) {
6069                     if (deltanext) {
6070                         FAIL("Variable length lookbehind not implemented");
6071                     }
6072                     else if (*minnextp > (I32)U8_MAX) {
6073                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
6074                               (UV)U8_MAX);
6075                     }
6076                     scan->flags = (U8)*minnextp;
6077                 }
6078
6079                 *minnextp += min;
6080
6081                 if (f & SCF_DO_STCLASS_AND) {
6082                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6083                     ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
6084                 }
6085                 if (data) {
6086                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6087                         pars++;
6088                     if (data_fake.flags & SF_HAS_EVAL)
6089                         data->flags |= SF_HAS_EVAL;
6090                     data->whilem_c = data_fake.whilem_c;
6091                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
6092                         int i;
6093                         if (RExC_rx->minlen<*minnextp)
6094                             RExC_rx->minlen=*minnextp;
6095                         scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
6096                         SvREFCNT_dec_NN(data_fake.last_found);
6097
6098                         for (i = 0; i < 2; i++) {
6099                             if (data_fake.substrs[i].minlenp != minlenp) {
6100                                 data->substrs[i].min_offset =
6101                                             data_fake.substrs[i].min_offset;
6102                                 data->substrs[i].max_offset =
6103                                             data_fake.substrs[i].max_offset;
6104                                 data->substrs[i].minlenp =
6105                                             data_fake.substrs[i].minlenp;
6106                                 data->substrs[i].lookbehind += scan->flags;
6107                             }
6108                         }
6109                     }
6110                 }
6111             }
6112 #endif
6113         }
6114
6115         else if (OP(scan) == OPEN) {
6116             if (stopparen != (I32)ARG(scan))
6117                 pars++;
6118         }
6119         else if (OP(scan) == CLOSE) {
6120             if (stopparen == (I32)ARG(scan)) {
6121                 break;
6122             }
6123             if ((I32)ARG(scan) == is_par) {
6124                 next = regnext(scan);
6125
6126                 if ( next && (OP(next) != WHILEM) && next < last)
6127                     is_par = 0;         /* Disable optimization */
6128             }
6129             if (data)
6130                 *(data->last_closep) = ARG(scan);
6131         }
6132         else if (OP(scan) == EVAL) {
6133                 if (data)
6134                     data->flags |= SF_HAS_EVAL;
6135         }
6136         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
6137             if (flags & SCF_DO_SUBSTR) {
6138                 scan_commit(pRExC_state, data, minlenp, is_inf);
6139                 flags &= ~SCF_DO_SUBSTR;
6140             }
6141             if (data && OP(scan)==ACCEPT) {
6142                 data->flags |= SCF_SEEN_ACCEPT;
6143                 if (stopmin > min)
6144                     stopmin = min;
6145             }
6146         }
6147         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
6148         {
6149                 if (flags & SCF_DO_SUBSTR) {
6150                     scan_commit(pRExC_state, data, minlenp, is_inf);
6151                     data->cur_is_floating = 1; /* float */
6152                 }
6153                 is_inf = is_inf_internal = 1;
6154                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
6155                     ssc_anything(data->start_class);
6156                 flags &= ~SCF_DO_STCLASS;
6157         }
6158         else if (OP(scan) == GPOS) {
6159             if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
6160                 !(delta || is_inf || (data && data->pos_delta)))
6161             {
6162                 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
6163                     RExC_rx->intflags |= PREGf_ANCH_GPOS;
6164                 if (RExC_rx->gofs < (STRLEN)min)
6165                     RExC_rx->gofs = min;
6166             } else {
6167                 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
6168                 RExC_rx->gofs = 0;
6169             }
6170         }
6171 #ifdef TRIE_STUDY_OPT
6172 #ifdef FULL_TRIE_STUDY
6173         else if (PL_regkind[OP(scan)] == TRIE) {
6174             /* NOTE - There is similar code to this block above for handling
6175                BRANCH nodes on the initial study.  If you change stuff here
6176                check there too. */
6177             regnode *trie_node= scan;
6178             regnode *tail= regnext(scan);
6179             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6180             SSize_t max1 = 0, min1 = SSize_t_MAX;
6181             regnode_ssc accum;
6182
6183             if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
6184                 /* Cannot merge strings after this. */
6185                 scan_commit(pRExC_state, data, minlenp, is_inf);
6186             }
6187             if (flags & SCF_DO_STCLASS)
6188                 ssc_init_zero(pRExC_state, &accum);
6189
6190             if (!trie->jump) {
6191                 min1= trie->minlen;
6192                 max1= trie->maxlen;
6193             } else {
6194                 const regnode *nextbranch= NULL;
6195                 U32 word;
6196
6197                 for ( word=1 ; word <= trie->wordcount ; word++)
6198                 {
6199                     SSize_t deltanext=0, minnext=0, f = 0, fake;
6200                     regnode_ssc this_class;
6201
6202                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6203                     if (data) {
6204                         data_fake.whilem_c = data->whilem_c;
6205                         data_fake.last_closep = data->last_closep;
6206                     }
6207                     else
6208                         data_fake.last_closep = &fake;
6209                     data_fake.pos_delta = delta;
6210                     if (flags & SCF_DO_STCLASS) {
6211                         ssc_init(pRExC_state, &this_class);
6212                         data_fake.start_class = &this_class;
6213                         f = SCF_DO_STCLASS_AND;
6214                     }
6215                     if (flags & SCF_WHILEM_VISITED_POS)
6216                         f |= SCF_WHILEM_VISITED_POS;
6217
6218                     if (trie->jump[word]) {
6219                         if (!nextbranch)
6220                             nextbranch = trie_node + trie->jump[0];
6221                         scan= trie_node + trie->jump[word];
6222                         /* We go from the jump point to the branch that follows
6223                            it. Note this means we need the vestigal unused
6224                            branches even though they arent otherwise used. */
6225                         /* optimise study_chunk() for TRIE */
6226                         minnext = study_chunk(pRExC_state, &scan, minlenp,
6227                             &deltanext, (regnode *)nextbranch, &data_fake,
6228                             stopparen, recursed_depth, NULL, f, depth+1);
6229                     }
6230                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6231                         nextbranch= regnext((regnode*)nextbranch);
6232
6233                     if (min1 > (SSize_t)(minnext + trie->minlen))
6234                         min1 = minnext + trie->minlen;
6235                     if (deltanext == SSize_t_MAX) {
6236                         is_inf = is_inf_internal = 1;
6237                         max1 = SSize_t_MAX;
6238                     } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6239                         max1 = minnext + deltanext + trie->maxlen;
6240
6241                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6242                         pars++;
6243                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
6244                         if ( stopmin > min + min1)
6245                             stopmin = min + min1;
6246                         flags &= ~SCF_DO_SUBSTR;
6247                         if (data)
6248                             data->flags |= SCF_SEEN_ACCEPT;
6249                     }
6250                     if (data) {
6251                         if (data_fake.flags & SF_HAS_EVAL)
6252                             data->flags |= SF_HAS_EVAL;
6253                         data->whilem_c = data_fake.whilem_c;
6254                     }
6255                     if (flags & SCF_DO_STCLASS)
6256                         ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6257                 }
6258             }
6259             if (flags & SCF_DO_SUBSTR) {
6260                 data->pos_min += min1;
6261                 data->pos_delta += max1 - min1;
6262                 if (max1 != min1 || is_inf)
6263                     data->cur_is_floating = 1; /* float */
6264             }
6265             min += min1;
6266             if (delta != SSize_t_MAX) {
6267                 if (SSize_t_MAX - (max1 - min1) >= delta)
6268                     delta += max1 - min1;
6269                 else
6270                     delta = SSize_t_MAX;
6271             }
6272             if (flags & SCF_DO_STCLASS_OR) {
6273                 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6274                 if (min1) {
6275                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6276                     flags &= ~SCF_DO_STCLASS;
6277                 }
6278             }
6279             else if (flags & SCF_DO_STCLASS_AND) {
6280                 if (min1) {
6281                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6282                     flags &= ~SCF_DO_STCLASS;
6283                 }
6284                 else {
6285                     /* Switch to OR mode: cache the old value of
6286                      * data->start_class */
6287                     INIT_AND_WITHP;
6288                     StructCopy(data->start_class, and_withp, regnode_ssc);
6289                     flags &= ~SCF_DO_STCLASS_AND;
6290                     StructCopy(&accum, data->start_class, regnode_ssc);
6291                     flags |= SCF_DO_STCLASS_OR;
6292                 }
6293             }
6294             scan= tail;
6295             continue;
6296         }
6297 #else
6298         else if (PL_regkind[OP(scan)] == TRIE) {
6299             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6300             U8*bang=NULL;
6301
6302             min += trie->minlen;
6303             delta += (trie->maxlen - trie->minlen);
6304             flags &= ~SCF_DO_STCLASS; /* xxx */
6305             if (flags & SCF_DO_SUBSTR) {
6306                 /* Cannot expect anything... */
6307                 scan_commit(pRExC_state, data, minlenp, is_inf);
6308                 data->pos_min += trie->minlen;
6309                 data->pos_delta += (trie->maxlen - trie->minlen);
6310                 if (trie->maxlen != trie->minlen)
6311                     data->cur_is_floating = 1; /* float */
6312             }
6313             if (trie->jump) /* no more substrings -- for now /grr*/
6314                flags &= ~SCF_DO_SUBSTR;
6315         }
6316 #endif /* old or new */
6317 #endif /* TRIE_STUDY_OPT */
6318
6319         /* Else: zero-length, ignore. */
6320         scan = regnext(scan);
6321     }
6322
6323   finish:
6324     if (frame) {
6325         /* we need to unwind recursion. */
6326         depth = depth - 1;
6327
6328         DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6329         DEBUG_PEEP("fend", scan, depth, flags);
6330
6331         /* restore previous context */
6332         last = frame->last_regnode;
6333         scan = frame->next_regnode;
6334         stopparen = frame->stopparen;
6335         recursed_depth = frame->prev_recursed_depth;
6336
6337         RExC_frame_last = frame->prev_frame;
6338         frame = frame->this_prev_frame;
6339         goto fake_study_recurse;
6340     }
6341
6342     assert(!frame);
6343     DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6344
6345     *scanp = scan;
6346     *deltap = is_inf_internal ? SSize_t_MAX : delta;
6347
6348     if (flags & SCF_DO_SUBSTR && is_inf)
6349         data->pos_delta = SSize_t_MAX - data->pos_min;
6350     if (is_par > (I32)U8_MAX)
6351         is_par = 0;
6352     if (is_par && pars==1 && data) {
6353         data->flags |= SF_IN_PAR;
6354         data->flags &= ~SF_HAS_PAR;
6355     }
6356     else if (pars && data) {
6357         data->flags |= SF_HAS_PAR;
6358         data->flags &= ~SF_IN_PAR;
6359     }
6360     if (flags & SCF_DO_STCLASS_OR)
6361         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6362     if (flags & SCF_TRIE_RESTUDY)
6363         data->flags |=  SCF_TRIE_RESTUDY;
6364
6365     DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6366
6367     {
6368         SSize_t final_minlen= min < stopmin ? min : stopmin;
6369
6370         if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6371             if (final_minlen > SSize_t_MAX - delta)
6372                 RExC_maxlen = SSize_t_MAX;
6373             else if (RExC_maxlen < final_minlen + delta)
6374                 RExC_maxlen = final_minlen + delta;
6375         }
6376         return final_minlen;
6377     }
6378     NOT_REACHED; /* NOTREACHED */
6379 }
6380
6381 STATIC U32
6382 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6383 {
6384     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6385
6386     PERL_ARGS_ASSERT_ADD_DATA;
6387
6388     Renewc(RExC_rxi->data,
6389            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6390            char, struct reg_data);
6391     if(count)
6392         Renew(RExC_rxi->data->what, count + n, U8);
6393     else
6394         Newx(RExC_rxi->data->what, n, U8);
6395     RExC_rxi->data->count = count + n;
6396     Copy(s, RExC_rxi->data->what + count, n, U8);
6397     return count;
6398 }
6399
6400 /*XXX: todo make this not included in a non debugging perl, but appears to be
6401  * used anyway there, in 'use re' */
6402 #ifndef PERL_IN_XSUB_RE
6403 void
6404 Perl_reginitcolors(pTHX)
6405 {
6406     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6407     if (s) {
6408         char *t = savepv(s);
6409         int i = 0;
6410         PL_colors[0] = t;
6411         while (++i < 6) {
6412             t = strchr(t, '\t');
6413             if (t) {
6414                 *t = '\0';
6415                 PL_colors[i] = ++t;
6416             }
6417             else
6418                 PL_colors[i] = t = (char *)"";
6419         }
6420     } else {
6421         int i = 0;
6422         while (i < 6)
6423             PL_colors[i++] = (char *)"";
6424     }
6425     PL_colorset = 1;
6426 }
6427 #endif
6428
6429
6430 #ifdef TRIE_STUDY_OPT
6431 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething)            \
6432     STMT_START {                                            \
6433         if (                                                \
6434               (data.flags & SCF_TRIE_RESTUDY)               \
6435               && ! restudied++                              \
6436         ) {                                                 \
6437             dOsomething;                                    \
6438             goto reStudy;                                   \
6439         }                                                   \
6440     } STMT_END
6441 #else
6442 #define CHECK_RESTUDY_GOTO_butfirst
6443 #endif
6444
6445 /*
6446  * pregcomp - compile a regular expression into internal code
6447  *
6448  * Decides which engine's compiler to call based on the hint currently in
6449  * scope
6450  */
6451
6452 #ifndef PERL_IN_XSUB_RE
6453
6454 /* return the currently in-scope regex engine (or the default if none)  */
6455
6456 regexp_engine const *
6457 Perl_current_re_engine(pTHX)
6458 {
6459     if (IN_PERL_COMPILETIME) {
6460         HV * const table = GvHV(PL_hintgv);
6461         SV **ptr;
6462
6463         if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6464             return &PL_core_reg_engine;
6465         ptr = hv_fetchs(table, "regcomp", FALSE);
6466         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6467             return &PL_core_reg_engine;
6468         return INT2PTR(regexp_engine*, SvIV(*ptr));
6469     }
6470     else {
6471         SV *ptr;
6472         if (!PL_curcop->cop_hints_hash)
6473             return &PL_core_reg_engine;
6474         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6475         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6476             return &PL_core_reg_engine;
6477         return INT2PTR(regexp_engine*, SvIV(ptr));
6478     }
6479 }
6480
6481
6482 REGEXP *
6483 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6484 {
6485     regexp_engine const *eng = current_re_engine();
6486     GET_RE_DEBUG_FLAGS_DECL;
6487
6488     PERL_ARGS_ASSERT_PREGCOMP;
6489
6490     /* Dispatch a request to compile a regexp to correct regexp engine. */
6491     DEBUG_COMPILE_r({
6492         Perl_re_printf( aTHX_  "Using engine %" UVxf "\n",
6493                         PTR2UV(eng));
6494     });
6495     return CALLREGCOMP_ENG(eng, pattern, flags);
6496 }
6497 #endif
6498
6499 /* public(ish) entry point for the perl core's own regex compiling code.
6500  * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6501  * pattern rather than a list of OPs, and uses the internal engine rather
6502  * than the current one */
6503
6504 REGEXP *
6505 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6506 {
6507     SV *pat = pattern; /* defeat constness! */
6508     PERL_ARGS_ASSERT_RE_COMPILE;
6509     return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6510 #ifdef PERL_IN_XSUB_RE
6511                                 &my_reg_engine,
6512 #else
6513                                 &PL_core_reg_engine,
6514 #endif
6515                                 NULL, NULL, rx_flags, 0);
6516 }
6517
6518
6519 static void
6520 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6521 {
6522     int n;
6523
6524     if (--cbs->refcnt > 0)
6525         return;
6526     for (n = 0; n < cbs->count; n++) {
6527         REGEXP *rx = cbs->cb[n].src_regex;
6528         if (rx) {
6529             cbs->cb[n].src_regex = NULL;
6530             SvREFCNT_dec_NN(rx);
6531         }
6532     }
6533     Safefree(cbs->cb);
6534     Safefree(cbs);
6535 }
6536
6537
6538 static struct reg_code_blocks *
6539 S_alloc_code_blocks(pTHX_  int ncode)
6540 {
6541      struct reg_code_blocks *cbs;
6542     Newx(cbs, 1, struct reg_code_blocks);
6543     cbs->count = ncode;
6544     cbs->refcnt = 1;
6545     SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6546     if (ncode)
6547         Newx(cbs->cb, ncode, struct reg_code_block);
6548     else
6549         cbs->cb = NULL;
6550     return cbs;
6551 }
6552
6553
6554 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6555  * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6556  * point to the realloced string and length.
6557  *
6558  * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6559  * stuff added */
6560
6561 static void
6562 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6563                     char **pat_p, STRLEN *plen_p, int num_code_blocks)
6564 {
6565     U8 *const src = (U8*)*pat_p;
6566     U8 *dst, *d;
6567     int n=0;
6568     STRLEN s = 0;
6569     bool do_end = 0;
6570     GET_RE_DEBUG_FLAGS_DECL;
6571
6572     DEBUG_PARSE_r(Perl_re_printf( aTHX_
6573         "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6574
6575     /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6576     Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6577     d = dst;
6578
6579     while (s < *plen_p) {
6580         append_utf8_from_native_byte(src[s], &d);
6581
6582         if (n < num_code_blocks) {
6583             assert(pRExC_state->code_blocks);
6584             if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6585                 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6586                 assert(*(d - 1) == '(');
6587                 do_end = 1;
6588             }
6589             else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6590                 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6591                 assert(*(d - 1) == ')');
6592                 do_end = 0;
6593                 n++;
6594             }
6595         }
6596         s++;
6597     }
6598     *d = '\0';
6599     *plen_p = d - dst;
6600     *pat_p = (char*) dst;
6601     SAVEFREEPV(*pat_p);
6602     RExC_orig_utf8 = RExC_utf8 = 1;
6603 }
6604
6605
6606
6607 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6608  * while recording any code block indices, and handling overloading,
6609  * nested qr// objects etc.  If pat is null, it will allocate a new
6610  * string, or just return the first arg, if there's only one.
6611  *
6612  * Returns the malloced/updated pat.
6613  * patternp and pat_count is the array of SVs to be concatted;
6614  * oplist is the optional list of ops that generated the SVs;
6615  * recompile_p is a pointer to a boolean that will be set if
6616  *   the regex will need to be recompiled.
6617  * delim, if non-null is an SV that will be inserted between each element
6618  */
6619
6620 static SV*
6621 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6622                 SV *pat, SV ** const patternp, int pat_count,
6623                 OP *oplist, bool *recompile_p, SV *delim)
6624 {
6625     SV **svp;
6626     int n = 0;
6627     bool use_delim = FALSE;
6628     bool alloced = FALSE;
6629
6630     /* if we know we have at least two args, create an empty string,
6631      * then concatenate args to that. For no args, return an empty string */
6632     if (!pat && pat_count != 1) {
6633         pat = newSVpvs("");
6634         SAVEFREESV(pat);
6635         alloced = TRUE;
6636     }
6637
6638     for (svp = patternp; svp < patternp + pat_count; svp++) {
6639         SV *sv;
6640         SV *rx  = NULL;
6641         STRLEN orig_patlen = 0;
6642         bool code = 0;
6643         SV *msv = use_delim ? delim : *svp;
6644         if (!msv) msv = &PL_sv_undef;
6645
6646         /* if we've got a delimiter, we go round the loop twice for each
6647          * svp slot (except the last), using the delimiter the second
6648          * time round */
6649         if (use_delim) {
6650             svp--;
6651             use_delim = FALSE;
6652         }
6653         else if (delim)
6654             use_delim = TRUE;
6655
6656         if (SvTYPE(msv) == SVt_PVAV) {
6657             /* we've encountered an interpolated array within
6658              * the pattern, e.g. /...@a..../. Expand the list of elements,
6659              * then recursively append elements.
6660              * The code in this block is based on S_pushav() */
6661
6662             AV *const av = (AV*)msv;
6663             const SSize_t maxarg = AvFILL(av) + 1;
6664             SV **array;
6665
6666             if (oplist) {
6667                 assert(oplist->op_type == OP_PADAV
6668                     || oplist->op_type == OP_RV2AV);
6669                 oplist = OpSIBLING(oplist);
6670             }
6671
6672             if (SvRMAGICAL(av)) {
6673                 SSize_t i;
6674
6675                 Newx(array, maxarg, SV*);
6676                 SAVEFREEPV(array);
6677                 for (i=0; i < maxarg; i++) {
6678                     SV ** const svp = av_fetch(av, i, FALSE);
6679                     array[i] = svp ? *svp : &PL_sv_undef;
6680                 }
6681             }
6682             else
6683                 array = AvARRAY(av);
6684
6685             pat = S_concat_pat(aTHX_ pRExC_state, pat,
6686                                 array, maxarg, NULL, recompile_p,
6687                                 /* $" */
6688                                 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6689
6690             continue;
6691         }
6692
6693
6694         /* we make the assumption here that each op in the list of
6695          * op_siblings maps to one SV pushed onto the stack,
6696          * except for code blocks, with have both an OP_NULL and
6697          * and OP_CONST.
6698          * This allows us to match up the list of SVs against the
6699          * list of OPs to find the next code block.
6700          *
6701          * Note that       PUSHMARK PADSV PADSV ..
6702          * is optimised to
6703          *                 PADRANGE PADSV  PADSV  ..
6704          * so the alignment still works. */
6705
6706         if (oplist) {
6707             if (oplist->op_type == OP_NULL
6708                 && (oplist->op_flags & OPf_SPECIAL))
6709             {
6710                 assert(n < pRExC_state->code_blocks->count);
6711                 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6712                 pRExC_state->code_blocks->cb[n].block = oplist;
6713                 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6714                 n++;
6715                 code = 1;
6716                 oplist = OpSIBLING(oplist); /* skip CONST */
6717                 assert(oplist);
6718             }
6719             oplist = OpSIBLING(oplist);;
6720         }
6721
6722         /* apply magic and QR overloading to arg */
6723
6724         SvGETMAGIC(msv);
6725         if (SvROK(msv) && SvAMAGIC(msv)) {
6726             SV *sv = AMG_CALLunary(msv, regexp_amg);
6727             if (sv) {
6728                 if (SvROK(sv))
6729                     sv = SvRV(sv);
6730                 if (SvTYPE(sv) != SVt_REGEXP)
6731                     Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6732                 msv = sv;
6733             }
6734         }
6735
6736         /* try concatenation overload ... */
6737         if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6738                 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6739         {
6740             sv_setsv(pat, sv);
6741             /* overloading involved: all bets are off over literal
6742              * code. Pretend we haven't seen it */
6743             if (n)
6744                 pRExC_state->code_blocks->count -= n;
6745             n = 0;
6746         }
6747         else  {
6748             /* ... or failing that, try "" overload */
6749             while (SvAMAGIC(msv)
6750                     && (sv = AMG_CALLunary(msv, string_amg))
6751                     && sv != msv
6752                     &&  !(   SvROK(msv)
6753                           && SvROK(sv)
6754                           && SvRV(msv) == SvRV(sv))
6755             ) {
6756                 msv = sv;
6757                 SvGETMAGIC(msv);
6758             }
6759             if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6760                 msv = SvRV(msv);
6761
6762             if (pat) {
6763                 /* this is a partially unrolled
6764                  *     sv_catsv_nomg(pat, msv);
6765                  * that allows us to adjust code block indices if
6766                  * needed */
6767                 STRLEN dlen;
6768                 char *dst = SvPV_force_nomg(pat, dlen);
6769                 orig_patlen = dlen;
6770                 if (SvUTF8(msv) && !SvUTF8(pat)) {
6771                     S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6772                     sv_setpvn(pat, dst, dlen);
6773                     SvUTF8_on(pat);
6774                 }
6775                 sv_catsv_nomg(pat, msv);
6776                 rx = msv;
6777             }
6778             else {
6779                 /* We have only one SV to process, but we need to verify
6780                  * it is properly null terminated or we will fail asserts
6781                  * later. In theory we probably shouldn't get such SV's,
6782                  * but if we do we should handle it gracefully. */
6783                 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
6784                     /* not a string, or a string with a trailing null */
6785                     pat = msv;
6786                 } else {
6787                     /* a string with no trailing null, we need to copy it
6788                      * so it has a trailing null */
6789                     pat = sv_2mortal(newSVsv(msv));
6790                 }
6791             }
6792
6793             if (code)
6794                 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
6795         }
6796
6797         /* extract any code blocks within any embedded qr//'s */
6798         if (rx && SvTYPE(rx) == SVt_REGEXP
6799             && RX_ENGINE((REGEXP*)rx)->op_comp)
6800         {
6801
6802             RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6803             if (ri->code_blocks && ri->code_blocks->count) {
6804                 int i;
6805                 /* the presence of an embedded qr// with code means
6806                  * we should always recompile: the text of the
6807                  * qr// may not have changed, but it may be a
6808                  * different closure than last time */
6809                 *recompile_p = 1;
6810                 if (pRExC_state->code_blocks) {
6811                     int new_count = pRExC_state->code_blocks->count
6812                             + ri->code_blocks->count;
6813                     Renew(pRExC_state->code_blocks->cb,
6814                             new_count, struct reg_code_block);
6815                     pRExC_state->code_blocks->count = new_count;
6816                 }
6817                 else
6818                     pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
6819                                                     ri->code_blocks->count);
6820
6821                 for (i=0; i < ri->code_blocks->count; i++) {
6822                     struct reg_code_block *src, *dst;
6823                     STRLEN offset =  orig_patlen
6824                         + ReANY((REGEXP *)rx)->pre_prefix;
6825                     assert(n < pRExC_state->code_blocks->count);
6826                     src = &ri->code_blocks->cb[i];
6827                     dst = &pRExC_state->code_blocks->cb[n];
6828                     dst->start      = src->start + offset;
6829                     dst->end        = src->end   + offset;
6830                     dst->block      = src->block;
6831                     dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
6832                                             src->src_regex
6833                                                 ? src->src_regex
6834                                                 : (REGEXP*)rx);
6835                     n++;
6836                 }
6837             }
6838         }
6839     }
6840     /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6841     if (alloced)
6842         SvSETMAGIC(pat);
6843
6844     return pat;
6845 }
6846
6847
6848
6849 /* see if there are any run-time code blocks in the pattern.
6850  * False positives are allowed */
6851
6852 static bool
6853 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6854                     char *pat, STRLEN plen)
6855 {
6856     int n = 0;
6857     STRLEN s;
6858
6859     PERL_UNUSED_CONTEXT;
6860
6861     for (s = 0; s < plen; s++) {
6862         if (   pRExC_state->code_blocks
6863             && n < pRExC_state->code_blocks->count
6864             && s == pRExC_state->code_blocks->cb[n].start)
6865         {
6866             s = pRExC_state->code_blocks->cb[n].end;
6867             n++;
6868             continue;
6869         }
6870         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
6871          * positives here */
6872         if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
6873             (pat[s+2] == '{'
6874                 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
6875         )
6876             return 1;
6877     }
6878     return 0;
6879 }
6880
6881 /* Handle run-time code blocks. We will already have compiled any direct
6882  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
6883  * copy of it, but with any literal code blocks blanked out and
6884  * appropriate chars escaped; then feed it into
6885  *
6886  *    eval "qr'modified_pattern'"
6887  *
6888  * For example,
6889  *
6890  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
6891  *
6892  * becomes
6893  *
6894  *    qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
6895  *
6896  * After eval_sv()-ing that, grab any new code blocks from the returned qr
6897  * and merge them with any code blocks of the original regexp.
6898  *
6899  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
6900  * instead, just save the qr and return FALSE; this tells our caller that
6901  * the original pattern needs upgrading to utf8.
6902  */
6903
6904 static bool
6905 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6906     char *pat, STRLEN plen)
6907 {
6908     SV *qr;
6909
6910     GET_RE_DEBUG_FLAGS_DECL;
6911
6912     if (pRExC_state->runtime_code_qr) {
6913         /* this is the second time we've been called; this should
6914          * only happen if the main pattern got upgraded to utf8
6915          * during compilation; re-use the qr we compiled first time
6916          * round (which should be utf8 too)
6917          */
6918         qr = pRExC_state->runtime_code_qr;
6919         pRExC_state->runtime_code_qr = NULL;
6920         assert(RExC_utf8 && SvUTF8(qr));
6921     }
6922     else {
6923         int n = 0;
6924         STRLEN s;
6925         char *p, *newpat;
6926         int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
6927         SV *sv, *qr_ref;
6928         dSP;
6929
6930         /* determine how many extra chars we need for ' and \ escaping */
6931         for (s = 0; s < plen; s++) {
6932             if (pat[s] == '\'' || pat[s] == '\\')
6933                 newlen++;
6934         }
6935
6936         Newx(newpat, newlen, char);
6937         p = newpat;
6938         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
6939
6940         for (s = 0; s < plen; s++) {
6941             if (   pRExC_state->code_blocks
6942                 && n < pRExC_state->code_blocks->count
6943                 && s == pRExC_state->code_blocks->cb[n].start)
6944             {
6945                 /* blank out literal code block so that they aren't
6946                  * recompiled: eg change from/to:
6947                  *     /(?{xyz})/
6948                  *     /(?=====)/
6949                  * and
6950                  *     /(??{xyz})/
6951                  *     /(?======)/
6952                  * and
6953                  *     /(?(?{xyz}))/
6954                  *     /(?(?=====))/
6955                 */
6956                 assert(pat[s]   == '(');
6957                 assert(pat[s+1] == '?');
6958                 *p++ = '(';
6959                 *p++ = '?';
6960                 s += 2;
6961                 while (s < pRExC_state->code_blocks->cb[n].end) {
6962                     *p++ = '=';
6963                     s++;
6964                 }
6965                 *p++ = ')';
6966                 n++;
6967                 continue;
6968             }
6969             if (pat[s] == '\'' || pat[s] == '\\')
6970                 *p++ = '\\';
6971             *p++ = pat[s];
6972         }
6973         *p++ = '\'';
6974         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
6975             *p++ = 'x';
6976             if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
6977                 *p++ = 'x';
6978             }
6979         }
6980         *p++ = '\0';
6981         DEBUG_COMPILE_r({
6982             Perl_re_printf( aTHX_
6983                 "%sre-parsing pattern for runtime code:%s %s\n",
6984                 PL_colors[4], PL_colors[5], newpat);
6985         });
6986
6987         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
6988         Safefree(newpat);
6989
6990         ENTER;
6991         SAVETMPS;
6992         save_re_context();
6993         PUSHSTACKi(PERLSI_REQUIRE);
6994         /* G_RE_REPARSING causes the toker to collapse \\ into \ when
6995          * parsing qr''; normally only q'' does this. It also alters
6996          * hints handling */
6997         eval_sv(sv, G_SCALAR|G_RE_REPARSING);
6998         SvREFCNT_dec_NN(sv);
6999         SPAGAIN;
7000         qr_ref = POPs;
7001         PUTBACK;
7002         {
7003             SV * const errsv = ERRSV;
7004             if (SvTRUE_NN(errsv))
7005                 /* use croak_sv ? */
7006                 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
7007         }
7008         assert(SvROK(qr_ref));
7009         qr = SvRV(qr_ref);
7010         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
7011         /* the leaving below frees the tmp qr_ref.
7012          * Give qr a life of its own */
7013         SvREFCNT_inc(qr);
7014         POPSTACK;
7015         FREETMPS;
7016         LEAVE;
7017
7018     }
7019
7020     if (!RExC_utf8 && SvUTF8(qr)) {
7021         /* first time through; the pattern got upgraded; save the
7022          * qr for the next time through */
7023         assert(!pRExC_state->runtime_code_qr);
7024         pRExC_state->runtime_code_qr = qr;
7025         return 0;
7026     }
7027
7028
7029     /* extract any code blocks within the returned qr//  */
7030
7031
7032     /* merge the main (r1) and run-time (r2) code blocks into one */
7033     {
7034         RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
7035         struct reg_code_block *new_block, *dst;
7036         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
7037         int i1 = 0, i2 = 0;
7038         int r1c, r2c;
7039
7040         if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
7041         {
7042             SvREFCNT_dec_NN(qr);
7043             return 1;
7044         }
7045
7046         if (!r1->code_blocks)
7047             r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
7048
7049         r1c = r1->code_blocks->count;
7050         r2c = r2->code_blocks->count;
7051
7052         Newx(new_block, r1c + r2c, struct reg_code_block);
7053
7054         dst = new_block;
7055
7056         while (i1 < r1c || i2 < r2c) {
7057             struct reg_code_block *src;
7058             bool is_qr = 0;
7059
7060             if (i1 == r1c) {
7061                 src = &r2->code_blocks->cb[i2++];
7062                 is_qr = 1;
7063             }
7064             else if (i2 == r2c)
7065                 src = &r1->code_blocks->cb[i1++];
7066             else if (  r1->code_blocks->cb[i1].start
7067                      < r2->code_blocks->cb[i2].start)
7068             {
7069                 src = &r1->code_blocks->cb[i1++];
7070                 assert(src->end < r2->code_blocks->cb[i2].start);
7071             }
7072             else {
7073                 assert(  r1->code_blocks->cb[i1].start
7074                        > r2->code_blocks->cb[i2].start);
7075                 src = &r2->code_blocks->cb[i2++];
7076                 is_qr = 1;
7077                 assert(src->end < r1->code_blocks->cb[i1].start);
7078             }
7079
7080             assert(pat[src->start] == '(');
7081             assert(pat[src->end]   == ')');
7082             dst->start      = src->start;
7083             dst->end        = src->end;
7084             dst->block      = src->block;
7085             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
7086                                     : src->src_regex;
7087             dst++;
7088         }
7089         r1->code_blocks->count += r2c;
7090         Safefree(r1->code_blocks->cb);
7091         r1->code_blocks->cb = new_block;
7092     }
7093
7094     SvREFCNT_dec_NN(qr);
7095     return 1;
7096 }
7097
7098
7099 STATIC bool
7100 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
7101                       struct reg_substr_datum  *rsd,
7102                       struct scan_data_substrs *sub,
7103                       STRLEN longest_length)
7104 {
7105     /* This is the common code for setting up the floating and fixed length
7106      * string data extracted from Perl_re_op_compile() below.  Returns a boolean
7107      * as to whether succeeded or not */
7108
7109     I32 t;
7110     SSize_t ml;
7111     bool eol  = cBOOL(sub->flags & SF_BEFORE_EOL);
7112     bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
7113
7114     if (! (longest_length
7115            || (eol /* Can't have SEOL and MULTI */
7116                && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
7117           )
7118             /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
7119         || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
7120     {
7121         return FALSE;
7122     }
7123
7124     /* copy the information about the longest from the reg_scan_data
7125         over to the program. */
7126     if (SvUTF8(sub->str)) {
7127         rsd->substr      = NULL;
7128         rsd->utf8_substr = sub->str;
7129     } else {
7130         rsd->substr      = sub->str;
7131         rsd->utf8_substr = NULL;
7132     }
7133     /* end_shift is how many chars that must be matched that
7134         follow this item. We calculate it ahead of time as once the
7135         lookbehind offset is added in we lose the ability to correctly
7136         calculate it.*/
7137     ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
7138     rsd->end_shift = ml - sub->min_offset
7139         - longest_length
7140             /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
7141              * intead? - DAPM
7142             + (SvTAIL(sub->str) != 0)
7143             */
7144         + sub->lookbehind;
7145
7146     t = (eol/* Can't have SEOL and MULTI */
7147          && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
7148     fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
7149
7150     return TRUE;
7151 }
7152
7153 STATIC void
7154 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
7155 {
7156     /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
7157      * properly wrapped with the right modifiers */
7158
7159     bool has_p     = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7160     bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
7161                                                 != REGEX_DEPENDS_CHARSET);
7162
7163     /* The caret is output if there are any defaults: if not all the STD
7164         * flags are set, or if no character set specifier is needed */
7165     bool has_default =
7166                 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7167                 || ! has_charset);
7168     bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7169                                                 == REG_RUN_ON_COMMENT_SEEN);
7170     U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
7171                         >> RXf_PMf_STD_PMMOD_SHIFT);
7172     const char *fptr = STD_PAT_MODS;        /*"msixxn"*/
7173     char *p;
7174     STRLEN pat_len = RExC_precomp_end - RExC_precomp;
7175
7176     /* We output all the necessary flags; we never output a minus, as all
7177         * those are defaults, so are
7178         * covered by the caret */
7179     const STRLEN wraplen = pat_len + has_p + has_runon
7180         + has_default       /* If needs a caret */
7181         + PL_bitcount[reganch] /* 1 char for each set standard flag */
7182
7183             /* If needs a character set specifier */
7184         + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7185         + (sizeof("(?:)") - 1);
7186
7187     PERL_ARGS_ASSERT_SET_REGEX_PV;
7188
7189     /* make sure PL_bitcount bounds not exceeded */
7190     assert(sizeof(STD_PAT_MODS) <= 8);
7191
7192     p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
7193     SvPOK_on(Rx);
7194     if (RExC_utf8)
7195         SvFLAGS(Rx) |= SVf_UTF8;
7196     *p++='('; *p++='?';
7197
7198     /* If a default, cover it using the caret */
7199     if (has_default) {
7200         *p++= DEFAULT_PAT_MOD;
7201     }
7202     if (has_charset) {
7203         STRLEN len;
7204         const char* name;
7205
7206         name = get_regex_charset_name(RExC_rx->extflags, &len);
7207         if strEQ(name, DEPENDS_PAT_MODS) {  /* /d under UTF-8 => /u */
7208             assert(RExC_utf8);
7209             name = UNICODE_PAT_MODS;
7210             len = sizeof(UNICODE_PAT_MODS) - 1;
7211         }
7212         Copy(name, p, len, char);
7213         p += len;
7214     }
7215     if (has_p)
7216         *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7217     {
7218         char ch;
7219         while((ch = *fptr++)) {
7220             if(reganch & 1)
7221                 *p++ = ch;
7222             reganch >>= 1;
7223         }
7224     }
7225
7226     *p++ = ':';
7227     Copy(RExC_precomp, p, pat_len, char);
7228     assert ((RX_WRAPPED(Rx) - p) < 16);
7229     RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7230     p += pat_len;
7231
7232     /* Adding a trailing \n causes this to compile properly:
7233             my $R = qr / A B C # D E/x; /($R)/
7234         Otherwise the parens are considered part of the comment */
7235     if (has_runon)
7236         *p++ = '\n';
7237     *p++ = ')';
7238     *p = 0;
7239     SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7240 }
7241
7242 /*
7243  * Perl_re_op_compile - the perl internal RE engine's function to compile a
7244  * regular expression into internal code.
7245  * The pattern may be passed either as:
7246  *    a list of SVs (patternp plus pat_count)
7247  *    a list of OPs (expr)
7248  * If both are passed, the SV list is used, but the OP list indicates
7249  * which SVs are actually pre-compiled code blocks
7250  *
7251  * The SVs in the list have magic and qr overloading applied to them (and
7252  * the list may be modified in-place with replacement SVs in the latter
7253  * case).
7254  *
7255  * If the pattern hasn't changed from old_re, then old_re will be
7256  * returned.
7257  *
7258  * eng is the current engine. If that engine has an op_comp method, then
7259  * handle directly (i.e. we assume that op_comp was us); otherwise, just
7260  * do the initial concatenation of arguments and pass on to the external
7261  * engine.
7262  *
7263  * If is_bare_re is not null, set it to a boolean indicating whether the
7264  * arg list reduced (after overloading) to a single bare regex which has
7265  * been returned (i.e. /$qr/).
7266  *
7267  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7268  *
7269  * pm_flags contains the PMf_* flags, typically based on those from the
7270  * pm_flags field of the related PMOP. Currently we're only interested in
7271  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
7272  *
7273  * For many years this code had an initial sizing pass that calculated
7274  * (sometimes incorrectly, leading to security holes) the size needed for the
7275  * compiled pattern.  That was changed by commit
7276  * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7277  * node at a time, as parsing goes along.  Patches welcome to fix any obsolete
7278  * references to this sizing pass.
7279  *
7280  * Now, an initial crude guess as to the size needed is made, based on the
7281  * length of the pattern.  Patches welcome to improve that guess.  That amount
7282  * of space is malloc'd and then immediately freed, and then clawed back node
7283  * by node.  This design is to minimze, to the extent possible, memory churn
7284  * when doing the the reallocs.
7285  *
7286  * A separate parentheses counting pass may be needed in some cases.
7287  * (Previously the sizing pass did this.)  Patches welcome to reduce the number
7288  * of these cases.
7289  *
7290  * The existence of a sizing pass necessitated design decisions that are no
7291  * longer needed.  There are potential areas of simplification.
7292  *
7293  * Beware that the optimization-preparation code in here knows about some
7294  * of the structure of the compiled regexp.  [I'll say.]
7295  */
7296
7297 REGEXP *
7298 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7299                     OP *expr, const regexp_engine* eng, REGEXP *old_re,
7300                      bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7301 {
7302     dVAR;
7303     REGEXP *Rx;         /* Capital 'R' means points to a REGEXP */
7304     STRLEN plen;
7305     char *exp;
7306     regnode *scan;
7307     I32 flags;
7308     SSize_t minlen = 0;
7309     U32 rx_flags;
7310     SV *pat;
7311     SV** new_patternp = patternp;
7312
7313     /* these are all flags - maybe they should be turned
7314      * into a single int with different bit masks */
7315     I32 sawlookahead = 0;
7316     I32 sawplus = 0;
7317     I32 sawopen = 0;
7318     I32 sawminmod = 0;
7319
7320     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7321     bool recompile = 0;
7322     bool runtime_code = 0;
7323     scan_data_t data;
7324     RExC_state_t RExC_state;
7325     RExC_state_t * const pRExC_state = &RExC_state;
7326 #ifdef TRIE_STUDY_OPT
7327     int restudied = 0;
7328     RExC_state_t copyRExC_state;
7329 #endif
7330     GET_RE_DEBUG_FLAGS_DECL;
7331
7332     PERL_ARGS_ASSERT_RE_OP_COMPILE;
7333
7334     DEBUG_r(if (!PL_colorset) reginitcolors());
7335
7336     /* Initialize these here instead of as-needed, as is quick and avoids
7337      * having to test them each time otherwise */
7338     if (! PL_InBitmap) {
7339 #ifdef DEBUGGING
7340         char * dump_len_string;
7341 #endif
7342
7343         /* This is calculated here, because the Perl program that generates the
7344          * static global ones doesn't currently have access to
7345          * NUM_ANYOF_CODE_POINTS */
7346         PL_InBitmap = _new_invlist(2);
7347         PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,
7348                                                     NUM_ANYOF_CODE_POINTS - 1);
7349 #ifdef DEBUGGING
7350         dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
7351         if (   ! dump_len_string
7352             || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
7353         {
7354             PL_dump_re_max_len = 60;    /* A reasonable default */
7355         }
7356 #endif
7357     }
7358
7359     pRExC_state->warn_text = NULL;
7360     pRExC_state->code_blocks = NULL;
7361
7362     if (is_bare_re)
7363         *is_bare_re = FALSE;
7364
7365     if (expr && (expr->op_type == OP_LIST ||
7366                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7367         /* allocate code_blocks if needed */
7368         OP *o;
7369         int ncode = 0;
7370
7371         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7372             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7373                 ncode++; /* count of DO blocks */
7374
7375         if (ncode)
7376             pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7377     }
7378
7379     if (!pat_count) {
7380         /* compile-time pattern with just OP_CONSTs and DO blocks */
7381
7382         int n;
7383         OP *o;
7384
7385         /* find how many CONSTs there are */
7386         assert(expr);
7387         n = 0;
7388         if (expr->op_type == OP_CONST)
7389             n = 1;
7390         else
7391             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7392                 if (o->op_type == OP_CONST)
7393                     n++;
7394             }
7395
7396         /* fake up an SV array */
7397
7398         assert(!new_patternp);
7399         Newx(new_patternp, n, SV*);
7400         SAVEFREEPV(new_patternp);
7401         pat_count = n;
7402
7403         n = 0;
7404         if (expr->op_type == OP_CONST)
7405             new_patternp[n] = cSVOPx_sv(expr);
7406         else
7407             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7408                 if (o->op_type == OP_CONST)
7409                     new_patternp[n++] = cSVOPo_sv;
7410             }
7411
7412     }
7413
7414     DEBUG_PARSE_r(Perl_re_printf( aTHX_
7415         "Assembling pattern from %d elements%s\n", pat_count,
7416             orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7417
7418     /* set expr to the first arg op */
7419
7420     if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7421          && expr->op_type != OP_CONST)
7422     {
7423             expr = cLISTOPx(expr)->op_first;
7424             assert(   expr->op_type == OP_PUSHMARK
7425                    || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7426                    || expr->op_type == OP_PADRANGE);
7427             expr = OpSIBLING(expr);
7428     }
7429
7430     pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7431                         expr, &recompile, NULL);
7432
7433     /* handle bare (possibly after overloading) regex: foo =~ $re */
7434     {
7435         SV *re = pat;
7436         if (SvROK(re))
7437             re = SvRV(re);
7438         if (SvTYPE(re) == SVt_REGEXP) {
7439             if (is_bare_re)
7440                 *is_bare_re = TRUE;
7441             SvREFCNT_inc(re);
7442             DEBUG_PARSE_r(Perl_re_printf( aTHX_
7443                 "Precompiled pattern%s\n",
7444                     orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7445
7446             return (REGEXP*)re;
7447         }
7448     }
7449
7450     exp = SvPV_nomg(pat, plen);
7451
7452     if (!eng->op_comp) {
7453         if ((SvUTF8(pat) && IN_BYTES)
7454                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7455         {
7456             /* make a temporary copy; either to convert to bytes,
7457              * or to avoid repeating get-magic / overloaded stringify */
7458             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7459                                         (IN_BYTES ? 0 : SvUTF8(pat)));
7460         }
7461         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7462     }
7463
7464     /* ignore the utf8ness if the pattern is 0 length */
7465     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7466     RExC_uni_semantics = 0;
7467     RExC_contains_locale = 0;
7468     RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7469     RExC_in_script_run = 0;
7470     RExC_study_started = 0;
7471     pRExC_state->runtime_code_qr = NULL;
7472     RExC_frame_head= NULL;
7473     RExC_frame_last= NULL;
7474     RExC_frame_count= 0;
7475     RExC_latest_warn_offset = 0;
7476     RExC_use_BRANCHJ = 0;
7477     RExC_total_parens = 0;
7478     RExC_open_parens = NULL;
7479     RExC_close_parens = NULL;
7480     RExC_paren_names = NULL;
7481     RExC_size = 0;
7482     RExC_seen_d_op = FALSE;
7483 #ifdef DEBUGGING
7484     RExC_paren_name_list = NULL;
7485 #endif
7486
7487     DEBUG_r({
7488         RExC_mysv1= sv_newmortal();
7489         RExC_mysv2= sv_newmortal();
7490     });
7491
7492     DEBUG_COMPILE_r({
7493             SV *dsv= sv_newmortal();
7494             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7495             Perl_re_printf( aTHX_  "%sCompiling REx%s %s\n",
7496                           PL_colors[4], PL_colors[5], s);
7497         });
7498
7499     /* we jump here if we have to recompile, e.g., from upgrading the pattern
7500      * to utf8 */
7501
7502     if ((pm_flags & PMf_USE_RE_EVAL)
7503                 /* this second condition covers the non-regex literal case,
7504                  * i.e.  $foo =~ '(?{})'. */
7505                 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7506     )
7507         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7508
7509   redo_parse:
7510     /* return old regex if pattern hasn't changed */
7511     /* XXX: note in the below we have to check the flags as well as the
7512      * pattern.
7513      *
7514      * Things get a touch tricky as we have to compare the utf8 flag
7515      * independently from the compile flags.  */
7516
7517     if (   old_re
7518         && !recompile
7519         && !!RX_UTF8(old_re) == !!RExC_utf8
7520         && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7521         && RX_PRECOMP(old_re)
7522         && RX_PRELEN(old_re) == plen
7523         && memEQ(RX_PRECOMP(old_re), exp, plen)
7524         && !runtime_code /* with runtime code, always recompile */ )
7525     {
7526         return old_re;
7527     }
7528
7529     /* Allocate the pattern's SV */
7530     RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7531     RExC_rx = ReANY(Rx);
7532     if ( RExC_rx == NULL )
7533         FAIL("Regexp out of space");
7534
7535     rx_flags = orig_rx_flags;
7536
7537     if (   (UTF || RExC_uni_semantics)
7538         && initial_charset == REGEX_DEPENDS_CHARSET)
7539     {
7540
7541         /* Set to use unicode semantics if the pattern is in utf8 and has the
7542          * 'depends' charset specified, as it means unicode when utf8  */
7543         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7544         RExC_uni_semantics = 1;
7545     }
7546
7547     RExC_pm_flags = pm_flags;
7548
7549     if (runtime_code) {
7550         assert(TAINTING_get || !TAINT_get);
7551         if (TAINT_get)
7552             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7553
7554         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7555             /* whoops, we have a non-utf8 pattern, whilst run-time code
7556              * got compiled as utf8. Try again with a utf8 pattern */
7557             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7558                 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7559             goto redo_parse;
7560         }
7561     }
7562     assert(!pRExC_state->runtime_code_qr);
7563
7564     RExC_sawback = 0;
7565
7566     RExC_seen = 0;
7567     RExC_maxlen = 0;
7568     RExC_in_lookbehind = 0;
7569     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7570 #ifdef EBCDIC
7571     RExC_recode_x_to_native = 0;
7572 #endif
7573     RExC_in_multi_char_class = 0;
7574
7575     RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7576     RExC_precomp_end = RExC_end = exp + plen;
7577     RExC_nestroot = 0;
7578     RExC_whilem_seen = 0;
7579     RExC_end_op = NULL;
7580     RExC_recurse = NULL;
7581     RExC_study_chunk_recursed = NULL;
7582     RExC_study_chunk_recursed_bytes= 0;
7583     RExC_recurse_count = 0;
7584     pRExC_state->code_index = 0;
7585
7586     /* Initialize the string in the compiled pattern.  This is so that there is
7587      * something to output if necessary */
7588     set_regex_pv(pRExC_state, Rx);
7589
7590     DEBUG_PARSE_r({
7591         Perl_re_printf( aTHX_
7592             "Starting parse and generation\n");
7593         RExC_lastnum=0;
7594         RExC_lastparse=NULL;
7595     });
7596
7597     /* Allocate space and zero-initialize. Note, the two step process
7598        of zeroing when in debug mode, thus anything assigned has to
7599        happen after that */
7600     if (!  RExC_size) {
7601
7602         /* On the first pass of the parse, we guess how big this will be.  Then
7603          * we grow in one operation to that amount and then give it back.  As
7604          * we go along, we re-allocate what we need.
7605          *
7606          * XXX Currently the guess is essentially that the pattern will be an
7607          * EXACT node with one byte input, one byte output.  This is crude, and
7608          * better heuristics are welcome.
7609          *
7610          * On any subsequent passes, we guess what we actually computed in the
7611          * latest earlier pass.  Such a pass probably didn't complete so is
7612          * missing stuff.  We could improve those guesses by knowing where the
7613          * parse stopped, and use the length so far plus apply the above
7614          * assumption to what's left. */
7615         RExC_size = STR_SZ(RExC_end - RExC_start);
7616     }
7617
7618     Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7619     if ( RExC_rxi == NULL )
7620         FAIL("Regexp out of space");
7621
7622     Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7623     RXi_SET( RExC_rx, RExC_rxi );
7624
7625     /* We start from 0 (over from 0 in the case this is a reparse.  The first
7626      * node parsed will give back any excess memory we have allocated so far).
7627      * */
7628     RExC_size = 0;
7629
7630     /* non-zero initialization begins here */
7631     RExC_rx->engine= eng;
7632     RExC_rx->extflags = rx_flags;
7633     RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7634
7635     if (pm_flags & PMf_IS_QR) {
7636         RExC_rxi->code_blocks = pRExC_state->code_blocks;
7637         if (RExC_rxi->code_blocks) {
7638             RExC_rxi->code_blocks->refcnt++;
7639         }
7640     }
7641
7642     RExC_rx->intflags = 0;
7643
7644     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
7645     RExC_parse = exp;
7646
7647     /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7648      * code makes sure the final byte is an uncounted NUL.  But should this
7649      * ever not be the case, lots of things could read beyond the end of the
7650      * buffer: loops like
7651      *      while(isFOO(*RExC_parse)) RExC_parse++;
7652      *      strchr(RExC_parse, "foo");
7653      * etc.  So it is worth noting. */
7654     assert(*RExC_end == '\0');
7655
7656     RExC_naughty = 0;
7657     RExC_npar = 1;
7658     RExC_emit_start = RExC_rxi->program;
7659     pRExC_state->code_index = 0;
7660
7661     *((char*) RExC_emit_start) = (char) REG_MAGIC;
7662     RExC_emit = 1;
7663
7664     /* Do the parse */
7665     if (reg(pRExC_state, 0, &flags, 1)) {
7666
7667         /* Success!, But if RExC_total_parens < 0, we need to redo the parse
7668          * knowing how many parens there actually are */
7669         if (RExC_total_parens < 0) {
7670             flags |= RESTART_PARSE;
7671         }
7672
7673         /* We have that number in RExC_npar */
7674         RExC_total_parens = RExC_npar;
7675     }
7676     else if (! MUST_RESTART(flags)) {
7677         ReREFCNT_dec(Rx);
7678         Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7679     }
7680
7681     /* Here, we either have success, or we have to redo the parse for some reason */
7682     if (MUST_RESTART(flags)) {
7683
7684         /* It's possible to write a regexp in ascii that represents Unicode
7685         codepoints outside of the byte range, such as via \x{100}. If we
7686         detect such a sequence we have to convert the entire pattern to utf8
7687         and then recompile, as our sizing calculation will have been based
7688         on 1 byte == 1 character, but we will need to use utf8 to encode
7689         at least some part of the pattern, and therefore must convert the whole
7690         thing.
7691         -- dmq */
7692         if (flags & NEED_UTF8) {
7693
7694             /* We have stored the offset of the final warning output so far.
7695              * That must be adjusted.  Any variant characters between the start
7696              * of the pattern and this warning count for 2 bytes in the final,
7697              * so just add them again */
7698             if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7699                 RExC_latest_warn_offset +=
7700                             variant_under_utf8_count((U8 *) exp, (U8 *) exp
7701                                                 + RExC_latest_warn_offset);
7702             }
7703             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7704             pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7705             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7706         }
7707         else {
7708             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7709         }
7710
7711         if (RExC_total_parens > 0) {
7712             /* Make enough room for all the known parens, and zero it */
7713             Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7714             Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7715             RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
7716
7717             Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7718             Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7719         }
7720         else { /* Parse did not complete.  Reinitialize the parentheses
7721                   structures */
7722             RExC_total_parens = 0;
7723             if (RExC_open_parens) {
7724                 Safefree(RExC_open_parens);
7725                 RExC_open_parens = NULL;
7726             }
7727             if (RExC_close_parens) {
7728                 Safefree(RExC_close_parens);
7729                 RExC_close_parens = NULL;
7730             }
7731         }
7732
7733         /* Clean up what we did in this parse */
7734         SvREFCNT_dec_NN(RExC_rx_sv);
7735
7736         goto redo_parse;
7737     }
7738
7739     /* Here, we have successfully parsed and generated the pattern's program
7740      * for the regex engine.  We are ready to finish things up and look for
7741      * optimizations. */
7742
7743     /* Update the string to compile, with correct modifiers, etc */
7744     set_regex_pv(pRExC_state, Rx);
7745
7746     RExC_rx->nparens = RExC_total_parens - 1;
7747
7748     /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7749     if (RExC_whilem_seen > 15)
7750         RExC_whilem_seen = 15;
7751
7752     DEBUG_PARSE_r({
7753         Perl_re_printf( aTHX_
7754             "Required size %" IVdf " nodes\n", (IV)RExC_size);
7755         RExC_lastnum=0;
7756         RExC_lastparse=NULL;
7757     });
7758
7759 #ifdef RE_TRACK_PATTERN_OFFSETS
7760     DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7761                           "%s %" UVuf " bytes for offset annotations.\n",
7762                           RExC_offsets ? "Got" : "Couldn't get",
7763                           (UV)((RExC_offsets[0] * 2 + 1))));
7764     DEBUG_OFFSETS_r(if (RExC_offsets) {
7765         const STRLEN len = RExC_offsets[0];
7766         STRLEN i;
7767         GET_RE_DEBUG_FLAGS_DECL;
7768         Perl_re_printf( aTHX_
7769                       "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7770         for (i = 1; i <= len; i++) {
7771             if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7772                 Perl_re_printf( aTHX_  "%" UVuf ":%" UVuf "[%" UVuf "] ",
7773                 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7774         }
7775         Perl_re_printf( aTHX_  "\n");
7776     });
7777
7778 #else
7779     SetProgLen(RExC_rxi,RExC_size);
7780 #endif
7781
7782     DEBUG_OPTIMISE_r(
7783         Perl_re_printf( aTHX_  "Starting post parse optimization\n");
7784     );
7785
7786     /* XXXX To minimize changes to RE engine we always allocate
7787        3-units-long substrs field. */
7788     Newx(RExC_rx->substrs, 1, struct reg_substr_data);
7789     if (RExC_recurse_count) {
7790         Newx(RExC_recurse, RExC_recurse_count, regnode *);
7791         SAVEFREEPV(RExC_recurse);
7792     }
7793
7794     if (RExC_seen & REG_RECURSE_SEEN) {
7795         /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
7796          * So its 1 if there are no parens. */
7797         RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
7798                                          ((RExC_total_parens & 0x07) != 0);
7799         Newx(RExC_study_chunk_recursed,
7800              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7801         SAVEFREEPV(RExC_study_chunk_recursed);
7802     }
7803
7804   reStudy:
7805     RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7806     DEBUG_r(
7807         RExC_study_chunk_recursed_count= 0;
7808     );
7809     Zero(RExC_rx->substrs, 1, struct reg_substr_data);
7810     if (RExC_study_chunk_recursed) {
7811         Zero(RExC_study_chunk_recursed,
7812              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7813     }
7814
7815
7816 #ifdef TRIE_STUDY_OPT
7817     if (!restudied) {
7818         StructCopy(&zero_scan_data, &data, scan_data_t);
7819         copyRExC_state = RExC_state;
7820     } else {
7821         U32 seen=RExC_seen;
7822         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
7823
7824         RExC_state = copyRExC_state;
7825         if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7826             RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7827         else
7828             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7829         StructCopy(&zero_scan_data, &data, scan_data_t);
7830     }
7831 #else
7832     StructCopy(&zero_scan_data, &data, scan_data_t);
7833 #endif
7834
7835     /* Dig out information for optimizations. */
7836     RExC_rx->extflags = RExC_flags; /* was pm_op */
7837     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7838
7839     if (UTF)
7840         SvUTF8_on(Rx);  /* Unicode in it? */
7841     RExC_rxi->regstclass = NULL;
7842     if (RExC_naughty >= TOO_NAUGHTY)    /* Probably an expensive pattern. */
7843         RExC_rx->intflags |= PREGf_NAUGHTY;
7844     scan = RExC_rxi->program + 1;               /* First BRANCH. */
7845
7846     /* testing for BRANCH here tells us whether there is "must appear"
7847        data in the pattern. If there is then we can use it for optimisations */
7848     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /*  Only one top-level choice.
7849                                                   */
7850         SSize_t fake;
7851         STRLEN longest_length[2];
7852         regnode_ssc ch_class; /* pointed to by data */
7853         int stclass_flag;
7854         SSize_t last_close = 0; /* pointed to by data */
7855         regnode *first= scan;
7856         regnode *first_next= regnext(first);
7857         int i;
7858
7859         /*
7860          * Skip introductions and multiplicators >= 1
7861          * so that we can extract the 'meat' of the pattern that must
7862          * match in the large if() sequence following.
7863          * NOTE that EXACT is NOT covered here, as it is normally
7864          * picked up by the optimiser separately.
7865          *
7866          * This is unfortunate as the optimiser isnt handling lookahead
7867          * properly currently.
7868          *
7869          */
7870         while ((OP(first) == OPEN && (sawopen = 1)) ||
7871                /* An OR of *one* alternative - should not happen now. */
7872             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
7873             /* for now we can't handle lookbehind IFMATCH*/
7874             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
7875             (OP(first) == PLUS) ||
7876             (OP(first) == MINMOD) ||
7877                /* An {n,m} with n>0 */
7878             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
7879             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
7880         {
7881                 /*
7882                  * the only op that could be a regnode is PLUS, all the rest
7883                  * will be regnode_1 or regnode_2.
7884                  *
7885                  * (yves doesn't think this is true)
7886                  */
7887                 if (OP(first) == PLUS)
7888                     sawplus = 1;
7889                 else {
7890                     if (OP(first) == MINMOD)
7891                         sawminmod = 1;
7892                     first += regarglen[OP(first)];
7893                 }
7894                 first = NEXTOPER(first);
7895                 first_next= regnext(first);
7896         }
7897
7898         /* Starting-point info. */
7899       again:
7900         DEBUG_PEEP("first:", first, 0, 0);
7901         /* Ignore EXACT as we deal with it later. */
7902         if (PL_regkind[OP(first)] == EXACT) {
7903             if (   OP(first) == EXACT
7904                 || OP(first) == EXACT_ONLY8
7905                 || OP(first) == EXACTL)
7906             {
7907                 NOOP;   /* Empty, get anchored substr later. */
7908             }
7909             else
7910                 RExC_rxi->regstclass = first;
7911         }
7912 #ifdef TRIE_STCLASS
7913         else if (PL_regkind[OP(first)] == TRIE &&
7914                 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
7915         {
7916             /* this can happen only on restudy */
7917             RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
7918         }
7919 #endif
7920         else if (REGNODE_SIMPLE(OP(first)))
7921             RExC_rxi->regstclass = first;
7922         else if (PL_regkind[OP(first)] == BOUND ||
7923                  PL_regkind[OP(first)] == NBOUND)
7924             RExC_rxi->regstclass = first;
7925         else if (PL_regkind[OP(first)] == BOL) {
7926             RExC_rx->intflags |= (OP(first) == MBOL
7927                            ? PREGf_ANCH_MBOL
7928                            : PREGf_ANCH_SBOL);
7929             first = NEXTOPER(first);
7930             goto again;
7931         }
7932         else if (OP(first) == GPOS) {
7933             RExC_rx->intflags |= PREGf_ANCH_GPOS;
7934             first = NEXTOPER(first);
7935             goto again;
7936         }
7937         else if ((!sawopen || !RExC_sawback) &&
7938             !sawlookahead &&
7939             (OP(first) == STAR &&
7940             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
7941             !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
7942         {
7943             /* turn .* into ^.* with an implied $*=1 */
7944             const int type =
7945                 (OP(NEXTOPER(first)) == REG_ANY)
7946                     ? PREGf_ANCH_MBOL
7947                     : PREGf_ANCH_SBOL;
7948             RExC_rx->intflags |= (type | PREGf_IMPLICIT);
7949             first = NEXTOPER(first);
7950             goto again;
7951         }
7952         if (sawplus && !sawminmod && !sawlookahead
7953             && (!sawopen || !RExC_sawback)
7954             && !pRExC_state->code_blocks) /* May examine pos and $& */
7955             /* x+ must match at the 1st pos of run of x's */
7956             RExC_rx->intflags |= PREGf_SKIP;
7957
7958         /* Scan is after the zeroth branch, first is atomic matcher. */
7959 #ifdef TRIE_STUDY_OPT
7960         DEBUG_PARSE_r(
7961             if (!restudied)
7962                 Perl_re_printf( aTHX_  "first at %" IVdf "\n",
7963                               (IV)(first - scan + 1))
7964         );
7965 #else
7966         DEBUG_PARSE_r(
7967             Perl_re_printf( aTHX_  "first at %" IVdf "\n",
7968                 (IV)(first - scan + 1))
7969         );
7970 #endif
7971
7972
7973         /*
7974         * If there's something expensive in the r.e., find the
7975         * longest literal string that must appear and make it the
7976         * regmust.  Resolve ties in favor of later strings, since
7977         * the regstart check works with the beginning of the r.e.
7978         * and avoiding duplication strengthens checking.  Not a
7979         * strong reason, but sufficient in the absence of others.
7980         * [Now we resolve ties in favor of the earlier string if
7981         * it happens that c_offset_min has been invalidated, since the
7982         * earlier string may buy us something the later one won't.]
7983         */
7984
7985         data.substrs[0].str = newSVpvs("");
7986         data.substrs[1].str = newSVpvs("");
7987         data.last_found = newSVpvs("");
7988         data.cur_is_floating = 0; /* initially any found substring is fixed */
7989         ENTER_with_name("study_chunk");
7990         SAVEFREESV(data.substrs[0].str);
7991         SAVEFREESV(data.substrs[1].str);
7992         SAVEFREESV(data.last_found);
7993         first = scan;
7994         if (!RExC_rxi->regstclass) {
7995             ssc_init(pRExC_state, &ch_class);
7996             data.start_class = &ch_class;
7997             stclass_flag = SCF_DO_STCLASS_AND;
7998         } else                          /* XXXX Check for BOUND? */
7999             stclass_flag = 0;
8000         data.last_closep = &last_close;
8001
8002         DEBUG_RExC_seen();
8003         /*
8004          * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
8005          * (NO top level branches)
8006          */
8007         minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
8008                              scan + RExC_size, /* Up to end */
8009             &data, -1, 0, NULL,
8010             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
8011                           | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
8012             0);
8013
8014
8015         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
8016
8017
8018         if ( RExC_total_parens == 1 && !data.cur_is_floating
8019              && data.last_start_min == 0 && data.last_end > 0
8020              && !RExC_seen_zerolen
8021              && !(RExC_seen & REG_VERBARG_SEEN)
8022              && !(RExC_seen & REG_GPOS_SEEN)
8023         ){
8024             RExC_rx->extflags |= RXf_CHECK_ALL;
8025         }
8026         scan_commit(pRExC_state, &data,&minlen, 0);
8027
8028
8029         /* XXX this is done in reverse order because that's the way the
8030          * code was before it was parameterised. Don't know whether it
8031          * actually needs doing in reverse order. DAPM */
8032         for (i = 1; i >= 0; i--) {
8033             longest_length[i] = CHR_SVLEN(data.substrs[i].str);
8034
8035             if (   !(   i
8036                      && SvCUR(data.substrs[0].str)  /* ok to leave SvCUR */
8037                      &&    data.substrs[0].min_offset
8038                         == data.substrs[1].min_offset
8039                      &&    SvCUR(data.substrs[0].str)
8040                         == SvCUR(data.substrs[1].str)
8041                     )
8042                 && S_setup_longest (aTHX_ pRExC_state,
8043                                         &(RExC_rx->substrs->data[i]),
8044                                         &(data.substrs[i]),
8045                                         longest_length[i]))
8046             {
8047                 RExC_rx->substrs->data[i].min_offset =
8048                         data.substrs[i].min_offset - data.substrs[i].lookbehind;
8049
8050                 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
8051                 /* Don't offset infinity */
8052                 if (data.substrs[i].max_offset < SSize_t_MAX)
8053                     RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
8054                 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
8055             }
8056             else {
8057                 RExC_rx->substrs->data[i].substr      = NULL;
8058                 RExC_rx->substrs->data[i].utf8_substr = NULL;
8059                 longest_length[i] = 0;
8060             }
8061         }
8062
8063         LEAVE_with_name("study_chunk");
8064
8065         if (RExC_rxi->regstclass
8066             && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
8067             RExC_rxi->regstclass = NULL;
8068
8069         if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
8070               || RExC_rx->substrs->data[0].min_offset)
8071             && stclass_flag
8072             && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8073             && is_ssc_worth_it(pRExC_state, data.start_class))
8074         {
8075             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8076
8077             ssc_finalize(pRExC_state, data.start_class);
8078
8079             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8080             StructCopy(data.start_class,
8081                        (regnode_ssc*)RExC_rxi->data->data[n],
8082                        regnode_ssc);
8083             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8084             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
8085             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
8086                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8087                       Perl_re_printf( aTHX_
8088                                     "synthetic stclass \"%s\".\n",
8089                                     SvPVX_const(sv));});
8090             data.start_class = NULL;
8091         }
8092
8093         /* A temporary algorithm prefers floated substr to fixed one of
8094          * same length to dig more info. */
8095         i = (longest_length[0] <= longest_length[1]);
8096         RExC_rx->substrs->check_ix = i;
8097         RExC_rx->check_end_shift  = RExC_rx->substrs->data[i].end_shift;
8098         RExC_rx->check_substr     = RExC_rx->substrs->data[i].substr;
8099         RExC_rx->check_utf8       = RExC_rx->substrs->data[i].utf8_substr;
8100         RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
8101         RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
8102         if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
8103             RExC_rx->intflags |= PREGf_NOSCAN;
8104
8105         if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
8106             RExC_rx->extflags |= RXf_USE_INTUIT;
8107             if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
8108                 RExC_rx->extflags |= RXf_INTUIT_TAIL;
8109         }
8110
8111         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
8112         if ( (STRLEN)minlen < longest_length[1] )
8113             minlen= longest_length[1];
8114         if ( (STRLEN)minlen < longest_length[0] )
8115             minlen= longest_length[0];
8116         */
8117     }
8118     else {
8119         /* Several toplevels. Best we can is to set minlen. */
8120         SSize_t fake;
8121         regnode_ssc ch_class;
8122         SSize_t last_close = 0;
8123
8124         DEBUG_PARSE_r(Perl_re_printf( aTHX_  "\nMulti Top Level\n"));
8125
8126         scan = RExC_rxi->program + 1;
8127         ssc_init(pRExC_state, &ch_class);
8128         data.start_class = &ch_class;
8129         data.last_closep = &last_close;
8130
8131         DEBUG_RExC_seen();
8132         /*
8133          * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
8134          * (patterns WITH top level branches)
8135          */
8136         minlen = study_chunk(pRExC_state,
8137             &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
8138             SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
8139                                                       ? SCF_TRIE_DOING_RESTUDY
8140                                                       : 0),
8141             0);
8142
8143         CHECK_RESTUDY_GOTO_butfirst(NOOP);
8144
8145         RExC_rx->check_substr = NULL;
8146         RExC_rx->check_utf8 = NULL;
8147         RExC_rx->substrs->data[0].substr      = NULL;
8148         RExC_rx->substrs->data[0].utf8_substr = NULL;
8149         RExC_rx->substrs->data[1].substr      = NULL;
8150         RExC_rx->substrs->data[1].utf8_substr = NULL;
8151
8152         if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8153             && is_ssc_worth_it(pRExC_state, data.start_class))
8154         {
8155             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8156
8157             ssc_finalize(pRExC_state, data.start_class);
8158
8159             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8160             StructCopy(data.start_class,
8161                        (regnode_ssc*)RExC_rxi->data->data[n],
8162                        regnode_ssc);
8163             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8164             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
8165             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
8166                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8167                       Perl_re_printf( aTHX_
8168                                     "synthetic stclass \"%s\".\n",
8169                                     SvPVX_const(sv));});
8170             data.start_class = NULL;
8171         }
8172     }
8173
8174     if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
8175         RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
8176         RExC_rx->maxlen = REG_INFTY;
8177     }
8178     else {
8179         RExC_rx->maxlen = RExC_maxlen;
8180     }
8181
8182     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
8183        the "real" pattern. */
8184     DEBUG_OPTIMISE_r({
8185         Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
8186                       (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
8187     });
8188     RExC_rx->minlenret = minlen;
8189     if (RExC_rx->minlen < minlen)
8190         RExC_rx->minlen = minlen;
8191
8192     if (RExC_seen & REG_RECURSE_SEEN ) {
8193         RExC_rx->intflags |= PREGf_RECURSE_SEEN;
8194         Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
8195     }
8196     if (RExC_seen & REG_GPOS_SEEN)
8197         RExC_rx->intflags |= PREGf_GPOS_SEEN;
8198     if (RExC_seen & REG_LOOKBEHIND_SEEN)
8199         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
8200                                                 lookbehind */
8201     if (pRExC_state->code_blocks)
8202         RExC_rx->extflags |= RXf_EVAL_SEEN;
8203     if (RExC_seen & REG_VERBARG_SEEN)
8204     {
8205         RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8206         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8207     }
8208     if (RExC_seen & REG_CUTGROUP_SEEN)
8209         RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8210     if (pm_flags & PMf_USE_RE_EVAL)
8211         RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8212     if (RExC_paren_names)
8213         RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8214     else
8215         RXp_PAREN_NAMES(RExC_rx) = NULL;
8216
8217     /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8218      * so it can be used in pp.c */
8219     if (RExC_rx->intflags & PREGf_ANCH)
8220         RExC_rx->extflags |= RXf_IS_ANCHORED;
8221
8222
8223     {
8224         /* this is used to identify "special" patterns that might result
8225          * in Perl NOT calling the regex engine and instead doing the match "itself",
8226          * particularly special cases in split//. By having the regex compiler
8227          * do this pattern matching at a regop level (instead of by inspecting the pattern)
8228          * we avoid weird issues with equivalent patterns resulting in different behavior,
8229          * AND we allow non Perl engines to get the same optimizations by the setting the
8230          * flags appropriately - Yves */
8231         regnode *first = RExC_rxi->program + 1;
8232         U8 fop = OP(first);
8233         regnode *next = regnext(first);
8234         U8 nop = OP(next);
8235
8236         if (PL_regkind[fop] == NOTHING && nop == END)
8237             RExC_rx->extflags |= RXf_NULL;
8238         else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8239             /* when fop is SBOL first->flags will be true only when it was
8240              * produced by parsing /\A/, and not when parsing /^/. This is
8241              * very important for the split code as there we want to
8242              * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8243              * See rt #122761 for more details. -- Yves */
8244             RExC_rx->extflags |= RXf_START_ONLY;
8245         else if (fop == PLUS
8246                  && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8247                  && nop == END)
8248             RExC_rx->extflags |= RXf_WHITE;
8249         else if ( RExC_rx->extflags & RXf_SPLIT
8250                   && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL)
8251                   && STR_LEN(first) == 1
8252                   && *(STRING(first)) == ' '
8253                   && nop == END )
8254             RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8255
8256     }
8257
8258     if (RExC_contains_locale) {
8259         RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8260     }
8261
8262 #ifdef DEBUGGING
8263     if (RExC_paren_names) {
8264         RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8265         RExC_rxi->data->data[RExC_rxi->name_list_idx]
8266                                    = (void*)SvREFCNT_inc(RExC_paren_name_list);
8267     } else
8268 #endif
8269     RExC_rxi->name_list_idx = 0;
8270
8271     while ( RExC_recurse_count > 0 ) {
8272         const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8273         /*
8274          * This data structure is set up in study_chunk() and is used
8275          * to calculate the distance between a GOSUB regopcode and
8276          * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8277          * it refers to.
8278          *
8279          * If for some reason someone writes code that optimises
8280          * away a GOSUB opcode then the assert should be changed to
8281          * an if(scan) to guard the ARG2L_SET() - Yves
8282          *
8283          */
8284         assert(scan && OP(scan) == GOSUB);
8285         ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8286     }
8287
8288     Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8289     /* assume we don't need to swap parens around before we match */
8290     DEBUG_TEST_r({
8291         Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8292             (unsigned long)RExC_study_chunk_recursed_count);
8293     });
8294     DEBUG_DUMP_r({
8295         DEBUG_RExC_seen();
8296         Perl_re_printf( aTHX_ "Final program:\n");
8297         regdump(RExC_rx);
8298     });
8299
8300     if (RExC_open_parens) {
8301         Safefree(RExC_open_parens);
8302         RExC_open_parens = NULL;
8303     }
8304     if (RExC_close_parens) {
8305         Safefree(RExC_close_parens);
8306         RExC_close_parens = NULL;
8307     }
8308
8309 #ifdef USE_ITHREADS
8310     /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8311      * by setting the regexp SV to readonly-only instead. If the
8312      * pattern's been recompiled, the USEDness should remain. */
8313     if (old_re && SvREADONLY(old_re))
8314         SvREADONLY_on(Rx);
8315 #endif
8316     return Rx;
8317 }
8318
8319
8320 SV*
8321 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8322                     const U32 flags)
8323 {
8324     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8325
8326     PERL_UNUSED_ARG(value);
8327
8328     if (flags & RXapif_FETCH) {
8329         return reg_named_buff_fetch(rx, key, flags);
8330     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8331         Perl_croak_no_modify();
8332         return NULL;
8333     } else if (flags & RXapif_EXISTS) {
8334         return reg_named_buff_exists(rx, key, flags)
8335             ? &PL_sv_yes
8336             : &PL_sv_no;
8337     } else if (flags & RXapif_REGNAMES) {
8338         return reg_named_buff_all(rx, flags);
8339     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8340         return reg_named_buff_scalar(rx, flags);
8341     } else {
8342         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8343         return NULL;
8344     }
8345 }
8346
8347 SV*
8348 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8349                          const U32 flags)
8350 {
8351     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8352     PERL_UNUSED_ARG(lastkey);
8353
8354     if (flags & RXapif_FIRSTKEY)
8355         return reg_named_buff_firstkey(rx, flags);
8356     else if (flags & RXapif_NEXTKEY)
8357         return reg_named_buff_nextkey(rx, flags);
8358     else {
8359         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8360                                             (int)flags);
8361         return NULL;
8362     }
8363 }
8364
8365 SV*
8366 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8367                           const U32 flags)
8368 {
8369     SV *ret;
8370     struct regexp *const rx = ReANY(r);
8371
8372     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8373
8374     if (rx && RXp_PAREN_NAMES(rx)) {
8375         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8376         if (he_str) {
8377             IV i;
8378             SV* sv_dat=HeVAL(he_str);
8379             I32 *nums=(I32*)SvPVX(sv_dat);
8380             AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8381             for ( i=0; i<SvIVX(sv_dat); i++ ) {
8382                 if ((I32)(rx->nparens) >= nums[i]
8383                     && rx->offs[nums[i]].start != -1
8384                     && rx->offs[nums[i]].end != -1)
8385                 {
8386                     ret = newSVpvs("");
8387                     CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8388                     if (!retarray)
8389                         return ret;
8390                 } else {
8391                     if (retarray)
8392                         ret = newSVsv(&PL_sv_undef);
8393                 }
8394                 if (retarray)
8395                     av_push(retarray, ret);
8396             }
8397             if (retarray)
8398                 return newRV_noinc(MUTABLE_SV(retarray));
8399         }
8400     }
8401     return NULL;
8402 }
8403
8404 bool
8405 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8406                            const U32 flags)
8407 {
8408     struct regexp *const rx = ReANY(r);
8409
8410     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8411
8412     if (rx && RXp_PAREN_NAMES(rx)) {
8413         if (flags & RXapif_ALL) {
8414             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8415         } else {
8416             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8417             if (sv) {
8418                 SvREFCNT_dec_NN(sv);
8419                 return TRUE;
8420             } else {
8421                 return FALSE;
8422             }
8423         }
8424     } else {
8425         return FALSE;
8426     }
8427 }
8428
8429 SV*
8430 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8431 {
8432     struct regexp *const rx = ReANY(r);
8433
8434     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8435
8436     if ( rx && RXp_PAREN_NAMES(rx) ) {
8437         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8438
8439         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8440     } else {
8441         return FALSE;
8442     }
8443 }
8444
8445 SV*
8446 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8447 {
8448     struct regexp *const rx = ReANY(r);
8449     GET_RE_DEBUG_FLAGS_DECL;
8450
8451     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8452
8453     if (rx && RXp_PAREN_NAMES(rx)) {
8454         HV *hv = RXp_PAREN_NAMES(rx);
8455         HE *temphe;
8456         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8457             IV i;
8458             IV parno = 0;
8459             SV* sv_dat = HeVAL(temphe);
8460             I32 *nums = (I32*)SvPVX(sv_dat);
8461             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8462                 if ((I32)(rx->lastparen) >= nums[i] &&
8463                     rx->offs[nums[i]].start != -1 &&
8464                     rx->offs[nums[i]].end != -1)
8465                 {
8466                     parno = nums[i];
8467                     break;
8468                 }
8469             }
8470             if (parno || flags & RXapif_ALL) {
8471                 return newSVhek(HeKEY_hek(temphe));
8472             }
8473         }
8474     }
8475     return NULL;
8476 }
8477
8478 SV*
8479 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8480 {
8481     SV *ret;
8482     AV *av;
8483     SSize_t length;
8484     struct regexp *const rx = ReANY(r);
8485
8486     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8487
8488     if (rx && RXp_PAREN_NAMES(rx)) {
8489         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8490             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8491         } else if (flags & RXapif_ONE) {
8492             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8493             av = MUTABLE_AV(SvRV(ret));
8494             length = av_tindex(av);
8495             SvREFCNT_dec_NN(ret);
8496             return newSViv(length + 1);
8497         } else {
8498             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8499                                                 (int)flags);
8500             return NULL;
8501         }
8502     }
8503     return &PL_sv_undef;
8504 }
8505
8506 SV*
8507 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8508 {
8509     struct regexp *const rx = ReANY(r);
8510     AV *av = newAV();
8511
8512     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8513
8514     if (rx && RXp_PAREN_NAMES(rx)) {
8515         HV *hv= RXp_PAREN_NAMES(rx);
8516         HE *temphe;
8517         (void)hv_iterinit(hv);
8518         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8519             IV i;
8520             IV parno = 0;
8521             SV* sv_dat = HeVAL(temphe);
8522             I32 *nums = (I32*)SvPVX(sv_dat);
8523             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8524                 if ((I32)(rx->lastparen) >= nums[i] &&
8525                     rx->offs[nums[i]].start != -1 &&
8526                     rx->offs[nums[i]].end != -1)
8527                 {
8528                     parno = nums[i];
8529                     break;
8530                 }
8531             }
8532             if (parno || flags & RXapif_ALL) {
8533                 av_push(av, newSVhek(HeKEY_hek(temphe)));
8534             }
8535         }
8536     }
8537
8538     return newRV_noinc(MUTABLE_SV(av));
8539 }
8540
8541 void
8542 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8543                              SV * const sv)
8544 {
8545     struct regexp *const rx = ReANY(r);
8546     char *s = NULL;
8547     SSize_t i = 0;
8548     SSize_t s1, t1;
8549     I32 n = paren;
8550
8551     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8552
8553     if (      n == RX_BUFF_IDX_CARET_PREMATCH
8554            || n == RX_BUFF_IDX_CARET_FULLMATCH
8555            || n == RX_BUFF_IDX_CARET_POSTMATCH
8556        )
8557     {
8558         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8559         if (!keepcopy) {
8560             /* on something like
8561              *    $r = qr/.../;
8562              *    /$qr/p;
8563              * the KEEPCOPY is set on the PMOP rather than the regex */
8564             if (PL_curpm && r == PM_GETRE(PL_curpm))
8565                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8566         }
8567         if (!keepcopy)
8568             goto ret_undef;
8569     }
8570
8571     if (!rx->subbeg)
8572         goto ret_undef;
8573
8574     if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8575         /* no need to distinguish between them any more */
8576         n = RX_BUFF_IDX_FULLMATCH;
8577
8578     if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8579         && rx->offs[0].start != -1)
8580     {
8581         /* $`, ${^PREMATCH} */
8582         i = rx->offs[0].start;
8583         s = rx->subbeg;
8584     }
8585     else
8586     if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8587         && rx->offs[0].end != -1)
8588     {
8589         /* $', ${^POSTMATCH} */
8590         s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8591         i = rx->sublen + rx->suboffset - rx->offs[0].end;
8592     }
8593     else
8594     if ( 0 <= n && n <= (I32)rx->nparens &&
8595         (s1 = rx->offs[n].start) != -1 &&
8596         (t1 = rx->offs[n].end) != -1)
8597     {
8598         /* $&, ${^MATCH},  $1 ... */
8599         i = t1 - s1;
8600         s = rx->subbeg + s1 - rx->suboffset;
8601     } else {
8602         goto ret_undef;
8603     }
8604
8605     assert(s >= rx->subbeg);
8606     assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8607     if (i >= 0) {
8608 #ifdef NO_TAINT_SUPPORT
8609         sv_setpvn(sv, s, i);
8610 #else
8611         const int oldtainted = TAINT_get;
8612         TAINT_NOT;
8613         sv_setpvn(sv, s, i);
8614         TAINT_set(oldtainted);
8615 #endif
8616         if (RXp_MATCH_UTF8(rx))
8617             SvUTF8_on(sv);
8618         else
8619             SvUTF8_off(sv);
8620         if (TAINTING_get) {
8621             if (RXp_MATCH_TAINTED(rx)) {
8622                 if (SvTYPE(sv) >= SVt_PVMG) {
8623                     MAGIC* const mg = SvMAGIC(sv);
8624                     MAGIC* mgt;
8625                     TAINT;
8626                     SvMAGIC_set(sv, mg->mg_moremagic);
8627                     SvTAINT(sv);
8628                     if ((mgt = SvMAGIC(sv))) {
8629                         mg->mg_moremagic = mgt;
8630                         SvMAGIC_set(sv, mg);
8631                     }
8632                 } else {
8633                     TAINT;
8634                     SvTAINT(sv);
8635                 }
8636             } else
8637                 SvTAINTED_off(sv);
8638         }
8639     } else {
8640       ret_undef:
8641         sv_set_undef(sv);
8642         return;
8643     }
8644 }
8645
8646 void
8647 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8648                                                          SV const * const value)
8649 {
8650     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8651
8652     PERL_UNUSED_ARG(rx);
8653     PERL_UNUSED_ARG(paren);
8654     PERL_UNUSED_ARG(value);
8655
8656     if (!PL_localizing)
8657         Perl_croak_no_modify();
8658 }
8659
8660 I32
8661 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8662                               const I32 paren)
8663 {
8664     struct regexp *const rx = ReANY(r);
8665     I32 i;
8666     I32 s1, t1;
8667
8668     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8669
8670     if (   paren == RX_BUFF_IDX_CARET_PREMATCH
8671         || paren == RX_BUFF_IDX_CARET_FULLMATCH
8672         || paren == RX_BUFF_IDX_CARET_POSTMATCH
8673     )
8674     {
8675         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8676         if (!keepcopy) {
8677             /* on something like
8678              *    $r = qr/.../;
8679              *    /$qr/p;
8680              * the KEEPCOPY is set on the PMOP rather than the regex */
8681             if (PL_curpm && r == PM_GETRE(PL_curpm))
8682                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8683         }
8684         if (!keepcopy)
8685             goto warn_undef;
8686     }
8687
8688     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8689     switch (paren) {
8690       case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8691       case RX_BUFF_IDX_PREMATCH:       /* $` */
8692         if (rx->offs[0].start != -1) {
8693                         i = rx->offs[0].start;
8694                         if (i > 0) {
8695                                 s1 = 0;
8696                                 t1 = i;
8697                                 goto getlen;
8698                         }
8699             }
8700         return 0;
8701
8702       case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8703       case RX_BUFF_IDX_POSTMATCH:       /* $' */
8704             if (rx->offs[0].end != -1) {
8705                         i = rx->sublen - rx->offs[0].end;
8706                         if (i > 0) {
8707                                 s1 = rx->offs[0].end;
8708                                 t1 = rx->sublen;
8709                                 goto getlen;
8710                         }
8711             }
8712         return 0;
8713
8714       default: /* $& / ${^MATCH}, $1, $2, ... */
8715             if (paren <= (I32)rx->nparens &&
8716             (s1 = rx->offs[paren].start) != -1 &&
8717             (t1 = rx->offs[paren].end) != -1)
8718             {
8719             i = t1 - s1;
8720             goto getlen;
8721         } else {
8722           warn_undef:
8723             if (ckWARN(WARN_UNINITIALIZED))
8724                 report_uninit((const SV *)sv);
8725             return 0;
8726         }
8727     }
8728   getlen:
8729     if (i > 0 && RXp_MATCH_UTF8(rx)) {
8730         const char * const s = rx->subbeg - rx->suboffset + s1;
8731         const U8 *ep;
8732         STRLEN el;
8733
8734         i = t1 - s1;
8735         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8736                         i = el;
8737     }
8738     return i;
8739 }
8740
8741 SV*
8742 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8743 {
8744     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8745         PERL_UNUSED_ARG(rx);
8746         if (0)
8747             return NULL;
8748         else
8749             return newSVpvs("Regexp");
8750 }
8751
8752 /* Scans the name of a named buffer from the pattern.
8753  * If flags is REG_RSN_RETURN_NULL returns null.
8754  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8755  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8756  * to the parsed name as looked up in the RExC_paren_names hash.
8757  * If there is an error throws a vFAIL().. type exception.
8758  */
8759
8760 #define REG_RSN_RETURN_NULL    0
8761 #define REG_RSN_RETURN_NAME    1
8762 #define REG_RSN_RETURN_DATA    2
8763
8764 STATIC SV*
8765 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8766 {
8767     char *name_start = RExC_parse;
8768     SV* sv_name;
8769
8770     PERL_ARGS_ASSERT_REG_SCAN_NAME;
8771
8772     assert (RExC_parse <= RExC_end);
8773     if (RExC_parse == RExC_end) NOOP;
8774     else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
8775          /* Note that the code here assumes well-formed UTF-8.  Skip IDFIRST by
8776           * using do...while */
8777         if (UTF)
8778             do {
8779                 RExC_parse += UTF8SKIP(RExC_parse);
8780             } while (   RExC_parse < RExC_end
8781                      && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
8782         else
8783             do {
8784                 RExC_parse++;
8785             } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
8786     } else {
8787         RExC_parse++; /* so the <- from the vFAIL is after the offending
8788                          character */
8789         vFAIL("Group name must start with a non-digit word character");
8790     }
8791     sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8792                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8793     if ( flags == REG_RSN_RETURN_NAME)
8794         return sv_name;
8795     else if (flags==REG_RSN_RETURN_DATA) {
8796         HE *he_str = NULL;
8797         SV *sv_dat = NULL;
8798         if ( ! sv_name )      /* should not happen*/
8799             Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8800         if (RExC_paren_names)
8801             he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8802         if ( he_str )
8803             sv_dat = HeVAL(he_str);
8804         if ( ! sv_dat ) {   /* Didn't find group */
8805
8806             /* It might be a forward reference; we can't fail until we
8807                 * know, by completing the parse to get all the groups, and
8808                 * then reparsing */
8809             if (RExC_total_parens > 0)  {
8810                 vFAIL("Reference to nonexistent named group");
8811             }
8812             else {
8813                 REQUIRE_PARENS_PASS;
8814             }
8815         }
8816         return sv_dat;
8817     }
8818
8819     Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8820                      (unsigned long) flags);
8821 }
8822
8823 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
8824     if (RExC_lastparse!=RExC_parse) {                           \
8825         Perl_re_printf( aTHX_  "%s",                            \
8826             Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse,        \
8827                 RExC_end - RExC_parse, 16,                      \
8828                 "", "",                                         \
8829                 PERL_PV_ESCAPE_UNI_DETECT |                     \
8830                 PERL_PV_PRETTY_ELLIPSES   |                     \
8831                 PERL_PV_PRETTY_LTGT       |                     \
8832                 PERL_PV_ESCAPE_RE         |                     \
8833                 PERL_PV_PRETTY_EXACTSIZE                        \
8834             )                                                   \
8835         );                                                      \
8836     } else                                                      \
8837         Perl_re_printf( aTHX_ "%16s","");                       \
8838                                                                 \
8839     if (RExC_lastnum!=RExC_emit)                                \
8840        Perl_re_printf( aTHX_ "|%4d", RExC_emit);                \
8841     else                                                        \
8842        Perl_re_printf( aTHX_ "|%4s","");                        \
8843     Perl_re_printf( aTHX_ "|%*s%-4s",                           \
8844         (int)((depth*2)), "",                                   \
8845         (funcname)                                              \
8846     );                                                          \
8847     RExC_lastnum=RExC_emit;                                     \
8848     RExC_lastparse=RExC_parse;                                  \
8849 })
8850
8851
8852
8853 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
8854     DEBUG_PARSE_MSG((funcname));                            \
8855     Perl_re_printf( aTHX_ "%4s","\n");                                  \
8856 })
8857 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({\
8858     DEBUG_PARSE_MSG((funcname));                            \
8859     Perl_re_printf( aTHX_ fmt "\n",args);                               \
8860 })
8861
8862 /* This section of code defines the inversion list object and its methods.  The
8863  * interfaces are highly subject to change, so as much as possible is static to
8864  * this file.  An inversion list is here implemented as a malloc'd C UV array
8865  * as an SVt_INVLIST scalar.
8866  *
8867  * An inversion list for Unicode is an array of code points, sorted by ordinal
8868  * number.  Each element gives the code point that begins a range that extends
8869  * up-to but not including the code point given by the next element.  The final
8870  * element gives the first code point of a range that extends to the platform's
8871  * infinity.  The even-numbered elements (invlist[0], invlist[2], invlist[4],
8872  * ...) give ranges whose code points are all in the inversion list.  We say
8873  * that those ranges are in the set.  The odd-numbered elements give ranges
8874  * whose code points are not in the inversion list, and hence not in the set.
8875  * Thus, element [0] is the first code point in the list.  Element [1]
8876  * is the first code point beyond that not in the list; and element [2] is the
8877  * first code point beyond that that is in the list.  In other words, the first
8878  * range is invlist[0]..(invlist[1]-1), and all code points in that range are
8879  * in the inversion list.  The second range is invlist[1]..(invlist[2]-1), and
8880  * all code points in that range are not in the inversion list.  The third
8881  * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
8882  * list, and so forth.  Thus every element whose index is divisible by two
8883  * gives the beginning of a range that is in the list, and every element whose
8884  * index is not divisible by two gives the beginning of a range not in the
8885  * list.  If the final element's index is divisible by two, the inversion list
8886  * extends to the platform's infinity; otherwise the highest code point in the
8887  * inversion list is the contents of that element minus 1.
8888  *
8889  * A range that contains just a single code point N will look like
8890  *  invlist[i]   == N
8891  *  invlist[i+1] == N+1
8892  *
8893  * If N is UV_MAX (the highest representable code point on the machine), N+1 is
8894  * impossible to represent, so element [i+1] is omitted.  The single element
8895  * inversion list
8896  *  invlist[0] == UV_MAX
8897  * contains just UV_MAX, but is interpreted as matching to infinity.
8898  *
8899  * Taking the complement (inverting) an inversion list is quite simple, if the
8900  * first element is 0, remove it; otherwise add a 0 element at the beginning.
8901  * This implementation reserves an element at the beginning of each inversion
8902  * list to always contain 0; there is an additional flag in the header which
8903  * indicates if the list begins at the 0, or is offset to begin at the next
8904  * element.  This means that the inversion list can be inverted without any
8905  * copying; just flip the flag.
8906  *
8907  * More about inversion lists can be found in "Unicode Demystified"
8908  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
8909  *
8910  * The inversion list data structure is currently implemented as an SV pointing
8911  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
8912  * array of UV whose memory management is automatically handled by the existing
8913  * facilities for SV's.
8914  *
8915  * Some of the methods should always be private to the implementation, and some
8916  * should eventually be made public */
8917
8918 /* The header definitions are in F<invlist_inline.h> */
8919
8920 #ifndef PERL_IN_XSUB_RE
8921
8922 PERL_STATIC_INLINE UV*
8923 S__invlist_array_init(SV* const invlist, const bool will_have_0)
8924 {
8925     /* Returns a pointer to the first element in the inversion list's array.
8926      * This is called upon initialization of an inversion list.  Where the
8927      * array begins depends on whether the list has the code point U+0000 in it
8928      * or not.  The other parameter tells it whether the code that follows this
8929      * call is about to put a 0 in the inversion list or not.  The first
8930      * element is either the element reserved for 0, if TRUE, or the element
8931      * after it, if FALSE */
8932
8933     bool* offset = get_invlist_offset_addr(invlist);
8934     UV* zero_addr = (UV *) SvPVX(invlist);
8935
8936     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
8937
8938     /* Must be empty */
8939     assert(! _invlist_len(invlist));
8940
8941     *zero_addr = 0;
8942
8943     /* 1^1 = 0; 1^0 = 1 */
8944     *offset = 1 ^ will_have_0;
8945     return zero_addr + *offset;
8946 }
8947
8948 PERL_STATIC_INLINE void
8949 S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
8950 {
8951     /* Sets the current number of elements stored in the inversion list.
8952      * Updates SvCUR correspondingly */
8953     PERL_UNUSED_CONTEXT;
8954     PERL_ARGS_ASSERT_INVLIST_SET_LEN;
8955
8956     assert(is_invlist(invlist));
8957
8958     SvCUR_set(invlist,
8959               (len == 0)
8960                ? 0
8961                : TO_INTERNAL_SIZE(len + offset));
8962     assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
8963 }
8964
8965 STATIC void
8966 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
8967 {
8968     /* Replaces the inversion list in 'dest' with the one from 'src'.  It
8969      * steals the list from 'src', so 'src' is made to have a NULL list.  This
8970      * is similar to what SvSetMagicSV() would do, if it were implemented on
8971      * inversion lists, though this routine avoids a copy */
8972
8973     const UV src_len          = _invlist_len(src);
8974     const bool src_offset     = *get_invlist_offset_addr(src);
8975     const STRLEN src_byte_len = SvLEN(src);
8976     char * array              = SvPVX(src);
8977
8978     const int oldtainted = TAINT_get;
8979
8980     PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
8981
8982     assert(is_invlist(src));
8983     assert(is_invlist(dest));
8984     assert(! invlist_is_iterating(src));
8985     assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
8986
8987     /* Make sure it ends in the right place with a NUL, as our inversion list
8988      * manipulations aren't careful to keep this true, but sv_usepvn_flags()
8989      * asserts it */
8990     array[src_byte_len - 1] = '\0';
8991
8992     TAINT_NOT;      /* Otherwise it breaks */
8993     sv_usepvn_flags(dest,
8994                     (char *) array,
8995                     src_byte_len - 1,
8996
8997                     /* This flag is documented to cause a copy to be avoided */
8998                     SV_HAS_TRAILING_NUL);
8999     TAINT_set(oldtainted);
9000     SvPV_set(src, 0);
9001     SvLEN_set(src, 0);
9002     SvCUR_set(src, 0);
9003
9004     /* Finish up copying over the other fields in an inversion list */
9005     *get_invlist_offset_addr(dest) = src_offset;
9006     invlist_set_len(dest, src_len, src_offset);
9007     *get_invlist_previous_index_addr(dest) = 0;
9008     invlist_iterfinish(dest);
9009 }
9010
9011 PERL_STATIC_INLINE IV*
9012 S_get_invlist_previous_index_addr(SV* invlist)
9013 {
9014     /* Return the address of the IV that is reserved to hold the cached index
9015      * */
9016     PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
9017
9018     assert(is_invlist(invlist));
9019
9020     return &(((XINVLIST*) SvANY(invlist))->prev_index);
9021 }
9022
9023 PERL_STATIC_INLINE IV
9024 S_invlist_previous_index(SV* const invlist)
9025 {
9026     /* Returns cached index of previous search */
9027
9028     PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
9029
9030     return *get_invlist_previous_index_addr(invlist);
9031 }
9032
9033 PERL_STATIC_INLINE void
9034 S_invlist_set_previous_index(SV* const invlist, const IV index)
9035 {
9036     /* Caches <index> for later retrieval */
9037
9038     PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
9039
9040     assert(index == 0 || index < (int) _invlist_len(invlist));
9041
9042     *get_invlist_previous_index_addr(invlist) = index;
9043 }
9044
9045 PERL_STATIC_INLINE void
9046 S_invlist_trim(SV* invlist)
9047 {
9048     /* Free the not currently-being-used space in an inversion list */
9049
9050     /* But don't free up the space needed for the 0 UV that is always at the
9051      * beginning of the list, nor the trailing NUL */
9052     const UV min_size = TO_INTERNAL_SIZE(1) + 1;
9053
9054     PERL_ARGS_ASSERT_INVLIST_TRIM;
9055
9056     assert(is_invlist(invlist));
9057
9058     SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
9059 }
9060
9061 PERL_STATIC_INLINE void
9062 S_invlist_clear(pTHX_ SV* invlist)    /* Empty the inversion list */
9063 {
9064     PERL_ARGS_ASSERT_INVLIST_CLEAR;
9065
9066     assert(is_invlist(invlist));
9067
9068     invlist_set_len(invlist, 0, 0);
9069     invlist_trim(invlist);
9070 }
9071
9072 #endif /* ifndef PERL_IN_XSUB_RE */
9073
9074 PERL_STATIC_INLINE bool
9075 S_invlist_is_iterating(SV* const invlist)
9076 {
9077     PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
9078
9079     return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
9080 }
9081
9082 #ifndef PERL_IN_XSUB_RE
9083
9084 PERL_STATIC_INLINE UV
9085 S_invlist_max(SV* const invlist)
9086 {
9087     /* Returns the maximum number of elements storable in the inversion list's
9088      * array, without having to realloc() */
9089
9090     PERL_ARGS_ASSERT_INVLIST_MAX;
9091
9092     assert(is_invlist(invlist));
9093
9094     /* Assumes worst case, in which the 0 element is not counted in the
9095      * inversion list, so subtracts 1 for that */
9096     return SvLEN(invlist) == 0  /* This happens under _new_invlist_C_array */
9097            ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
9098            : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
9099 }
9100
9101 STATIC void
9102 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
9103 {
9104     PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
9105
9106     /* First 1 is in case the zero element isn't in the list; second 1 is for
9107      * trailing NUL */
9108     SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
9109     invlist_set_len(invlist, 0, 0);
9110
9111     /* Force iterinit() to be used to get iteration to work */
9112     invlist_iterfinish(invlist);
9113
9114     *get_invlist_previous_index_addr(invlist) = 0;
9115 }
9116
9117 SV*
9118 Perl__new_invlist(pTHX_ IV initial_size)
9119 {
9120
9121     /* Return a pointer to a newly constructed inversion list, with enough
9122      * space to store 'initial_size' elements.  If that number is negative, a
9123      * system default is used instead */
9124
9125     SV* new_list;
9126
9127     if (initial_size < 0) {
9128         initial_size = 10;
9129     }
9130
9131     new_list = newSV_type(SVt_INVLIST);
9132     initialize_invlist_guts(new_list, initial_size);
9133
9134     return new_list;
9135 }
9136
9137 SV*
9138 Perl__new_invlist_C_array(pTHX_ const UV* const list)
9139 {
9140     /* Return a pointer to a newly constructed inversion list, initialized to
9141      * point to <list>, which has to be in the exact correct inversion list
9142      * form, including internal fields.  Thus this is a dangerous routine that
9143      * should not be used in the wrong hands.  The passed in 'list' contains
9144      * several header fields at the beginning that are not part of the
9145      * inversion list body proper */
9146
9147     const STRLEN length = (STRLEN) list[0];
9148     const UV version_id =          list[1];
9149     const bool offset   =    cBOOL(list[2]);
9150 #define HEADER_LENGTH 3
9151     /* If any of the above changes in any way, you must change HEADER_LENGTH
9152      * (if appropriate) and regenerate INVLIST_VERSION_ID by running
9153      *      perl -E 'say int(rand 2**31-1)'
9154      */
9155 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
9156                                         data structure type, so that one being
9157                                         passed in can be validated to be an
9158                                         inversion list of the correct vintage.
9159                                        */
9160
9161     SV* invlist = newSV_type(SVt_INVLIST);
9162
9163     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
9164
9165     if (version_id != INVLIST_VERSION_ID) {
9166         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
9167     }
9168
9169     /* The generated array passed in includes header elements that aren't part
9170      * of the list proper, so start it just after them */
9171     SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
9172
9173     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
9174                                shouldn't touch it */
9175
9176     *(get_invlist_offset_addr(invlist)) = offset;
9177
9178     /* The 'length' passed to us is the physical number of elements in the
9179      * inversion list.  But if there is an offset the logical number is one
9180      * less than that */
9181     invlist_set_len(invlist, length  - offset, offset);
9182
9183     invlist_set_previous_index(invlist, 0);
9184
9185     /* Initialize the iteration pointer. */
9186     invlist_iterfinish(invlist);
9187
9188     SvREADONLY_on(invlist);
9189
9190     return invlist;
9191 }
9192
9193 STATIC void
9194 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
9195 {
9196     /* Grow the maximum size of an inversion list */
9197
9198     PERL_ARGS_ASSERT_INVLIST_EXTEND;
9199
9200     assert(is_invlist(invlist));
9201
9202     /* Add one to account for the zero element at the beginning which may not
9203      * be counted by the calling parameters */
9204     SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
9205 }
9206
9207 STATIC void
9208 S__append_range_to_invlist(pTHX_ SV* const invlist,
9209                                  const UV start, const UV end)
9210 {
9211    /* Subject to change or removal.  Append the range from 'start' to 'end' at
9212     * the end of the inversion list.  The range must be above any existing
9213     * ones. */
9214
9215     UV* array;
9216     UV max = invlist_max(invlist);
9217     UV len = _invlist_len(invlist);
9218     bool offset;
9219
9220     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9221
9222     if (len == 0) { /* Empty lists must be initialized */
9223         offset = start != 0;
9224         array = _invlist_array_init(invlist, ! offset);
9225     }
9226     else {
9227         /* Here, the existing list is non-empty. The current max entry in the
9228          * list is generally the first value not in the set, except when the
9229          * set extends to the end of permissible values, in which case it is
9230          * the first entry in that final set, and so this call is an attempt to
9231          * append out-of-order */
9232
9233         UV final_element = len - 1;
9234         array = invlist_array(invlist);
9235         if (   array[final_element] > start
9236             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9237         {
9238             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",
9239                      array[final_element], start,
9240                      ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9241         }
9242
9243         /* Here, it is a legal append.  If the new range begins 1 above the end
9244          * of the range below it, it is extending the range below it, so the
9245          * new first value not in the set is one greater than the newly
9246          * extended range.  */
9247         offset = *get_invlist_offset_addr(invlist);
9248         if (array[final_element] == start) {
9249             if (end != UV_MAX) {
9250                 array[final_element] = end + 1;
9251             }
9252             else {
9253                 /* But if the end is the maximum representable on the machine,
9254                  * assume that infinity was actually what was meant.  Just let
9255                  * the range that this would extend to have no end */
9256                 invlist_set_len(invlist, len - 1, offset);
9257             }
9258             return;
9259         }
9260     }
9261
9262     /* Here the new range doesn't extend any existing set.  Add it */
9263
9264     len += 2;   /* Includes an element each for the start and end of range */
9265
9266     /* If wll overflow the existing space, extend, which may cause the array to
9267      * be moved */
9268     if (max < len) {
9269         invlist_extend(invlist, len);
9270
9271         /* Have to set len here to avoid assert failure in invlist_array() */
9272         invlist_set_len(invlist, len, offset);
9273
9274         array = invlist_array(invlist);
9275     }
9276     else {
9277         invlist_set_len(invlist, len, offset);
9278     }
9279
9280     /* The next item on the list starts the range, the one after that is
9281      * one past the new range.  */
9282     array[len - 2] = start;
9283     if (end != UV_MAX) {
9284         array[len - 1] = end + 1;
9285     }
9286     else {
9287         /* But if the end is the maximum representable on the machine, just let
9288          * the range have no end */
9289         invlist_set_len(invlist, len - 1, offset);
9290     }
9291 }
9292
9293 SSize_t
9294 Perl__invlist_search(SV* const invlist, const UV cp)
9295 {
9296     /* Searches the inversion list for the entry that contains the input code
9297      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
9298      * return value is the index into the list's array of the range that
9299      * contains <cp>, that is, 'i' such that
9300      *  array[i] <= cp < array[i+1]
9301      */
9302
9303     IV low = 0;
9304     IV mid;
9305     IV high = _invlist_len(invlist);
9306     const IV highest_element = high - 1;
9307     const UV* array;
9308
9309     PERL_ARGS_ASSERT__INVLIST_SEARCH;
9310
9311     /* If list is empty, return failure. */
9312     if (high == 0) {
9313         return -1;
9314     }
9315
9316     /* (We can't get the array unless we know the list is non-empty) */
9317     array = invlist_array(invlist);
9318
9319     mid = invlist_previous_index(invlist);
9320     assert(mid >=0);
9321     if (mid > highest_element) {
9322         mid = highest_element;
9323     }
9324
9325     /* <mid> contains the cache of the result of the previous call to this
9326      * function (0 the first time).  See if this call is for the same result,
9327      * or if it is for mid-1.  This is under the theory that calls to this
9328      * function will often be for related code points that are near each other.
9329      * And benchmarks show that caching gives better results.  We also test
9330      * here if the code point is within the bounds of the list.  These tests
9331      * replace others that would have had to be made anyway to make sure that
9332      * the array bounds were not exceeded, and these give us extra information
9333      * at the same time */
9334     if (cp >= array[mid]) {
9335         if (cp >= array[highest_element]) {
9336             return highest_element;
9337         }
9338
9339         /* Here, array[mid] <= cp < array[highest_element].  This means that
9340          * the final element is not the answer, so can exclude it; it also
9341          * means that <mid> is not the final element, so can refer to 'mid + 1'
9342          * safely */
9343         if (cp < array[mid + 1]) {
9344             return mid;
9345         }
9346         high--;
9347         low = mid + 1;
9348     }
9349     else { /* cp < aray[mid] */
9350         if (cp < array[0]) { /* Fail if outside the array */
9351             return -1;
9352         }
9353         high = mid;
9354         if (cp >= array[mid - 1]) {
9355             goto found_entry;
9356         }
9357     }
9358
9359     /* Binary search.  What we are looking for is <i> such that
9360      *  array[i] <= cp < array[i+1]
9361      * The loop below converges on the i+1.  Note that there may not be an
9362      * (i+1)th element in the array, and things work nonetheless */
9363     while (low < high) {
9364         mid = (low + high) / 2;
9365         assert(mid <= highest_element);
9366         if (array[mid] <= cp) { /* cp >= array[mid] */
9367             low = mid + 1;
9368
9369             /* We could do this extra test to exit the loop early.
9370             if (cp < array[low]) {
9371                 return mid;
9372             }
9373             */
9374         }
9375         else { /* cp < array[mid] */
9376             high = mid;
9377         }
9378     }
9379
9380   found_entry:
9381     high--;
9382     invlist_set_previous_index(invlist, high);
9383     return high;
9384 }
9385
9386 void
9387 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9388                                          const bool complement_b, SV** output)
9389 {
9390     /* Take the union of two inversion lists and point '*output' to it.  On
9391      * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9392      * even 'a' or 'b').  If to an inversion list, the contents of the original
9393      * list will be replaced by the union.  The first list, 'a', may be
9394      * NULL, in which case a copy of the second list is placed in '*output'.
9395      * If 'complement_b' is TRUE, the union is taken of the complement
9396      * (inversion) of 'b' instead of b itself.
9397      *
9398      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9399      * Richard Gillam, published by Addison-Wesley, and explained at some
9400      * length there.  The preface says to incorporate its examples into your
9401      * code at your own risk.
9402      *
9403      * The algorithm is like a merge sort. */
9404
9405     const UV* array_a;    /* a's array */
9406     const UV* array_b;
9407     UV len_a;       /* length of a's array */
9408     UV len_b;
9409
9410     SV* u;                      /* the resulting union */
9411     UV* array_u;
9412     UV len_u = 0;
9413
9414     UV i_a = 0;             /* current index into a's array */
9415     UV i_b = 0;
9416     UV i_u = 0;
9417
9418     /* running count, as explained in the algorithm source book; items are
9419      * stopped accumulating and are output when the count changes to/from 0.
9420      * The count is incremented when we start a range that's in an input's set,
9421      * and decremented when we start a range that's not in a set.  So this
9422      * variable can be 0, 1, or 2.  When it is 0 neither input is in their set,
9423      * and hence nothing goes into the union; 1, just one of the inputs is in
9424      * its set (and its current range gets added to the union); and 2 when both
9425      * inputs are in their sets.  */
9426     UV count = 0;
9427
9428     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9429     assert(a != b);
9430     assert(*output == NULL || is_invlist(*output));
9431
9432     len_b = _invlist_len(b);
9433     if (len_b == 0) {
9434
9435         /* Here, 'b' is empty, hence it's complement is all possible code
9436          * points.  So if the union includes the complement of 'b', it includes
9437          * everything, and we need not even look at 'a'.  It's easiest to
9438          * create a new inversion list that matches everything.  */
9439         if (complement_b) {
9440             SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9441
9442             if (*output == NULL) { /* If the output didn't exist, just point it
9443                                       at the new list */
9444                 *output = everything;
9445             }
9446             else { /* Otherwise, replace its contents with the new list */
9447                 invlist_replace_list_destroys_src(*output, everything);
9448                 SvREFCNT_dec_NN(everything);
9449             }
9450
9451             return;
9452         }
9453
9454         /* Here, we don't want the complement of 'b', and since 'b' is empty,
9455          * the union will come entirely from 'a'.  If 'a' is NULL or empty, the
9456          * output will be empty */
9457
9458         if (a == NULL || _invlist_len(a) == 0) {
9459             if (*output == NULL) {
9460                 *output = _new_invlist(0);
9461             }
9462             else {
9463                 invlist_clear(*output);
9464             }
9465             return;
9466         }
9467
9468         /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9469          * union.  We can just return a copy of 'a' if '*output' doesn't point
9470          * to an existing list */
9471         if (*output == NULL) {
9472             *output = invlist_clone(a, NULL);
9473             return;
9474         }
9475
9476         /* If the output is to overwrite 'a', we have a no-op, as it's
9477          * already in 'a' */
9478         if (*output == a) {
9479             return;
9480         }
9481
9482         /* Here, '*output' is to be overwritten by 'a' */
9483         u = invlist_clone(a, NULL);
9484         invlist_replace_list_destroys_src(*output, u);
9485         SvREFCNT_dec_NN(u);
9486
9487         return;
9488     }
9489
9490     /* Here 'b' is not empty.  See about 'a' */
9491
9492     if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9493
9494         /* Here, 'a' is empty (and b is not).  That means the union will come
9495          * entirely from 'b'.  If '*output' is NULL, we can directly return a
9496          * clone of 'b'.  Otherwise, we replace the contents of '*output' with
9497          * the clone */
9498
9499         SV ** dest = (*output == NULL) ? output : &u;
9500         *dest = invlist_clone(b, NULL);
9501         if (complement_b) {
9502             _invlist_invert(*dest);
9503         }
9504
9505         if (dest == &u) {
9506             invlist_replace_list_destroys_src(*output, u);
9507             SvREFCNT_dec_NN(u);
9508         }
9509
9510         return;
9511     }
9512
9513     /* Here both lists exist and are non-empty */
9514     array_a = invlist_array(a);
9515     array_b = invlist_array(b);
9516
9517     /* If are to take the union of 'a' with the complement of b, set it
9518      * up so are looking at b's complement. */
9519     if (complement_b) {
9520
9521         /* To complement, we invert: if the first element is 0, remove it.  To
9522          * do this, we just pretend the array starts one later */
9523         if (array_b[0] == 0) {
9524             array_b++;
9525             len_b--;
9526         }
9527         else {
9528
9529             /* But if the first element is not zero, we pretend the list starts
9530              * at the 0 that is always stored immediately before the array. */
9531             array_b--;
9532             len_b++;
9533         }
9534     }
9535
9536     /* Size the union for the worst case: that the sets are completely
9537      * disjoint */
9538     u = _new_invlist(len_a + len_b);
9539
9540     /* Will contain U+0000 if either component does */
9541     array_u = _invlist_array_init(u, (    len_a > 0 && array_a[0] == 0)
9542                                       || (len_b > 0 && array_b[0] == 0));
9543
9544     /* Go through each input list item by item, stopping when have exhausted
9545      * one of them */
9546     while (i_a < len_a && i_b < len_b) {
9547         UV cp;      /* The element to potentially add to the union's array */
9548         bool cp_in_set;   /* is it in the the input list's set or not */
9549
9550         /* We need to take one or the other of the two inputs for the union.
9551          * Since we are merging two sorted lists, we take the smaller of the
9552          * next items.  In case of a tie, we take first the one that is in its
9553          * set.  If we first took the one not in its set, it would decrement
9554          * the count, possibly to 0 which would cause it to be output as ending
9555          * the range, and the next time through we would take the same number,
9556          * and output it again as beginning the next range.  By doing it the
9557          * opposite way, there is no possibility that the count will be
9558          * momentarily decremented to 0, and thus the two adjoining ranges will
9559          * be seamlessly merged.  (In a tie and both are in the set or both not
9560          * in the set, it doesn't matter which we take first.) */
9561         if (       array_a[i_a] < array_b[i_b]
9562             || (   array_a[i_a] == array_b[i_b]
9563                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9564         {
9565             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9566             cp = array_a[i_a++];
9567         }
9568         else {
9569             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9570             cp = array_b[i_b++];
9571         }
9572
9573         /* Here, have chosen which of the two inputs to look at.  Only output
9574          * if the running count changes to/from 0, which marks the
9575          * beginning/end of a range that's in the set */
9576         if (cp_in_set) {
9577             if (count == 0) {
9578                 array_u[i_u++] = cp;
9579             }
9580             count++;
9581         }
9582         else {
9583             count--;
9584             if (count == 0) {
9585                 array_u[i_u++] = cp;
9586             }
9587         }
9588     }
9589
9590
9591     /* The loop above increments the index into exactly one of the input lists
9592      * each iteration, and ends when either index gets to its list end.  That
9593      * means the other index is lower than its end, and so something is
9594      * remaining in that one.  We decrement 'count', as explained below, if
9595      * that list is in its set.  (i_a and i_b each currently index the element
9596      * beyond the one we care about.) */
9597     if (   (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9598         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9599     {
9600         count--;
9601     }
9602
9603     /* Above we decremented 'count' if the list that had unexamined elements in
9604      * it was in its set.  This has made it so that 'count' being non-zero
9605      * means there isn't anything left to output; and 'count' equal to 0 means
9606      * that what is left to output is precisely that which is left in the
9607      * non-exhausted input list.
9608      *
9609      * To see why, note first that the exhausted input obviously has nothing
9610      * left to add to the union.  If it was in its set at its end, that means
9611      * the set extends from here to the platform's infinity, and hence so does
9612      * the union and the non-exhausted set is irrelevant.  The exhausted set
9613      * also contributed 1 to 'count'.  If 'count' was 2, it got decremented to
9614      * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9615      * 'count' remains at 1.  This is consistent with the decremented 'count'
9616      * != 0 meaning there's nothing left to add to the union.
9617      *
9618      * But if the exhausted input wasn't in its set, it contributed 0 to
9619      * 'count', and the rest of the union will be whatever the other input is.
9620      * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9621      * otherwise it gets decremented to 0.  This is consistent with 'count'
9622      * == 0 meaning the remainder of the union is whatever is left in the
9623      * non-exhausted list. */
9624     if (count != 0) {
9625         len_u = i_u;
9626     }
9627     else {
9628         IV copy_count = len_a - i_a;
9629         if (copy_count > 0) {   /* The non-exhausted input is 'a' */
9630             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9631         }
9632         else { /* The non-exhausted input is b */
9633             copy_count = len_b - i_b;
9634             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9635         }
9636         len_u = i_u + copy_count;
9637     }
9638
9639     /* Set the result to the final length, which can change the pointer to
9640      * array_u, so re-find it.  (Note that it is unlikely that this will
9641      * change, as we are shrinking the space, not enlarging it) */
9642     if (len_u != _invlist_len(u)) {
9643         invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9644         invlist_trim(u);
9645         array_u = invlist_array(u);
9646     }
9647
9648     if (*output == NULL) {  /* Simply return the new inversion list */
9649         *output = u;
9650     }
9651     else {
9652         /* Otherwise, overwrite the inversion list that was in '*output'.  We
9653          * could instead free '*output', and then set it to 'u', but experience
9654          * has shown [perl #127392] that if the input is a mortal, we can get a
9655          * huge build-up of these during regex compilation before they get
9656          * freed. */
9657         invlist_replace_list_destroys_src(*output, u);
9658         SvREFCNT_dec_NN(u);
9659     }
9660
9661     return;
9662 }
9663
9664 void
9665 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9666                                                const bool complement_b, SV** i)
9667 {
9668     /* Take the intersection of two inversion lists and point '*i' to it.  On
9669      * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9670      * even 'a' or 'b').  If to an inversion list, the contents of the original
9671      * list will be replaced by the intersection.  The first list, 'a', may be
9672      * NULL, in which case '*i' will be an empty list.  If 'complement_b' is
9673      * TRUE, the result will be the intersection of 'a' and the complement (or
9674      * inversion) of 'b' instead of 'b' directly.
9675      *
9676      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9677      * Richard Gillam, published by Addison-Wesley, and explained at some
9678      * length there.  The preface says to incorporate its examples into your
9679      * code at your own risk.  In fact, it had bugs
9680      *
9681      * The algorithm is like a merge sort, and is essentially the same as the
9682      * union above
9683      */
9684
9685     const UV* array_a;          /* a's array */
9686     const UV* array_b;
9687     UV len_a;   /* length of a's array */
9688     UV len_b;
9689
9690     SV* r;                   /* the resulting intersection */
9691     UV* array_r;
9692     UV len_r = 0;
9693
9694     UV i_a = 0;             /* current index into a's array */
9695     UV i_b = 0;
9696     UV i_r = 0;
9697
9698     /* running count of how many of the two inputs are postitioned at ranges
9699      * that are in their sets.  As explained in the algorithm source book,
9700      * items are stopped accumulating and are output when the count changes
9701      * to/from 2.  The count is incremented when we start a range that's in an
9702      * input's set, and decremented when we start a range that's not in a set.
9703      * Only when it is 2 are we in the intersection. */
9704     UV count = 0;
9705
9706     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9707     assert(a != b);
9708     assert(*i == NULL || is_invlist(*i));
9709
9710     /* Special case if either one is empty */
9711     len_a = (a == NULL) ? 0 : _invlist_len(a);
9712     if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9713         if (len_a != 0 && complement_b) {
9714
9715             /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9716              * must be empty.  Here, also we are using 'b's complement, which
9717              * hence must be every possible code point.  Thus the intersection
9718              * is simply 'a'. */
9719
9720             if (*i == a) {  /* No-op */
9721                 return;
9722             }
9723
9724             if (*i == NULL) {
9725                 *i = invlist_clone(a, NULL);
9726                 return;
9727             }
9728
9729             r = invlist_clone(a, NULL);
9730             invlist_replace_list_destroys_src(*i, r);
9731             SvREFCNT_dec_NN(r);
9732             return;
9733         }
9734
9735         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
9736          * intersection must be empty */
9737         if (*i == NULL) {
9738             *i = _new_invlist(0);
9739             return;
9740         }
9741
9742         invlist_clear(*i);
9743         return;
9744     }
9745
9746     /* Here both lists exist and are non-empty */
9747     array_a = invlist_array(a);
9748     array_b = invlist_array(b);
9749
9750     /* If are to take the intersection of 'a' with the complement of b, set it
9751      * up so are looking at b's complement. */
9752     if (complement_b) {
9753
9754         /* To complement, we invert: if the first element is 0, remove it.  To
9755          * do this, we just pretend the array starts one later */
9756         if (array_b[0] == 0) {
9757             array_b++;
9758             len_b--;
9759         }
9760         else {
9761
9762             /* But if the first element is not zero, we pretend the list starts
9763              * at the 0 that is always stored immediately before the array. */
9764             array_b--;
9765             len_b++;
9766         }
9767     }
9768
9769     /* Size the intersection for the worst case: that the intersection ends up
9770      * fragmenting everything to be completely disjoint */
9771     r= _new_invlist(len_a + len_b);
9772
9773     /* Will contain U+0000 iff both components do */
9774     array_r = _invlist_array_init(r,    len_a > 0 && array_a[0] == 0
9775                                      && len_b > 0 && array_b[0] == 0);
9776
9777     /* Go through each list item by item, stopping when have exhausted one of
9778      * them */
9779     while (i_a < len_a && i_b < len_b) {
9780         UV cp;      /* The element to potentially add to the intersection's
9781                        array */
9782         bool cp_in_set; /* Is it in the input list's set or not */
9783
9784         /* We need to take one or the other of the two inputs for the
9785          * intersection.  Since we are merging two sorted lists, we take the
9786          * smaller of the next items.  In case of a tie, we take first the one
9787          * that is not in its set (a difference from the union algorithm).  If
9788          * we first took the one in its set, it would increment the count,
9789          * possibly to 2 which would cause it to be output as starting a range
9790          * in the intersection, and the next time through we would take that
9791          * same number, and output it again as ending the set.  By doing the
9792          * opposite of this, there is no possibility that the count will be
9793          * momentarily incremented to 2.  (In a tie and both are in the set or
9794          * both not in the set, it doesn't matter which we take first.) */
9795         if (       array_a[i_a] < array_b[i_b]
9796             || (   array_a[i_a] == array_b[i_b]
9797                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9798         {
9799             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9800             cp = array_a[i_a++];
9801         }
9802         else {
9803             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9804             cp= array_b[i_b++];
9805         }
9806
9807         /* Here, have chosen which of the two inputs to look at.  Only output
9808          * if the running count changes to/from 2, which marks the
9809          * beginning/end of a range that's in the intersection */
9810         if (cp_in_set) {
9811             count++;
9812             if (count == 2) {
9813                 array_r[i_r++] = cp;
9814             }
9815         }
9816         else {
9817             if (count == 2) {
9818                 array_r[i_r++] = cp;
9819             }
9820             count--;
9821         }
9822
9823     }
9824
9825     /* The loop above increments the index into exactly one of the input lists
9826      * each iteration, and ends when either index gets to its list end.  That
9827      * means the other index is lower than its end, and so something is
9828      * remaining in that one.  We increment 'count', as explained below, if the
9829      * exhausted list was in its set.  (i_a and i_b each currently index the
9830      * element beyond the one we care about.) */
9831     if (   (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9832         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9833     {
9834         count++;
9835     }
9836
9837     /* Above we incremented 'count' if the exhausted list was in its set.  This
9838      * has made it so that 'count' being below 2 means there is nothing left to
9839      * output; otheriwse what's left to add to the intersection is precisely
9840      * that which is left in the non-exhausted input list.
9841      *
9842      * To see why, note first that the exhausted input obviously has nothing
9843      * left to affect the intersection.  If it was in its set at its end, that
9844      * means the set extends from here to the platform's infinity, and hence
9845      * anything in the non-exhausted's list will be in the intersection, and
9846      * anything not in it won't be.  Hence, the rest of the intersection is
9847      * precisely what's in the non-exhausted list  The exhausted set also
9848      * contributed 1 to 'count', meaning 'count' was at least 1.  Incrementing
9849      * it means 'count' is now at least 2.  This is consistent with the
9850      * incremented 'count' being >= 2 means to add the non-exhausted list to
9851      * the intersection.
9852      *
9853      * But if the exhausted input wasn't in its set, it contributed 0 to
9854      * 'count', and the intersection can't include anything further; the
9855      * non-exhausted set is irrelevant.  'count' was at most 1, and doesn't get
9856      * incremented.  This is consistent with 'count' being < 2 meaning nothing
9857      * further to add to the intersection. */
9858     if (count < 2) { /* Nothing left to put in the intersection. */
9859         len_r = i_r;
9860     }
9861     else { /* copy the non-exhausted list, unchanged. */
9862         IV copy_count = len_a - i_a;
9863         if (copy_count > 0) {   /* a is the one with stuff left */
9864             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9865         }
9866         else {  /* b is the one with stuff left */
9867             copy_count = len_b - i_b;
9868             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9869         }
9870         len_r = i_r + copy_count;
9871     }
9872
9873     /* Set the result to the final length, which can change the pointer to
9874      * array_r, so re-find it.  (Note that it is unlikely that this will
9875      * change, as we are shrinking the space, not enlarging it) */
9876     if (len_r != _invlist_len(r)) {
9877         invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9878         invlist_trim(r);
9879         array_r = invlist_array(r);
9880     }
9881
9882     if (*i == NULL) { /* Simply return the calculated intersection */
9883         *i = r;
9884     }
9885     else { /* Otherwise, replace the existing inversion list in '*i'.  We could
9886               instead free '*i', and then set it to 'r', but experience has
9887               shown [perl #127392] that if the input is a mortal, we can get a
9888               huge build-up of these during regex compilation before they get
9889               freed. */
9890         if (len_r) {
9891             invlist_replace_list_destroys_src(*i, r);
9892         }
9893         else {
9894             invlist_clear(*i);
9895         }
9896         SvREFCNT_dec_NN(r);
9897     }
9898
9899     return;
9900 }
9901
9902 SV*
9903 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
9904 {
9905     /* Add the range from 'start' to 'end' inclusive to the inversion list's
9906      * set.  A pointer to the inversion list is returned.  This may actually be
9907      * a new list, in which case the passed in one has been destroyed.  The
9908      * passed-in inversion list can be NULL, in which case a new one is created
9909      * with just the one range in it.  The new list is not necessarily
9910      * NUL-terminated.  Space is not freed if the inversion list shrinks as a
9911      * result of this function.  The gain would not be large, and in many
9912      * cases, this is called multiple times on a single inversion list, so
9913      * anything freed may almost immediately be needed again.
9914      *
9915      * This used to mostly call the 'union' routine, but that is much more
9916      * heavyweight than really needed for a single range addition */
9917
9918     UV* array;              /* The array implementing the inversion list */
9919     UV len;                 /* How many elements in 'array' */
9920     SSize_t i_s;            /* index into the invlist array where 'start'
9921                                should go */
9922     SSize_t i_e = 0;        /* And the index where 'end' should go */
9923     UV cur_highest;         /* The highest code point in the inversion list
9924                                upon entry to this function */
9925
9926     /* This range becomes the whole inversion list if none already existed */
9927     if (invlist == NULL) {
9928         invlist = _new_invlist(2);
9929         _append_range_to_invlist(invlist, start, end);
9930         return invlist;
9931     }
9932
9933     /* Likewise, if the inversion list is currently empty */
9934     len = _invlist_len(invlist);
9935     if (len == 0) {
9936         _append_range_to_invlist(invlist, start, end);
9937         return invlist;
9938     }
9939
9940     /* Starting here, we have to know the internals of the list */
9941     array = invlist_array(invlist);
9942
9943     /* If the new range ends higher than the current highest ... */
9944     cur_highest = invlist_highest(invlist);
9945     if (end > cur_highest) {
9946
9947         /* If the whole range is higher, we can just append it */
9948         if (start > cur_highest) {
9949             _append_range_to_invlist(invlist, start, end);
9950             return invlist;
9951         }
9952
9953         /* Otherwise, add the portion that is higher ... */
9954         _append_range_to_invlist(invlist, cur_highest + 1, end);
9955
9956         /* ... and continue on below to handle the rest.  As a result of the
9957          * above append, we know that the index of the end of the range is the
9958          * final even numbered one of the array.  Recall that the final element
9959          * always starts a range that extends to infinity.  If that range is in
9960          * the set (meaning the set goes from here to infinity), it will be an
9961          * even index, but if it isn't in the set, it's odd, and the final
9962          * range in the set is one less, which is even. */
9963         if (end == UV_MAX) {
9964             i_e = len;
9965         }
9966         else {
9967             i_e = len - 2;
9968         }
9969     }
9970
9971     /* We have dealt with appending, now see about prepending.  If the new
9972      * range starts lower than the current lowest ... */
9973     if (start < array[0]) {
9974
9975         /* Adding something which has 0 in it is somewhat tricky, and uncommon.
9976          * Let the union code handle it, rather than having to know the
9977          * trickiness in two code places.  */
9978         if (UNLIKELY(start == 0)) {
9979             SV* range_invlist;
9980
9981             range_invlist = _new_invlist(2);
9982             _append_range_to_invlist(range_invlist, start, end);
9983
9984             _invlist_union(invlist, range_invlist, &invlist);
9985
9986             SvREFCNT_dec_NN(range_invlist);
9987
9988             return invlist;
9989         }
9990
9991         /* If the whole new range comes before the first entry, and doesn't
9992          * extend it, we have to insert it as an additional range */
9993         if (end < array[0] - 1) {
9994             i_s = i_e = -1;
9995             goto splice_in_new_range;
9996         }
9997
9998         /* Here the new range adjoins the existing first range, extending it
9999          * downwards. */
10000         array[0] = start;
10001
10002         /* And continue on below to handle the rest.  We know that the index of
10003          * the beginning of the range is the first one of the array */
10004         i_s = 0;
10005     }
10006     else { /* Not prepending any part of the new range to the existing list.
10007             * Find where in the list it should go.  This finds i_s, such that:
10008             *     invlist[i_s] <= start < array[i_s+1]
10009             */
10010         i_s = _invlist_search(invlist, start);
10011     }
10012
10013     /* At this point, any extending before the beginning of the inversion list
10014      * and/or after the end has been done.  This has made it so that, in the
10015      * code below, each endpoint of the new range is either in a range that is
10016      * in the set, or is in a gap between two ranges that are.  This means we
10017      * don't have to worry about exceeding the array bounds.
10018      *
10019      * Find where in the list the new range ends (but we can skip this if we
10020      * have already determined what it is, or if it will be the same as i_s,
10021      * which we already have computed) */
10022     if (i_e == 0) {
10023         i_e = (start == end)
10024               ? i_s
10025               : _invlist_search(invlist, end);
10026     }
10027
10028     /* Here generally invlist[i_e] <= end < array[i_e+1].  But if invlist[i_e]
10029      * is a range that goes to infinity there is no element at invlist[i_e+1],
10030      * so only the first relation holds. */
10031
10032     if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10033
10034         /* Here, the ranges on either side of the beginning of the new range
10035          * are in the set, and this range starts in the gap between them.
10036          *
10037          * The new range extends the range above it downwards if the new range
10038          * ends at or above that range's start */
10039         const bool extends_the_range_above = (   end == UV_MAX
10040                                               || end + 1 >= array[i_s+1]);
10041
10042         /* The new range extends the range below it upwards if it begins just
10043          * after where that range ends */
10044         if (start == array[i_s]) {
10045
10046             /* If the new range fills the entire gap between the other ranges,
10047              * they will get merged together.  Other ranges may also get
10048              * merged, depending on how many of them the new range spans.  In
10049              * the general case, we do the merge later, just once, after we
10050              * figure out how many to merge.  But in the case where the new
10051              * range exactly spans just this one gap (possibly extending into
10052              * the one above), we do the merge here, and an early exit.  This
10053              * is done here to avoid having to special case later. */
10054             if (i_e - i_s <= 1) {
10055
10056                 /* If i_e - i_s == 1, it means that the new range terminates
10057                  * within the range above, and hence 'extends_the_range_above'
10058                  * must be true.  (If the range above it extends to infinity,
10059                  * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
10060                  * will be 0, so no harm done.) */
10061                 if (extends_the_range_above) {
10062                     Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
10063                     invlist_set_len(invlist,
10064                                     len - 2,
10065                                     *(get_invlist_offset_addr(invlist)));
10066                     return invlist;
10067                 }
10068
10069                 /* Here, i_e must == i_s.  We keep them in sync, as they apply
10070                  * to the same range, and below we are about to decrement i_s
10071                  * */
10072                 i_e--;
10073             }
10074
10075             /* Here, the new range is adjacent to the one below.  (It may also
10076              * span beyond the range above, but that will get resolved later.)
10077              * Extend the range below to include this one. */
10078             array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
10079             i_s--;
10080             start = array[i_s];
10081         }
10082         else if (extends_the_range_above) {
10083
10084             /* Here the new range only extends the range above it, but not the
10085              * one below.  It merges with the one above.  Again, we keep i_e
10086              * and i_s in sync if they point to the same range */
10087             if (i_e == i_s) {
10088                 i_e++;
10089             }
10090             i_s++;
10091             array[i_s] = start;
10092         }
10093     }
10094
10095     /* Here, we've dealt with the new range start extending any adjoining
10096      * existing ranges.
10097      *
10098      * If the new range extends to infinity, it is now the final one,
10099      * regardless of what was there before */
10100     if (UNLIKELY(end == UV_MAX)) {
10101         invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10102         return invlist;
10103     }
10104
10105     /* If i_e started as == i_s, it has also been dealt with,
10106      * and been updated to the new i_s, which will fail the following if */
10107     if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10108
10109         /* Here, the ranges on either side of the end of the new range are in
10110          * the set, and this range ends in the gap between them.
10111          *
10112          * If this range is adjacent to (hence extends) the range above it, it
10113          * becomes part of that range; likewise if it extends the range below,
10114          * it becomes part of that range */
10115         if (end + 1 == array[i_e+1]) {
10116             i_e++;
10117             array[i_e] = start;
10118         }
10119         else if (start <= array[i_e]) {
10120             array[i_e] = end + 1;
10121             i_e--;
10122         }
10123     }
10124
10125     if (i_s == i_e) {
10126
10127         /* If the range fits entirely in an existing range (as possibly already
10128          * extended above), it doesn't add anything new */
10129         if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10130             return invlist;
10131         }
10132
10133         /* Here, no part of the range is in the list.  Must add it.  It will
10134          * occupy 2 more slots */
10135       splice_in_new_range:
10136
10137         invlist_extend(invlist, len + 2);
10138         array = invlist_array(invlist);
10139         /* Move the rest of the array down two slots. Don't include any
10140          * trailing NUL */
10141         Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10142
10143         /* Do the actual splice */
10144         array[i_e+1] = start;
10145         array[i_e+2] = end + 1;
10146         invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10147         return invlist;
10148     }
10149
10150     /* Here the new range crossed the boundaries of a pre-existing range.  The
10151      * code above has adjusted things so that both ends are in ranges that are
10152      * in the set.  This means everything in between must also be in the set.
10153      * Just squash things together */
10154     Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10155     invlist_set_len(invlist,
10156                     len - i_e + i_s,
10157                     *(get_invlist_offset_addr(invlist)));
10158
10159     return invlist;
10160 }
10161
10162 SV*
10163 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10164                                  UV** other_elements_ptr)
10165 {
10166     /* Create and return an inversion list whose contents are to be populated
10167      * by the caller.  The caller gives the number of elements (in 'size') and
10168      * the very first element ('element0').  This function will set
10169      * '*other_elements_ptr' to an array of UVs, where the remaining elements
10170      * are to be placed.
10171      *
10172      * Obviously there is some trust involved that the caller will properly
10173      * fill in the other elements of the array.
10174      *
10175      * (The first element needs to be passed in, as the underlying code does
10176      * things differently depending on whether it is zero or non-zero) */
10177
10178     SV* invlist = _new_invlist(size);
10179     bool offset;
10180
10181     PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10182
10183     invlist = add_cp_to_invlist(invlist, element0);
10184     offset = *get_invlist_offset_addr(invlist);
10185
10186     invlist_set_len(invlist, size, offset);
10187     *other_elements_ptr = invlist_array(invlist) + 1;
10188     return invlist;
10189 }
10190
10191 #endif
10192
10193 PERL_STATIC_INLINE SV*
10194 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
10195     return _add_range_to_invlist(invlist, cp, cp);
10196 }
10197
10198 #ifndef PERL_IN_XSUB_RE
10199 void
10200 Perl__invlist_invert(pTHX_ SV* const invlist)
10201 {
10202     /* Complement the input inversion list.  This adds a 0 if the list didn't
10203      * have a zero; removes it otherwise.  As described above, the data
10204      * structure is set up so that this is very efficient */
10205
10206     PERL_ARGS_ASSERT__INVLIST_INVERT;
10207
10208     assert(! invlist_is_iterating(invlist));
10209
10210     /* The inverse of matching nothing is matching everything */
10211     if (_invlist_len(invlist) == 0) {
10212         _append_range_to_invlist(invlist, 0, UV_MAX);
10213         return;
10214     }
10215
10216     *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10217 }
10218
10219 SV*
10220 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10221 {
10222     /* Return a new inversion list that is a copy of the input one, which is
10223      * unchanged.  The new list will not be mortal even if the old one was. */
10224
10225     const STRLEN nominal_length = _invlist_len(invlist);
10226     const STRLEN physical_length = SvCUR(invlist);
10227     const bool offset = *(get_invlist_offset_addr(invlist));
10228
10229     PERL_ARGS_ASSERT_INVLIST_CLONE;
10230
10231     if (new_invlist == NULL) {
10232         new_invlist = _new_invlist(nominal_length);
10233     }
10234     else {
10235         sv_upgrade(new_invlist, SVt_INVLIST);
10236         initialize_invlist_guts(new_invlist, nominal_length);
10237     }
10238
10239     *(get_invlist_offset_addr(new_invlist)) = offset;
10240     invlist_set_len(new_invlist, nominal_length, offset);
10241     Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10242
10243     return new_invlist;
10244 }
10245
10246 #endif
10247
10248 PERL_STATIC_INLINE STRLEN*
10249 S_get_invlist_iter_addr(SV* invlist)
10250 {
10251     /* Return the address of the UV that contains the current iteration
10252      * position */
10253
10254     PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
10255
10256     assert(is_invlist(invlist));
10257
10258     return &(((XINVLIST*) SvANY(invlist))->iterator);
10259 }
10260
10261 PERL_STATIC_INLINE void
10262 S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */
10263 {
10264     PERL_ARGS_ASSERT_INVLIST_ITERINIT;
10265
10266     *get_invlist_iter_addr(invlist) = 0;
10267 }
10268
10269 PERL_STATIC_INLINE void
10270 S_invlist_iterfinish(SV* invlist)
10271 {
10272     /* Terminate iterator for invlist.  This is to catch development errors.
10273      * Any iteration that is interrupted before completed should call this
10274      * function.  Functions that add code points anywhere else but to the end
10275      * of an inversion list assert that they are not in the middle of an
10276      * iteration.  If they were, the addition would make the iteration
10277      * problematical: if the iteration hadn't reached the place where things
10278      * were being added, it would be ok */
10279
10280     PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
10281
10282     *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
10283 }
10284
10285 STATIC bool
10286 S_invlist_iternext(SV* invlist, UV* start, UV* end)
10287 {
10288     /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
10289      * This call sets in <*start> and <*end>, the next range in <invlist>.
10290      * Returns <TRUE> if successful and the next call will return the next
10291      * range; <FALSE> if was already at the end of the list.  If the latter,
10292      * <*start> and <*end> are unchanged, and the next call to this function
10293      * will start over at the beginning of the list */
10294
10295     STRLEN* pos = get_invlist_iter_addr(invlist);
10296     UV len = _invlist_len(invlist);
10297     UV *array;
10298
10299     PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
10300
10301     if (*pos >= len) {
10302         *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
10303         return FALSE;
10304     }
10305
10306     array = invlist_array(invlist);
10307
10308     *start = array[(*pos)++];
10309
10310     if (*pos >= len) {
10311         *end = UV_MAX;
10312     }
10313     else {
10314         *end = array[(*pos)++] - 1;
10315     }
10316
10317     return TRUE;
10318 }
10319
10320 PERL_STATIC_INLINE UV
10321 S_invlist_highest(SV* const invlist)
10322 {
10323     /* Returns the highest code point that matches an inversion list.  This API
10324      * has an ambiguity, as it returns 0 under either the highest is actually
10325      * 0, or if the list is empty.  If this distinction matters to you, check
10326      * for emptiness before calling this function */
10327
10328     UV len = _invlist_len(invlist);
10329     UV *array;
10330
10331     PERL_ARGS_ASSERT_INVLIST_HIGHEST;
10332
10333     if (len == 0) {
10334         return 0;
10335     }
10336
10337     array = invlist_array(invlist);
10338
10339     /* The last element in the array in the inversion list always starts a
10340      * range that goes to infinity.  That range may be for code points that are
10341      * matched in the inversion list, or it may be for ones that aren't
10342      * matched.  In the latter case, the highest code point in the set is one
10343      * less than the beginning of this range; otherwise it is the final element
10344      * of this range: infinity */
10345     return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
10346            ? UV_MAX
10347            : array[len - 1] - 1;
10348 }
10349
10350 STATIC SV *
10351 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10352 {
10353     /* Get the contents of an inversion list into a string SV so that they can
10354      * be printed out.  If 'traditional_style' is TRUE, it uses the format
10355      * traditionally done for debug tracing; otherwise it uses a format
10356      * suitable for just copying to the output, with blanks between ranges and
10357      * a dash between range components */
10358
10359     UV start, end;
10360     SV* output;
10361     const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10362     const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10363
10364     if (traditional_style) {
10365         output = newSVpvs("\n");
10366     }
10367     else {
10368         output = newSVpvs("");
10369     }
10370
10371     PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10372
10373     assert(! invlist_is_iterating(invlist));
10374
10375     invlist_iterinit(invlist);
10376     while (invlist_iternext(invlist, &start, &end)) {
10377         if (end == UV_MAX) {
10378             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
10379                                           start, intra_range_delimiter,
10380                                                  inter_range_delimiter);
10381         }
10382         else if (end != start) {
10383             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10384                                           start,
10385                                                    intra_range_delimiter,
10386                                                   end, inter_range_delimiter);
10387         }
10388         else {
10389             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10390                                           start, inter_range_delimiter);
10391         }
10392     }
10393
10394     if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10395         SvCUR_set(output, SvCUR(output) - 1);
10396     }
10397
10398     return output;
10399 }
10400
10401 #ifndef PERL_IN_XSUB_RE
10402 void
10403 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10404                          const char * const indent, SV* const invlist)
10405 {
10406     /* Designed to be called only by do_sv_dump().  Dumps out the ranges of the
10407      * inversion list 'invlist' to 'file' at 'level'  Each line is prefixed by
10408      * the string 'indent'.  The output looks like this:
10409          [0] 0x000A .. 0x000D
10410          [2] 0x0085
10411          [4] 0x2028 .. 0x2029
10412          [6] 0x3104 .. INFTY
10413      * This means that the first range of code points matched by the list are
10414      * 0xA through 0xD; the second range contains only the single code point
10415      * 0x85, etc.  An inversion list is an array of UVs.  Two array elements
10416      * are used to define each range (except if the final range extends to
10417      * infinity, only a single element is needed).  The array index of the
10418      * first element for the corresponding range is given in brackets. */
10419
10420     UV start, end;
10421     STRLEN count = 0;
10422
10423     PERL_ARGS_ASSERT__INVLIST_DUMP;
10424
10425     if (invlist_is_iterating(invlist)) {
10426         Perl_dump_indent(aTHX_ level, file,
10427              "%sCan't dump inversion list because is in middle of iterating\n",
10428              indent);
10429         return;
10430     }
10431
10432     invlist_iterinit(invlist);
10433     while (invlist_iternext(invlist, &start, &end)) {
10434         if (end == UV_MAX) {
10435             Perl_dump_indent(aTHX_ level, file,
10436                                        "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
10437                                    indent, (UV)count, start);
10438         }
10439         else if (end != start) {
10440             Perl_dump_indent(aTHX_ level, file,
10441                                     "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10442                                 indent, (UV)count, start,         end);
10443         }
10444         else {
10445             Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10446                                             indent, (UV)count, start);
10447         }
10448         count += 2;
10449     }
10450 }
10451
10452 #endif
10453
10454 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10455 bool
10456 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10457 {
10458     /* Return a boolean as to if the two passed in inversion lists are
10459      * identical.  The final argument, if TRUE, says to take the complement of
10460      * the second inversion list before doing the comparison */
10461
10462     const UV len_a = _invlist_len(a);
10463     UV len_b = _invlist_len(b);
10464
10465     const UV* array_a = NULL;
10466     const UV* array_b = NULL;
10467
10468     PERL_ARGS_ASSERT__INVLISTEQ;
10469
10470     /* This code avoids accessing the arrays unless it knows the length is
10471      * non-zero */
10472
10473     if (len_a == 0) {
10474         if (len_b == 0) {
10475             return ! complement_b;
10476         }
10477     }
10478     else {
10479         array_a = invlist_array(a);
10480     }
10481
10482     if (len_b != 0) {
10483         array_b = invlist_array(b);
10484     }
10485
10486     /* If are to compare 'a' with the complement of b, set it
10487      * up so are looking at b's complement. */
10488     if (complement_b) {
10489
10490         /* The complement of nothing is everything, so <a> would have to have
10491          * just one element, starting at zero (ending at infinity) */
10492         if (len_b == 0) {
10493             return (len_a == 1 && array_a[0] == 0);
10494         }
10495         if (array_b[0] == 0) {
10496
10497             /* Otherwise, to complement, we invert.  Here, the first element is
10498              * 0, just remove it.  To do this, we just pretend the array starts
10499              * one later */
10500
10501             array_b++;
10502             len_b--;
10503         }
10504         else {
10505
10506             /* But if the first element is not zero, we pretend the list starts
10507              * at the 0 that is always stored immediately before the array. */
10508             array_b--;
10509             len_b++;
10510         }
10511     }
10512
10513     return    len_a == len_b
10514            && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10515
10516 }
10517 #endif
10518
10519 /*
10520  * As best we can, determine the characters that can match the start of
10521  * the given EXACTF-ish node.  This is for use in creating ssc nodes, so there
10522  * can be false positive matches
10523  *
10524  * Returns the invlist as a new SV*; it is the caller's responsibility to
10525  * call SvREFCNT_dec() when done with it.
10526  */
10527 STATIC SV*
10528 S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10529 {
10530     dVAR;
10531     const U8 * s = (U8*)STRING(node);
10532     SSize_t bytelen = STR_LEN(node);
10533     UV uc;
10534     /* Start out big enough for 2 separate code points */
10535     SV* invlist = _new_invlist(4);
10536
10537     PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST;
10538
10539     if (! UTF) {
10540         uc = *s;
10541
10542         /* We punt and assume can match anything if the node begins
10543          * with a multi-character fold.  Things are complicated.  For
10544          * example, /ffi/i could match any of:
10545          *  "\N{LATIN SMALL LIGATURE FFI}"
10546          *  "\N{LATIN SMALL LIGATURE FF}I"
10547          *  "F\N{LATIN SMALL LIGATURE FI}"
10548          *  plus several other things; and making sure we have all the
10549          *  possibilities is hard. */
10550         if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10551             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10552         }
10553         else {
10554             /* Any Latin1 range character can potentially match any
10555              * other depending on the locale, and in Turkic locales, U+130 and
10556              * U+131 */
10557             if (OP(node) == EXACTFL) {
10558                 _invlist_union(invlist, PL_Latin1, &invlist);
10559                 invlist = add_cp_to_invlist(invlist,
10560                                                 LATIN_SMALL_LETTER_DOTLESS_I);
10561                 invlist = add_cp_to_invlist(invlist,
10562                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10563             }
10564             else {
10565                 /* But otherwise, it matches at least itself.  We can
10566                  * quickly tell if it has a distinct fold, and if so,
10567                  * it matches that as well */
10568                 invlist = add_cp_to_invlist(invlist, uc);
10569                 if (IS_IN_SOME_FOLD_L1(uc))
10570                     invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10571             }
10572
10573             /* Some characters match above-Latin1 ones under /i.  This
10574              * is true of EXACTFL ones when the locale is UTF-8 */
10575             if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10576                 && (! isASCII(uc) || (OP(node) != EXACTFAA
10577                                     && OP(node) != EXACTFAA_NO_TRIE)))
10578             {
10579                 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10580             }
10581         }
10582     }
10583     else {  /* Pattern is UTF-8 */
10584         U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10585         const U8* e = s + bytelen;
10586         IV fc;
10587
10588         fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10589
10590         /* The only code points that aren't folded in a UTF EXACTFish
10591          * node are are the problematic ones in EXACTFL nodes */
10592         if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10593             /* We need to check for the possibility that this EXACTFL
10594              * node begins with a multi-char fold.  Therefore we fold
10595              * the first few characters of it so that we can make that
10596              * check */
10597             U8 *d = folded;
10598             int i;
10599
10600             fc = -1;
10601             for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10602                 if (isASCII(*s)) {
10603                     *(d++) = (U8) toFOLD(*s);
10604                     if (fc < 0) {       /* Save the first fold */
10605                         fc = *(d-1);
10606                     }
10607                     s++;
10608                 }
10609                 else {
10610                     STRLEN len;
10611                     UV fold = toFOLD_utf8_safe(s, e, d, &len);
10612                     if (fc < 0) {       /* Save the first fold */
10613                         fc = fold;
10614                     }
10615                     d += len;
10616                     s += UTF8SKIP(s);
10617                 }
10618             }
10619
10620             /* And set up so the code below that looks in this folded
10621              * buffer instead of the node's string */
10622             e = d;
10623             s = folded;
10624         }
10625
10626         /* When we reach here 's' points to the fold of the first
10627          * character(s) of the node; and 'e' points to far enough along
10628          * the folded string to be just past any possible multi-char
10629          * fold.
10630          *
10631          * Unlike the non-UTF-8 case, the macro for determining if a
10632          * string is a multi-char fold requires all the characters to
10633          * already be folded.  This is because of all the complications
10634          * if not.  Note that they are folded anyway, except in EXACTFL
10635          * nodes.  Like the non-UTF case above, we punt if the node
10636          * begins with a multi-char fold  */
10637
10638         if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10639             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10640         }
10641         else {  /* Single char fold */
10642             unsigned int k;
10643             unsigned int first_fold;
10644             const unsigned int * remaining_folds;
10645             Size_t folds_count;
10646
10647             /* It matches itself */
10648             invlist = add_cp_to_invlist(invlist, fc);
10649
10650             /* ... plus all the things that fold to it, which are found in
10651              * PL_utf8_foldclosures */
10652             folds_count = _inverse_folds(fc, &first_fold,
10653                                                 &remaining_folds);
10654             for (k = 0; k < folds_count; k++) {
10655                 UV c = (k == 0) ? first_fold : remaining_folds[k-1];
10656
10657                 /* /aa doesn't allow folds between ASCII and non- */
10658                 if (   (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10659                     && isASCII(c) != isASCII(fc))
10660                 {
10661                     continue;
10662                 }
10663
10664                 invlist = add_cp_to_invlist(invlist, c);
10665             }
10666
10667             if (OP(node) == EXACTFL) {
10668
10669                 /* If either [iI] are present in an EXACTFL node the above code
10670                  * should have added its normal case pair, but under a Turkish
10671                  * locale they could match instead the case pairs from it.  Add
10672                  * those as potential matches as well */
10673                 if (isALPHA_FOLD_EQ(fc, 'I')) {
10674                     invlist = add_cp_to_invlist(invlist,
10675                                                 LATIN_SMALL_LETTER_DOTLESS_I);
10676                     invlist = add_cp_to_invlist(invlist,
10677                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10678                 }
10679                 else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
10680                     invlist = add_cp_to_invlist(invlist, 'I');
10681                 }
10682                 else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10683                     invlist = add_cp_to_invlist(invlist, 'i');
10684                 }
10685             }
10686         }
10687     }
10688
10689     return invlist;
10690 }
10691
10692 #undef HEADER_LENGTH
10693 #undef TO_INTERNAL_SIZE
10694 #undef FROM_INTERNAL_SIZE
10695 #undef INVLIST_VERSION_ID
10696
10697 /* End of inversion list object */
10698
10699 STATIC void
10700 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10701 {
10702     /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10703      * constructs, and updates RExC_flags with them.  On input, RExC_parse
10704      * should point to the first flag; it is updated on output to point to the
10705      * final ')' or ':'.  There needs to be at least one flag, or this will
10706      * abort */
10707
10708     /* for (?g), (?gc), and (?o) warnings; warning
10709        about (?c) will warn about (?g) -- japhy    */
10710
10711 #define WASTED_O  0x01
10712 #define WASTED_G  0x02
10713 #define WASTED_C  0x04
10714 #define WASTED_GC (WASTED_G|WASTED_C)
10715     I32 wastedflags = 0x00;
10716     U32 posflags = 0, negflags = 0;
10717     U32 *flagsp = &posflags;
10718     char has_charset_modifier = '\0';
10719     regex_charset cs;
10720     bool has_use_defaults = FALSE;
10721     const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10722     int x_mod_count = 0;
10723
10724     PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10725
10726     /* '^' as an initial flag sets certain defaults */
10727     if (UCHARAT(RExC_parse) == '^') {
10728         RExC_parse++;
10729         has_use_defaults = TRUE;
10730         STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10731         cs = (RExC_uni_semantics)
10732              ? REGEX_UNICODE_CHARSET
10733              : REGEX_DEPENDS_CHARSET;
10734         set_regex_charset(&RExC_flags, cs);
10735     }
10736     else {
10737         cs = get_regex_charset(RExC_flags);
10738         if (   cs == REGEX_DEPENDS_CHARSET
10739             && RExC_uni_semantics)
10740         {
10741             cs = REGEX_UNICODE_CHARSET;
10742         }
10743     }
10744
10745     while (RExC_parse < RExC_end) {
10746         /* && strchr("iogcmsx", *RExC_parse) */
10747         /* (?g), (?gc) and (?o) are useless here
10748            and must be globally applied -- japhy */
10749         switch (*RExC_parse) {
10750
10751             /* Code for the imsxn flags */
10752             CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10753
10754             case LOCALE_PAT_MOD:
10755                 if (has_charset_modifier) {
10756                     goto excess_modifier;
10757                 }
10758                 else if (flagsp == &negflags) {
10759                     goto neg_modifier;
10760                 }
10761                 cs = REGEX_LOCALE_CHARSET;
10762                 has_charset_modifier = LOCALE_PAT_MOD;
10763                 break;
10764             case UNICODE_PAT_MOD:
10765                 if (has_charset_modifier) {
10766                     goto excess_modifier;
10767                 }
10768                 else if (flagsp == &negflags) {
10769                     goto neg_modifier;
10770                 }
10771                 cs = REGEX_UNICODE_CHARSET;
10772                 has_charset_modifier = UNICODE_PAT_MOD;
10773                 break;
10774             case ASCII_RESTRICT_PAT_MOD:
10775                 if (flagsp == &negflags) {
10776                     goto neg_modifier;
10777                 }
10778                 if (has_charset_modifier) {
10779                     if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10780                         goto excess_modifier;
10781                     }
10782                     /* Doubled modifier implies more restricted */
10783                     cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10784                 }
10785                 else {
10786                     cs = REGEX_ASCII_RESTRICTED_CHARSET;
10787                 }
10788                 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10789                 break;
10790             case DEPENDS_PAT_MOD:
10791                 if (has_use_defaults) {
10792                     goto fail_modifiers;
10793                 }
10794                 else if (flagsp == &negflags) {
10795                     goto neg_modifier;
10796                 }
10797                 else if (has_charset_modifier) {
10798                     goto excess_modifier;
10799                 }
10800
10801                 /* The dual charset means unicode semantics if the
10802                  * pattern (or target, not known until runtime) are
10803                  * utf8, or something in the pattern indicates unicode
10804                  * semantics */
10805                 cs = (RExC_uni_semantics)
10806                      ? REGEX_UNICODE_CHARSET
10807                      : REGEX_DEPENDS_CHARSET;
10808                 has_charset_modifier = DEPENDS_PAT_MOD;
10809                 break;
10810               excess_modifier:
10811                 RExC_parse++;
10812                 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10813                     vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10814                 }
10815                 else if (has_charset_modifier == *(RExC_parse - 1)) {
10816                     vFAIL2("Regexp modifier \"%c\" may not appear twice",
10817                                         *(RExC_parse - 1));
10818                 }
10819                 else {
10820                     vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10821                 }
10822                 NOT_REACHED; /*NOTREACHED*/
10823               neg_modifier:
10824                 RExC_parse++;
10825                 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10826                                     *(RExC_parse - 1));
10827                 NOT_REACHED; /*NOTREACHED*/
10828             case ONCE_PAT_MOD: /* 'o' */
10829             case GLOBAL_PAT_MOD: /* 'g' */
10830                 if (ckWARN(WARN_REGEXP)) {
10831                     const I32 wflagbit = *RExC_parse == 'o'
10832                                          ? WASTED_O
10833                                          : WASTED_G;
10834                     if (! (wastedflags & wflagbit) ) {
10835                         wastedflags |= wflagbit;
10836                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10837                         vWARN5(
10838                             RExC_parse + 1,
10839                             "Useless (%s%c) - %suse /%c modifier",
10840                             flagsp == &negflags ? "?-" : "?",
10841                             *RExC_parse,
10842                             flagsp == &negflags ? "don't " : "",
10843                             *RExC_parse
10844                         );
10845                     }
10846                 }
10847                 break;
10848
10849             case CONTINUE_PAT_MOD: /* 'c' */
10850                 if (ckWARN(WARN_REGEXP)) {
10851                     if (! (wastedflags & WASTED_C) ) {
10852                         wastedflags |= WASTED_GC;
10853                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10854                         vWARN3(
10855                             RExC_parse + 1,
10856                             "Useless (%sc) - %suse /gc modifier",
10857                             flagsp == &negflags ? "?-" : "?",
10858                             flagsp == &negflags ? "don't " : ""
10859                         );
10860                     }
10861                 }
10862                 break;
10863             case KEEPCOPY_PAT_MOD: /* 'p' */
10864                 if (flagsp == &negflags) {
10865                     ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10866                 } else {
10867                     *flagsp |= RXf_PMf_KEEPCOPY;
10868                 }
10869                 break;
10870             case '-':
10871                 /* A flag is a default iff it is following a minus, so
10872                  * if there is a minus, it means will be trying to
10873                  * re-specify a default which is an error */
10874                 if (has_use_defaults || flagsp == &negflags) {
10875                     goto fail_modifiers;
10876                 }
10877                 flagsp = &negflags;
10878                 wastedflags = 0;  /* reset so (?g-c) warns twice */
10879                 x_mod_count = 0;
10880                 break;
10881             case ':':
10882             case ')':
10883
10884                 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
10885                     negflags |= RXf_PMf_EXTENDED_MORE;
10886                 }
10887                 RExC_flags |= posflags;
10888
10889                 if (negflags & RXf_PMf_EXTENDED) {
10890                     negflags |= RXf_PMf_EXTENDED_MORE;
10891                 }
10892                 RExC_flags &= ~negflags;
10893                 set_regex_charset(&RExC_flags, cs);
10894
10895                 return;
10896             default:
10897               fail_modifiers:
10898                 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10899                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10900                 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
10901                       UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10902                 NOT_REACHED; /*NOTREACHED*/
10903         }
10904
10905         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10906     }
10907
10908     vFAIL("Sequence (?... not terminated");
10909 }
10910
10911 /*
10912  - reg - regular expression, i.e. main body or parenthesized thing
10913  *
10914  * Caller must absorb opening parenthesis.
10915  *
10916  * Combining parenthesis handling with the base level of regular expression
10917  * is a trifle forced, but the need to tie the tails of the branches to what
10918  * follows makes it hard to avoid.
10919  */
10920 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10921 #ifdef DEBUGGING
10922 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10923 #else
10924 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10925 #endif
10926
10927 PERL_STATIC_INLINE regnode_offset
10928 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10929                              I32 *flagp,
10930                              char * parse_start,
10931                              char ch
10932                       )
10933 {
10934     regnode_offset ret;
10935     char* name_start = RExC_parse;
10936     U32 num = 0;
10937     SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
10938     GET_RE_DEBUG_FLAGS_DECL;
10939
10940     PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
10941
10942     if (RExC_parse == name_start || *RExC_parse != ch) {
10943         /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
10944         vFAIL2("Sequence %.3s... not terminated", parse_start);
10945     }
10946
10947     if (sv_dat) {
10948         num = add_data( pRExC_state, STR_WITH_LEN("S"));
10949         RExC_rxi->data->data[num]=(void*)sv_dat;
10950         SvREFCNT_inc_simple_void_NN(sv_dat);
10951     }
10952     RExC_sawback = 1;
10953     ret = reganode(pRExC_state,
10954                    ((! FOLD)
10955                      ? NREF
10956                      : (ASCII_FOLD_RESTRICTED)
10957                        ? NREFFA
10958                        : (AT_LEAST_UNI_SEMANTICS)
10959                          ? NREFFU
10960                          : (LOC)
10961                            ? NREFFL
10962                            : NREFF),
10963                     num);
10964     *flagp |= HASWIDTH;
10965
10966     Set_Node_Offset(REGNODE_p(ret), parse_start+1);
10967     Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
10968
10969     nextchar(pRExC_state);
10970     return ret;
10971 }
10972
10973 /* On success, returns the offset at which any next node should be placed into
10974  * the regex engine program being compiled.
10975  *
10976  * Returns 0 otherwise, with *flagp set to indicate why:
10977  *  TRYAGAIN        at the end of (?) that only sets flags.
10978  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
10979  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
10980  *  Otherwise would only return 0 if regbranch() returns 0, which cannot
10981  *  happen.  */
10982 STATIC regnode_offset
10983 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
10984     /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
10985      * 2 is like 1, but indicates that nextchar() has been called to advance
10986      * RExC_parse beyond the '('.  Things like '(?' are indivisible tokens, and
10987      * this flag alerts us to the need to check for that */
10988 {
10989     regnode_offset ret = 0;    /* Will be the head of the group. */
10990     regnode_offset br;
10991     regnode_offset lastbr;
10992     regnode_offset ender = 0;
10993     I32 parno = 0;
10994     I32 flags;
10995     U32 oregflags = RExC_flags;
10996     bool have_branch = 0;
10997     bool is_open = 0;
10998     I32 freeze_paren = 0;
10999     I32 after_freeze = 0;
11000     I32 num; /* numeric backreferences */
11001
11002     char * parse_start = RExC_parse; /* MJD */
11003     char * const oregcomp_parse = RExC_parse;
11004
11005     GET_RE_DEBUG_FLAGS_DECL;
11006
11007     PERL_ARGS_ASSERT_REG;
11008     DEBUG_PARSE("reg ");
11009
11010     *flagp = 0;                         /* Tentatively. */
11011
11012     /* Having this true makes it feasible to have a lot fewer tests for the
11013      * parse pointer being in scope.  For example, we can write
11014      *      while(isFOO(*RExC_parse)) RExC_parse++;
11015      * instead of
11016      *      while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
11017      */
11018     assert(*RExC_end == '\0');
11019
11020     /* Make an OPEN node, if parenthesized. */
11021     if (paren) {
11022
11023         /* Under /x, space and comments can be gobbled up between the '(' and
11024          * here (if paren ==2).  The forms '(*VERB' and '(?...' disallow such
11025          * intervening space, as the sequence is a token, and a token should be
11026          * indivisible */
11027         bool has_intervening_patws = (paren == 2)
11028                                   && *(RExC_parse - 1) != '(';
11029
11030         if (RExC_parse >= RExC_end) {
11031             vFAIL("Unmatched (");
11032         }
11033
11034         if (paren == 'r') {     /* Atomic script run */
11035             paren = '>';
11036             goto parse_rest;
11037         }
11038         else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
11039             char *start_verb = RExC_parse + 1;
11040             STRLEN verb_len;
11041             char *start_arg = NULL;
11042             unsigned char op = 0;
11043             int arg_required = 0;
11044             int internal_argval = -1; /* if >-1 we are not allowed an argument*/
11045             bool has_upper = FALSE;
11046
11047             if (has_intervening_patws) {
11048                 RExC_parse++;   /* past the '*' */
11049
11050                 /* For strict backwards compatibility, don't change the message
11051                  * now that we also have lowercase operands */
11052                 if (isUPPER(*RExC_parse)) {
11053                     vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
11054                 }
11055                 else {
11056                     vFAIL("In '(*...)', the '(' and '*' must be adjacent");
11057                 }
11058             }
11059             while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
11060                 if ( *RExC_parse == ':' ) {
11061                     start_arg = RExC_parse + 1;
11062                     break;
11063                 }
11064                 else if (! UTF) {
11065                     if (isUPPER(*RExC_parse)) {
11066                         has_upper = TRUE;
11067                     }
11068                     RExC_parse++;
11069                 }
11070                 else {
11071                     RExC_parse += UTF8SKIP(RExC_parse);
11072                 }
11073             }
11074             verb_len = RExC_parse - start_verb;
11075             if ( start_arg ) {
11076                 if (RExC_parse >= RExC_end) {
11077                     goto unterminated_verb_pattern;
11078                 }
11079
11080                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11081                 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
11082                     RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11083                 }
11084                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11085                   unterminated_verb_pattern:
11086                     if (has_upper) {
11087                         vFAIL("Unterminated verb pattern argument");
11088                     }
11089                     else {
11090                         vFAIL("Unterminated '(*...' argument");
11091                     }
11092                 }
11093             } else {
11094                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11095                     if (has_upper) {
11096                         vFAIL("Unterminated verb pattern");
11097                     }
11098                     else {
11099                         vFAIL("Unterminated '(*...' construct");
11100                     }
11101                 }
11102             }
11103
11104             /* Here, we know that RExC_parse < RExC_end */
11105
11106             switch ( *start_verb ) {
11107             case 'A':  /* (*ACCEPT) */
11108                 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
11109                     op = ACCEPT;
11110                     internal_argval = RExC_nestroot;
11111                 }
11112                 break;
11113             case 'C':  /* (*COMMIT) */
11114                 if ( memEQs(start_verb, verb_len,"COMMIT") )
11115                     op = COMMIT;
11116                 break;
11117             case 'F':  /* (*FAIL) */
11118                 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
11119                     op = OPFAIL;
11120                 }
11121                 break;
11122             case ':':  /* (*:NAME) */
11123             case 'M':  /* (*MARK:NAME) */
11124                 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
11125                     op = MARKPOINT;
11126                     arg_required = 1;
11127                 }
11128                 break;
11129             case 'P':  /* (*PRUNE) */
11130                 if ( memEQs(start_verb, verb_len,"PRUNE") )
11131                     op = PRUNE;
11132                 break;
11133             case 'S':   /* (*SKIP) */
11134                 if ( memEQs(start_verb, verb_len,"SKIP") )
11135                     op = SKIP;
11136                 break;
11137             case 'T':  /* (*THEN) */
11138                 /* [19:06] <TimToady> :: is then */
11139                 if ( memEQs(start_verb, verb_len,"THEN") ) {
11140                     op = CUTGROUP;
11141                     RExC_seen |= REG_CUTGROUP_SEEN;
11142                 }
11143                 break;
11144             case 'a':
11145                 if (   memEQs(start_verb, verb_len, "asr")
11146                     || memEQs(start_verb, verb_len, "atomic_script_run"))
11147                 {
11148                     paren = 'r';        /* Mnemonic: recursed run */
11149                     goto script_run;
11150                 }
11151                 else if (memEQs(start_verb, verb_len, "atomic")) {
11152                     paren = 't';    /* AtOMIC */
11153                     goto alpha_assertions;
11154                 }
11155                 break;
11156             case 'p':
11157                 if (   memEQs(start_verb, verb_len, "plb")
11158                     || memEQs(start_verb, verb_len, "positive_lookbehind"))
11159                 {
11160                     paren = 'b';
11161                     goto lookbehind_alpha_assertions;
11162                 }
11163                 else if (   memEQs(start_verb, verb_len, "pla")
11164                          || memEQs(start_verb, verb_len, "positive_lookahead"))
11165                 {
11166                     paren = 'a';
11167                     goto alpha_assertions;
11168                 }
11169                 break;
11170             case 'n':
11171                 if (   memEQs(start_verb, verb_len, "nlb")
11172                     || memEQs(start_verb, verb_len, "negative_lookbehind"))
11173                 {
11174                     paren = 'B';
11175                     goto lookbehind_alpha_assertions;
11176                 }
11177                 else if (   memEQs(start_verb, verb_len, "nla")
11178                          || memEQs(start_verb, verb_len, "negative_lookahead"))
11179                 {
11180                     paren = 'A';
11181                     goto alpha_assertions;
11182                 }
11183                 break;
11184             case 's':
11185                 if (   memEQs(start_verb, verb_len, "sr")
11186                     || memEQs(start_verb, verb_len, "script_run"))
11187                 {
11188                     regnode_offset atomic;
11189
11190                     paren = 's';
11191
11192                    script_run:
11193
11194                     /* This indicates Unicode rules. */
11195                     REQUIRE_UNI_RULES(flagp, 0);
11196
11197                     if (! start_arg) {
11198                         goto no_colon;
11199                     }
11200
11201                     RExC_parse = start_arg;
11202
11203                     if (RExC_in_script_run) {
11204
11205                         /*  Nested script runs are treated as no-ops, because
11206                          *  if the nested one fails, the outer one must as
11207                          *  well.  It could fail sooner, and avoid (??{} with
11208                          *  side effects, but that is explicitly documented as
11209                          *  undefined behavior. */
11210
11211                         ret = 0;
11212
11213                         if (paren == 's') {
11214                             paren = ':';
11215                             goto parse_rest;
11216                         }
11217
11218                         /* But, the atomic part of a nested atomic script run
11219                          * isn't a no-op, but can be treated just like a '(?>'
11220                          * */
11221                         paren = '>';
11222                         goto parse_rest;
11223                     }
11224
11225                     /* By doing this here, we avoid extra warnings for nested
11226                      * script runs */
11227                     ckWARNexperimental(RExC_parse,
11228                         WARN_EXPERIMENTAL__SCRIPT_RUN,
11229                         "The script_run feature is experimental");
11230
11231                     if (paren == 's') {
11232                         /* Here, we're starting a new regular script run */
11233                         ret = reg_node(pRExC_state, SROPEN);
11234                         RExC_in_script_run = 1;
11235                         is_open = 1;
11236                         goto parse_rest;
11237                     }
11238
11239                     /* Here, we are starting an atomic script run.  This is
11240                      * handled by recursing to deal with the atomic portion
11241                      * separately, enclosed in SROPEN ... SRCLOSE nodes */
11242
11243                     ret = reg_node(pRExC_state, SROPEN);
11244
11245                     RExC_in_script_run = 1;
11246
11247                     atomic = reg(pRExC_state, 'r', &flags, depth);
11248                     if (flags & (RESTART_PARSE|NEED_UTF8)) {
11249                         *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11250                         return 0;
11251                     }
11252
11253                     REGTAIL(pRExC_state, ret, atomic);
11254
11255                     REGTAIL(pRExC_state, atomic,
11256                            reg_node(pRExC_state, SRCLOSE));
11257
11258                     RExC_in_script_run = 0;
11259                     return ret;
11260                 }
11261
11262                 break;
11263
11264             lookbehind_alpha_assertions:
11265                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11266                 RExC_in_lookbehind++;
11267                 /*FALLTHROUGH*/
11268
11269             alpha_assertions:
11270                 ckWARNexperimental(RExC_parse,
11271                         WARN_EXPERIMENTAL__ALPHA_ASSERTIONS,
11272                         "The alpha_assertions feature is experimental");
11273
11274                 RExC_seen_zerolen++;
11275
11276                 if (! start_arg) {
11277                     goto no_colon;
11278                 }
11279
11280                 /* An empty negative lookahead assertion simply is failure */
11281                 if (paren == 'A' && RExC_parse == start_arg) {
11282                     ret=reganode(pRExC_state, OPFAIL, 0);
11283                     nextchar(pRExC_state);
11284                     return ret;
11285                 }
11286
11287                 RExC_parse = start_arg;
11288                 goto parse_rest;
11289
11290               no_colon:
11291                 vFAIL2utf8f(
11292                 "'(*%" UTF8f "' requires a terminating ':'",
11293                 UTF8fARG(UTF, verb_len, start_verb));
11294                 NOT_REACHED; /*NOTREACHED*/
11295
11296             } /* End of switch */
11297             if ( ! op ) {
11298                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11299                 if (has_upper || verb_len == 0) {
11300                     vFAIL2utf8f(
11301                     "Unknown verb pattern '%" UTF8f "'",
11302                     UTF8fARG(UTF, verb_len, start_verb));
11303                 }
11304                 else {
11305                     vFAIL2utf8f(
11306                     "Unknown '(*...)' construct '%" UTF8f "'",
11307                     UTF8fARG(UTF, verb_len, start_verb));
11308                 }
11309             }
11310             if ( RExC_parse == start_arg ) {
11311                 start_arg = NULL;
11312             }
11313             if ( arg_required && !start_arg ) {
11314                 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11315                     verb_len, start_verb);
11316             }
11317             if (internal_argval == -1) {
11318                 ret = reganode(pRExC_state, op, 0);
11319             } else {
11320                 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11321             }
11322             RExC_seen |= REG_VERBARG_SEEN;
11323             if (start_arg) {
11324                 SV *sv = newSVpvn( start_arg,
11325                                     RExC_parse - start_arg);
11326                 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11327                                         STR_WITH_LEN("S"));
11328                 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11329                 FLAGS(REGNODE_p(ret)) = 1;
11330             } else {
11331                 FLAGS(REGNODE_p(ret)) = 0;
11332             }
11333             if ( internal_argval != -1 )
11334                 ARG2L_SET(REGNODE_p(ret), internal_argval);
11335             nextchar(pRExC_state);
11336             return ret;
11337         }
11338         else if (*RExC_parse == '?') { /* (?...) */
11339             bool is_logical = 0;
11340             const char * const seqstart = RExC_parse;
11341             const char * endptr;
11342             if (has_intervening_patws) {
11343                 RExC_parse++;
11344                 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11345             }
11346
11347             RExC_parse++;           /* past the '?' */
11348             paren = *RExC_parse;    /* might be a trailing NUL, if not
11349                                        well-formed */
11350             RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11351             if (RExC_parse > RExC_end) {
11352                 paren = '\0';
11353             }
11354             ret = 0;                    /* For look-ahead/behind. */
11355             switch (paren) {
11356
11357             case 'P':   /* (?P...) variants for those used to PCRE/Python */
11358                 paren = *RExC_parse;
11359                 if ( paren == '<') {    /* (?P<...>) named capture */
11360                     RExC_parse++;
11361                     if (RExC_parse >= RExC_end) {
11362                         vFAIL("Sequence (?P<... not terminated");
11363                     }
11364                     goto named_capture;
11365                 }
11366                 else if (paren == '>') {   /* (?P>name) named recursion */
11367                     RExC_parse++;
11368                     if (RExC_parse >= RExC_end) {
11369                         vFAIL("Sequence (?P>... not terminated");
11370                     }
11371                     goto named_recursion;
11372                 }
11373                 else if (paren == '=') {   /* (?P=...)  named backref */
11374                     RExC_parse++;
11375                     return handle_named_backref(pRExC_state, flagp,
11376                                                 parse_start, ')');
11377                 }
11378                 RExC_parse += SKIP_IF_CHAR(RExC_parse);
11379                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11380                 vFAIL3("Sequence (%.*s...) not recognized",
11381                                 RExC_parse-seqstart, seqstart);
11382                 NOT_REACHED; /*NOTREACHED*/
11383             case '<':           /* (?<...) */
11384                 if (*RExC_parse == '!')
11385                     paren = ',';
11386                 else if (*RExC_parse != '=')
11387               named_capture:
11388                 {               /* (?<...>) */
11389                     char *name_start;
11390                     SV *svname;
11391                     paren= '>';
11392                 /* FALLTHROUGH */
11393             case '\'':          /* (?'...') */
11394                     name_start = RExC_parse;
11395                     svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11396                     if (   RExC_parse == name_start
11397                         || RExC_parse >= RExC_end
11398                         || *RExC_parse != paren)
11399                     {
11400                         vFAIL2("Sequence (?%c... not terminated",
11401                             paren=='>' ? '<' : paren);
11402                     }
11403                     {
11404                         HE *he_str;
11405                         SV *sv_dat = NULL;
11406                         if (!svname) /* shouldn't happen */
11407                             Perl_croak(aTHX_
11408                                 "panic: reg_scan_name returned NULL");
11409                         if (!RExC_paren_names) {
11410                             RExC_paren_names= newHV();
11411                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
11412 #ifdef DEBUGGING
11413                             RExC_paren_name_list= newAV();
11414                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11415 #endif
11416                         }
11417                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11418                         if ( he_str )
11419                             sv_dat = HeVAL(he_str);
11420                         if ( ! sv_dat ) {
11421                             /* croak baby croak */
11422                             Perl_croak(aTHX_
11423                                 "panic: paren_name hash element allocation failed");
11424                         } else if ( SvPOK(sv_dat) ) {
11425                             /* (?|...) can mean we have dupes so scan to check
11426                                its already been stored. Maybe a flag indicating
11427                                we are inside such a construct would be useful,
11428                                but the arrays are likely to be quite small, so
11429                                for now we punt -- dmq */
11430                             IV count = SvIV(sv_dat);
11431                             I32 *pv = (I32*)SvPVX(sv_dat);
11432                             IV i;
11433                             for ( i = 0 ; i < count ; i++ ) {
11434                                 if ( pv[i] == RExC_npar ) {
11435                                     count = 0;
11436                                     break;
11437                                 }
11438                             }
11439                             if ( count ) {
11440                                 pv = (I32*)SvGROW(sv_dat,
11441                                                 SvCUR(sv_dat) + sizeof(I32)+1);
11442                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11443                                 pv[count] = RExC_npar;
11444                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11445                             }
11446                         } else {
11447                             (void)SvUPGRADE(sv_dat, SVt_PVNV);
11448                             sv_setpvn(sv_dat, (char *)&(RExC_npar),
11449                                                                 sizeof(I32));
11450                             SvIOK_on(sv_dat);
11451                             SvIV_set(sv_dat, 1);
11452                         }
11453 #ifdef DEBUGGING
11454                         /* Yes this does cause a memory leak in debugging Perls
11455                          * */
11456                         if (!av_store(RExC_paren_name_list,
11457                                       RExC_npar, SvREFCNT_inc_NN(svname)))
11458                             SvREFCNT_dec_NN(svname);
11459 #endif
11460
11461                         /*sv_dump(sv_dat);*/
11462                     }
11463                     nextchar(pRExC_state);
11464                     paren = 1;
11465                     goto capturing_parens;
11466                 }
11467
11468                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11469                 RExC_in_lookbehind++;
11470                 RExC_parse++;
11471                 if (RExC_parse >= RExC_end) {
11472                     vFAIL("Sequence (?... not terminated");
11473                 }
11474
11475                 /* FALLTHROUGH */
11476             case '=':           /* (?=...) */
11477                 RExC_seen_zerolen++;
11478                 break;
11479             case '!':           /* (?!...) */
11480                 RExC_seen_zerolen++;
11481                 /* check if we're really just a "FAIL" assertion */
11482                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11483                                         FALSE /* Don't force to /x */ );
11484                 if (*RExC_parse == ')') {
11485                     ret=reganode(pRExC_state, OPFAIL, 0);
11486                     nextchar(pRExC_state);
11487                     return ret;
11488                 }
11489                 break;
11490             case '|':           /* (?|...) */
11491                 /* branch reset, behave like a (?:...) except that
11492                    buffers in alternations share the same numbers */
11493                 paren = ':';
11494                 after_freeze = freeze_paren = RExC_npar;
11495
11496                 /* XXX This construct currently requires an extra pass.
11497                  * Investigation would be required to see if that could be
11498                  * changed */
11499                 REQUIRE_PARENS_PASS;
11500                 break;
11501             case ':':           /* (?:...) */
11502             case '>':           /* (?>...) */
11503                 break;
11504             case '$':           /* (?$...) */
11505             case '@':           /* (?@...) */
11506                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11507                 break;
11508             case '0' :           /* (?0) */
11509             case 'R' :           /* (?R) */
11510                 if (RExC_parse == RExC_end || *RExC_parse != ')')
11511                     FAIL("Sequence (?R) not terminated");
11512                 num = 0;
11513                 RExC_seen |= REG_RECURSE_SEEN;
11514
11515                 /* XXX These constructs currently require an extra pass.
11516                  * It probably could be changed */
11517                 REQUIRE_PARENS_PASS;
11518
11519                 *flagp |= POSTPONED;
11520                 goto gen_recurse_regop;
11521                 /*notreached*/
11522             /* named and numeric backreferences */
11523             case '&':            /* (?&NAME) */
11524                 parse_start = RExC_parse - 1;
11525               named_recursion:
11526                 {
11527                     SV *sv_dat = reg_scan_name(pRExC_state,
11528                                                REG_RSN_RETURN_DATA);
11529                    num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11530                 }
11531                 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11532                     vFAIL("Sequence (?&... not terminated");
11533                 goto gen_recurse_regop;
11534                 /* NOTREACHED */
11535             case '+':
11536                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
11537                     RExC_parse++;
11538                     vFAIL("Illegal pattern");
11539                 }
11540                 goto parse_recursion;
11541                 /* NOTREACHED*/
11542             case '-': /* (?-1) */
11543                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
11544                     RExC_parse--; /* rewind to let it be handled later */
11545                     goto parse_flags;
11546                 }
11547                 /* FALLTHROUGH */
11548             case '1': case '2': case '3': case '4': /* (?1) */
11549             case '5': case '6': case '7': case '8': case '9':
11550                 RExC_parse = (char *) seqstart + 1;  /* Point to the digit */
11551               parse_recursion:
11552                 {
11553                     bool is_neg = FALSE;
11554                     UV unum;
11555                     parse_start = RExC_parse - 1; /* MJD */
11556                     if (*RExC_parse == '-') {
11557                         RExC_parse++;
11558                         is_neg = TRUE;
11559                     }
11560                     endptr = RExC_end;
11561                     if (grok_atoUV(RExC_parse, &unum, &endptr)
11562                         && unum <= I32_MAX
11563                     ) {
11564                         num = (I32)unum;
11565                         RExC_parse = (char*)endptr;
11566                     } else
11567                         num = I32_MAX;
11568                     if (is_neg) {
11569                         /* Some limit for num? */
11570                         num = -num;
11571                     }
11572                 }
11573                 if (*RExC_parse!=')')
11574                     vFAIL("Expecting close bracket");
11575
11576               gen_recurse_regop:
11577                 if ( paren == '-' ) {
11578                     /*
11579                     Diagram of capture buffer numbering.
11580                     Top line is the normal capture buffer numbers
11581                     Bottom line is the negative indexing as from
11582                     the X (the (?-2))
11583
11584                     +   1 2    3 4 5 X          6 7
11585                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11586                     -   5 4    3 2 1 X          x x
11587
11588                     */
11589                     num = RExC_npar + num;
11590                     if (num < 1)  {
11591
11592                         /* It might be a forward reference; we can't fail until
11593                          * we know, by completing the parse to get all the
11594                          * groups, and then reparsing */
11595                         if (RExC_total_parens > 0)  {
11596                             RExC_parse++;
11597                             vFAIL("Reference to nonexistent group");
11598                         }
11599                         else {
11600                             REQUIRE_PARENS_PASS;
11601                         }
11602                     }
11603                 } else if ( paren == '+' ) {
11604                     num = RExC_npar + num - 1;
11605                 }
11606                 /* We keep track how many GOSUB items we have produced.
11607                    To start off the ARG2L() of the GOSUB holds its "id",
11608                    which is used later in conjunction with RExC_recurse
11609                    to calculate the offset we need to jump for the GOSUB,
11610                    which it will store in the final representation.
11611                    We have to defer the actual calculation until much later
11612                    as the regop may move.
11613                  */
11614
11615                 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11616                 if (num >= RExC_npar) {
11617
11618                     /* It might be a forward reference; we can't fail until we
11619                      * know, by completing the parse to get all the groups, and
11620                      * then reparsing */
11621                     if (RExC_total_parens > 0)  {
11622                         if (num >= RExC_total_parens) {
11623                             RExC_parse++;
11624                             vFAIL("Reference to nonexistent group");
11625                         }
11626                     }
11627                     else {
11628                         REQUIRE_PARENS_PASS;
11629                     }
11630                 }
11631                 RExC_recurse_count++;
11632                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11633                     "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11634                             22, "|    |", (int)(depth * 2 + 1), "",
11635                             (UV)ARG(REGNODE_p(ret)),
11636                             (IV)ARG2L(REGNODE_p(ret))));
11637                 RExC_seen |= REG_RECURSE_SEEN;
11638
11639                 Set_Node_Length(REGNODE_p(ret),
11640                                 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11641                 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11642
11643                 *flagp |= POSTPONED;
11644                 assert(*RExC_parse == ')');
11645                 nextchar(pRExC_state);
11646                 return ret;
11647
11648             /* NOTREACHED */
11649
11650             case '?':           /* (??...) */
11651                 is_logical = 1;
11652                 if (*RExC_parse != '{') {
11653                     RExC_parse += SKIP_IF_CHAR(RExC_parse);
11654                     /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11655                     vFAIL2utf8f(
11656                         "Sequence (%" UTF8f "...) not recognized",
11657                         UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11658                     NOT_REACHED; /*NOTREACHED*/
11659                 }
11660                 *flagp |= POSTPONED;
11661                 paren = '{';
11662                 RExC_parse++;
11663                 /* FALLTHROUGH */
11664             case '{':           /* (?{...}) */
11665             {
11666                 U32 n = 0;
11667                 struct reg_code_block *cb;
11668                 OP * o;
11669
11670                 RExC_seen_zerolen++;
11671
11672                 if (   !pRExC_state->code_blocks
11673                     || pRExC_state->code_index
11674                                         >= pRExC_state->code_blocks->count
11675                     || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11676                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11677                             - RExC_start)
11678                 ) {
11679                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
11680                         FAIL("panic: Sequence (?{...}): no code block found\n");
11681                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
11682                 }
11683                 /* this is a pre-compiled code block (?{...}) */
11684                 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11685                 RExC_parse = RExC_start + cb->end;
11686                 o = cb->block;
11687                 if (cb->src_regex) {
11688                     n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11689                     RExC_rxi->data->data[n] =
11690                         (void*)SvREFCNT_inc((SV*)cb->src_regex);
11691                     RExC_rxi->data->data[n+1] = (void*)o;
11692                 }
11693                 else {
11694                     n = add_data(pRExC_state,
11695                             (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11696                     RExC_rxi->data->data[n] = (void*)o;
11697                 }
11698                 pRExC_state->code_index++;
11699                 nextchar(pRExC_state);
11700
11701                 if (is_logical) {
11702                     regnode_offset eval;
11703                     ret = reg_node(pRExC_state, LOGICAL);
11704
11705                     eval = reg2Lanode(pRExC_state, EVAL,
11706                                        n,
11707
11708                                        /* for later propagation into (??{})
11709                                         * return value */
11710                                        RExC_flags & RXf_PMf_COMPILETIME
11711                                       );
11712                     FLAGS(REGNODE_p(ret)) = 2;
11713                     REGTAIL(pRExC_state, ret, eval);
11714                     /* deal with the length of this later - MJD */
11715                     return ret;
11716                 }
11717                 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11718                 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11719                 Set_Node_Offset(REGNODE_p(ret), parse_start);
11720                 return ret;
11721             }
11722             case '(':           /* (?(?{...})...) and (?(?=...)...) */
11723             {
11724                 int is_define= 0;
11725                 const int DEFINE_len = sizeof("DEFINE") - 1;
11726                 if (    RExC_parse < RExC_end - 1
11727                     && (   (       RExC_parse[0] == '?'        /* (?(?...)) */
11728                             && (   RExC_parse[1] == '='
11729                                 || RExC_parse[1] == '!'
11730                                 || RExC_parse[1] == '<'
11731                                 || RExC_parse[1] == '{'))
11732                         || (       RExC_parse[0] == '*'        /* (?(*...)) */
11733                             && (   memBEGINs(RExC_parse + 1,
11734                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11735                                          "pla:")
11736                                 || memBEGINs(RExC_parse + 1,
11737                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11738                                          "plb:")
11739                                 || memBEGINs(RExC_parse + 1,
11740                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11741                                          "nla:")
11742                                 || memBEGINs(RExC_parse + 1,
11743                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11744                                          "nlb:")
11745                                 || memBEGINs(RExC_parse + 1,
11746                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11747                                          "positive_lookahead:")
11748                                 || memBEGINs(RExC_parse + 1,
11749                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11750                                          "positive_lookbehind:")
11751                                 || memBEGINs(RExC_parse + 1,
11752                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11753                                          "negative_lookahead:")
11754                                 || memBEGINs(RExC_parse + 1,
11755                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11756                                          "negative_lookbehind:"))))
11757                 ) { /* Lookahead or eval. */
11758                     I32 flag;
11759                     regnode_offset tail;
11760
11761                     ret = reg_node(pRExC_state, LOGICAL);
11762                     FLAGS(REGNODE_p(ret)) = 1;
11763
11764                     tail = reg(pRExC_state, 1, &flag, depth+1);
11765                     RETURN_FAIL_ON_RESTART(flag, flagp);
11766                     REGTAIL(pRExC_state, ret, tail);
11767                     goto insert_if;
11768                 }
11769                 else if (   RExC_parse[0] == '<'     /* (?(<NAME>)...) */
11770                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11771                 {
11772                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
11773                     char *name_start= RExC_parse++;
11774                     U32 num = 0;
11775                     SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11776                     if (   RExC_parse == name_start
11777                         || RExC_parse >= RExC_end
11778                         || *RExC_parse != ch)
11779                     {
11780                         vFAIL2("Sequence (?(%c... not terminated",
11781                             (ch == '>' ? '<' : ch));
11782                     }
11783                     RExC_parse++;
11784                     if (sv_dat) {
11785                         num = add_data( pRExC_state, STR_WITH_LEN("S"));
11786                         RExC_rxi->data->data[num]=(void*)sv_dat;
11787                         SvREFCNT_inc_simple_void_NN(sv_dat);
11788                     }
11789                     ret = reganode(pRExC_state, NGROUPP, num);
11790                     goto insert_if_check_paren;
11791                 }
11792                 else if (memBEGINs(RExC_parse,
11793                                    (STRLEN) (RExC_end - RExC_parse),
11794                                    "DEFINE"))
11795                 {
11796                     ret = reganode(pRExC_state, DEFINEP, 0);
11797                     RExC_parse += DEFINE_len;
11798                     is_define = 1;
11799                     goto insert_if_check_paren;
11800                 }
11801                 else if (RExC_parse[0] == 'R') {
11802                     RExC_parse++;
11803                     /* parno == 0 => /(?(R)YES|NO)/  "in any form of recursion OR eval"
11804                      * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
11805                      * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
11806                      */
11807                     parno = 0;
11808                     if (RExC_parse[0] == '0') {
11809                         parno = 1;
11810                         RExC_parse++;
11811                     }
11812                     else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
11813                         UV uv;
11814                         endptr = RExC_end;
11815                         if (grok_atoUV(RExC_parse, &uv, &endptr)
11816                             && uv <= I32_MAX
11817                         ) {
11818                             parno = (I32)uv + 1;
11819                             RExC_parse = (char*)endptr;
11820                         }
11821                         /* else "Switch condition not recognized" below */
11822                     } else if (RExC_parse[0] == '&') {
11823                         SV *sv_dat;
11824                         RExC_parse++;
11825                         sv_dat = reg_scan_name(pRExC_state,
11826                                                REG_RSN_RETURN_DATA);
11827                         if (sv_dat)
11828                             parno = 1 + *((I32 *)SvPVX(sv_dat));
11829                     }
11830                     ret = reganode(pRExC_state, INSUBP, parno);
11831                     goto insert_if_check_paren;
11832                 }
11833                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
11834                     /* (?(1)...) */
11835                     char c;
11836                     UV uv;
11837                     endptr = RExC_end;
11838                     if (grok_atoUV(RExC_parse, &uv, &endptr)
11839                         && uv <= I32_MAX
11840                     ) {
11841                         parno = (I32)uv;
11842                         RExC_parse = (char*)endptr;
11843                     }
11844                     else {
11845                         vFAIL("panic: grok_atoUV returned FALSE");
11846                     }
11847                     ret = reganode(pRExC_state, GROUPP, parno);
11848
11849                  insert_if_check_paren:
11850                     if (UCHARAT(RExC_parse) != ')') {
11851                         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11852                         vFAIL("Switch condition not recognized");
11853                     }
11854                     nextchar(pRExC_state);
11855                   insert_if:
11856                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
11857                     br = regbranch(pRExC_state, &flags, 1, depth+1);
11858                     if (br == 0) {
11859                         RETURN_FAIL_ON_RESTART(flags,flagp);
11860                         FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11861                               (UV) flags);
11862                     } else
11863                         REGTAIL(pRExC_state, br, reganode(pRExC_state,
11864                                                           LONGJMP, 0));
11865                     c = UCHARAT(RExC_parse);
11866                     nextchar(pRExC_state);
11867                     if (flags&HASWIDTH)
11868                         *flagp |= HASWIDTH;
11869                     if (c == '|') {
11870                         if (is_define)
11871                             vFAIL("(?(DEFINE)....) does not allow branches");
11872
11873                         /* Fake one for optimizer.  */
11874                         lastbr = reganode(pRExC_state, IFTHEN, 0);
11875
11876                         if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
11877                             RETURN_FAIL_ON_RESTART(flags, flagp);
11878                             FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11879                                   (UV) flags);
11880                         }
11881                         REGTAIL(pRExC_state, ret, lastbr);
11882                         if (flags&HASWIDTH)
11883                             *flagp |= HASWIDTH;
11884                         c = UCHARAT(RExC_parse);
11885                         nextchar(pRExC_state);
11886                     }
11887                     else
11888                         lastbr = 0;
11889                     if (c != ')') {
11890                         if (RExC_parse >= RExC_end)
11891                             vFAIL("Switch (?(condition)... not terminated");
11892                         else
11893                             vFAIL("Switch (?(condition)... contains too many branches");
11894                     }
11895                     ender = reg_node(pRExC_state, TAIL);
11896                     REGTAIL(pRExC_state, br, ender);
11897                     if (lastbr) {
11898                         REGTAIL(pRExC_state, lastbr, ender);
11899                         REGTAIL(pRExC_state, REGNODE_OFFSET(
11900                                                 NEXTOPER(
11901                                                 NEXTOPER(REGNODE_p(lastbr)))),
11902                                              ender);
11903                     }
11904                     else
11905                         REGTAIL(pRExC_state, ret, ender);
11906 #if 0  /* Removing this doesn't cause failures in the test suite -- khw */
11907                     RExC_size++; /* XXX WHY do we need this?!!
11908                                     For large programs it seems to be required
11909                                     but I can't figure out why. -- dmq*/
11910 #endif
11911                     return ret;
11912                 }
11913                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11914                 vFAIL("Unknown switch condition (?(...))");
11915             }
11916             case '[':           /* (?[ ... ]) */
11917                 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
11918                                          oregcomp_parse);
11919             case 0: /* A NUL */
11920                 RExC_parse--; /* for vFAIL to print correctly */
11921                 vFAIL("Sequence (? incomplete");
11922                 break;
11923             default: /* e.g., (?i) */
11924                 RExC_parse = (char *) seqstart + 1;
11925               parse_flags:
11926                 parse_lparen_question_flags(pRExC_state);
11927                 if (UCHARAT(RExC_parse) != ':') {
11928                     if (RExC_parse < RExC_end)
11929                         nextchar(pRExC_state);
11930                     *flagp = TRYAGAIN;
11931                     return 0;
11932                 }
11933                 paren = ':';
11934                 nextchar(pRExC_state);
11935                 ret = 0;
11936                 goto parse_rest;
11937             } /* end switch */
11938         }
11939         else {
11940             if (*RExC_parse == '{') {
11941                 ckWARNregdep(RExC_parse + 1,
11942                             "Unescaped left brace in regex is "
11943                             "deprecated here (and will be fatal "
11944                             "in Perl 5.32), passed through");
11945             }
11946             /* Not bothering to indent here, as the above 'else' is temporary
11947              * */
11948         if (!(RExC_flags & RXf_PMf_NOCAPTURE)) {   /* (...) */
11949           capturing_parens:
11950             parno = RExC_npar;
11951             RExC_npar++;
11952             if (RExC_total_parens <= 0) {
11953                 /* If we are in our first pass through (and maybe only pass),
11954                  * we  need to allocate memory for the capturing parentheses
11955                  * data structures.  Since we start at npar=1, when it reaches
11956                  * 2, for the first time it has something to put in it.  Above
11957                  * 2 means we extend what we already have */
11958                 if (RExC_npar == 2) {
11959                     /* setup RExC_open_parens, which holds the address of each
11960                      * OPEN tag, and to make things simpler for the 0 index the
11961                      * start of the program - this is used later for offsets */
11962                     Newxz(RExC_open_parens, RExC_npar, regnode_offset);
11963                     RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
11964
11965                     /* setup RExC_close_parens, which holds the address of each
11966                      * CLOSE tag, and to make things simpler for the 0 index
11967                      * the end of the program - this is used later for offsets
11968                      * */
11969                     Newxz(RExC_close_parens, RExC_npar, regnode_offset);
11970                     /* we dont know where end op starts yet, so we dont need to
11971                      * set RExC_close_parens[0] like we do RExC_open_parens[0]
11972                      * above */
11973                 }
11974                 else {
11975                     Renew(RExC_open_parens, RExC_npar, regnode_offset);
11976                     Zero(RExC_open_parens + RExC_npar - 1, 1, regnode_offset);
11977
11978                     Renew(RExC_close_parens, RExC_npar, regnode_offset);
11979                     Zero(RExC_close_parens + RExC_npar - 1, 1, regnode_offset);
11980                 }
11981             }
11982
11983             ret = reganode(pRExC_state, OPEN, parno);
11984             if (!RExC_nestroot)
11985                 RExC_nestroot = parno;
11986             if (RExC_open_parens && !RExC_open_parens[parno])
11987             {
11988                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11989                     "%*s%*s Setting open paren #%" IVdf " to %d\n",
11990                     22, "|    |", (int)(depth * 2 + 1), "",
11991                     (IV)parno, ret));
11992                 RExC_open_parens[parno]= ret;
11993             }
11994
11995             Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
11996             Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
11997             is_open = 1;
11998         } else {
11999             /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
12000             paren = ':';
12001             ret = 0;
12002         }
12003         }
12004     }
12005     else                        /* ! paren */
12006         ret = 0;
12007
12008    parse_rest:
12009     /* Pick up the branches, linking them together. */
12010     parse_start = RExC_parse;   /* MJD */
12011     br = regbranch(pRExC_state, &flags, 1, depth+1);
12012
12013     /*     branch_len = (paren != 0); */
12014
12015     if (br == 0) {
12016         RETURN_FAIL_ON_RESTART(flags, flagp);
12017         FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12018     }
12019     if (*RExC_parse == '|') {
12020         if (RExC_use_BRANCHJ) {
12021             reginsert(pRExC_state, BRANCHJ, br, depth+1);
12022         }
12023         else {                  /* MJD */
12024             reginsert(pRExC_state, BRANCH, br, depth+1);
12025             Set_Node_Length(REGNODE_p(br), paren != 0);
12026             Set_Node_Offset_To_R(br, parse_start-RExC_start);
12027         }
12028         have_branch = 1;
12029     }
12030     else if (paren == ':') {
12031         *flagp |= flags&SIMPLE;
12032     }
12033     if (is_open) {                              /* Starts with OPEN. */
12034         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
12035     }
12036     else if (paren != '?')              /* Not Conditional */
12037         ret = br;
12038     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12039     lastbr = br;
12040     while (*RExC_parse == '|') {
12041         if (RExC_use_BRANCHJ) {
12042             ender = reganode(pRExC_state, LONGJMP, 0);
12043
12044             /* Append to the previous. */
12045             REGTAIL(pRExC_state,
12046                     REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
12047                     ender);
12048         }
12049         nextchar(pRExC_state);
12050         if (freeze_paren) {
12051             if (RExC_npar > after_freeze)
12052                 after_freeze = RExC_npar;
12053             RExC_npar = freeze_paren;
12054         }
12055         br = regbranch(pRExC_state, &flags, 0, depth+1);
12056
12057         if (br == 0) {
12058             RETURN_FAIL_ON_RESTART(flags, flagp);
12059             FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12060         }
12061         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
12062         lastbr = br;
12063         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12064     }
12065
12066     if (have_branch || paren != ':') {
12067         regnode * br;
12068
12069         /* Make a closing node, and hook it on the end. */
12070         switch (paren) {
12071         case ':':
12072             ender = reg_node(pRExC_state, TAIL);
12073             break;
12074         case 1: case 2:
12075             ender = reganode(pRExC_state, CLOSE, parno);
12076             if ( RExC_close_parens ) {
12077                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12078                         "%*s%*s Setting close paren #%" IVdf " to %d\n",
12079                         22, "|    |", (int)(depth * 2 + 1), "",
12080                         (IV)parno, ender));
12081                 RExC_close_parens[parno]= ender;
12082                 if (RExC_nestroot == parno)
12083                     RExC_nestroot = 0;
12084             }
12085             Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
12086             Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
12087             break;
12088         case 's':
12089             ender = reg_node(pRExC_state, SRCLOSE);
12090             RExC_in_script_run = 0;
12091             break;
12092         case '<':
12093         case 'a':
12094         case 'A':
12095         case 'b':
12096         case 'B':
12097         case ',':
12098         case '=':
12099         case '!':
12100             *flagp &= ~HASWIDTH;
12101             /* FALLTHROUGH */
12102         case 't':   /* aTomic */
12103         case '>':
12104             ender = reg_node(pRExC_state, SUCCEED);
12105             break;
12106         case 0:
12107             ender = reg_node(pRExC_state, END);
12108             assert(!RExC_end_op); /* there can only be one! */
12109             RExC_end_op = REGNODE_p(ender);
12110             if (RExC_close_parens) {
12111                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12112                     "%*s%*s Setting close paren #0 (END) to %d\n",
12113                     22, "|    |", (int)(depth * 2 + 1), "",
12114                     ender));
12115
12116                 RExC_close_parens[0]= ender;
12117             }
12118             break;
12119         }
12120         DEBUG_PARSE_r(
12121             DEBUG_PARSE_MSG("lsbr");
12122             regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
12123             regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
12124             Perl_re_printf( aTHX_  "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12125                           SvPV_nolen_const(RExC_mysv1),
12126                           (IV)lastbr,
12127                           SvPV_nolen_const(RExC_mysv2),
12128                           (IV)ender,
12129                           (IV)(ender - lastbr)
12130             );
12131         );
12132         REGTAIL(pRExC_state, lastbr, ender);
12133
12134         if (have_branch) {
12135             char is_nothing= 1;
12136             if (depth==1)
12137                 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
12138
12139             /* Hook the tails of the branches to the closing node. */
12140             for (br = REGNODE_p(ret); br; br = regnext(br)) {
12141                 const U8 op = PL_regkind[OP(br)];
12142                 if (op == BRANCH) {
12143                     REGTAIL_STUDY(pRExC_state,
12144                                   REGNODE_OFFSET(NEXTOPER(br)),
12145                                   ender);
12146                     if ( OP(NEXTOPER(br)) != NOTHING
12147                          || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12148                         is_nothing= 0;
12149                 }
12150                 else if (op == BRANCHJ) {
12151                     REGTAIL_STUDY(pRExC_state,
12152                                   REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12153                                   ender);
12154                     /* for now we always disable this optimisation * /
12155                     if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12156                          || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12157                     */
12158                         is_nothing= 0;
12159                 }
12160             }
12161             if (is_nothing) {
12162                 regnode * ret_as_regnode = REGNODE_p(ret);
12163                 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12164                                ? regnext(ret_as_regnode)
12165                                : ret_as_regnode;
12166                 DEBUG_PARSE_r(
12167                     DEBUG_PARSE_MSG("NADA");
12168                     regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12169                                      NULL, pRExC_state);
12170                     regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12171                                      NULL, pRExC_state);
12172                     Perl_re_printf( aTHX_  "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12173                                   SvPV_nolen_const(RExC_mysv1),
12174                                   (IV)REG_NODE_NUM(ret_as_regnode),
12175                                   SvPV_nolen_const(RExC_mysv2),
12176                                   (IV)ender,
12177                                   (IV)(ender - ret)
12178                     );
12179                 );
12180                 OP(br)= NOTHING;
12181                 if (OP(REGNODE_p(ender)) == TAIL) {
12182                     NEXT_OFF(br)= 0;
12183                     RExC_emit= REGNODE_OFFSET(br) + 1;
12184                 } else {
12185                     regnode *opt;
12186                     for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12187                         OP(opt)= OPTIMIZED;
12188                     NEXT_OFF(br)= REGNODE_p(ender) - br;
12189                 }
12190             }
12191         }
12192     }
12193
12194     {
12195         const char *p;
12196          /* Even/odd or x=don't care: 010101x10x */
12197         static const char parens[] = "=!aA<,>Bbt";
12198          /* flag below is set to 0 up through 'A'; 1 for larger */
12199
12200         if (paren && (p = strchr(parens, paren))) {
12201             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12202             int flag = (p - parens) > 3;
12203
12204             if (paren == '>' || paren == 't') {
12205                 node = SUSPEND, flag = 0;
12206             }
12207
12208             reginsert(pRExC_state, node, ret, depth+1);
12209             Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12210             Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12211             FLAGS(REGNODE_p(ret)) = flag;
12212             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
12213         }
12214     }
12215
12216     /* Check for proper termination. */
12217     if (paren) {
12218         /* restore original flags, but keep (?p) and, if we've encountered
12219          * something in the parse that changes /d rules into /u, keep the /u */
12220         RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12221         if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12222             set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12223         }
12224         if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12225             RExC_parse = oregcomp_parse;
12226             vFAIL("Unmatched (");
12227         }
12228         nextchar(pRExC_state);
12229     }
12230     else if (!paren && RExC_parse < RExC_end) {
12231         if (*RExC_parse == ')') {
12232             RExC_parse++;
12233             vFAIL("Unmatched )");
12234         }
12235         else
12236             FAIL("Junk on end of regexp");      /* "Can't happen". */
12237         NOT_REACHED; /* NOTREACHED */
12238     }
12239
12240     if (RExC_in_lookbehind) {
12241         RExC_in_lookbehind--;
12242     }
12243     if (after_freeze > RExC_npar)
12244         RExC_npar = after_freeze;
12245     return(ret);
12246 }
12247
12248 /*
12249  - regbranch - one alternative of an | operator
12250  *
12251  * Implements the concatenation operator.
12252  *
12253  * On success, returns the offset at which any next node should be placed into
12254  * the regex engine program being compiled.
12255  *
12256  * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12257  * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12258  * UTF-8
12259  */
12260 STATIC regnode_offset
12261 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12262 {
12263     regnode_offset ret;
12264     regnode_offset chain = 0;
12265     regnode_offset latest;
12266     I32 flags = 0, c = 0;
12267     GET_RE_DEBUG_FLAGS_DECL;
12268
12269     PERL_ARGS_ASSERT_REGBRANCH;
12270
12271     DEBUG_PARSE("brnc");
12272
12273     if (first)
12274         ret = 0;
12275     else {
12276         if (RExC_use_BRANCHJ)
12277             ret = reganode(pRExC_state, BRANCHJ, 0);
12278         else {
12279             ret = reg_node(pRExC_state, BRANCH);
12280             Set_Node_Length(REGNODE_p(ret), 1);
12281         }
12282     }
12283
12284     *flagp = WORST;                     /* Tentatively. */
12285
12286     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12287                             FALSE /* Don't force to /x */ );
12288     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12289         flags &= ~TRYAGAIN;
12290         latest = regpiece(pRExC_state, &flags, depth+1);
12291         if (latest == 0) {
12292             if (flags & TRYAGAIN)
12293                 continue;
12294             RETURN_FAIL_ON_RESTART(flags, flagp);
12295             FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12296         }
12297         else if (ret == 0)
12298             ret = latest;
12299         *flagp |= flags&(HASWIDTH|POSTPONED);
12300         if (chain == 0)         /* First piece. */
12301             *flagp |= flags&SPSTART;
12302         else {
12303             /* FIXME adding one for every branch after the first is probably
12304              * excessive now we have TRIE support. (hv) */
12305             MARK_NAUGHTY(1);
12306             if (     chain > (SSize_t) BRANCH_MAX_OFFSET
12307                 && ! RExC_use_BRANCHJ)
12308             {
12309                 /* XXX We could just redo this branch, but figuring out what
12310                  * bookkeeping needs to be reset is a pain */
12311                 REQUIRE_BRANCHJ(flagp, 0);
12312             }
12313             REGTAIL(pRExC_state, chain, latest);
12314         }
12315         chain = latest;
12316         c++;
12317     }
12318     if (chain == 0) {   /* Loop ran zero times. */
12319         chain = reg_node(pRExC_state, NOTHING);
12320         if (ret == 0)
12321             ret = chain;
12322     }
12323     if (c == 1) {
12324         *flagp |= flags&SIMPLE;
12325     }
12326
12327     return ret;
12328 }
12329
12330 /*
12331  - regpiece - something followed by possible quantifier * + ? {n,m}
12332  *
12333  * Note that the branching code sequences used for ? and the general cases
12334  * of * and + are somewhat optimized:  they use the same NOTHING node as
12335  * both the endmarker for their branch list and the body of the last branch.
12336  * It might seem that this node could be dispensed with entirely, but the
12337  * endmarker role is not redundant.
12338  *
12339  * On success, returns the offset at which any next node should be placed into
12340  * the regex engine program being compiled.
12341  *
12342  * Returns 0 otherwise, with *flagp set to indicate why:
12343  *  TRYAGAIN        if regatom() returns 0 with TRYAGAIN.
12344  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
12345  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12346  */
12347 STATIC regnode_offset
12348 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12349 {
12350     regnode_offset ret;
12351     char op;
12352     char *next;
12353     I32 flags;
12354     const char * const origparse = RExC_parse;
12355     I32 min;
12356     I32 max = REG_INFTY;
12357 #ifdef RE_TRACK_PATTERN_OFFSETS
12358     char *parse_start;
12359 #endif
12360     const char *maxpos = NULL;
12361     UV uv;
12362
12363     /* Save the original in case we change the emitted regop to a FAIL. */
12364     const regnode_offset orig_emit = RExC_emit;
12365
12366     GET_RE_DEBUG_FLAGS_DECL;
12367
12368     PERL_ARGS_ASSERT_REGPIECE;
12369
12370     DEBUG_PARSE("piec");
12371
12372     ret = regatom(pRExC_state, &flags, depth+1);
12373     if (ret == 0) {
12374         RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12375         FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12376     }
12377
12378     op = *RExC_parse;
12379
12380     if (op == '{' && regcurly(RExC_parse)) {
12381         maxpos = NULL;
12382 #ifdef RE_TRACK_PATTERN_OFFSETS
12383         parse_start = RExC_parse; /* MJD */
12384 #endif
12385         next = RExC_parse + 1;
12386         while (isDIGIT(*next) || *next == ',') {
12387             if (*next == ',') {
12388                 if (maxpos)
12389                     break;
12390                 else
12391                     maxpos = next;
12392             }
12393             next++;
12394         }
12395         if (*next == '}') {             /* got one */
12396             const char* endptr;
12397             if (!maxpos)
12398                 maxpos = next;
12399             RExC_parse++;
12400             if (isDIGIT(*RExC_parse)) {
12401                 endptr = RExC_end;
12402                 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12403                     vFAIL("Invalid quantifier in {,}");
12404                 if (uv >= REG_INFTY)
12405                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12406                 min = (I32)uv;
12407             } else {
12408                 min = 0;
12409             }
12410             if (*maxpos == ',')
12411                 maxpos++;
12412             else
12413                 maxpos = RExC_parse;
12414             if (isDIGIT(*maxpos)) {
12415                 endptr = RExC_end;
12416                 if (!grok_atoUV(maxpos, &uv, &endptr))
12417                     vFAIL("Invalid quantifier in {,}");
12418                 if (uv >= REG_INFTY)
12419                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12420                 max = (I32)uv;
12421             } else {
12422                 max = REG_INFTY;                /* meaning "infinity" */
12423             }
12424             RExC_parse = next;
12425             nextchar(pRExC_state);
12426             if (max < min) {    /* If can't match, warn and optimize to fail
12427                                    unconditionally */
12428                 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12429                 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12430                 NEXT_OFF(REGNODE_p(orig_emit)) =
12431                                     regarglen[OPFAIL] + NODE_STEP_REGNODE;
12432                 return ret;
12433             }
12434             else if (min == max && *RExC_parse == '?')
12435             {
12436                 ckWARN2reg(RExC_parse + 1,
12437                            "Useless use of greediness modifier '%c'",
12438                            *RExC_parse);
12439             }
12440
12441           do_curly:
12442             if ((flags&SIMPLE)) {
12443                 if (min == 0 && max == REG_INFTY) {
12444                     reginsert(pRExC_state, STAR, ret, depth+1);
12445                     MARK_NAUGHTY(4);
12446                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12447                     goto nest_check;
12448                 }
12449                 if (min == 1 && max == REG_INFTY) {
12450                     reginsert(pRExC_state, PLUS, ret, depth+1);
12451                     MARK_NAUGHTY(3);
12452                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12453                     goto nest_check;
12454                 }
12455                 MARK_NAUGHTY_EXP(2, 2);
12456                 reginsert(pRExC_state, CURLY, ret, depth+1);
12457                 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12458                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12459             }
12460             else {
12461                 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12462
12463                 FLAGS(REGNODE_p(w)) = 0;
12464                 REGTAIL(pRExC_state, ret, w);
12465                 if (RExC_use_BRANCHJ) {
12466                     reginsert(pRExC_state, LONGJMP, ret, depth+1);
12467                     reginsert(pRExC_state, NOTHING, ret, depth+1);
12468                     NEXT_OFF(REGNODE_p(ret)) = 3;       /* Go over LONGJMP. */
12469                 }
12470                 reginsert(pRExC_state, CURLYX, ret, depth+1);
12471                                 /* MJD hk */
12472                 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12473                 Set_Node_Length(REGNODE_p(ret),
12474                                 op == '{' ? (RExC_parse - parse_start) : 1);
12475
12476                 if (RExC_use_BRANCHJ)
12477                     NEXT_OFF(REGNODE_p(ret)) = 3;   /* Go over NOTHING to
12478                                                        LONGJMP. */
12479                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
12480                 RExC_whilem_seen++;
12481                 MARK_NAUGHTY_EXP(1, 4);     /* compound interest */
12482             }
12483             FLAGS(REGNODE_p(ret)) = 0;
12484
12485             if (min > 0)
12486                 *flagp = WORST;
12487             if (max > 0)
12488                 *flagp |= HASWIDTH;
12489             ARG1_SET(REGNODE_p(ret), (U16)min);
12490             ARG2_SET(REGNODE_p(ret), (U16)max);
12491             if (max == REG_INFTY)
12492                 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12493
12494             goto nest_check;
12495         }
12496     }
12497
12498     if (!ISMULT1(op)) {
12499         *flagp = flags;
12500         return(ret);
12501     }
12502
12503 #if 0                           /* Now runtime fix should be reliable. */
12504
12505     /* if this is reinstated, don't forget to put this back into perldiag:
12506
12507             =item Regexp *+ operand could be empty at {#} in regex m/%s/
12508
12509            (F) The part of the regexp subject to either the * or + quantifier
12510            could match an empty string. The {#} shows in the regular
12511            expression about where the problem was discovered.
12512
12513     */
12514
12515     if (!(flags&HASWIDTH) && op != '?')
12516       vFAIL("Regexp *+ operand could be empty");
12517 #endif
12518
12519 #ifdef RE_TRACK_PATTERN_OFFSETS
12520     parse_start = RExC_parse;
12521 #endif
12522     nextchar(pRExC_state);
12523
12524     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12525
12526     if (op == '*') {
12527         min = 0;
12528         goto do_curly;
12529     }
12530     else if (op == '+') {
12531         min = 1;
12532         goto do_curly;
12533     }
12534     else if (op == '?') {
12535         min = 0; max = 1;
12536         goto do_curly;
12537     }
12538   nest_check:
12539     if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12540         ckWARN2reg(RExC_parse,
12541                    "%" UTF8f " matches null string many times",
12542                    UTF8fARG(UTF, (RExC_parse >= origparse
12543                                  ? RExC_parse - origparse
12544                                  : 0),
12545                    origparse));
12546     }
12547
12548     if (*RExC_parse == '?') {
12549         nextchar(pRExC_state);
12550         reginsert(pRExC_state, MINMOD, ret, depth+1);
12551         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
12552     }
12553     else if (*RExC_parse == '+') {
12554         regnode_offset ender;
12555         nextchar(pRExC_state);
12556         ender = reg_node(pRExC_state, SUCCEED);
12557         REGTAIL(pRExC_state, ret, ender);
12558         reginsert(pRExC_state, SUSPEND, ret, depth+1);
12559         ender = reg_node(pRExC_state, TAIL);
12560         REGTAIL(pRExC_state, ret, ender);
12561     }
12562
12563     if (ISMULT2(RExC_parse)) {
12564         RExC_parse++;
12565         vFAIL("Nested quantifiers");
12566     }
12567
12568     return(ret);
12569 }
12570
12571 STATIC bool
12572 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12573                 regnode_offset * node_p,
12574                 UV * code_point_p,
12575                 int * cp_count,
12576                 I32 * flagp,
12577                 const bool strict,
12578                 const U32 depth
12579     )
12580 {
12581  /* This routine teases apart the various meanings of \N and returns
12582   * accordingly.  The input parameters constrain which meaning(s) is/are valid
12583   * in the current context.
12584   *
12585   * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12586   *
12587   * If <code_point_p> is not NULL, the context is expecting the result to be a
12588   * single code point.  If this \N instance turns out to a single code point,
12589   * the function returns TRUE and sets *code_point_p to that code point.
12590   *
12591   * If <node_p> is not NULL, the context is expecting the result to be one of
12592   * the things representable by a regnode.  If this \N instance turns out to be
12593   * one such, the function generates the regnode, returns TRUE and sets *node_p
12594   * to point to the offset of that regnode into the regex engine program being
12595   * compiled.
12596   *
12597   * If this instance of \N isn't legal in any context, this function will
12598   * generate a fatal error and not return.
12599   *
12600   * On input, RExC_parse should point to the first char following the \N at the
12601   * time of the call.  On successful return, RExC_parse will have been updated
12602   * to point to just after the sequence identified by this routine.  Also
12603   * *flagp has been updated as needed.
12604   *
12605   * When there is some problem with the current context and this \N instance,
12606   * the function returns FALSE, without advancing RExC_parse, nor setting
12607   * *node_p, nor *code_point_p, nor *flagp.
12608   *
12609   * If <cp_count> is not NULL, the caller wants to know the length (in code
12610   * points) that this \N sequence matches.  This is set, and the input is
12611   * parsed for errors, even if the function returns FALSE, as detailed below.
12612   *
12613   * There are 5 possibilities here, as detailed in the next 5 paragraphs.
12614   *
12615   * Probably the most common case is for the \N to specify a single code point.
12616   * *cp_count will be set to 1, and *code_point_p will be set to that code
12617   * point.
12618   *
12619   * Another possibility is for the input to be an empty \N{}, which for
12620   * backwards compatibility we accept.  *cp_count will be set to 0. *node_p
12621   * will be set to a generated NOTHING node.
12622   *
12623   * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12624   * set to 0. *node_p will be set to a generated REG_ANY node.
12625   *
12626   * The fourth possibility is that \N resolves to a sequence of more than one
12627   * code points.  *cp_count will be set to the number of code points in the
12628   * sequence. *node_p will be set to a generated node returned by this
12629   * function calling S_reg().
12630   *
12631   * The final possibility is that it is premature to be calling this function;
12632   * the parse needs to be restarted.  This can happen when this changes from
12633   * /d to /u rules, or when the pattern needs to be upgraded to UTF-8.  The
12634   * latter occurs only when the fourth possibility would otherwise be in
12635   * effect, and is because one of those code points requires the pattern to be
12636   * recompiled as UTF-8.  The function returns FALSE, and sets the
12637   * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate.  When this
12638   * happens, the caller needs to desist from continuing parsing, and return
12639   * this information to its caller.  This is not set for when there is only one
12640   * code point, as this can be called as part of an ANYOF node, and they can
12641   * store above-Latin1 code points without the pattern having to be in UTF-8.
12642   *
12643   * For non-single-quoted regexes, the tokenizer has resolved character and
12644   * sequence names inside \N{...} into their Unicode values, normalizing the
12645   * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12646   * hex-represented code points in the sequence.  This is done there because
12647   * the names can vary based on what charnames pragma is in scope at the time,
12648   * so we need a way to take a snapshot of what they resolve to at the time of
12649   * the original parse. [perl #56444].
12650   *
12651   * That parsing is skipped for single-quoted regexes, so we may here get
12652   * '\N{NAME}'.  This is a fatal error.  These names have to be resolved by the
12653   * parser.  But if the single-quoted regex is something like '\N{U+41}', that
12654   * is legal and handled here.  The code point is Unicode, and has to be
12655   * translated into the native character set for non-ASCII platforms.
12656   */
12657
12658     char * endbrace;    /* points to '}' following the name */
12659     char* p = RExC_parse; /* Temporary */
12660
12661     SV * substitute_parse = NULL;
12662     char *orig_end;
12663     char *save_start;
12664     I32 flags;
12665     Size_t count = 0;   /* code point count kept internally by this function */
12666
12667     GET_RE_DEBUG_FLAGS_DECL;
12668
12669     PERL_ARGS_ASSERT_GROK_BSLASH_N;
12670
12671     GET_RE_DEBUG_FLAGS;
12672
12673     assert(cBOOL(node_p) ^ cBOOL(code_point_p));  /* Exactly one should be set */
12674     assert(! (node_p && cp_count));               /* At most 1 should be set */
12675
12676     if (cp_count) {     /* Initialize return for the most common case */
12677         *cp_count = 1;
12678     }
12679
12680     /* The [^\n] meaning of \N ignores spaces and comments under the /x
12681      * modifier.  The other meanings do not, so use a temporary until we find
12682      * out which we are being called with */
12683     skip_to_be_ignored_text(pRExC_state, &p,
12684                             FALSE /* Don't force to /x */ );
12685
12686     /* Disambiguate between \N meaning a named character versus \N meaning
12687      * [^\n].  The latter is assumed when the {...} following the \N is a legal
12688      * quantifier, or there is no '{' at all */
12689     if (*p != '{' || regcurly(p)) {
12690         RExC_parse = p;
12691         if (cp_count) {
12692             *cp_count = -1;
12693         }
12694
12695         if (! node_p) {
12696             return FALSE;
12697         }
12698
12699         *node_p = reg_node(pRExC_state, REG_ANY);
12700         *flagp |= HASWIDTH|SIMPLE;
12701         MARK_NAUGHTY(1);
12702         Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
12703         return TRUE;
12704     }
12705
12706     /* The test above made sure that the next real character is a '{', but
12707      * under the /x modifier, it could be separated by space (or a comment and
12708      * \n) and this is not allowed (for consistency with \x{...} and the
12709      * tokenizer handling of \N{NAME}). */
12710     if (*RExC_parse != '{') {
12711         vFAIL("Missing braces on \\N{}");
12712     }
12713
12714     RExC_parse++;       /* Skip past the '{' */
12715
12716     endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
12717     if (! endbrace) { /* no trailing brace */
12718         vFAIL2("Missing right brace on \\%c{}", 'N');
12719     }
12720
12721     /* Here, we have decided it should be a named character or sequence */
12722     REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode
12723                                         semantics */
12724
12725     if (endbrace == RExC_parse) {   /* empty: \N{} */
12726         if (strict) {
12727             RExC_parse++;   /* Position after the "}" */
12728             vFAIL("Zero length \\N{}");
12729         }
12730         if (cp_count) {
12731             *cp_count = 0;
12732         }
12733         nextchar(pRExC_state);
12734         if (! node_p) {
12735             return FALSE;
12736         }
12737
12738         *node_p = reg_node(pRExC_state, NOTHING);
12739         return TRUE;
12740     }
12741
12742     /* If we haven't got something that begins with 'U+', then it didn't get lexed. */
12743     if (   endbrace - RExC_parse < 2
12744         || strnNE(RExC_parse, "U+", 2))
12745     {
12746         RExC_parse = endbrace;  /* position msg's '<--HERE' */
12747         vFAIL("\\N{NAME} must be resolved by the lexer");
12748     }
12749
12750         /* This code purposely indented below because of future changes coming */
12751
12752         /* We can get to here when the input is \N{U+...} or when toke.c has
12753          * converted a name to the \N{U+...} form.  This include changing a
12754          * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
12755
12756         RExC_parse += 2;    /* Skip past the 'U+' */
12757
12758         /* Code points are separated by dots.  The '}' terminates the whole
12759          * thing. */
12760
12761         do {    /* Loop until the ending brace */
12762             UV cp = 0;
12763             char * start_digit;     /* The first of the current code point */
12764             if (! isXDIGIT(*RExC_parse)) {
12765                 RExC_parse++;
12766                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12767             }
12768
12769             start_digit = RExC_parse;
12770             count++;
12771
12772             /* Loop through the hex digits of the current code point */
12773             do {
12774                 /* Adding this digit will shift the result 4 bits.  If that
12775                  * result would be above the legal max, it's overflow */
12776                 if (cp > MAX_LEGAL_CP >> 4) {
12777
12778                     /* Find the end of the code point */
12779                     do {
12780                         RExC_parse ++;
12781                     } while (isXDIGIT(*RExC_parse) || *RExC_parse == '_');
12782
12783                     /* Be sure to synchronize this message with the similar one
12784                      * in utf8.c */
12785                     vFAIL4("Use of code point 0x%.*s is not allowed; the"
12786                         " permissible max is 0x%" UVxf,
12787                         (int) (RExC_parse - start_digit), start_digit,
12788                         MAX_LEGAL_CP);
12789                 }
12790
12791                 /* Accumulate this (valid) digit into the running total */
12792                 cp  = (cp << 4) + READ_XDIGIT(RExC_parse);
12793
12794                 /* READ_XDIGIT advanced the input pointer.  Ignore a single
12795                  * underscore separator */
12796                 if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) {
12797                     RExC_parse++;
12798                 }
12799             } while (isXDIGIT(*RExC_parse));
12800
12801             /* Here, have accumulated the next code point */
12802             if (RExC_parse >= endbrace) {   /* If done ... */
12803                 if (count != 1) {
12804                     goto do_concat;
12805                 }
12806
12807                 /* Here, is a single code point; fail if doesn't want that */
12808                 if (! code_point_p) {
12809                     RExC_parse = p;
12810                     return FALSE;
12811                 }
12812
12813                 /* A single code point is easy to handle; just return it */
12814                 *code_point_p = UNI_TO_NATIVE(cp);
12815                 RExC_parse = endbrace;
12816                 nextchar(pRExC_state);
12817                 return TRUE;
12818             }
12819
12820             /* Here, the only legal thing would be a multiple character
12821              * sequence (of the form "\N{U+c1.c2. ... }".   So the next
12822              * character must be a dot (and the one after that can't be the
12823              * endbrace, or we'd have something like \N{U+100.} ) */
12824             if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
12825                 RExC_parse += (RExC_orig_utf8)  /* point to after 1st invalid */
12826                                 ? UTF8SKIP(RExC_parse)
12827                                 : 1;
12828                 if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */
12829                     RExC_parse = endbrace;
12830                 }
12831                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12832             }
12833
12834             /* Here, looks like its really a multiple character sequence.  Fail
12835              * if that's not what the caller wants.  But continue with counting
12836              * and error checking if they still want a count */
12837             if (! node_p && ! cp_count) {
12838                 return FALSE;
12839             }
12840
12841             /* What is done here is to convert this to a sub-pattern of the
12842              * form \x{char1}\x{char2}...  and then call reg recursively to
12843              * parse it (enclosing in "(?: ... )" ).  That way, it retains its
12844              * atomicness, while not having to worry about special handling
12845              * that some code points may have.  We don't create a subpattern,
12846              * but go through the motions of code point counting and error
12847              * checking, if the caller doesn't want a node returned. */
12848
12849             if (node_p && count == 1) {
12850                 substitute_parse = newSVpvs("?:");
12851             }
12852
12853           do_concat:
12854
12855             if (node_p) {
12856                 /* Convert to notation the rest of the code understands */
12857                 sv_catpvs(substitute_parse, "\\x{");
12858                 sv_catpvn(substitute_parse, start_digit,
12859                                             RExC_parse - start_digit);
12860                 sv_catpvs(substitute_parse, "}");
12861             }
12862
12863             /* Move to after the dot (or ending brace the final time through.)
12864              * */
12865             RExC_parse++;
12866             count++;
12867
12868         } while (RExC_parse < endbrace);
12869
12870         if (! node_p) { /* Doesn't want the node */
12871             assert (cp_count);
12872
12873             *cp_count = count;
12874             return FALSE;
12875         }
12876
12877         sv_catpvs(substitute_parse, ")");
12878
12879 #ifdef EBCDIC
12880         /* The values are Unicode, and therefore have to be converted to native
12881          * on a non-Unicode (meaning non-ASCII) platform. */
12882         RExC_recode_x_to_native = 1;
12883 #endif
12884
12885     /* Here, we have the string the name evaluates to, ready to be parsed,
12886      * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
12887      * constructs.  This can be called from within a substitute parse already.
12888      * The error reporting mechanism doesn't work for 2 levels of this, but the
12889      * code above has validated this new construct, so there should be no
12890      * errors generated by the below.  And this isn' an exact copy, so the
12891      * mechanism to seamlessly deal with this won't work, so turn off warnings
12892      * during it */
12893     save_start = RExC_start;
12894     orig_end = RExC_end;
12895
12896     RExC_parse = RExC_start = SvPVX(substitute_parse);
12897     RExC_end = RExC_parse + SvCUR(substitute_parse);
12898     TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
12899
12900     *node_p = reg(pRExC_state, 1, &flags, depth+1);
12901
12902     /* Restore the saved values */
12903     RESTORE_WARNINGS;
12904     RExC_start = save_start;
12905     RExC_parse = endbrace;
12906     RExC_end = orig_end;
12907 #ifdef EBCDIC
12908     RExC_recode_x_to_native = 0;
12909 #endif
12910
12911     SvREFCNT_dec_NN(substitute_parse);
12912
12913     if (! *node_p) {
12914         RETURN_FAIL_ON_RESTART(flags, flagp);
12915         FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
12916             (UV) flags);
12917     }
12918     *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
12919
12920     nextchar(pRExC_state);
12921
12922     return TRUE;
12923 }
12924
12925
12926 PERL_STATIC_INLINE U8
12927 S_compute_EXACTish(RExC_state_t *pRExC_state)
12928 {
12929     U8 op;
12930
12931     PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
12932
12933     if (! FOLD) {
12934         return (LOC)
12935                 ? EXACTL
12936                 : EXACT;
12937     }
12938
12939     op = get_regex_charset(RExC_flags);
12940     if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
12941         op--; /* /a is same as /u, and map /aa's offset to what /a's would have
12942                  been, so there is no hole */
12943     }
12944
12945     return op + EXACTF;
12946 }
12947
12948 STATIC bool
12949 S_new_regcurly(const char *s, const char *e)
12950 {
12951     /* This is a temporary function designed to match the most lenient form of
12952      * a {m,n} quantifier we ever envision, with either number omitted, and
12953      * spaces anywhere between/before/after them.
12954      *
12955      * If this function fails, then the string it matches is very unlikely to
12956      * ever be considered a valid quantifier, so we can allow the '{' that
12957      * begins it to be considered as a literal */
12958
12959     bool has_min = FALSE;
12960     bool has_max = FALSE;
12961
12962     PERL_ARGS_ASSERT_NEW_REGCURLY;
12963
12964     if (s >= e || *s++ != '{')
12965         return FALSE;
12966
12967     while (s < e && isSPACE(*s)) {
12968         s++;
12969     }
12970     while (s < e && isDIGIT(*s)) {
12971         has_min = TRUE;
12972         s++;
12973     }
12974     while (s < e && isSPACE(*s)) {
12975         s++;
12976     }
12977
12978     if (*s == ',') {
12979         s++;
12980         while (s < e && isSPACE(*s)) {
12981             s++;
12982         }
12983         while (s < e && isDIGIT(*s)) {
12984             has_max = TRUE;
12985             s++;
12986         }
12987         while (s < e && isSPACE(*s)) {
12988             s++;
12989         }
12990     }
12991
12992     return s < e && *s == '}' && (has_min || has_max);
12993 }
12994
12995 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
12996  * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
12997
12998 static I32
12999 S_backref_value(char *p, char *e)
13000 {
13001     const char* endptr = e;
13002     UV val;
13003     if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13004         return (I32)val;
13005     return I32_MAX;
13006 }
13007
13008
13009 /*
13010  - regatom - the lowest level
13011
13012    Try to identify anything special at the start of the current parse position.
13013    If there is, then handle it as required. This may involve generating a
13014    single regop, such as for an assertion; or it may involve recursing, such as
13015    to handle a () structure.
13016
13017    If the string doesn't start with something special then we gobble up
13018    as much literal text as we can.  If we encounter a quantifier, we have to
13019    back off the final literal character, as that quantifier applies to just it
13020    and not to the whole string of literals.
13021
13022    Once we have been able to handle whatever type of thing started the
13023    sequence, we return the offset into the regex engine program being compiled
13024    at which any  next regnode should be placed.
13025
13026    Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13027    Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13028    restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13029    Otherwise does not return 0.
13030
13031    Note: we have to be careful with escapes, as they can be both literal
13032    and special, and in the case of \10 and friends, context determines which.
13033
13034    A summary of the code structure is:
13035
13036    switch (first_byte) {
13037         cases for each special:
13038             handle this special;
13039             break;
13040         case '\\':
13041             switch (2nd byte) {
13042                 cases for each unambiguous special:
13043                     handle this special;
13044                     break;
13045                 cases for each ambigous special/literal:
13046                     disambiguate;
13047                     if (special)  handle here
13048                     else goto defchar;
13049                 default: // unambiguously literal:
13050                     goto defchar;
13051             }
13052         default:  // is a literal char
13053             // FALL THROUGH
13054         defchar:
13055             create EXACTish node for literal;
13056             while (more input and node isn't full) {
13057                 switch (input_byte) {
13058                    cases for each special;
13059                        make sure parse pointer is set so that the next call to
13060                            regatom will see this special first
13061                        goto loopdone; // EXACTish node terminated by prev. char
13062                    default:
13063                        append char to EXACTISH node;
13064                 }
13065                 get next input byte;
13066             }
13067         loopdone:
13068    }
13069    return the generated node;
13070
13071    Specifically there are two separate switches for handling
13072    escape sequences, with the one for handling literal escapes requiring
13073    a dummy entry for all of the special escapes that are actually handled
13074    by the other.
13075
13076 */
13077
13078 STATIC regnode_offset
13079 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13080 {
13081     dVAR;
13082     regnode_offset ret = 0;
13083     I32 flags = 0;
13084     char *parse_start;
13085     U8 op;
13086     int invert = 0;
13087     U8 arg;
13088
13089     GET_RE_DEBUG_FLAGS_DECL;
13090
13091     *flagp = WORST;             /* Tentatively. */
13092
13093     DEBUG_PARSE("atom");
13094
13095     PERL_ARGS_ASSERT_REGATOM;
13096
13097   tryagain:
13098     parse_start = RExC_parse;
13099     assert(RExC_parse < RExC_end);
13100     switch ((U8)*RExC_parse) {
13101     case '^':
13102         RExC_seen_zerolen++;
13103         nextchar(pRExC_state);
13104         if (RExC_flags & RXf_PMf_MULTILINE)
13105             ret = reg_node(pRExC_state, MBOL);
13106         else
13107             ret = reg_node(pRExC_state, SBOL);
13108         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13109         break;
13110     case '$':
13111         nextchar(pRExC_state);
13112         if (*RExC_parse)
13113             RExC_seen_zerolen++;
13114         if (RExC_flags & RXf_PMf_MULTILINE)
13115             ret = reg_node(pRExC_state, MEOL);
13116         else
13117             ret = reg_node(pRExC_state, SEOL);
13118         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13119         break;
13120     case '.':
13121         nextchar(pRExC_state);
13122         if (RExC_flags & RXf_PMf_SINGLELINE)
13123             ret = reg_node(pRExC_state, SANY);
13124         else
13125             ret = reg_node(pRExC_state, REG_ANY);
13126         *flagp |= HASWIDTH|SIMPLE;
13127         MARK_NAUGHTY(1);
13128         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13129         break;
13130     case '[':
13131     {
13132         char * const oregcomp_parse = ++RExC_parse;
13133         ret = regclass(pRExC_state, flagp, depth+1,
13134                        FALSE, /* means parse the whole char class */
13135                        TRUE, /* allow multi-char folds */
13136                        FALSE, /* don't silence non-portable warnings. */
13137                        (bool) RExC_strict,
13138                        TRUE, /* Allow an optimized regnode result */
13139                        NULL);
13140         if (ret == 0) {
13141             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13142             FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13143                   (UV) *flagp);
13144         }
13145         if (*RExC_parse != ']') {
13146             RExC_parse = oregcomp_parse;
13147             vFAIL("Unmatched [");
13148         }
13149         nextchar(pRExC_state);
13150         Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13151         break;
13152     }
13153     case '(':
13154         nextchar(pRExC_state);
13155         ret = reg(pRExC_state, 2, &flags, depth+1);
13156         if (ret == 0) {
13157                 if (flags & TRYAGAIN) {
13158                     if (RExC_parse >= RExC_end) {
13159                          /* Make parent create an empty node if needed. */
13160                         *flagp |= TRYAGAIN;
13161                         return(0);
13162                     }
13163                     goto tryagain;
13164                 }
13165                 RETURN_FAIL_ON_RESTART(flags, flagp);
13166                 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13167                                                                  (UV) flags);
13168         }
13169         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13170         break;
13171     case '|':
13172     case ')':
13173         if (flags & TRYAGAIN) {
13174             *flagp |= TRYAGAIN;
13175             return 0;
13176         }
13177         vFAIL("Internal urp");
13178                                 /* Supposed to be caught earlier. */
13179         break;
13180     case '?':
13181     case '+':
13182     case '*':
13183         RExC_parse++;
13184         vFAIL("Quantifier follows nothing");
13185         break;
13186     case '\\':
13187         /* Special Escapes
13188
13189            This switch handles escape sequences that resolve to some kind
13190            of special regop and not to literal text. Escape sequences that
13191            resolve to literal text are handled below in the switch marked
13192            "Literal Escapes".
13193
13194            Every entry in this switch *must* have a corresponding entry
13195            in the literal escape switch. However, the opposite is not
13196            required, as the default for this switch is to jump to the
13197            literal text handling code.
13198         */
13199         RExC_parse++;
13200         switch ((U8)*RExC_parse) {
13201         /* Special Escapes */
13202         case 'A':
13203             RExC_seen_zerolen++;
13204             ret = reg_node(pRExC_state, SBOL);
13205             /* SBOL is shared with /^/ so we set the flags so we can tell
13206              * /\A/ from /^/ in split. */
13207             FLAGS(REGNODE_p(ret)) = 1;
13208             *flagp |= SIMPLE;
13209             goto finish_meta_pat;
13210         case 'G':
13211             ret = reg_node(pRExC_state, GPOS);
13212             RExC_seen |= REG_GPOS_SEEN;
13213             *flagp |= SIMPLE;
13214             goto finish_meta_pat;
13215         case 'K':
13216             RExC_seen_zerolen++;
13217             ret = reg_node(pRExC_state, KEEPS);
13218             *flagp |= SIMPLE;
13219             /* XXX:dmq : disabling in-place substitution seems to
13220              * be necessary here to avoid cases of memory corruption, as
13221              * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13222              */
13223             RExC_seen |= REG_LOOKBEHIND_SEEN;
13224             goto finish_meta_pat;
13225         case 'Z':
13226             ret = reg_node(pRExC_state, SEOL);
13227             *flagp |= SIMPLE;
13228             RExC_seen_zerolen++;                /* Do not optimize RE away */
13229             goto finish_meta_pat;
13230         case 'z':
13231             ret = reg_node(pRExC_state, EOS);
13232             *flagp |= SIMPLE;
13233             RExC_seen_zerolen++;                /* Do not optimize RE away */
13234             goto finish_meta_pat;
13235         case 'C':
13236             vFAIL("\\C no longer supported");
13237         case 'X':
13238             ret = reg_node(pRExC_state, CLUMP);
13239             *flagp |= HASWIDTH;
13240             goto finish_meta_pat;
13241
13242         case 'W':
13243             invert = 1;
13244             /* FALLTHROUGH */
13245         case 'w':
13246             arg = ANYOF_WORDCHAR;
13247             goto join_posix;
13248
13249         case 'B':
13250             invert = 1;
13251             /* FALLTHROUGH */
13252         case 'b':
13253           {
13254             U8 flags = 0;
13255             regex_charset charset = get_regex_charset(RExC_flags);
13256
13257             RExC_seen_zerolen++;
13258             RExC_seen |= REG_LOOKBEHIND_SEEN;
13259             op = BOUND + charset;
13260
13261             if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13262                 flags = TRADITIONAL_BOUND;
13263                 if (op > BOUNDA) {  /* /aa is same as /a */
13264                     op = BOUNDA;
13265                 }
13266             }
13267             else {
13268                 STRLEN length;
13269                 char name = *RExC_parse;
13270                 char * endbrace = NULL;
13271                 RExC_parse += 2;
13272                 if (RExC_parse < RExC_end) {
13273                     endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13274                 }
13275
13276                 if (! endbrace) {
13277                     vFAIL2("Missing right brace on \\%c{}", name);
13278                 }
13279                 /* XXX Need to decide whether to take spaces or not.  Should be
13280                  * consistent with \p{}, but that currently is SPACE, which
13281                  * means vertical too, which seems wrong
13282                  * while (isBLANK(*RExC_parse)) {
13283                     RExC_parse++;
13284                 }*/
13285                 if (endbrace == RExC_parse) {
13286                     RExC_parse++;  /* After the '}' */
13287                     vFAIL2("Empty \\%c{}", name);
13288                 }
13289                 length = endbrace - RExC_parse;
13290                 /*while (isBLANK(*(RExC_parse + length - 1))) {
13291                     length--;
13292                 }*/
13293                 switch (*RExC_parse) {
13294                     case 'g':
13295                         if (    length != 1
13296                             && (memNEs(RExC_parse + 1, length - 1, "cb")))
13297                         {
13298                             goto bad_bound_type;
13299                         }
13300                         flags = GCB_BOUND;
13301                         break;
13302                     case 'l':
13303                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13304                             goto bad_bound_type;
13305                         }
13306                         flags = LB_BOUND;
13307                         break;
13308                     case 's':
13309                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13310                             goto bad_bound_type;
13311                         }
13312                         flags = SB_BOUND;
13313                         break;
13314                     case 'w':
13315                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13316                             goto bad_bound_type;
13317                         }
13318                         flags = WB_BOUND;
13319                         break;
13320                     default:
13321                       bad_bound_type:
13322                         RExC_parse = endbrace;
13323                         vFAIL2utf8f(
13324                             "'%" UTF8f "' is an unknown bound type",
13325                             UTF8fARG(UTF, length, endbrace - length));
13326                         NOT_REACHED; /*NOTREACHED*/
13327                 }
13328                 RExC_parse = endbrace;
13329                 REQUIRE_UNI_RULES(flagp, 0);
13330
13331                 if (op == BOUND) {
13332                     op = BOUNDU;
13333                 }
13334                 else if (op >= BOUNDA) {  /* /aa is same as /a */
13335                     op = BOUNDU;
13336                     length += 4;
13337
13338                     /* Don't have to worry about UTF-8, in this message because
13339                      * to get here the contents of the \b must be ASCII */
13340                     ckWARN4reg(RExC_parse + 1,  /* Include the '}' in msg */
13341                               "Using /u for '%.*s' instead of /%s",
13342                               (unsigned) length,
13343                               endbrace - length + 1,
13344                               (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13345                               ? ASCII_RESTRICT_PAT_MODS
13346                               : ASCII_MORE_RESTRICT_PAT_MODS);
13347                 }
13348             }
13349
13350             if (op == BOUND) {
13351                 RExC_seen_d_op = TRUE;
13352             }
13353             else if (op == BOUNDL) {
13354                 RExC_contains_locale = 1;
13355             }
13356
13357             if (invert) {
13358                 op += NBOUND - BOUND;
13359             }
13360
13361             ret = reg_node(pRExC_state, op);
13362             FLAGS(REGNODE_p(ret)) = flags;
13363
13364             *flagp |= SIMPLE;
13365
13366             goto finish_meta_pat;
13367           }
13368
13369         case 'D':
13370             invert = 1;
13371             /* FALLTHROUGH */
13372         case 'd':
13373             arg = ANYOF_DIGIT;
13374             if (! DEPENDS_SEMANTICS) {
13375                 goto join_posix;
13376             }
13377
13378             /* \d doesn't have any matches in the upper Latin1 range, hence /d
13379              * is equivalent to /u.  Changing to /u saves some branches at
13380              * runtime */
13381             op = POSIXU;
13382             goto join_posix_op_known;
13383
13384         case 'R':
13385             ret = reg_node(pRExC_state, LNBREAK);
13386             *flagp |= HASWIDTH|SIMPLE;
13387             goto finish_meta_pat;
13388
13389         case 'H':
13390             invert = 1;
13391             /* FALLTHROUGH */
13392         case 'h':
13393             arg = ANYOF_BLANK;
13394             op = POSIXU;
13395             goto join_posix_op_known;
13396
13397         case 'V':
13398             invert = 1;
13399             /* FALLTHROUGH */
13400         case 'v':
13401             arg = ANYOF_VERTWS;
13402             op = POSIXU;
13403             goto join_posix_op_known;
13404
13405         case 'S':
13406             invert = 1;
13407             /* FALLTHROUGH */
13408         case 's':
13409             arg = ANYOF_SPACE;
13410
13411           join_posix:
13412
13413             op = POSIXD + get_regex_charset(RExC_flags);
13414             if (op > POSIXA) {  /* /aa is same as /a */
13415                 op = POSIXA;
13416             }
13417             else if (op == POSIXL) {
13418                 RExC_contains_locale = 1;
13419             }
13420             else if (op == POSIXD) {
13421                 RExC_seen_d_op = TRUE;
13422             }
13423
13424           join_posix_op_known:
13425
13426             if (invert) {
13427                 op += NPOSIXD - POSIXD;
13428             }
13429
13430             ret = reg_node(pRExC_state, op);
13431             FLAGS(REGNODE_p(ret)) = namedclass_to_classnum(arg);
13432
13433             *flagp |= HASWIDTH|SIMPLE;
13434             /* FALLTHROUGH */
13435
13436           finish_meta_pat:
13437             if (   UCHARAT(RExC_parse + 1) == '{'
13438                 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13439             {
13440                 RExC_parse += 2;
13441                 vFAIL("Unescaped left brace in regex is illegal here");
13442             }
13443             nextchar(pRExC_state);
13444             Set_Node_Length(REGNODE_p(ret), 2); /* MJD */
13445             break;
13446         case 'p':
13447         case 'P':
13448             RExC_parse--;
13449
13450             ret = regclass(pRExC_state, flagp, depth+1,
13451                            TRUE, /* means just parse this element */
13452                            FALSE, /* don't allow multi-char folds */
13453                            FALSE, /* don't silence non-portable warnings.  It
13454                                      would be a bug if these returned
13455                                      non-portables */
13456                            (bool) RExC_strict,
13457                            TRUE, /* Allow an optimized regnode result */
13458                            NULL);
13459             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13460             /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13461              * multi-char folds are allowed.  */
13462             if (!ret)
13463                 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13464                       (UV) *flagp);
13465
13466             RExC_parse--;
13467
13468             Set_Node_Offset(REGNODE_p(ret), parse_start);
13469             Set_Node_Cur_Length(REGNODE_p(ret), parse_start - 2);
13470             nextchar(pRExC_state);
13471             break;
13472         case 'N':
13473             /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13474              * \N{...} evaluates to a sequence of more than one code points).
13475              * The function call below returns a regnode, which is our result.
13476              * The parameters cause it to fail if the \N{} evaluates to a
13477              * single code point; we handle those like any other literal.  The
13478              * reason that the multicharacter case is handled here and not as
13479              * part of the EXACtish code is because of quantifiers.  In
13480              * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13481              * this way makes that Just Happen. dmq.
13482              * join_exact() will join this up with adjacent EXACTish nodes
13483              * later on, if appropriate. */
13484             ++RExC_parse;
13485             if (grok_bslash_N(pRExC_state,
13486                               &ret,     /* Want a regnode returned */
13487                               NULL,     /* Fail if evaluates to a single code
13488                                            point */
13489                               NULL,     /* Don't need a count of how many code
13490                                            points */
13491                               flagp,
13492                               RExC_strict,
13493                               depth)
13494             ) {
13495                 break;
13496             }
13497
13498             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13499
13500             /* Here, evaluates to a single code point.  Go get that */
13501             RExC_parse = parse_start;
13502             goto defchar;
13503
13504         case 'k':    /* Handle \k<NAME> and \k'NAME' */
13505       parse_named_seq:
13506         {
13507             char ch;
13508             if (   RExC_parse >= RExC_end - 1
13509                 || ((   ch = RExC_parse[1]) != '<'
13510                                       && ch != '\''
13511                                       && ch != '{'))
13512             {
13513                 RExC_parse++;
13514                 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13515                 vFAIL2("Sequence %.2s... not terminated", parse_start);
13516             } else {
13517                 RExC_parse += 2;
13518                 ret = handle_named_backref(pRExC_state,
13519                                            flagp,
13520                                            parse_start,
13521                                            (ch == '<')
13522                                            ? '>'
13523                                            : (ch == '{')
13524                                              ? '}'
13525                                              : '\'');
13526             }
13527             break;
13528         }
13529         case 'g':
13530         case '1': case '2': case '3': case '4':
13531         case '5': case '6': case '7': case '8': case '9':
13532             {
13533                 I32 num;
13534                 bool hasbrace = 0;
13535
13536                 if (*RExC_parse == 'g') {
13537                     bool isrel = 0;
13538
13539                     RExC_parse++;
13540                     if (*RExC_parse == '{') {
13541                         RExC_parse++;
13542                         hasbrace = 1;
13543                     }
13544                     if (*RExC_parse == '-') {
13545                         RExC_parse++;
13546                         isrel = 1;
13547                     }
13548                     if (hasbrace && !isDIGIT(*RExC_parse)) {
13549                         if (isrel) RExC_parse--;
13550                         RExC_parse -= 2;
13551                         goto parse_named_seq;
13552                     }
13553
13554                     if (RExC_parse >= RExC_end) {
13555                         goto unterminated_g;
13556                     }
13557                     num = S_backref_value(RExC_parse, RExC_end);
13558                     if (num == 0)
13559                         vFAIL("Reference to invalid group 0");
13560                     else if (num == I32_MAX) {
13561                          if (isDIGIT(*RExC_parse))
13562                             vFAIL("Reference to nonexistent group");
13563                         else
13564                           unterminated_g:
13565                             vFAIL("Unterminated \\g... pattern");
13566                     }
13567
13568                     if (isrel) {
13569                         num = RExC_npar - num;
13570                         if (num < 1)
13571                             vFAIL("Reference to nonexistent or unclosed group");
13572                     }
13573                 }
13574                 else {
13575                     num = S_backref_value(RExC_parse, RExC_end);
13576                     /* bare \NNN might be backref or octal - if it is larger
13577                      * than or equal RExC_npar then it is assumed to be an
13578                      * octal escape. Note RExC_npar is +1 from the actual
13579                      * number of parens. */
13580                     /* Note we do NOT check if num == I32_MAX here, as that is
13581                      * handled by the RExC_npar check */
13582
13583                     if (
13584                         /* any numeric escape < 10 is always a backref */
13585                         num > 9
13586                         /* any numeric escape < RExC_npar is a backref */
13587                         && num >= RExC_npar
13588                         /* cannot be an octal escape if it starts with 8 */
13589                         && *RExC_parse != '8'
13590                         /* cannot be an octal escape it it starts with 9 */
13591                         && *RExC_parse != '9'
13592                     ) {
13593                         /* Probably not meant to be a backref, instead likely
13594                          * to be an octal character escape, e.g. \35 or \777.
13595                          * The above logic should make it obvious why using
13596                          * octal escapes in patterns is problematic. - Yves */
13597                         RExC_parse = parse_start;
13598                         goto defchar;
13599                     }
13600                 }
13601
13602                 /* At this point RExC_parse points at a numeric escape like
13603                  * \12 or \88 or something similar, which we should NOT treat
13604                  * as an octal escape. It may or may not be a valid backref
13605                  * escape. For instance \88888888 is unlikely to be a valid
13606                  * backref. */
13607                 while (isDIGIT(*RExC_parse))
13608                     RExC_parse++;
13609                 if (hasbrace) {
13610                     if (*RExC_parse != '}')
13611                         vFAIL("Unterminated \\g{...} pattern");
13612                     RExC_parse++;
13613                 }
13614                 if (num >= (I32)RExC_npar) {
13615
13616                     /* It might be a forward reference; we can't fail until we
13617                      * know, by completing the parse to get all the groups, and
13618                      * then reparsing */
13619                     if (RExC_total_parens > 0)  {
13620                         if (num >= RExC_total_parens)  {
13621                             vFAIL("Reference to nonexistent group");
13622                         }
13623                     }
13624                     else {
13625                         REQUIRE_PARENS_PASS;
13626                     }
13627                 }
13628                 RExC_sawback = 1;
13629                 ret = reganode(pRExC_state,
13630                                ((! FOLD)
13631                                  ? REF
13632                                  : (ASCII_FOLD_RESTRICTED)
13633                                    ? REFFA
13634                                    : (AT_LEAST_UNI_SEMANTICS)
13635                                      ? REFFU
13636                                      : (LOC)
13637                                        ? REFFL
13638                                        : REFF),
13639                                 num);
13640                 if (OP(REGNODE_p(ret)) == REFF) {
13641                     RExC_seen_d_op = TRUE;
13642                 }
13643                 *flagp |= HASWIDTH;
13644
13645                 /* override incorrect value set in reganode MJD */
13646                 Set_Node_Offset(REGNODE_p(ret), parse_start);
13647                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
13648                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13649                                         FALSE /* Don't force to /x */ );
13650             }
13651             break;
13652         case '\0':
13653             if (RExC_parse >= RExC_end)
13654                 FAIL("Trailing \\");
13655             /* FALLTHROUGH */
13656         default:
13657             /* Do not generate "unrecognized" warnings here, we fall
13658                back into the quick-grab loop below */
13659             RExC_parse = parse_start;
13660             goto defchar;
13661         } /* end of switch on a \foo sequence */
13662         break;
13663
13664     case '#':
13665
13666         /* '#' comments should have been spaced over before this function was
13667          * called */
13668         assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
13669         /*
13670         if (RExC_flags & RXf_PMf_EXTENDED) {
13671             RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
13672             if (RExC_parse < RExC_end)
13673                 goto tryagain;
13674         }
13675         */
13676
13677         /* FALLTHROUGH */
13678
13679     default:
13680           defchar: {
13681
13682             /* Here, we have determined that the next thing is probably a
13683              * literal character.  RExC_parse points to the first byte of its
13684              * definition.  (It still may be an escape sequence that evaluates
13685              * to a single character) */
13686
13687             STRLEN len = 0;
13688             UV ender = 0;
13689             char *p;
13690             char *s;
13691
13692 /* This allows us to fill a node with just enough spare so that if the final
13693  * character folds, its expansion is guaranteed to fit */
13694 #define MAX_NODE_STRING_SIZE (255-UTF8_MAXBYTES_CASE)
13695
13696             char *s0;
13697             U8 upper_parse = MAX_NODE_STRING_SIZE;
13698
13699             /* We start out as an EXACT node, even if under /i, until we find a
13700              * character which is in a fold.  The algorithm now segregates into
13701              * separate nodes, characters that fold from those that don't under
13702              * /i.  (This hopefully will create nodes that are fixed strings
13703              * even under /i, giving the optimizer something to grab on to.)
13704              * So, if a node has something in it and the next character is in
13705              * the opposite category, that node is closed up, and the function
13706              * returns.  Then regatom is called again, and a new node is
13707              * created for the new category. */
13708             U8 node_type = EXACT;
13709
13710             /* Assume the node will be fully used; the excess is given back at
13711              * the end.  We can't make any other length assumptions, as a byte
13712              * input sequence could shrink down. */
13713             Ptrdiff_t initial_size = STR_SZ(256);
13714
13715             bool next_is_quantifier;
13716             char * oldp = NULL;
13717
13718             /* We can convert EXACTF nodes to EXACTFU if they contain only
13719              * characters that match identically regardless of the target
13720              * string's UTF8ness.  The reason to do this is that EXACTF is not
13721              * trie-able, EXACTFU is, and EXACTFU requires fewer operations at
13722              * runtime.
13723              *
13724              * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
13725              * contain only above-Latin1 characters (hence must be in UTF8),
13726              * which don't participate in folds with Latin1-range characters,
13727              * as the latter's folds aren't known until runtime. */
13728             bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
13729
13730             /* Single-character EXACTish nodes are almost always SIMPLE.  This
13731              * allows us to override this as encountered */
13732             U8 maybe_SIMPLE = SIMPLE;
13733
13734             /* Does this node contain something that can't match unless the
13735              * target string is (also) in UTF-8 */
13736             bool requires_utf8_target = FALSE;
13737
13738             /* The sequence 'ss' is problematic in non-UTF-8 patterns. */
13739             bool has_ss = FALSE;
13740
13741             /* So is the MICRO SIGN */
13742             bool has_micro_sign = FALSE;
13743
13744             /* Allocate an EXACT node.  The node_type may change below to
13745              * another EXACTish node, but since the size of the node doesn't
13746              * change, it works */
13747             ret = regnode_guts(pRExC_state, node_type, initial_size, "exact");
13748             FILL_NODE(ret, node_type);
13749             RExC_emit++;
13750
13751             s = STRING(REGNODE_p(ret));
13752
13753             s0 = s;
13754
13755           reparse:
13756
13757             /* This breaks under rare circumstances.  If folding, we do not
13758              * want to split a node at a character that is a non-final in a
13759              * multi-char fold, as an input string could just happen to want to
13760              * match across the node boundary.  The code at the end of the loop
13761              * looks for this, and backs off until it finds not such a
13762              * character, but it is possible (though extremely, extremely
13763              * unlikely) for all characters in the node to be non-final fold
13764              * ones, in which case we just leave the node fully filled, and
13765              * hope that it doesn't match the string in just the wrong place */
13766
13767             assert( ! UTF     /* Is at the beginning of a character */
13768                    || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
13769                    || UTF8_IS_START(UCHARAT(RExC_parse)));
13770
13771
13772             /* Here, we have a literal character.  Find the maximal string of
13773              * them in the input that we can fit into a single EXACTish node.
13774              * We quit at the first non-literal or when the node gets full, or
13775              * under /i the categorization of folding/non-folding character
13776              * changes */
13777             for (p = RExC_parse; len < upper_parse && p < RExC_end; ) {
13778
13779                 /* In most cases each iteration adds one byte to the output.
13780                  * The exceptions override this */
13781                 Size_t added_len = 1;
13782
13783                 oldp = p;
13784
13785                 /* White space has already been ignored */
13786                 assert(   (RExC_flags & RXf_PMf_EXTENDED) == 0
13787                        || ! is_PATWS_safe((p), RExC_end, UTF));
13788
13789                 switch ((U8)*p) {
13790                 case '^':
13791                 case '$':
13792                 case '.':
13793                 case '[':
13794                 case '(':
13795                 case ')':
13796                 case '|':
13797                     goto loopdone;
13798                 case '\\':
13799                     /* Literal Escapes Switch
13800
13801                        This switch is meant to handle escape sequences that
13802                        resolve to a literal character.
13803
13804                        Every escape sequence that represents something
13805                        else, like an assertion or a char class, is handled
13806                        in the switch marked 'Special Escapes' above in this
13807                        routine, but also has an entry here as anything that
13808                        isn't explicitly mentioned here will be treated as
13809                        an unescaped equivalent literal.
13810                     */
13811
13812                     switch ((U8)*++p) {
13813
13814                     /* These are all the special escapes. */
13815                     case 'A':             /* Start assertion */
13816                     case 'b': case 'B':   /* Word-boundary assertion*/
13817                     case 'C':             /* Single char !DANGEROUS! */
13818                     case 'd': case 'D':   /* digit class */
13819                     case 'g': case 'G':   /* generic-backref, pos assertion */
13820                     case 'h': case 'H':   /* HORIZWS */
13821                     case 'k': case 'K':   /* named backref, keep marker */
13822                     case 'p': case 'P':   /* Unicode property */
13823                               case 'R':   /* LNBREAK */
13824                     case 's': case 'S':   /* space class */
13825                     case 'v': case 'V':   /* VERTWS */
13826                     case 'w': case 'W':   /* word class */
13827                     case 'X':             /* eXtended Unicode "combining
13828                                              character sequence" */
13829                     case 'z': case 'Z':   /* End of line/string assertion */
13830                         --p;
13831                         goto loopdone;
13832
13833                     /* Anything after here is an escape that resolves to a
13834                        literal. (Except digits, which may or may not)
13835                      */
13836                     case 'n':
13837                         ender = '\n';
13838                         p++;
13839                         break;
13840                     case 'N': /* Handle a single-code point named character. */
13841                         RExC_parse = p + 1;
13842                         if (! grok_bslash_N(pRExC_state,
13843                                             NULL,   /* Fail if evaluates to
13844                                                        anything other than a
13845                                                        single code point */
13846                                             &ender, /* The returned single code
13847                                                        point */
13848                                             NULL,   /* Don't need a count of
13849                                                        how many code points */
13850                                             flagp,
13851                                             RExC_strict,
13852                                             depth)
13853                         ) {
13854                             if (*flagp & NEED_UTF8)
13855                                 FAIL("panic: grok_bslash_N set NEED_UTF8");
13856                             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13857
13858                             /* Here, it wasn't a single code point.  Go close
13859                              * up this EXACTish node.  The switch() prior to
13860                              * this switch handles the other cases */
13861                             RExC_parse = p = oldp;
13862                             goto loopdone;
13863                         }
13864                         p = RExC_parse;
13865                         RExC_parse = parse_start;
13866
13867                         /* The \N{} means the pattern, if previously /d,
13868                          * becomes /u.  That means it can't be an EXACTF node,
13869                          * but an EXACTFU */
13870                         if (node_type == EXACTF) {
13871                             node_type = EXACTFU;
13872
13873                             /* If the node already contains something that
13874                              * differs between EXACTF and EXACTFU, reparse it
13875                              * as EXACTFU */
13876                             if (! maybe_exactfu) {
13877                                 len = 0;
13878                                 s = s0;
13879                                 goto reparse;
13880                             }
13881                         }
13882
13883                         break;
13884                     case 'r':
13885                         ender = '\r';
13886                         p++;
13887                         break;
13888                     case 't':
13889                         ender = '\t';
13890                         p++;
13891                         break;
13892                     case 'f':
13893                         ender = '\f';
13894                         p++;
13895                         break;
13896                     case 'e':
13897                         ender = ESC_NATIVE;
13898                         p++;
13899                         break;
13900                     case 'a':
13901                         ender = '\a';
13902                         p++;
13903                         break;
13904                     case 'o':
13905                         {
13906                             UV result;
13907                             const char* error_msg;
13908
13909                             bool valid = grok_bslash_o(&p,
13910                                                        RExC_end,
13911                                                        &result,
13912                                                        &error_msg,
13913                                                        TO_OUTPUT_WARNINGS(p),
13914                                                        (bool) RExC_strict,
13915                                                        TRUE, /* Output warnings
13916                                                                 for non-
13917                                                                 portables */
13918                                                        UTF);
13919                             if (! valid) {
13920                                 RExC_parse = p; /* going to die anyway; point
13921                                                    to exact spot of failure */
13922                                 vFAIL(error_msg);
13923                             }
13924                             UPDATE_WARNINGS_LOC(p - 1);
13925                             ender = result;
13926                             break;
13927                         }
13928                     case 'x':
13929                         {
13930                             UV result = UV_MAX; /* initialize to erroneous
13931                                                    value */
13932                             const char* error_msg;
13933
13934                             bool valid = grok_bslash_x(&p,
13935                                                        RExC_end,
13936                                                        &result,
13937                                                        &error_msg,
13938                                                        TO_OUTPUT_WARNINGS(p),
13939                                                        (bool) RExC_strict,
13940                                                        TRUE, /* Silence warnings
13941                                                                 for non-
13942                                                                 portables */
13943                                                        UTF);
13944                             if (! valid) {
13945                                 RExC_parse = p; /* going to die anyway; point
13946                                                    to exact spot of failure */
13947                                 vFAIL(error_msg);
13948                             }
13949                             UPDATE_WARNINGS_LOC(p - 1);
13950                             ender = result;
13951
13952                             if (ender < 0x100) {
13953 #ifdef EBCDIC
13954                                 if (RExC_recode_x_to_native) {
13955                                     ender = LATIN1_TO_NATIVE(ender);
13956                                 }
13957 #endif
13958                             }
13959                             break;
13960                         }
13961                     case 'c':
13962                         p++;
13963                         ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p));
13964                         UPDATE_WARNINGS_LOC(p);
13965                         p++;
13966                         break;
13967                     case '8': case '9': /* must be a backreference */
13968                         --p;
13969                         /* we have an escape like \8 which cannot be an octal escape
13970                          * so we exit the loop, and let the outer loop handle this
13971                          * escape which may or may not be a legitimate backref. */
13972                         goto loopdone;
13973                     case '1': case '2': case '3':case '4':
13974                     case '5': case '6': case '7':
13975                         /* When we parse backslash escapes there is ambiguity
13976                          * between backreferences and octal escapes. Any escape
13977                          * from \1 - \9 is a backreference, any multi-digit
13978                          * escape which does not start with 0 and which when
13979                          * evaluated as decimal could refer to an already
13980                          * parsed capture buffer is a back reference. Anything
13981                          * else is octal.
13982                          *
13983                          * Note this implies that \118 could be interpreted as
13984                          * 118 OR as "\11" . "8" depending on whether there
13985                          * were 118 capture buffers defined already in the
13986                          * pattern.  */
13987
13988                         /* NOTE, RExC_npar is 1 more than the actual number of
13989                          * parens we have seen so far, hence the "<" as opposed
13990                          * to "<=" */
13991                         if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
13992                         {  /* Not to be treated as an octal constant, go
13993                                    find backref */
13994                             --p;
13995                             goto loopdone;
13996                         }
13997                         /* FALLTHROUGH */
13998                     case '0':
13999                         {
14000                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
14001                             STRLEN numlen = 3;
14002                             ender = grok_oct(p, &numlen, &flags, NULL);
14003                             p += numlen;
14004                             if (   isDIGIT(*p)  /* like \08, \178 */
14005                                 && ckWARN(WARN_REGEXP)
14006                                 && numlen < 3)
14007                             {
14008                                 reg_warn_non_literal_string(
14009                                          p + 1,
14010                                          form_short_octal_warning(p, numlen));
14011                             }
14012                         }
14013                         break;
14014                     case '\0':
14015                         if (p >= RExC_end)
14016                             FAIL("Trailing \\");
14017                         /* FALLTHROUGH */
14018                     default:
14019                         if (isALPHANUMERIC(*p)) {
14020                             /* An alpha followed by '{' is going to fail next
14021                              * iteration, so don't output this warning in that
14022                              * case */
14023                             if (! isALPHA(*p) || *(p + 1) != '{') {
14024                                 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14025                                                   " passed through", p);
14026                             }
14027                         }
14028                         goto normal_default;
14029                     } /* End of switch on '\' */
14030                     break;
14031                 case '{':
14032                     /* Trying to gain new uses for '{' without breaking too
14033                      * much existing code is hard.  The solution currently
14034                      * adopted is:
14035                      *  1)  If there is no ambiguity that a '{' should always
14036                      *      be taken literally, at the start of a construct, we
14037                      *      just do so.
14038                      *  2)  If the literal '{' conflicts with our desired use
14039                      *      of it as a metacharacter, we die.  The deprecation
14040                      *      cycles for this have come and gone.
14041                      *  3)  If there is ambiguity, we raise a simple warning.
14042                      *      This could happen, for example, if the user
14043                      *      intended it to introduce a quantifier, but slightly
14044                      *      misspelled the quantifier.  Without this warning,
14045                      *      the quantifier would silently be taken as a literal
14046                      *      string of characters instead of a meta construct */
14047                     if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14048                         if (      RExC_strict
14049                             || (  p > parse_start + 1
14050                                 && isALPHA_A(*(p - 1))
14051                                 && *(p - 2) == '\\')
14052                             || new_regcurly(p, RExC_end))
14053                         {
14054                             RExC_parse = p + 1;
14055                             vFAIL("Unescaped left brace in regex is "
14056                                   "illegal here");
14057                         }
14058                         ckWARNreg(p + 1, "Unescaped left brace in regex is"
14059                                          " passed through");
14060                     }
14061                     goto normal_default;
14062                 case '}':
14063                 case ']':
14064                     if (p > RExC_parse && RExC_strict) {
14065                         ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14066                     }
14067                     /*FALLTHROUGH*/
14068                 default:    /* A literal character */
14069                   normal_default:
14070                     if (! UTF8_IS_INVARIANT(*p) && UTF) {
14071                         STRLEN numlen;
14072                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14073                                                &numlen, UTF8_ALLOW_DEFAULT);
14074                         p += numlen;
14075                     }
14076                     else
14077                         ender = (U8) *p++;
14078                     break;
14079                 } /* End of switch on the literal */
14080
14081                 /* Here, have looked at the literal character, and <ender>
14082                  * contains its ordinal; <p> points to the character after it.
14083                  * */
14084
14085                 if (ender > 255) {
14086                     REQUIRE_UTF8(flagp);
14087                 }
14088
14089                 /* We need to check if the next non-ignored thing is a
14090                  * quantifier.  Move <p> to after anything that should be
14091                  * ignored, which, as a side effect, positions <p> for the next
14092                  * loop iteration */
14093                 skip_to_be_ignored_text(pRExC_state, &p,
14094                                         FALSE /* Don't force to /x */ );
14095
14096                 /* If the next thing is a quantifier, it applies to this
14097                  * character only, which means that this character has to be in
14098                  * its own node and can't just be appended to the string in an
14099                  * existing node, so if there are already other characters in
14100                  * the node, close the node with just them, and set up to do
14101                  * this character again next time through, when it will be the
14102                  * only thing in its new node */
14103
14104                 next_is_quantifier =    LIKELY(p < RExC_end)
14105                                      && UNLIKELY(ISMULT2(p));
14106
14107                 if (next_is_quantifier && LIKELY(len)) {
14108                     p = oldp;
14109                     goto loopdone;
14110                 }
14111
14112                 /* Ready to add 'ender' to the node */
14113
14114                 if (! FOLD) {  /* The simple case, just append the literal */
14115
14116                       not_fold_common:
14117                         if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14118                             *(s++) = (char) ender;
14119                         }
14120                         else {
14121                             U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14122                             added_len = (char *) new_s - s;
14123                             s = (char *) new_s;
14124
14125                             if (ender > 255)  {
14126                                 requires_utf8_target = TRUE;
14127                             }
14128                         }
14129                 }
14130                 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14131
14132                     /* Here are folding under /l, and the code point is
14133                      * problematic.  If this is the first character in the
14134                      * node, change the node type to folding.   Otherwise, if
14135                      * this is the first problematic character, close up the
14136                      * existing node, so can start a new node with this one */
14137                     if (! len) {
14138                         node_type = EXACTFL;
14139                         RExC_contains_locale = 1;
14140                     }
14141                     else if (node_type == EXACT) {
14142                         p = oldp;
14143                         goto loopdone;
14144                     }
14145
14146                     /* This problematic code point means we can't simplify
14147                      * things */
14148                     maybe_exactfu = FALSE;
14149
14150                     /* Here, we are adding a problematic fold character.
14151                      * "Problematic" in this context means that its fold isn't
14152                      * known until runtime.  (The non-problematic code points
14153                      * are the above-Latin1 ones that fold to also all
14154                      * above-Latin1.  Their folds don't vary no matter what the
14155                      * locale is.) But here we have characters whose fold
14156                      * depends on the locale.  We just add in the unfolded
14157                      * character, and wait until runtime to fold it */
14158                     goto not_fold_common;
14159                 }
14160                 else /* regular fold; see if actually is in a fold */
14161                      if (   (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14162                          || (ender > 255
14163                             && ! _invlist_contains_cp(PL_in_some_fold, ender)))
14164                 {
14165                     /* Here, folding, but the character isn't in a fold.
14166                      *
14167                      * Start a new node if previous characters in the node were
14168                      * folded */
14169                     if (len && node_type != EXACT) {
14170                         p = oldp;
14171                         goto loopdone;
14172                     }
14173
14174                     /* Here, continuing a node with non-folded characters.  Add
14175                      * this one */
14176                     goto not_fold_common;
14177                 }
14178                 else {  /* Here, does participate in some fold */
14179
14180                     /* If this is the first character in the node, change its
14181                      * type to folding.  Otherwise, if this is the first
14182                      * folding character in the node, close up the existing
14183                      * node, so can start a new node with this one.  */
14184                     if (! len) {
14185                         node_type = compute_EXACTish(pRExC_state);
14186                     }
14187                     else if (node_type == EXACT) {
14188                         p = oldp;
14189                         goto loopdone;
14190                     }
14191
14192                     if (UTF) {  /* Use the folded value */
14193                         if (UVCHR_IS_INVARIANT(ender)) {
14194                             *(s)++ = (U8) toFOLD(ender);
14195                         }
14196                         else {
14197                             ender = _to_uni_fold_flags(
14198                                     ender,
14199                                     (U8 *) s,
14200                                     &added_len,
14201                                     FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14202                                                     ? FOLD_FLAGS_NOMIX_ASCII
14203                                                     : 0));
14204                             s += added_len;
14205
14206                             if (   ender > 255
14207                                 && LIKELY(ender != GREEK_SMALL_LETTER_MU))
14208                             {
14209                                 /* U+B5 folds to the MU, so its possible for a
14210                                  * non-UTF-8 target to match it */
14211                                 requires_utf8_target = TRUE;
14212                             }
14213                         }
14214                     }
14215                     else {
14216
14217                         /* Here is non-UTF8.  First, see if the character's
14218                          * fold differs between /d and /u. */
14219                         if (PL_fold[ender] != PL_fold_latin1[ender]) {
14220                             maybe_exactfu = FALSE;
14221                         }
14222
14223 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
14224    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
14225                                       || UNICODE_DOT_DOT_VERSION > 0)
14226
14227                         /* On non-ancient Unicode versions, this includes the
14228                          * multi-char fold SHARP S to 'ss' */
14229
14230                         if (   UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)
14231                                  || (   isALPHA_FOLD_EQ(ender, 's')
14232                                      && len > 0
14233                                      && isALPHA_FOLD_EQ(*(s-1), 's')))
14234                         {
14235                             /* Here, we have one of the following:
14236                              *  a)  a SHARP S.  This folds to 'ss' only under
14237                              *      /u rules.  If we are in that situation,
14238                              *      fold the SHARP S to 'ss'.  See the comments
14239                              *      for join_exact() as to why we fold this
14240                              *      non-UTF at compile time, and no others.
14241                              *  b)  'ss'.  When under /u, there's nothing
14242                              *      special needed to be done here.  The
14243                              *      previous iteration handled the first 's',
14244                              *      and this iteration will handle the second.
14245                              *      If, on the otherhand it's not /u, we have
14246                              *      to exclude the possibility of moving to /u,
14247                              *      so that we won't generate an unwanted
14248                              *      match, unless, at runtime, the target
14249                              *      string is in UTF-8.
14250                              * */
14251
14252                             has_ss = TRUE;
14253                             maybe_exactfu = FALSE;  /* Can't generate an
14254                                                        EXACTFU node (unless we
14255                                                        already are in one) */
14256                             if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14257                                 maybe_SIMPLE = 0;
14258                                 if (node_type == EXACTFU) {
14259                                     *(s++) = 's';
14260
14261                                     /* Let the code below add in the extra 's' */
14262                                     ender = 's';
14263                                     added_len = 2;
14264                                 }
14265                             }
14266                         }
14267 #endif
14268
14269                         else if (UNLIKELY(ender == MICRO_SIGN)) {
14270                             has_micro_sign = TRUE;
14271                         }
14272
14273                         *(s++) = (char) (DEPENDS_SEMANTICS)
14274                                         ? toFOLD(ender)
14275
14276                                           /* Under /u, the fold of any
14277                                            * character in the 0-255 range
14278                                            * happens to be its lowercase
14279                                            * equivalent, except for LATIN SMALL
14280                                            * LETTER SHARP S, which was handled
14281                                            * above, and the MICRO SIGN, whose
14282                                            * fold requires UTF-8 to represent.
14283                                            * */
14284                                         : toLOWER_L1(ender);
14285                     }
14286                 } /* End of adding current character to the node */
14287
14288                 len += added_len;
14289
14290                 if (next_is_quantifier) {
14291
14292                     /* Here, the next input is a quantifier, and to get here,
14293                      * the current character is the only one in the node. */
14294                     goto loopdone;
14295                 }
14296
14297             } /* End of loop through literal characters */
14298
14299             /* Here we have either exhausted the input or ran out of room in
14300              * the node.  (If we encountered a character that can't be in the
14301              * node, transfer is made directly to <loopdone>, and so we
14302              * wouldn't have fallen off the end of the loop.)  In the latter
14303              * case, we artificially have to split the node into two, because
14304              * we just don't have enough space to hold everything.  This
14305              * creates a problem if the final character participates in a
14306              * multi-character fold in the non-final position, as a match that
14307              * should have occurred won't, due to the way nodes are matched,
14308              * and our artificial boundary.  So back off until we find a non-
14309              * problematic character -- one that isn't at the beginning or
14310              * middle of such a fold.  (Either it doesn't participate in any
14311              * folds, or appears only in the final position of all the folds it
14312              * does participate in.)  A better solution with far fewer false
14313              * positives, and that would fill the nodes more completely, would
14314              * be to actually have available all the multi-character folds to
14315              * test against, and to back-off only far enough to be sure that
14316              * this node isn't ending with a partial one.  <upper_parse> is set
14317              * further below (if we need to reparse the node) to include just
14318              * up through that final non-problematic character that this code
14319              * identifies, so when it is set to less than the full node, we can
14320              * skip the rest of this */
14321             if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
14322                 PERL_UINT_FAST8_T backup_count = 0;
14323
14324                 const STRLEN full_len = len;
14325
14326                 assert(len >= MAX_NODE_STRING_SIZE);
14327
14328                 /* Here, <s> points to just beyond where we have output the
14329                  * final character of the node.  Look backwards through the
14330                  * string until find a non- problematic character */
14331
14332                 if (! UTF) {
14333
14334                     /* This has no multi-char folds to non-UTF characters */
14335                     if (ASCII_FOLD_RESTRICTED) {
14336                         goto loopdone;
14337                     }
14338
14339                     while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) {
14340                         backup_count++;
14341                     }
14342                     len = s - s0 + 1;
14343                 }
14344                 else {
14345
14346                     /* Point to the first byte of the final character */
14347                     s = (char *) utf8_hop((U8 *) s, -1);
14348
14349                     while (s >= s0) {   /* Search backwards until find
14350                                            a non-problematic char */
14351                         if (UTF8_IS_INVARIANT(*s)) {
14352
14353                             /* There are no ascii characters that participate
14354                              * in multi-char folds under /aa.  In EBCDIC, the
14355                              * non-ascii invariants are all control characters,
14356                              * so don't ever participate in any folds. */
14357                             if (ASCII_FOLD_RESTRICTED
14358                                 || ! IS_NON_FINAL_FOLD(*s))
14359                             {
14360                                 break;
14361                             }
14362                         }
14363                         else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
14364                             if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE(
14365                                                                   *s, *(s+1))))
14366                             {
14367                                 break;
14368                             }
14369                         }
14370                         else if (! _invlist_contains_cp(
14371                                         PL_NonFinalFold,
14372                                         valid_utf8_to_uvchr((U8 *) s, NULL)))
14373                         {
14374                             break;
14375                         }
14376
14377                         /* Here, the current character is problematic in that
14378                          * it does occur in the non-final position of some
14379                          * fold, so try the character before it, but have to
14380                          * special case the very first byte in the string, so
14381                          * we don't read outside the string */
14382                         s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
14383                         backup_count++;
14384                     } /* End of loop backwards through the string */
14385
14386                     /* If there were only problematic characters in the string,
14387                      * <s> will point to before s0, in which case the length
14388                      * should be 0, otherwise include the length of the
14389                      * non-problematic character just found */
14390                     len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
14391                 }
14392
14393                 /* Here, have found the final character, if any, that is
14394                  * non-problematic as far as ending the node without splitting
14395                  * it across a potential multi-char fold.  <len> contains the
14396                  * number of bytes in the node up-to and including that
14397                  * character, or is 0 if there is no such character, meaning
14398                  * the whole node contains only problematic characters.  In
14399                  * this case, give up and just take the node as-is.  We can't
14400                  * do any better */
14401                 if (len == 0) {
14402                     len = full_len;
14403
14404                 } else {
14405
14406                     /* Here, the node does contain some characters that aren't
14407                      * problematic.  If we didn't have to backup any, then the
14408                      * final character in the node is non-problematic, and we
14409                      * can take the node as-is */
14410                     if (backup_count == 0) {
14411                         goto loopdone;
14412                     }
14413                     else if (backup_count == 1) {
14414
14415                         /* If the final character is problematic, but the
14416                          * penultimate is not, back-off that last character to
14417                          * later start a new node with it */
14418                         p = oldp;
14419                         goto loopdone;
14420                     }
14421
14422                     /* Here, the final non-problematic character is earlier
14423                      * in the input than the penultimate character.  What we do
14424                      * is reparse from the beginning, going up only as far as
14425                      * this final ok one, thus guaranteeing that the node ends
14426                      * in an acceptable character.  The reason we reparse is
14427                      * that we know how far in the character is, but we don't
14428                      * know how to correlate its position with the input parse.
14429                      * An alternate implementation would be to build that
14430                      * correlation as we go along during the original parse,
14431                      * but that would entail extra work for every node, whereas
14432                      * this code gets executed only when the string is too
14433                      * large for the node, and the final two characters are
14434                      * problematic, an infrequent occurrence.  Yet another
14435                      * possible strategy would be to save the tail of the
14436                      * string, and the next time regatom is called, initialize
14437                      * with that.  The problem with this is that unless you
14438                      * back off one more character, you won't be guaranteed
14439                      * regatom will get called again, unless regbranch,
14440                      * regpiece ... are also changed.  If you do back off that
14441                      * extra character, so that there is input guaranteed to
14442                      * force calling regatom, you can't handle the case where
14443                      * just the first character in the node is acceptable.  I
14444                      * (khw) decided to try this method which doesn't have that
14445                      * pitfall; if performance issues are found, we can do a
14446                      * combination of the current approach plus that one */
14447                     upper_parse = len;
14448                     len = 0;
14449                     s = s0;
14450                     goto reparse;
14451                 }
14452             }   /* End of verifying node ends with an appropriate char */
14453
14454           loopdone:   /* Jumped to when encounters something that shouldn't be
14455                          in the node */
14456
14457             /* Free up any over-allocated space */
14458             change_engine_size(pRExC_state, - (initial_size - STR_SZ(len)));
14459
14460             /* I (khw) don't know if you can get here with zero length, but the
14461              * old code handled this situation by creating a zero-length EXACT
14462              * node.  Might as well be NOTHING instead */
14463             if (len == 0) {
14464                 OP(REGNODE_p(ret)) = NOTHING;
14465             }
14466             else {
14467
14468                 /* If the node type is EXACT here, check to see if it
14469                  * should be EXACTL, or EXACT_ONLY8. */
14470                 if (node_type == EXACT) {
14471                     if (LOC) {
14472                         node_type = EXACTL;
14473                     }
14474                     else if (requires_utf8_target) {
14475                         node_type = EXACT_ONLY8;
14476                     }
14477                 } else if (FOLD) {
14478                     if (    UNLIKELY(has_micro_sign || has_ss)
14479                         && (node_type == EXACTFU || (   node_type == EXACTF
14480                                                      && maybe_exactfu)))
14481                     {   /* These two conditions are problematic in non-UTF-8
14482                            EXACTFU nodes. */
14483                         assert(! UTF);
14484                         node_type = EXACTFUP;
14485                     }
14486                     else if (node_type == EXACTFL) {
14487
14488                         /* 'maybe_exactfu' is deliberately set above to
14489                          * indicate this node type, where all code points in it
14490                          * are above 255 */
14491                         if (maybe_exactfu) {
14492                             node_type = EXACTFLU8;
14493                         }
14494                     }
14495                     else if (node_type == EXACTF) {  /* Means is /di */
14496
14497                         /* If 'maybe_exactfu' is clear, then we need to stay
14498                          * /di.  If it is set, it means there are no code
14499                          * points that match differently depending on UTF8ness
14500                          * of the target string, so it can become an EXACTFU
14501                          * node */
14502                         if (! maybe_exactfu) {
14503                             RExC_seen_d_op = TRUE;
14504                         }
14505                         else if (   isALPHA_FOLD_EQ(* STRING(REGNODE_p(ret)), 's')
14506                                  || isALPHA_FOLD_EQ(ender, 's'))
14507                         {
14508                             /* But, if the node begins or ends in an 's' we
14509                              * have to defer changing it into an EXACTFU, as
14510                              * the node could later get joined with another one
14511                              * that ends or begins with 's' creating an 'ss'
14512                              * sequence which would then wrongly match the
14513                              * sharp s without the target being UTF-8.  We
14514                              * create a special node that we resolve later when
14515                              * we join nodes together */
14516
14517                             node_type = EXACTFU_S_EDGE;
14518                         }
14519                         else {
14520                             node_type = EXACTFU;
14521                         }
14522                     }
14523
14524                     if (requires_utf8_target && node_type == EXACTFU) {
14525                         node_type = EXACTFU_ONLY8;
14526                     }
14527                 }
14528
14529                 OP(REGNODE_p(ret)) = node_type;
14530                 STR_LEN(REGNODE_p(ret)) = len;
14531                 RExC_emit += STR_SZ(len);
14532
14533                 /* If the node isn't a single character, it can't be SIMPLE */
14534                 if (len > ((UTF) ? UVCHR_SKIP(ender) : 1)) {
14535                     maybe_SIMPLE = 0;
14536                 }
14537
14538                 *flagp |= HASWIDTH | maybe_SIMPLE;
14539             }
14540
14541             Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
14542             RExC_parse = p;
14543
14544             {
14545                 /* len is STRLEN which is unsigned, need to copy to signed */
14546                 IV iv = len;
14547                 if (iv < 0)
14548                     vFAIL("Internal disaster");
14549             }
14550
14551         } /* End of label 'defchar:' */
14552         break;
14553     } /* End of giant switch on input character */
14554
14555     /* Position parse to next real character */
14556     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14557                                             FALSE /* Don't force to /x */ );
14558     if (   *RExC_parse == '{'
14559         && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
14560     {
14561         if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
14562             RExC_parse++;
14563             vFAIL("Unescaped left brace in regex is illegal here");
14564         }
14565         ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
14566                                   " passed through");
14567     }
14568
14569     return(ret);
14570 }
14571
14572
14573 STATIC void
14574 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
14575 {
14576     /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'.  It
14577      * sets up the bitmap and any flags, removing those code points from the
14578      * inversion list, setting it to NULL should it become completely empty */
14579
14580     dVAR;
14581
14582     PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
14583     assert(PL_regkind[OP(node)] == ANYOF);
14584
14585     /* There is no bitmap for this node type */
14586     if (OP(node) == ANYOFH) {
14587         return;
14588     }
14589
14590     ANYOF_BITMAP_ZERO(node);
14591     if (*invlist_ptr) {
14592
14593         /* This gets set if we actually need to modify things */
14594         bool change_invlist = FALSE;
14595
14596         UV start, end;
14597
14598         /* Start looking through *invlist_ptr */
14599         invlist_iterinit(*invlist_ptr);
14600         while (invlist_iternext(*invlist_ptr, &start, &end)) {
14601             UV high;
14602             int i;
14603
14604             if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
14605                 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
14606             }
14607
14608             /* Quit if are above what we should change */
14609             if (start >= NUM_ANYOF_CODE_POINTS) {
14610                 break;
14611             }
14612
14613             change_invlist = TRUE;
14614
14615             /* Set all the bits in the range, up to the max that we are doing */
14616             high = (end < NUM_ANYOF_CODE_POINTS - 1)
14617                    ? end
14618                    : NUM_ANYOF_CODE_POINTS - 1;
14619             for (i = start; i <= (int) high; i++) {
14620                 if (! ANYOF_BITMAP_TEST(node, i)) {
14621                     ANYOF_BITMAP_SET(node, i);
14622                 }
14623             }
14624         }
14625         invlist_iterfinish(*invlist_ptr);
14626
14627         /* Done with loop; remove any code points that are in the bitmap from
14628          * *invlist_ptr; similarly for code points above the bitmap if we have
14629          * a flag to match all of them anyways */
14630         if (change_invlist) {
14631             _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
14632         }
14633         if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
14634             _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
14635         }
14636
14637         /* If have completely emptied it, remove it completely */
14638         if (_invlist_len(*invlist_ptr) == 0) {
14639             SvREFCNT_dec_NN(*invlist_ptr);
14640             *invlist_ptr = NULL;
14641         }
14642     }
14643 }
14644
14645 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
14646    Character classes ([:foo:]) can also be negated ([:^foo:]).
14647    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
14648    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
14649    but trigger failures because they are currently unimplemented. */
14650
14651 #define POSIXCC_DONE(c)   ((c) == ':')
14652 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
14653 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
14654 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
14655
14656 #define WARNING_PREFIX              "Assuming NOT a POSIX class since "
14657 #define NO_BLANKS_POSIX_WARNING     "no blanks are allowed in one"
14658 #define SEMI_COLON_POSIX_WARNING    "a semi-colon was found instead of a colon"
14659
14660 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
14661
14662 /* 'posix_warnings' and 'warn_text' are names of variables in the following
14663  * routine. q.v. */
14664 #define ADD_POSIX_WARNING(p, text)  STMT_START {                            \
14665         if (posix_warnings) {                                               \
14666             if (! RExC_warn_text ) RExC_warn_text =                         \
14667                                          (AV *) sv_2mortal((SV *) newAV()); \
14668             av_push(RExC_warn_text, Perl_newSVpvf(aTHX_                     \
14669                                              WARNING_PREFIX                 \
14670                                              text                           \
14671                                              REPORT_LOCATION,               \
14672                                              REPORT_LOCATION_ARGS(p)));     \
14673         }                                                                   \
14674     } STMT_END
14675 #define CLEAR_POSIX_WARNINGS()                                              \
14676     STMT_START {                                                            \
14677         if (posix_warnings && RExC_warn_text)                               \
14678             av_clear(RExC_warn_text);                                       \
14679     } STMT_END
14680
14681 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret)                                \
14682     STMT_START {                                                            \
14683         CLEAR_POSIX_WARNINGS();                                             \
14684         return ret;                                                         \
14685     } STMT_END
14686
14687 STATIC int
14688 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
14689
14690     const char * const s,      /* Where the putative posix class begins.
14691                                   Normally, this is one past the '['.  This
14692                                   parameter exists so it can be somewhere
14693                                   besides RExC_parse. */
14694     char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
14695                                   NULL */
14696     AV ** posix_warnings,      /* Where to place any generated warnings, or
14697                                   NULL */
14698     const bool check_only      /* Don't die if error */
14699 )
14700 {
14701     /* This parses what the caller thinks may be one of the three POSIX
14702      * constructs:
14703      *  1) a character class, like [:blank:]
14704      *  2) a collating symbol, like [. .]
14705      *  3) an equivalence class, like [= =]
14706      * In the latter two cases, it croaks if it finds a syntactically legal
14707      * one, as these are not handled by Perl.
14708      *
14709      * The main purpose is to look for a POSIX character class.  It returns:
14710      *  a) the class number
14711      *      if it is a completely syntactically and semantically legal class.
14712      *      'updated_parse_ptr', if not NULL, is set to point to just after the
14713      *      closing ']' of the class
14714      *  b) OOB_NAMEDCLASS
14715      *      if it appears that one of the three POSIX constructs was meant, but
14716      *      its specification was somehow defective.  'updated_parse_ptr', if
14717      *      not NULL, is set to point to the character just after the end
14718      *      character of the class.  See below for handling of warnings.
14719      *  c) NOT_MEANT_TO_BE_A_POSIX_CLASS
14720      *      if it  doesn't appear that a POSIX construct was intended.
14721      *      'updated_parse_ptr' is not changed.  No warnings nor errors are
14722      *      raised.
14723      *
14724      * In b) there may be errors or warnings generated.  If 'check_only' is
14725      * TRUE, then any errors are discarded.  Warnings are returned to the
14726      * caller via an AV* created into '*posix_warnings' if it is not NULL.  If
14727      * instead it is NULL, warnings are suppressed.
14728      *
14729      * The reason for this function, and its complexity is that a bracketed
14730      * character class can contain just about anything.  But it's easy to
14731      * mistype the very specific posix class syntax but yielding a valid
14732      * regular bracketed class, so it silently gets compiled into something
14733      * quite unintended.
14734      *
14735      * The solution adopted here maintains backward compatibility except that
14736      * it adds a warning if it looks like a posix class was intended but
14737      * improperly specified.  The warning is not raised unless what is input
14738      * very closely resembles one of the 14 legal posix classes.  To do this,
14739      * it uses fuzzy parsing.  It calculates how many single-character edits it
14740      * would take to transform what was input into a legal posix class.  Only
14741      * if that number is quite small does it think that the intention was a
14742      * posix class.  Obviously these are heuristics, and there will be cases
14743      * where it errs on one side or another, and they can be tweaked as
14744      * experience informs.
14745      *
14746      * The syntax for a legal posix class is:
14747      *
14748      * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
14749      *
14750      * What this routine considers syntactically to be an intended posix class
14751      * is this (the comments indicate some restrictions that the pattern
14752      * doesn't show):
14753      *
14754      *  qr/(?x: \[?                         # The left bracket, possibly
14755      *                                      # omitted
14756      *          \h*                         # possibly followed by blanks
14757      *          (?: \^ \h* )?               # possibly a misplaced caret
14758      *          [:;]?                       # The opening class character,
14759      *                                      # possibly omitted.  A typo
14760      *                                      # semi-colon can also be used.
14761      *          \h*
14762      *          \^?                         # possibly a correctly placed
14763      *                                      # caret, but not if there was also
14764      *                                      # a misplaced one
14765      *          \h*
14766      *          .{3,15}                     # The class name.  If there are
14767      *                                      # deviations from the legal syntax,
14768      *                                      # its edit distance must be close
14769      *                                      # to a real class name in order
14770      *                                      # for it to be considered to be
14771      *                                      # an intended posix class.
14772      *          \h*
14773      *          [[:punct:]]?                # The closing class character,
14774      *                                      # possibly omitted.  If not a colon
14775      *                                      # nor semi colon, the class name
14776      *                                      # must be even closer to a valid
14777      *                                      # one
14778      *          \h*
14779      *          \]?                         # The right bracket, possibly
14780      *                                      # omitted.
14781      *     )/
14782      *
14783      * In the above, \h must be ASCII-only.
14784      *
14785      * These are heuristics, and can be tweaked as field experience dictates.
14786      * There will be cases when someone didn't intend to specify a posix class
14787      * that this warns as being so.  The goal is to minimize these, while
14788      * maximizing the catching of things intended to be a posix class that
14789      * aren't parsed as such.
14790      */
14791
14792     const char* p             = s;
14793     const char * const e      = RExC_end;
14794     unsigned complement       = 0;      /* If to complement the class */
14795     bool found_problem        = FALSE;  /* Assume OK until proven otherwise */
14796     bool has_opening_bracket  = FALSE;
14797     bool has_opening_colon    = FALSE;
14798     int class_number          = OOB_NAMEDCLASS; /* Out-of-bounds until find
14799                                                    valid class */
14800     const char * possible_end = NULL;   /* used for a 2nd parse pass */
14801     const char* name_start;             /* ptr to class name first char */
14802
14803     /* If the number of single-character typos the input name is away from a
14804      * legal name is no more than this number, it is considered to have meant
14805      * the legal name */
14806     int max_distance          = 2;
14807
14808     /* to store the name.  The size determines the maximum length before we
14809      * decide that no posix class was intended.  Should be at least
14810      * sizeof("alphanumeric") */
14811     UV input_text[15];
14812     STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
14813
14814     PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
14815
14816     CLEAR_POSIX_WARNINGS();
14817
14818     if (p >= e) {
14819         return NOT_MEANT_TO_BE_A_POSIX_CLASS;
14820     }
14821
14822     if (*(p - 1) != '[') {
14823         ADD_POSIX_WARNING(p, "it doesn't start with a '['");
14824         found_problem = TRUE;
14825     }
14826     else {
14827         has_opening_bracket = TRUE;
14828     }
14829
14830     /* They could be confused and think you can put spaces between the
14831      * components */
14832     if (isBLANK(*p)) {
14833         found_problem = TRUE;
14834
14835         do {
14836             p++;
14837         } while (p < e && isBLANK(*p));
14838
14839         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14840     }
14841
14842     /* For [. .] and [= =].  These are quite different internally from [: :],
14843      * so they are handled separately.  */
14844     if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
14845                                             and 1 for at least one char in it
14846                                           */
14847     {
14848         const char open_char  = *p;
14849         const char * temp_ptr = p + 1;
14850
14851         /* These two constructs are not handled by perl, and if we find a
14852          * syntactically valid one, we croak.  khw, who wrote this code, finds
14853          * this explanation of them very unclear:
14854          * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
14855          * And searching the rest of the internet wasn't very helpful either.
14856          * It looks like just about any byte can be in these constructs,
14857          * depending on the locale.  But unless the pattern is being compiled
14858          * under /l, which is very rare, Perl runs under the C or POSIX locale.
14859          * In that case, it looks like [= =] isn't allowed at all, and that
14860          * [. .] could be any single code point, but for longer strings the
14861          * constituent characters would have to be the ASCII alphabetics plus
14862          * the minus-hyphen.  Any sensible locale definition would limit itself
14863          * to these.  And any portable one definitely should.  Trying to parse
14864          * the general case is a nightmare (see [perl #127604]).  So, this code
14865          * looks only for interiors of these constructs that match:
14866          *      qr/.|[-\w]{2,}/
14867          * Using \w relaxes the apparent rules a little, without adding much
14868          * danger of mistaking something else for one of these constructs.
14869          *
14870          * [. .] in some implementations described on the internet is usable to
14871          * escape a character that otherwise is special in bracketed character
14872          * classes.  For example [.].] means a literal right bracket instead of
14873          * the ending of the class
14874          *
14875          * [= =] can legitimately contain a [. .] construct, but we don't
14876          * handle this case, as that [. .] construct will later get parsed
14877          * itself and croak then.  And [= =] is checked for even when not under
14878          * /l, as Perl has long done so.
14879          *
14880          * The code below relies on there being a trailing NUL, so it doesn't
14881          * have to keep checking if the parse ptr < e.
14882          */
14883         if (temp_ptr[1] == open_char) {
14884             temp_ptr++;
14885         }
14886         else while (    temp_ptr < e
14887                     && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
14888         {
14889             temp_ptr++;
14890         }
14891
14892         if (*temp_ptr == open_char) {
14893             temp_ptr++;
14894             if (*temp_ptr == ']') {
14895                 temp_ptr++;
14896                 if (! found_problem && ! check_only) {
14897                     RExC_parse = (char *) temp_ptr;
14898                     vFAIL3("POSIX syntax [%c %c] is reserved for future "
14899                             "extensions", open_char, open_char);
14900                 }
14901
14902                 /* Here, the syntax wasn't completely valid, or else the call
14903                  * is to check-only */
14904                 if (updated_parse_ptr) {
14905                     *updated_parse_ptr = (char *) temp_ptr;
14906                 }
14907
14908                 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
14909             }
14910         }
14911
14912         /* If we find something that started out to look like one of these
14913          * constructs, but isn't, we continue below so that it can be checked
14914          * for being a class name with a typo of '.' or '=' instead of a colon.
14915          * */
14916     }
14917
14918     /* Here, we think there is a possibility that a [: :] class was meant, and
14919      * we have the first real character.  It could be they think the '^' comes
14920      * first */
14921     if (*p == '^') {
14922         found_problem = TRUE;
14923         ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
14924         complement = 1;
14925         p++;
14926
14927         if (isBLANK(*p)) {
14928             found_problem = TRUE;
14929
14930             do {
14931                 p++;
14932             } while (p < e && isBLANK(*p));
14933
14934             ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14935         }
14936     }
14937
14938     /* But the first character should be a colon, which they could have easily
14939      * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
14940      * distinguish from a colon, so treat that as a colon).  */
14941     if (*p == ':') {
14942         p++;
14943         has_opening_colon = TRUE;
14944     }
14945     else if (*p == ';') {
14946         found_problem = TRUE;
14947         p++;
14948         ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
14949         has_opening_colon = TRUE;
14950     }
14951     else {
14952         found_problem = TRUE;
14953         ADD_POSIX_WARNING(p, "there must be a starting ':'");
14954
14955         /* Consider an initial punctuation (not one of the recognized ones) to
14956          * be a left terminator */
14957         if (*p != '^' && *p != ']' && isPUNCT(*p)) {
14958             p++;
14959         }
14960     }
14961
14962     /* They may think that you can put spaces between the components */
14963     if (isBLANK(*p)) {
14964         found_problem = TRUE;
14965
14966         do {
14967             p++;
14968         } while (p < e && isBLANK(*p));
14969
14970         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14971     }
14972
14973     if (*p == '^') {
14974
14975         /* We consider something like [^:^alnum:]] to not have been intended to
14976          * be a posix class, but XXX maybe we should */
14977         if (complement) {
14978             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
14979         }
14980
14981         complement = 1;
14982         p++;
14983     }
14984
14985     /* Again, they may think that you can put spaces between the components */
14986     if (isBLANK(*p)) {
14987         found_problem = TRUE;
14988
14989         do {
14990             p++;
14991         } while (p < e && isBLANK(*p));
14992
14993         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14994     }
14995
14996     if (*p == ']') {
14997
14998         /* XXX This ']' may be a typo, and something else was meant.  But
14999          * treating it as such creates enough complications, that that
15000          * possibility isn't currently considered here.  So we assume that the
15001          * ']' is what is intended, and if we've already found an initial '[',
15002          * this leaves this construct looking like [:] or [:^], which almost
15003          * certainly weren't intended to be posix classes */
15004         if (has_opening_bracket) {
15005             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15006         }
15007
15008         /* But this function can be called when we parse the colon for
15009          * something like qr/[alpha:]]/, so we back up to look for the
15010          * beginning */
15011         p--;
15012
15013         if (*p == ';') {
15014             found_problem = TRUE;
15015             ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15016         }
15017         else if (*p != ':') {
15018
15019             /* XXX We are currently very restrictive here, so this code doesn't
15020              * consider the possibility that, say, /[alpha.]]/ was intended to
15021              * be a posix class. */
15022             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15023         }
15024
15025         /* Here we have something like 'foo:]'.  There was no initial colon,
15026          * and we back up over 'foo.  XXX Unlike the going forward case, we
15027          * don't handle typos of non-word chars in the middle */
15028         has_opening_colon = FALSE;
15029         p--;
15030
15031         while (p > RExC_start && isWORDCHAR(*p)) {
15032             p--;
15033         }
15034         p++;
15035
15036         /* Here, we have positioned ourselves to where we think the first
15037          * character in the potential class is */
15038     }
15039
15040     /* Now the interior really starts.  There are certain key characters that
15041      * can end the interior, or these could just be typos.  To catch both
15042      * cases, we may have to do two passes.  In the first pass, we keep on
15043      * going unless we come to a sequence that matches
15044      *      qr/ [[:punct:]] [[:blank:]]* \] /xa
15045      * This means it takes a sequence to end the pass, so two typos in a row if
15046      * that wasn't what was intended.  If the class is perfectly formed, just
15047      * this one pass is needed.  We also stop if there are too many characters
15048      * being accumulated, but this number is deliberately set higher than any
15049      * real class.  It is set high enough so that someone who thinks that
15050      * 'alphanumeric' is a correct name would get warned that it wasn't.
15051      * While doing the pass, we keep track of where the key characters were in
15052      * it.  If we don't find an end to the class, and one of the key characters
15053      * was found, we redo the pass, but stop when we get to that character.
15054      * Thus the key character was considered a typo in the first pass, but a
15055      * terminator in the second.  If two key characters are found, we stop at
15056      * the second one in the first pass.  Again this can miss two typos, but
15057      * catches a single one
15058      *
15059      * In the first pass, 'possible_end' starts as NULL, and then gets set to
15060      * point to the first key character.  For the second pass, it starts as -1.
15061      * */
15062
15063     name_start = p;
15064   parse_name:
15065     {
15066         bool has_blank               = FALSE;
15067         bool has_upper               = FALSE;
15068         bool has_terminating_colon   = FALSE;
15069         bool has_terminating_bracket = FALSE;
15070         bool has_semi_colon          = FALSE;
15071         unsigned int name_len        = 0;
15072         int punct_count              = 0;
15073
15074         while (p < e) {
15075
15076             /* Squeeze out blanks when looking up the class name below */
15077             if (isBLANK(*p) ) {
15078                 has_blank = TRUE;
15079                 found_problem = TRUE;
15080                 p++;
15081                 continue;
15082             }
15083
15084             /* The name will end with a punctuation */
15085             if (isPUNCT(*p)) {
15086                 const char * peek = p + 1;
15087
15088                 /* Treat any non-']' punctuation followed by a ']' (possibly
15089                  * with intervening blanks) as trying to terminate the class.
15090                  * ']]' is very likely to mean a class was intended (but
15091                  * missing the colon), but the warning message that gets
15092                  * generated shows the error position better if we exit the
15093                  * loop at the bottom (eventually), so skip it here. */
15094                 if (*p != ']') {
15095                     if (peek < e && isBLANK(*peek)) {
15096                         has_blank = TRUE;
15097                         found_problem = TRUE;
15098                         do {
15099                             peek++;
15100                         } while (peek < e && isBLANK(*peek));
15101                     }
15102
15103                     if (peek < e && *peek == ']') {
15104                         has_terminating_bracket = TRUE;
15105                         if (*p == ':') {
15106                             has_terminating_colon = TRUE;
15107                         }
15108                         else if (*p == ';') {
15109                             has_semi_colon = TRUE;
15110                             has_terminating_colon = TRUE;
15111                         }
15112                         else {
15113                             found_problem = TRUE;
15114                         }
15115                         p = peek + 1;
15116                         goto try_posix;
15117                     }
15118                 }
15119
15120                 /* Here we have punctuation we thought didn't end the class.
15121                  * Keep track of the position of the key characters that are
15122                  * more likely to have been class-enders */
15123                 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15124
15125                     /* Allow just one such possible class-ender not actually
15126                      * ending the class. */
15127                     if (possible_end) {
15128                         break;
15129                     }
15130                     possible_end = p;
15131                 }
15132
15133                 /* If we have too many punctuation characters, no use in
15134                  * keeping going */
15135                 if (++punct_count > max_distance) {
15136                     break;
15137                 }
15138
15139                 /* Treat the punctuation as a typo. */
15140                 input_text[name_len++] = *p;
15141                 p++;
15142             }
15143             else if (isUPPER(*p)) { /* Use lowercase for lookup */
15144                 input_text[name_len++] = toLOWER(*p);
15145                 has_upper = TRUE;
15146                 found_problem = TRUE;
15147                 p++;
15148             } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15149                 input_text[name_len++] = *p;
15150                 p++;
15151             }
15152             else {
15153                 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15154                 p+= UTF8SKIP(p);
15155             }
15156
15157             /* The declaration of 'input_text' is how long we allow a potential
15158              * class name to be, before saying they didn't mean a class name at
15159              * all */
15160             if (name_len >= C_ARRAY_LENGTH(input_text)) {
15161                 break;
15162             }
15163         }
15164
15165         /* We get to here when the possible class name hasn't been properly
15166          * terminated before:
15167          *   1) we ran off the end of the pattern; or
15168          *   2) found two characters, each of which might have been intended to
15169          *      be the name's terminator
15170          *   3) found so many punctuation characters in the purported name,
15171          *      that the edit distance to a valid one is exceeded
15172          *   4) we decided it was more characters than anyone could have
15173          *      intended to be one. */
15174
15175         found_problem = TRUE;
15176
15177         /* In the final two cases, we know that looking up what we've
15178          * accumulated won't lead to a match, even a fuzzy one. */
15179         if (   name_len >= C_ARRAY_LENGTH(input_text)
15180             || punct_count > max_distance)
15181         {
15182             /* If there was an intermediate key character that could have been
15183              * an intended end, redo the parse, but stop there */
15184             if (possible_end && possible_end != (char *) -1) {
15185                 possible_end = (char *) -1; /* Special signal value to say
15186                                                we've done a first pass */
15187                 p = name_start;
15188                 goto parse_name;
15189             }
15190
15191             /* Otherwise, it can't have meant to have been a class */
15192             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15193         }
15194
15195         /* If we ran off the end, and the final character was a punctuation
15196          * one, back up one, to look at that final one just below.  Later, we
15197          * will restore the parse pointer if appropriate */
15198         if (name_len && p == e && isPUNCT(*(p-1))) {
15199             p--;
15200             name_len--;
15201         }
15202
15203         if (p < e && isPUNCT(*p)) {
15204             if (*p == ']') {
15205                 has_terminating_bracket = TRUE;
15206
15207                 /* If this is a 2nd ']', and the first one is just below this
15208                  * one, consider that to be the real terminator.  This gives a
15209                  * uniform and better positioning for the warning message  */
15210                 if (   possible_end
15211                     && possible_end != (char *) -1
15212                     && *possible_end == ']'
15213                     && name_len && input_text[name_len - 1] == ']')
15214                 {
15215                     name_len--;
15216                     p = possible_end;
15217
15218                     /* And this is actually equivalent to having done the 2nd
15219                      * pass now, so set it to not try again */
15220                     possible_end = (char *) -1;
15221                 }
15222             }
15223             else {
15224                 if (*p == ':') {
15225                     has_terminating_colon = TRUE;
15226                 }
15227                 else if (*p == ';') {
15228                     has_semi_colon = TRUE;
15229                     has_terminating_colon = TRUE;
15230                 }
15231                 p++;
15232             }
15233         }
15234
15235     try_posix:
15236
15237         /* Here, we have a class name to look up.  We can short circuit the
15238          * stuff below for short names that can't possibly be meant to be a
15239          * class name.  (We can do this on the first pass, as any second pass
15240          * will yield an even shorter name) */
15241         if (name_len < 3) {
15242             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15243         }
15244
15245         /* Find which class it is.  Initially switch on the length of the name.
15246          * */
15247         switch (name_len) {
15248             case 4:
15249                 if (memEQs(name_start, 4, "word")) {
15250                     /* this is not POSIX, this is the Perl \w */
15251                     class_number = ANYOF_WORDCHAR;
15252                 }
15253                 break;
15254             case 5:
15255                 /* Names all of length 5: alnum alpha ascii blank cntrl digit
15256                  *                        graph lower print punct space upper
15257                  * Offset 4 gives the best switch position.  */
15258                 switch (name_start[4]) {
15259                     case 'a':
15260                         if (memBEGINs(name_start, 5, "alph")) /* alpha */
15261                             class_number = ANYOF_ALPHA;
15262                         break;
15263                     case 'e':
15264                         if (memBEGINs(name_start, 5, "spac")) /* space */
15265                             class_number = ANYOF_SPACE;
15266                         break;
15267                     case 'h':
15268                         if (memBEGINs(name_start, 5, "grap")) /* graph */
15269                             class_number = ANYOF_GRAPH;
15270                         break;
15271                     case 'i':
15272                         if (memBEGINs(name_start, 5, "asci")) /* ascii */
15273                             class_number = ANYOF_ASCII;
15274                         break;
15275                     case 'k':
15276                         if (memBEGINs(name_start, 5, "blan")) /* blank */
15277                             class_number = ANYOF_BLANK;
15278                         break;
15279                     case 'l':
15280                         if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
15281                             class_number = ANYOF_CNTRL;
15282                         break;
15283                     case 'm':
15284                         if (memBEGINs(name_start, 5, "alnu")) /* alnum */
15285                             class_number = ANYOF_ALPHANUMERIC;
15286                         break;
15287                     case 'r':
15288                         if (memBEGINs(name_start, 5, "lowe")) /* lower */
15289                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
15290                         else if (memBEGINs(name_start, 5, "uppe")) /* upper */
15291                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
15292                         break;
15293                     case 't':
15294                         if (memBEGINs(name_start, 5, "digi")) /* digit */
15295                             class_number = ANYOF_DIGIT;
15296                         else if (memBEGINs(name_start, 5, "prin")) /* print */
15297                             class_number = ANYOF_PRINT;
15298                         else if (memBEGINs(name_start, 5, "punc")) /* punct */
15299                             class_number = ANYOF_PUNCT;
15300                         break;
15301                 }
15302                 break;
15303             case 6:
15304                 if (memEQs(name_start, 6, "xdigit"))
15305                     class_number = ANYOF_XDIGIT;
15306                 break;
15307         }
15308
15309         /* If the name exactly matches a posix class name the class number will
15310          * here be set to it, and the input almost certainly was meant to be a
15311          * posix class, so we can skip further checking.  If instead the syntax
15312          * is exactly correct, but the name isn't one of the legal ones, we
15313          * will return that as an error below.  But if neither of these apply,
15314          * it could be that no posix class was intended at all, or that one
15315          * was, but there was a typo.  We tease these apart by doing fuzzy
15316          * matching on the name */
15317         if (class_number == OOB_NAMEDCLASS && found_problem) {
15318             const UV posix_names[][6] = {
15319                                                 { 'a', 'l', 'n', 'u', 'm' },
15320                                                 { 'a', 'l', 'p', 'h', 'a' },
15321                                                 { 'a', 's', 'c', 'i', 'i' },
15322                                                 { 'b', 'l', 'a', 'n', 'k' },
15323                                                 { 'c', 'n', 't', 'r', 'l' },
15324                                                 { 'd', 'i', 'g', 'i', 't' },
15325                                                 { 'g', 'r', 'a', 'p', 'h' },
15326                                                 { 'l', 'o', 'w', 'e', 'r' },
15327                                                 { 'p', 'r', 'i', 'n', 't' },
15328                                                 { 'p', 'u', 'n', 'c', 't' },
15329                                                 { 's', 'p', 'a', 'c', 'e' },
15330                                                 { 'u', 'p', 'p', 'e', 'r' },
15331                                                 { 'w', 'o', 'r', 'd' },
15332                                                 { 'x', 'd', 'i', 'g', 'i', 't' }
15333                                             };
15334             /* The names of the above all have added NULs to make them the same
15335              * size, so we need to also have the real lengths */
15336             const UV posix_name_lengths[] = {
15337                                                 sizeof("alnum") - 1,
15338                                                 sizeof("alpha") - 1,
15339                                                 sizeof("ascii") - 1,
15340                                                 sizeof("blank") - 1,
15341                                                 sizeof("cntrl") - 1,
15342                                                 sizeof("digit") - 1,
15343                                                 sizeof("graph") - 1,
15344                                                 sizeof("lower") - 1,
15345                                                 sizeof("print") - 1,
15346                                                 sizeof("punct") - 1,
15347                                                 sizeof("space") - 1,
15348                                                 sizeof("upper") - 1,
15349                                                 sizeof("word")  - 1,
15350                                                 sizeof("xdigit")- 1
15351                                             };
15352             unsigned int i;
15353             int temp_max = max_distance;    /* Use a temporary, so if we
15354                                                reparse, we haven't changed the
15355                                                outer one */
15356
15357             /* Use a smaller max edit distance if we are missing one of the
15358              * delimiters */
15359             if (   has_opening_bracket + has_opening_colon < 2
15360                 || has_terminating_bracket + has_terminating_colon < 2)
15361             {
15362                 temp_max--;
15363             }
15364
15365             /* See if the input name is close to a legal one */
15366             for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
15367
15368                 /* Short circuit call if the lengths are too far apart to be
15369                  * able to match */
15370                 if (abs( (int) (name_len - posix_name_lengths[i]))
15371                     > temp_max)
15372                 {
15373                     continue;
15374                 }
15375
15376                 if (edit_distance(input_text,
15377                                   posix_names[i],
15378                                   name_len,
15379                                   posix_name_lengths[i],
15380                                   temp_max
15381                                  )
15382                     > -1)
15383                 { /* If it is close, it probably was intended to be a class */
15384                     goto probably_meant_to_be;
15385                 }
15386             }
15387
15388             /* Here the input name is not close enough to a valid class name
15389              * for us to consider it to be intended to be a posix class.  If
15390              * we haven't already done so, and the parse found a character that
15391              * could have been terminators for the name, but which we absorbed
15392              * as typos during the first pass, repeat the parse, signalling it
15393              * to stop at that character */
15394             if (possible_end && possible_end != (char *) -1) {
15395                 possible_end = (char *) -1;
15396                 p = name_start;
15397                 goto parse_name;
15398             }
15399
15400             /* Here neither pass found a close-enough class name */
15401             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15402         }
15403
15404     probably_meant_to_be:
15405
15406         /* Here we think that a posix specification was intended.  Update any
15407          * parse pointer */
15408         if (updated_parse_ptr) {
15409             *updated_parse_ptr = (char *) p;
15410         }
15411
15412         /* If a posix class name was intended but incorrectly specified, we
15413          * output or return the warnings */
15414         if (found_problem) {
15415
15416             /* We set flags for these issues in the parse loop above instead of
15417              * adding them to the list of warnings, because we can parse it
15418              * twice, and we only want one warning instance */
15419             if (has_upper) {
15420                 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
15421             }
15422             if (has_blank) {
15423                 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15424             }
15425             if (has_semi_colon) {
15426                 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15427             }
15428             else if (! has_terminating_colon) {
15429                 ADD_POSIX_WARNING(p, "there is no terminating ':'");
15430             }
15431             if (! has_terminating_bracket) {
15432                 ADD_POSIX_WARNING(p, "there is no terminating ']'");
15433             }
15434
15435             if (   posix_warnings
15436                 && RExC_warn_text
15437                 && av_top_index(RExC_warn_text) > -1)
15438             {
15439                 *posix_warnings = RExC_warn_text;
15440             }
15441         }
15442         else if (class_number != OOB_NAMEDCLASS) {
15443             /* If it is a known class, return the class.  The class number
15444              * #defines are structured so each complement is +1 to the normal
15445              * one */
15446             CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
15447         }
15448         else if (! check_only) {
15449
15450             /* Here, it is an unrecognized class.  This is an error (unless the
15451             * call is to check only, which we've already handled above) */
15452             const char * const complement_string = (complement)
15453                                                    ? "^"
15454                                                    : "";
15455             RExC_parse = (char *) p;
15456             vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
15457                         complement_string,
15458                         UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
15459         }
15460     }
15461
15462     return OOB_NAMEDCLASS;
15463 }
15464 #undef ADD_POSIX_WARNING
15465
15466 STATIC unsigned  int
15467 S_regex_set_precedence(const U8 my_operator) {
15468
15469     /* Returns the precedence in the (?[...]) construct of the input operator,
15470      * specified by its character representation.  The precedence follows
15471      * general Perl rules, but it extends this so that ')' and ']' have (low)
15472      * precedence even though they aren't really operators */
15473
15474     switch (my_operator) {
15475         case '!':
15476             return 5;
15477         case '&':
15478             return 4;
15479         case '^':
15480         case '|':
15481         case '+':
15482         case '-':
15483             return 3;
15484         case ')':
15485             return 2;
15486         case ']':
15487             return 1;
15488     }
15489
15490     NOT_REACHED; /* NOTREACHED */
15491     return 0;   /* Silence compiler warning */
15492 }
15493
15494 STATIC regnode_offset
15495 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
15496                     I32 *flagp, U32 depth,
15497                     char * const oregcomp_parse)
15498 {
15499     /* Handle the (?[...]) construct to do set operations */
15500
15501     U8 curchar;                     /* Current character being parsed */
15502     UV start, end;                  /* End points of code point ranges */
15503     SV* final = NULL;               /* The end result inversion list */
15504     SV* result_string;              /* 'final' stringified */
15505     AV* stack;                      /* stack of operators and operands not yet
15506                                        resolved */
15507     AV* fence_stack = NULL;         /* A stack containing the positions in
15508                                        'stack' of where the undealt-with left
15509                                        parens would be if they were actually
15510                                        put there */
15511     /* The 'volatile' is a workaround for an optimiser bug
15512      * in Solaris Studio 12.3. See RT #127455 */
15513     volatile IV fence = 0;          /* Position of where most recent undealt-
15514                                        with left paren in stack is; -1 if none.
15515                                      */
15516     STRLEN len;                     /* Temporary */
15517     regnode_offset node;                  /* Temporary, and final regnode returned by
15518                                        this function */
15519     const bool save_fold = FOLD;    /* Temporary */
15520     char *save_end, *save_parse;    /* Temporaries */
15521     const bool in_locale = LOC;     /* we turn off /l during processing */
15522
15523     GET_RE_DEBUG_FLAGS_DECL;
15524
15525     PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
15526
15527     DEBUG_PARSE("xcls");
15528
15529     if (in_locale) {
15530         set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
15531     }
15532
15533     /* The use of this operator implies /u.  This is required so that the
15534      * compile time values are valid in all runtime cases */
15535     REQUIRE_UNI_RULES(flagp, 0);
15536
15537     ckWARNexperimental(RExC_parse,
15538                        WARN_EXPERIMENTAL__REGEX_SETS,
15539                        "The regex_sets feature is experimental");
15540
15541     /* Everything in this construct is a metacharacter.  Operands begin with
15542      * either a '\' (for an escape sequence), or a '[' for a bracketed
15543      * character class.  Any other character should be an operator, or
15544      * parenthesis for grouping.  Both types of operands are handled by calling
15545      * regclass() to parse them.  It is called with a parameter to indicate to
15546      * return the computed inversion list.  The parsing here is implemented via
15547      * a stack.  Each entry on the stack is a single character representing one
15548      * of the operators; or else a pointer to an operand inversion list. */
15549
15550 #define IS_OPERATOR(a) SvIOK(a)
15551 #define IS_OPERAND(a)  (! IS_OPERATOR(a))
15552
15553     /* The stack is kept in Łukasiewicz order.  (That's pronounced similar
15554      * to luke-a-shave-itch (or -itz), but people who didn't want to bother
15555      * with pronouncing it called it Reverse Polish instead, but now that YOU
15556      * know how to pronounce it you can use the correct term, thus giving due
15557      * credit to the person who invented it, and impressing your geek friends.
15558      * Wikipedia says that the pronounciation of "Ł" has been changing so that
15559      * it is now more like an English initial W (as in wonk) than an L.)
15560      *
15561      * This means that, for example, 'a | b & c' is stored on the stack as
15562      *
15563      * c  [4]
15564      * b  [3]
15565      * &  [2]
15566      * a  [1]
15567      * |  [0]
15568      *
15569      * where the numbers in brackets give the stack [array] element number.
15570      * In this implementation, parentheses are not stored on the stack.
15571      * Instead a '(' creates a "fence" so that the part of the stack below the
15572      * fence is invisible except to the corresponding ')' (this allows us to
15573      * replace testing for parens, by using instead subtraction of the fence
15574      * position).  As new operands are processed they are pushed onto the stack
15575      * (except as noted in the next paragraph).  New operators of higher
15576      * precedence than the current final one are inserted on the stack before
15577      * the lhs operand (so that when the rhs is pushed next, everything will be
15578      * in the correct positions shown above.  When an operator of equal or
15579      * lower precedence is encountered in parsing, all the stacked operations
15580      * of equal or higher precedence are evaluated, leaving the result as the
15581      * top entry on the stack.  This makes higher precedence operations
15582      * evaluate before lower precedence ones, and causes operations of equal
15583      * precedence to left associate.
15584      *
15585      * The only unary operator '!' is immediately pushed onto the stack when
15586      * encountered.  When an operand is encountered, if the top of the stack is
15587      * a '!", the complement is immediately performed, and the '!' popped.  The
15588      * resulting value is treated as a new operand, and the logic in the
15589      * previous paragraph is executed.  Thus in the expression
15590      *      [a] + ! [b]
15591      * the stack looks like
15592      *
15593      * !
15594      * a
15595      * +
15596      *
15597      * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
15598      * becomes
15599      *
15600      * !b
15601      * a
15602      * +
15603      *
15604      * A ')' is treated as an operator with lower precedence than all the
15605      * aforementioned ones, which causes all operations on the stack above the
15606      * corresponding '(' to be evaluated down to a single resultant operand.
15607      * Then the fence for the '(' is removed, and the operand goes through the
15608      * algorithm above, without the fence.
15609      *
15610      * A separate stack is kept of the fence positions, so that the position of
15611      * the latest so-far unbalanced '(' is at the top of it.
15612      *
15613      * The ']' ending the construct is treated as the lowest operator of all,
15614      * so that everything gets evaluated down to a single operand, which is the
15615      * result */
15616
15617     sv_2mortal((SV *)(stack = newAV()));
15618     sv_2mortal((SV *)(fence_stack = newAV()));
15619
15620     while (RExC_parse < RExC_end) {
15621         I32 top_index;              /* Index of top-most element in 'stack' */
15622         SV** top_ptr;               /* Pointer to top 'stack' element */
15623         SV* current = NULL;         /* To contain the current inversion list
15624                                        operand */
15625         SV* only_to_avoid_leaks;
15626
15627         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15628                                 TRUE /* Force /x */ );
15629         if (RExC_parse >= RExC_end) {   /* Fail */
15630             break;
15631         }
15632
15633         curchar = UCHARAT(RExC_parse);
15634
15635 redo_curchar:
15636
15637 #ifdef ENABLE_REGEX_SETS_DEBUGGING
15638                     /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
15639         DEBUG_U(dump_regex_sets_structures(pRExC_state,
15640                                            stack, fence, fence_stack));
15641 #endif
15642
15643         top_index = av_tindex_skip_len_mg(stack);
15644
15645         switch (curchar) {
15646             SV** stacked_ptr;       /* Ptr to something already on 'stack' */
15647             char stacked_operator;  /* The topmost operator on the 'stack'. */
15648             SV* lhs;                /* Operand to the left of the operator */
15649             SV* rhs;                /* Operand to the right of the operator */
15650             SV* fence_ptr;          /* Pointer to top element of the fence
15651                                        stack */
15652
15653             case '(':
15654
15655                 if (   RExC_parse < RExC_end - 2
15656                     && UCHARAT(RExC_parse + 1) == '?'
15657                     && UCHARAT(RExC_parse + 2) == '^')
15658                 {
15659                     /* If is a '(?', could be an embedded '(?^flags:(?[...])'.
15660                      * This happens when we have some thing like
15661                      *
15662                      *   my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
15663                      *   ...
15664                      *   qr/(?[ \p{Digit} & $thai_or_lao ])/;
15665                      *
15666                      * Here we would be handling the interpolated
15667                      * '$thai_or_lao'.  We handle this by a recursive call to
15668                      * ourselves which returns the inversion list the
15669                      * interpolated expression evaluates to.  We use the flags
15670                      * from the interpolated pattern. */
15671                     U32 save_flags = RExC_flags;
15672                     const char * save_parse;
15673
15674                     RExC_parse += 2;        /* Skip past the '(?' */
15675                     save_parse = RExC_parse;
15676
15677                     /* Parse the flags for the '(?'.  We already know the first
15678                      * flag to parse is a '^' */
15679                     parse_lparen_question_flags(pRExC_state);
15680
15681                     if (   RExC_parse >= RExC_end - 4
15682                         || UCHARAT(RExC_parse) != ':'
15683                         || UCHARAT(++RExC_parse) != '('
15684                         || UCHARAT(++RExC_parse) != '?'
15685                         || UCHARAT(++RExC_parse) != '[')
15686                     {
15687
15688                         /* In combination with the above, this moves the
15689                          * pointer to the point just after the first erroneous
15690                          * character. */
15691                         if (RExC_parse >= RExC_end - 4) {
15692                             RExC_parse = RExC_end;
15693                         }
15694                         else if (RExC_parse != save_parse) {
15695                             RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15696                         }
15697                         vFAIL("Expecting '(?flags:(?[...'");
15698                     }
15699
15700                     /* Recurse, with the meat of the embedded expression */
15701                     RExC_parse++;
15702                     (void) handle_regex_sets(pRExC_state, &current, flagp,
15703                                                     depth+1, oregcomp_parse);
15704
15705                     /* Here, 'current' contains the embedded expression's
15706                      * inversion list, and RExC_parse points to the trailing
15707                      * ']'; the next character should be the ')' */
15708                     RExC_parse++;
15709                     if (UCHARAT(RExC_parse) != ')')
15710                         vFAIL("Expecting close paren for nested extended charclass");
15711
15712                     /* Then the ')' matching the original '(' handled by this
15713                      * case: statement */
15714                     RExC_parse++;
15715                     if (UCHARAT(RExC_parse) != ')')
15716                         vFAIL("Expecting close paren for wrapper for nested extended charclass");
15717
15718                     RExC_flags = save_flags;
15719                     goto handle_operand;
15720                 }
15721
15722                 /* A regular '('.  Look behind for illegal syntax */
15723                 if (top_index - fence >= 0) {
15724                     /* If the top entry on the stack is an operator, it had
15725                      * better be a '!', otherwise the entry below the top
15726                      * operand should be an operator */
15727                     if (   ! (top_ptr = av_fetch(stack, top_index, FALSE))
15728                         || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
15729                         || (   IS_OPERAND(*top_ptr)
15730                             && (   top_index - fence < 1
15731                                 || ! (stacked_ptr = av_fetch(stack,
15732                                                              top_index - 1,
15733                                                              FALSE))
15734                                 || ! IS_OPERATOR(*stacked_ptr))))
15735                     {
15736                         RExC_parse++;
15737                         vFAIL("Unexpected '(' with no preceding operator");
15738                     }
15739                 }
15740
15741                 /* Stack the position of this undealt-with left paren */
15742                 av_push(fence_stack, newSViv(fence));
15743                 fence = top_index + 1;
15744                 break;
15745
15746             case '\\':
15747                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
15748                  * multi-char folds are allowed.  */
15749                 if (!regclass(pRExC_state, flagp, depth+1,
15750                               TRUE, /* means parse just the next thing */
15751                               FALSE, /* don't allow multi-char folds */
15752                               FALSE, /* don't silence non-portable warnings.  */
15753                               TRUE,  /* strict */
15754                               FALSE, /* Require return to be an ANYOF */
15755                               &current))
15756                 {
15757                     FAIL2("panic: regclass returned failure to handle_sets, "
15758                           "flags=%#" UVxf, (UV) *flagp);
15759                 }
15760
15761                 /* regclass() will return with parsing just the \ sequence,
15762                  * leaving the parse pointer at the next thing to parse */
15763                 RExC_parse--;
15764                 goto handle_operand;
15765
15766             case '[':   /* Is a bracketed character class */
15767             {
15768                 /* See if this is a [:posix:] class. */
15769                 bool is_posix_class = (OOB_NAMEDCLASS
15770                             < handle_possible_posix(pRExC_state,
15771                                                 RExC_parse + 1,
15772                                                 NULL,
15773                                                 NULL,
15774                                                 TRUE /* checking only */));
15775                 /* If it is a posix class, leave the parse pointer at the '['
15776                  * to fool regclass() into thinking it is part of a
15777                  * '[[:posix:]]'. */
15778                 if (! is_posix_class) {
15779                     RExC_parse++;
15780                 }
15781
15782                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
15783                  * multi-char folds are allowed.  */
15784                 if (!regclass(pRExC_state, flagp, depth+1,
15785                                 is_posix_class, /* parse the whole char
15786                                                     class only if not a
15787                                                     posix class */
15788                                 FALSE, /* don't allow multi-char folds */
15789                                 TRUE, /* silence non-portable warnings. */
15790                                 TRUE, /* strict */
15791                                 FALSE, /* Require return to be an ANYOF */
15792                                 &current))
15793                 {
15794                     FAIL2("panic: regclass returned failure to handle_sets, "
15795                           "flags=%#" UVxf, (UV) *flagp);
15796                 }
15797
15798                 if (! current) {
15799                     break;
15800                 }
15801
15802                 /* function call leaves parse pointing to the ']', except if we
15803                  * faked it */
15804                 if (is_posix_class) {
15805                     RExC_parse--;
15806                 }
15807
15808                 goto handle_operand;
15809             }
15810
15811             case ']':
15812                 if (top_index >= 1) {
15813                     goto join_operators;
15814                 }
15815
15816                 /* Only a single operand on the stack: are done */
15817                 goto done;
15818
15819             case ')':
15820                 if (av_tindex_skip_len_mg(fence_stack) < 0) {
15821                     if (UCHARAT(RExC_parse - 1) == ']')  {
15822                         break;
15823                     }
15824                     RExC_parse++;
15825                     vFAIL("Unexpected ')'");
15826                 }
15827
15828                 /* If nothing after the fence, is missing an operand */
15829                 if (top_index - fence < 0) {
15830                     RExC_parse++;
15831                     goto bad_syntax;
15832                 }
15833                 /* If at least two things on the stack, treat this as an
15834                   * operator */
15835                 if (top_index - fence >= 1) {
15836                     goto join_operators;
15837                 }
15838
15839                 /* Here only a single thing on the fenced stack, and there is a
15840                  * fence.  Get rid of it */
15841                 fence_ptr = av_pop(fence_stack);
15842                 assert(fence_ptr);
15843                 fence = SvIV(fence_ptr);
15844                 SvREFCNT_dec_NN(fence_ptr);
15845                 fence_ptr = NULL;
15846
15847                 if (fence < 0) {
15848                     fence = 0;
15849                 }
15850
15851                 /* Having gotten rid of the fence, we pop the operand at the
15852                  * stack top and process it as a newly encountered operand */
15853                 current = av_pop(stack);
15854                 if (IS_OPERAND(current)) {
15855                     goto handle_operand;
15856                 }
15857
15858                 RExC_parse++;
15859                 goto bad_syntax;
15860
15861             case '&':
15862             case '|':
15863             case '+':
15864             case '-':
15865             case '^':
15866
15867                 /* These binary operators should have a left operand already
15868                  * parsed */
15869                 if (   top_index - fence < 0
15870                     || top_index - fence == 1
15871                     || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
15872                     || ! IS_OPERAND(*top_ptr))
15873                 {
15874                     goto unexpected_binary;
15875                 }
15876
15877                 /* If only the one operand is on the part of the stack visible
15878                  * to us, we just place this operator in the proper position */
15879                 if (top_index - fence < 2) {
15880
15881                     /* Place the operator before the operand */
15882
15883                     SV* lhs = av_pop(stack);
15884                     av_push(stack, newSVuv(curchar));
15885                     av_push(stack, lhs);
15886                     break;
15887                 }
15888
15889                 /* But if there is something else on the stack, we need to
15890                  * process it before this new operator if and only if the
15891                  * stacked operation has equal or higher precedence than the
15892                  * new one */
15893
15894              join_operators:
15895
15896                 /* The operator on the stack is supposed to be below both its
15897                  * operands */
15898                 if (   ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
15899                     || IS_OPERAND(*stacked_ptr))
15900                 {
15901                     /* But if not, it's legal and indicates we are completely
15902                      * done if and only if we're currently processing a ']',
15903                      * which should be the final thing in the expression */
15904                     if (curchar == ']') {
15905                         goto done;
15906                     }
15907
15908                   unexpected_binary:
15909                     RExC_parse++;
15910                     vFAIL2("Unexpected binary operator '%c' with no "
15911                            "preceding operand", curchar);
15912                 }
15913                 stacked_operator = (char) SvUV(*stacked_ptr);
15914
15915                 if (regex_set_precedence(curchar)
15916                     > regex_set_precedence(stacked_operator))
15917                 {
15918                     /* Here, the new operator has higher precedence than the
15919                      * stacked one.  This means we need to add the new one to
15920                      * the stack to await its rhs operand (and maybe more
15921                      * stuff).  We put it before the lhs operand, leaving
15922                      * untouched the stacked operator and everything below it
15923                      * */
15924                     lhs = av_pop(stack);
15925                     assert(IS_OPERAND(lhs));
15926
15927                     av_push(stack, newSVuv(curchar));
15928                     av_push(stack, lhs);
15929                     break;
15930                 }
15931
15932                 /* Here, the new operator has equal or lower precedence than
15933                  * what's already there.  This means the operation already
15934                  * there should be performed now, before the new one. */
15935
15936                 rhs = av_pop(stack);
15937                 if (! IS_OPERAND(rhs)) {
15938
15939                     /* This can happen when a ! is not followed by an operand,
15940                      * like in /(?[\t &!])/ */
15941                     goto bad_syntax;
15942                 }
15943
15944                 lhs = av_pop(stack);
15945
15946                 if (! IS_OPERAND(lhs)) {
15947
15948                     /* This can happen when there is an empty (), like in
15949                      * /(?[[0]+()+])/ */
15950                     goto bad_syntax;
15951                 }
15952
15953                 switch (stacked_operator) {
15954                     case '&':
15955                         _invlist_intersection(lhs, rhs, &rhs);
15956                         break;
15957
15958                     case '|':
15959                     case '+':
15960                         _invlist_union(lhs, rhs, &rhs);
15961                         break;
15962
15963                     case '-':
15964                         _invlist_subtract(lhs, rhs, &rhs);
15965                         break;
15966
15967                     case '^':   /* The union minus the intersection */
15968                     {
15969                         SV* i = NULL;
15970                         SV* u = NULL;
15971
15972                         _invlist_union(lhs, rhs, &u);
15973                         _invlist_intersection(lhs, rhs, &i);
15974                         _invlist_subtract(u, i, &rhs);
15975                         SvREFCNT_dec_NN(i);
15976                         SvREFCNT_dec_NN(u);
15977                         break;
15978                     }
15979                 }
15980                 SvREFCNT_dec(lhs);
15981
15982                 /* Here, the higher precedence operation has been done, and the
15983                  * result is in 'rhs'.  We overwrite the stacked operator with
15984                  * the result.  Then we redo this code to either push the new
15985                  * operator onto the stack or perform any higher precedence
15986                  * stacked operation */
15987                 only_to_avoid_leaks = av_pop(stack);
15988                 SvREFCNT_dec(only_to_avoid_leaks);
15989                 av_push(stack, rhs);
15990                 goto redo_curchar;
15991
15992             case '!':   /* Highest priority, right associative */
15993
15994                 /* If what's already at the top of the stack is another '!",
15995                  * they just cancel each other out */
15996                 if (   (top_ptr = av_fetch(stack, top_index, FALSE))
15997                     && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
15998                 {
15999                     only_to_avoid_leaks = av_pop(stack);
16000                     SvREFCNT_dec(only_to_avoid_leaks);
16001                 }
16002                 else { /* Otherwise, since it's right associative, just push
16003                           onto the stack */
16004                     av_push(stack, newSVuv(curchar));
16005                 }
16006                 break;
16007
16008             default:
16009                 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16010                 if (RExC_parse >= RExC_end) {
16011                     break;
16012                 }
16013                 vFAIL("Unexpected character");
16014
16015           handle_operand:
16016
16017             /* Here 'current' is the operand.  If something is already on the
16018              * stack, we have to check if it is a !.  But first, the code above
16019              * may have altered the stack in the time since we earlier set
16020              * 'top_index'.  */
16021
16022             top_index = av_tindex_skip_len_mg(stack);
16023             if (top_index - fence >= 0) {
16024                 /* If the top entry on the stack is an operator, it had better
16025                  * be a '!', otherwise the entry below the top operand should
16026                  * be an operator */
16027                 top_ptr = av_fetch(stack, top_index, FALSE);
16028                 assert(top_ptr);
16029                 if (IS_OPERATOR(*top_ptr)) {
16030
16031                     /* The only permissible operator at the top of the stack is
16032                      * '!', which is applied immediately to this operand. */
16033                     curchar = (char) SvUV(*top_ptr);
16034                     if (curchar != '!') {
16035                         SvREFCNT_dec(current);
16036                         vFAIL2("Unexpected binary operator '%c' with no "
16037                                 "preceding operand", curchar);
16038                     }
16039
16040                     _invlist_invert(current);
16041
16042                     only_to_avoid_leaks = av_pop(stack);
16043                     SvREFCNT_dec(only_to_avoid_leaks);
16044
16045                     /* And we redo with the inverted operand.  This allows
16046                      * handling multiple ! in a row */
16047                     goto handle_operand;
16048                 }
16049                           /* Single operand is ok only for the non-binary ')'
16050                            * operator */
16051                 else if ((top_index - fence == 0 && curchar != ')')
16052                          || (top_index - fence > 0
16053                              && (! (stacked_ptr = av_fetch(stack,
16054                                                            top_index - 1,
16055                                                            FALSE))
16056                                  || IS_OPERAND(*stacked_ptr))))
16057                 {
16058                     SvREFCNT_dec(current);
16059                     vFAIL("Operand with no preceding operator");
16060                 }
16061             }
16062
16063             /* Here there was nothing on the stack or the top element was
16064              * another operand.  Just add this new one */
16065             av_push(stack, current);
16066
16067         } /* End of switch on next parse token */
16068
16069         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16070     } /* End of loop parsing through the construct */
16071
16072     vFAIL("Syntax error in (?[...])");
16073
16074   done:
16075
16076     if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16077         if (RExC_parse < RExC_end) {
16078             RExC_parse++;
16079         }
16080
16081         vFAIL("Unexpected ']' with no following ')' in (?[...");
16082     }
16083
16084     if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16085         vFAIL("Unmatched (");
16086     }
16087
16088     if (av_tindex_skip_len_mg(stack) < 0   /* Was empty */
16089         || ((final = av_pop(stack)) == NULL)
16090         || ! IS_OPERAND(final)
16091         || ! is_invlist(final)
16092         || av_tindex_skip_len_mg(stack) >= 0)  /* More left on stack */
16093     {
16094       bad_syntax:
16095         SvREFCNT_dec(final);
16096         vFAIL("Incomplete expression within '(?[ ])'");
16097     }
16098
16099     /* Here, 'final' is the resultant inversion list from evaluating the
16100      * expression.  Return it if so requested */
16101     if (return_invlist) {
16102         *return_invlist = final;
16103         return END;
16104     }
16105
16106     /* Otherwise generate a resultant node, based on 'final'.  regclass() is
16107      * expecting a string of ranges and individual code points */
16108     invlist_iterinit(final);
16109     result_string = newSVpvs("");
16110     while (invlist_iternext(final, &start, &end)) {
16111         if (start == end) {
16112             Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16113         }
16114         else {
16115             Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}",
16116                                                      start,          end);
16117         }
16118     }
16119
16120     /* About to generate an ANYOF (or similar) node from the inversion list we
16121      * have calculated */
16122     save_parse = RExC_parse;
16123     RExC_parse = SvPV(result_string, len);
16124     save_end = RExC_end;
16125     RExC_end = RExC_parse + len;
16126     TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16127
16128     /* We turn off folding around the call, as the class we have constructed
16129      * already has all folding taken into consideration, and we don't want
16130      * regclass() to add to that */
16131     RExC_flags &= ~RXf_PMf_FOLD;
16132     /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16133      * folds are allowed.  */
16134     node = regclass(pRExC_state, flagp, depth+1,
16135                     FALSE, /* means parse the whole char class */
16136                     FALSE, /* don't allow multi-char folds */
16137                     TRUE, /* silence non-portable warnings.  The above may very
16138                              well have generated non-portable code points, but
16139                              they're valid on this machine */
16140                     FALSE, /* similarly, no need for strict */
16141                     FALSE, /* Require return to be an ANYOF */
16142                     NULL
16143                 );
16144
16145     RESTORE_WARNINGS;
16146     RExC_parse = save_parse + 1;
16147     RExC_end = save_end;
16148     SvREFCNT_dec_NN(final);
16149     SvREFCNT_dec_NN(result_string);
16150
16151     if (save_fold) {
16152         RExC_flags |= RXf_PMf_FOLD;
16153     }
16154
16155     if (!node)
16156         FAIL2("panic: regclass returned failure to handle_sets, flags=%#" UVxf,
16157                     PTR2UV(flagp));
16158
16159     /* Fix up the node type if we are in locale.  (We have pretended we are
16160      * under /u for the purposes of regclass(), as this construct will only
16161      * work under UTF-8 locales.  But now we change the opcode to be ANYOFL (so
16162      * as to cause any warnings about bad locales to be output in regexec.c),
16163      * and add the flag that indicates to check if not in a UTF-8 locale.  The
16164      * reason we above forbid optimization into something other than an ANYOF
16165      * node is simply to minimize the number of code changes in regexec.c.
16166      * Otherwise we would have to create new EXACTish node types and deal with
16167      * them.  This decision could be revisited should this construct become
16168      * popular.
16169      *
16170      * (One might think we could look at the resulting ANYOF node and suppress
16171      * the flag if everything is above 255, as those would be UTF-8 only,
16172      * but this isn't true, as the components that led to that result could
16173      * have been locale-affected, and just happen to cancel each other out
16174      * under UTF-8 locales.) */
16175     if (in_locale) {
16176         set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16177
16178         assert(OP(REGNODE_p(node)) == ANYOF);
16179
16180         OP(REGNODE_p(node)) = ANYOFL;
16181         ANYOF_FLAGS(REGNODE_p(node))
16182                 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16183     }
16184
16185     nextchar(pRExC_state);
16186     Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16187     return node;
16188 }
16189
16190 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16191
16192 STATIC void
16193 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
16194                              AV * stack, const IV fence, AV * fence_stack)
16195 {   /* Dumps the stacks in handle_regex_sets() */
16196
16197     const SSize_t stack_top = av_tindex_skip_len_mg(stack);
16198     const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
16199     SSize_t i;
16200
16201     PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
16202
16203     PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
16204
16205     if (stack_top < 0) {
16206         PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
16207     }
16208     else {
16209         PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
16210         for (i = stack_top; i >= 0; i--) {
16211             SV ** element_ptr = av_fetch(stack, i, FALSE);
16212             if (! element_ptr) {
16213             }
16214
16215             if (IS_OPERATOR(*element_ptr)) {
16216                 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
16217                                             (int) i, (int) SvIV(*element_ptr));
16218             }
16219             else {
16220                 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
16221                 sv_dump(*element_ptr);
16222             }
16223         }
16224     }
16225
16226     if (fence_stack_top < 0) {
16227         PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
16228     }
16229     else {
16230         PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
16231         for (i = fence_stack_top; i >= 0; i--) {
16232             SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
16233             if (! element_ptr) {
16234             }
16235
16236             PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
16237                                             (int) i, (int) SvIV(*element_ptr));
16238         }
16239     }
16240 }
16241
16242 #endif
16243
16244 #undef IS_OPERATOR
16245 #undef IS_OPERAND
16246
16247 STATIC void
16248 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
16249 {
16250     /* This adds the Latin1/above-Latin1 folding rules.
16251      *
16252      * This should be called only for a Latin1-range code points, cp, which is
16253      * known to be involved in a simple fold with other code points above
16254      * Latin1.  It would give false results if /aa has been specified.
16255      * Multi-char folds are outside the scope of this, and must be handled
16256      * specially. */
16257
16258     PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
16259
16260     assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
16261
16262     /* The rules that are valid for all Unicode versions are hard-coded in */
16263     switch (cp) {
16264         case 'k':
16265         case 'K':
16266           *invlist =
16267              add_cp_to_invlist(*invlist, KELVIN_SIGN);
16268             break;
16269         case 's':
16270         case 'S':
16271           *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
16272             break;
16273         case MICRO_SIGN:
16274           *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
16275           *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
16276             break;
16277         case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
16278         case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
16279           *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
16280             break;
16281         case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
16282           *invlist = add_cp_to_invlist(*invlist,
16283                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
16284             break;
16285
16286         default:    /* Other code points are checked against the data for the
16287                        current Unicode version */
16288           {
16289             Size_t folds_count;
16290             unsigned int first_fold;
16291             const unsigned int * remaining_folds;
16292             UV folded_cp;
16293
16294             if (isASCII(cp)) {
16295                 folded_cp = toFOLD(cp);
16296             }
16297             else {
16298                 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
16299                 Size_t dummy_len;
16300                 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
16301             }
16302
16303             if (folded_cp > 255) {
16304                 *invlist = add_cp_to_invlist(*invlist, folded_cp);
16305             }
16306
16307             folds_count = _inverse_folds(folded_cp, &first_fold,
16308                                                     &remaining_folds);
16309             if (folds_count == 0) {
16310
16311                 /* Use deprecated warning to increase the chances of this being
16312                  * output */
16313                 ckWARN2reg_d(RExC_parse,
16314                         "Perl folding rules are not up-to-date for 0x%02X;"
16315                         " please use the perlbug utility to report;", cp);
16316             }
16317             else {
16318                 unsigned int i;
16319
16320                 if (first_fold > 255) {
16321                     *invlist = add_cp_to_invlist(*invlist, first_fold);
16322                 }
16323                 for (i = 0; i < folds_count - 1; i++) {
16324                     if (remaining_folds[i] > 255) {
16325                         *invlist = add_cp_to_invlist(*invlist,
16326                                                     remaining_folds[i]);
16327                     }
16328                 }
16329             }
16330             break;
16331          }
16332     }
16333 }
16334
16335 STATIC void
16336 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
16337 {
16338     /* Output the elements of the array given by '*posix_warnings' as REGEXP
16339      * warnings. */
16340
16341     SV * msg;
16342     const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
16343
16344     PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
16345
16346     if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
16347         return;
16348     }
16349
16350     while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
16351         if (first_is_fatal) {           /* Avoid leaking this */
16352             av_undef(posix_warnings);   /* This isn't necessary if the
16353                                             array is mortal, but is a
16354                                             fail-safe */
16355             (void) sv_2mortal(msg);
16356             PREPARE_TO_DIE;
16357         }
16358         Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
16359         SvREFCNT_dec_NN(msg);
16360     }
16361
16362     UPDATE_WARNINGS_LOC(RExC_parse);
16363 }
16364
16365 STATIC AV *
16366 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
16367 {
16368     /* This adds the string scalar <multi_string> to the array
16369      * <multi_char_matches>.  <multi_string> is known to have exactly
16370      * <cp_count> code points in it.  This is used when constructing a
16371      * bracketed character class and we find something that needs to match more
16372      * than a single character.
16373      *
16374      * <multi_char_matches> is actually an array of arrays.  Each top-level
16375      * element is an array that contains all the strings known so far that are
16376      * the same length.  And that length (in number of code points) is the same
16377      * as the index of the top-level array.  Hence, the [2] element is an
16378      * array, each element thereof is a string containing TWO code points;
16379      * while element [3] is for strings of THREE characters, and so on.  Since
16380      * this is for multi-char strings there can never be a [0] nor [1] element.
16381      *
16382      * When we rewrite the character class below, we will do so such that the
16383      * longest strings are written first, so that it prefers the longest
16384      * matching strings first.  This is done even if it turns out that any
16385      * quantifier is non-greedy, out of this programmer's (khw) laziness.  Tom
16386      * Christiansen has agreed that this is ok.  This makes the test for the
16387      * ligature 'ffi' come before the test for 'ff', for example */
16388
16389     AV* this_array;
16390     AV** this_array_ptr;
16391
16392     PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
16393
16394     if (! multi_char_matches) {
16395         multi_char_matches = newAV();
16396     }
16397
16398     if (av_exists(multi_char_matches, cp_count)) {
16399         this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
16400         this_array = *this_array_ptr;
16401     }
16402     else {
16403         this_array = newAV();
16404         av_store(multi_char_matches, cp_count,
16405                  (SV*) this_array);
16406     }
16407     av_push(this_array, multi_string);
16408
16409     return multi_char_matches;
16410 }
16411
16412 /* The names of properties whose definitions are not known at compile time are
16413  * stored in this SV, after a constant heading.  So if the length has been
16414  * changed since initialization, then there is a run-time definition. */
16415 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION                            \
16416                                         (SvCUR(listsv) != initial_listsv_len)
16417
16418 /* There is a restricted set of white space characters that are legal when
16419  * ignoring white space in a bracketed character class.  This generates the
16420  * code to skip them.
16421  *
16422  * There is a line below that uses the same white space criteria but is outside
16423  * this macro.  Both here and there must use the same definition */
16424 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p)                          \
16425     STMT_START {                                                        \
16426         if (do_skip) {                                                  \
16427             while (isBLANK_A(UCHARAT(p)))                               \
16428             {                                                           \
16429                 p++;                                                    \
16430             }                                                           \
16431         }                                                               \
16432     } STMT_END
16433
16434 STATIC regnode_offset
16435 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
16436                  const bool stop_at_1,  /* Just parse the next thing, don't
16437                                            look for a full character class */
16438                  bool allow_multi_folds,
16439                  const bool silence_non_portable,   /* Don't output warnings
16440                                                        about too large
16441                                                        characters */
16442                  const bool strict,
16443                  bool optimizable,                  /* ? Allow a non-ANYOF return
16444                                                        node */
16445                  SV** ret_invlist  /* Return an inversion list, not a node */
16446           )
16447 {
16448     /* parse a bracketed class specification.  Most of these will produce an
16449      * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
16450      * EXACTFish node; [[:ascii:]], a POSIXA node; etc.  It is more complex
16451      * under /i with multi-character folds: it will be rewritten following the
16452      * paradigm of this example, where the <multi-fold>s are characters which
16453      * fold to multiple character sequences:
16454      *      /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
16455      * gets effectively rewritten as:
16456      *      /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
16457      * reg() gets called (recursively) on the rewritten version, and this
16458      * function will return what it constructs.  (Actually the <multi-fold>s
16459      * aren't physically removed from the [abcdefghi], it's just that they are
16460      * ignored in the recursion by means of a flag:
16461      * <RExC_in_multi_char_class>.)
16462      *
16463      * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
16464      * characters, with the corresponding bit set if that character is in the
16465      * list.  For characters above this, an inversion list is used.  There
16466      * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
16467      * determinable at compile time
16468      *
16469      * On success, returns the offset at which any next node should be placed
16470      * into the regex engine program being compiled.
16471      *
16472      * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
16473      * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
16474      * UTF-8
16475      */
16476
16477     dVAR;
16478     UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
16479     IV range = 0;
16480     UV value = OOB_UNICODE, save_value = OOB_UNICODE;
16481     regnode_offset ret;
16482     STRLEN numlen;
16483     int namedclass = OOB_NAMEDCLASS;
16484     char *rangebegin = NULL;
16485     SV *listsv = NULL;      /* List of \p{user-defined} whose definitions
16486                                aren't available at the time this was called */
16487     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
16488                                       than just initialized.  */
16489     SV* properties = NULL;    /* Code points that match \p{} \P{} */
16490     SV* posixes = NULL;     /* Code points that match classes like [:word:],
16491                                extended beyond the Latin1 range.  These have to
16492                                be kept separate from other code points for much
16493                                of this function because their handling  is
16494                                different under /i, and for most classes under
16495                                /d as well */
16496     SV* nposixes = NULL;    /* Similarly for [:^word:].  These are kept
16497                                separate for a while from the non-complemented
16498                                versions because of complications with /d
16499                                matching */
16500     SV* simple_posixes = NULL; /* But under some conditions, the classes can be
16501                                   treated more simply than the general case,
16502                                   leading to less compilation and execution
16503                                   work */
16504     UV element_count = 0;   /* Number of distinct elements in the class.
16505                                Optimizations may be possible if this is tiny */
16506     AV * multi_char_matches = NULL; /* Code points that fold to more than one
16507                                        character; used under /i */
16508     UV n;
16509     char * stop_ptr = RExC_end;    /* where to stop parsing */
16510
16511     /* ignore unescaped whitespace? */
16512     const bool skip_white = cBOOL(   ret_invlist
16513                                   || (RExC_flags & RXf_PMf_EXTENDED_MORE));
16514
16515     /* inversion list of code points this node matches only when the target
16516      * string is in UTF-8.  These are all non-ASCII, < 256.  (Because is under
16517      * /d) */
16518     SV* upper_latin1_only_utf8_matches = NULL;
16519
16520     /* Inversion list of code points this node matches regardless of things
16521      * like locale, folding, utf8ness of the target string */
16522     SV* cp_list = NULL;
16523
16524     /* Like cp_list, but code points on this list need to be checked for things
16525      * that fold to/from them under /i */
16526     SV* cp_foldable_list = NULL;
16527
16528     /* Like cp_list, but code points on this list are valid only when the
16529      * runtime locale is UTF-8 */
16530     SV* only_utf8_locale_list = NULL;
16531
16532     /* In a range, if one of the endpoints is non-character-set portable,
16533      * meaning that it hard-codes a code point that may mean a different
16534      * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
16535      * mnemonic '\t' which each mean the same character no matter which
16536      * character set the platform is on. */
16537     unsigned int non_portable_endpoint = 0;
16538
16539     /* Is the range unicode? which means on a platform that isn't 1-1 native
16540      * to Unicode (i.e. non-ASCII), each code point in it should be considered
16541      * to be a Unicode value.  */
16542     bool unicode_range = FALSE;
16543     bool invert = FALSE;    /* Is this class to be complemented */
16544
16545     bool warn_super = ALWAYS_WARN_SUPER;
16546
16547     const char * orig_parse = RExC_parse;
16548
16549     /* This variable is used to mark where the end in the input is of something
16550      * that looks like a POSIX construct but isn't.  During the parse, when
16551      * something looks like it could be such a construct is encountered, it is
16552      * checked for being one, but not if we've already checked this area of the
16553      * input.  Only after this position is reached do we check again */
16554     char *not_posix_region_end = RExC_parse - 1;
16555
16556     AV* posix_warnings = NULL;
16557     const bool do_posix_warnings = ckWARN(WARN_REGEXP);
16558     U8 op = END;    /* The returned node-type, initialized to an impossible
16559                        one.  */
16560     U8 anyof_flags = 0;   /* flag bits if the node is an ANYOF-type */
16561     U32 posixl = 0;       /* bit field of posix classes matched under /l */
16562
16563
16564 /* Flags as to what things aren't knowable until runtime.  (Note that these are
16565  * mutually exclusive.) */
16566 #define HAS_USER_DEFINED_PROPERTY 0x01   /* /u any user-defined properties that
16567                                             haven't been defined as of yet */
16568 #define HAS_D_RUNTIME_DEPENDENCY  0x02   /* /d if the target being matched is
16569                                             UTF-8 or not */
16570 #define HAS_L_RUNTIME_DEPENDENCY   0x04 /* /l what the posix classes match and
16571                                             what gets folded */
16572     U32 has_runtime_dependency = 0;     /* OR of the above flags */
16573
16574     GET_RE_DEBUG_FLAGS_DECL;
16575
16576     PERL_ARGS_ASSERT_REGCLASS;
16577 #ifndef DEBUGGING
16578     PERL_UNUSED_ARG(depth);
16579 #endif
16580
16581
16582     /* If wants an inversion list returned, we can't optimize to something
16583      * else. */
16584     if (ret_invlist) {
16585         optimizable = FALSE;
16586     }
16587
16588     DEBUG_PARSE("clas");
16589
16590 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */      \
16591     || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0          \
16592                                    && UNICODE_DOT_DOT_VERSION == 0)
16593     allow_multi_folds = FALSE;
16594 #endif
16595
16596     /* We include the /i status at the beginning of this so that we can
16597      * know it at runtime */
16598     listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
16599     initial_listsv_len = SvCUR(listsv);
16600     SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated.  */
16601
16602     SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16603
16604     assert(RExC_parse <= RExC_end);
16605
16606     if (UCHARAT(RExC_parse) == '^') {   /* Complement the class */
16607         RExC_parse++;
16608         invert = TRUE;
16609         allow_multi_folds = FALSE;
16610         MARK_NAUGHTY(1);
16611         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16612     }
16613
16614     /* Check that they didn't say [:posix:] instead of [[:posix:]] */
16615     if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
16616         int maybe_class = handle_possible_posix(pRExC_state,
16617                                                 RExC_parse,
16618                                                 &not_posix_region_end,
16619                                                 NULL,
16620                                                 TRUE /* checking only */);
16621         if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
16622             ckWARN4reg(not_posix_region_end,
16623                     "POSIX syntax [%c %c] belongs inside character classes%s",
16624                     *RExC_parse, *RExC_parse,
16625                     (maybe_class == OOB_NAMEDCLASS)
16626                     ? ((POSIXCC_NOTYET(*RExC_parse))
16627                         ? " (but this one isn't implemented)"
16628                         : " (but this one isn't fully valid)")
16629                     : ""
16630                     );
16631         }
16632     }
16633
16634     /* If the caller wants us to just parse a single element, accomplish this
16635      * by faking the loop ending condition */
16636     if (stop_at_1 && RExC_end > RExC_parse) {
16637         stop_ptr = RExC_parse + 1;
16638     }
16639
16640     /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
16641     if (UCHARAT(RExC_parse) == ']')
16642         goto charclassloop;
16643
16644     while (1) {
16645
16646         if (   posix_warnings
16647             && av_tindex_skip_len_mg(posix_warnings) >= 0
16648             && RExC_parse > not_posix_region_end)
16649         {
16650             /* Warnings about posix class issues are considered tentative until
16651              * we are far enough along in the parse that we can no longer
16652              * change our mind, at which point we output them.  This is done
16653              * each time through the loop so that a later class won't zap them
16654              * before they have been dealt with. */
16655             output_posix_warnings(pRExC_state, posix_warnings);
16656         }
16657
16658         if  (RExC_parse >= stop_ptr) {
16659             break;
16660         }
16661
16662         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16663
16664         if  (UCHARAT(RExC_parse) == ']') {
16665             break;
16666         }
16667
16668       charclassloop:
16669
16670         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
16671         save_value = value;
16672         save_prevvalue = prevvalue;
16673
16674         if (!range) {
16675             rangebegin = RExC_parse;
16676             element_count++;
16677             non_portable_endpoint = 0;
16678         }
16679         if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
16680             value = utf8n_to_uvchr((U8*)RExC_parse,
16681                                    RExC_end - RExC_parse,
16682                                    &numlen, UTF8_ALLOW_DEFAULT);
16683             RExC_parse += numlen;
16684         }
16685         else
16686             value = UCHARAT(RExC_parse++);
16687
16688         if (value == '[') {
16689             char * posix_class_end;
16690             namedclass = handle_possible_posix(pRExC_state,
16691                                                RExC_parse,
16692                                                &posix_class_end,
16693                                                do_posix_warnings ? &posix_warnings : NULL,
16694                                                FALSE    /* die if error */);
16695             if (namedclass > OOB_NAMEDCLASS) {
16696
16697                 /* If there was an earlier attempt to parse this particular
16698                  * posix class, and it failed, it was a false alarm, as this
16699                  * successful one proves */
16700                 if (   posix_warnings
16701                     && av_tindex_skip_len_mg(posix_warnings) >= 0
16702                     && not_posix_region_end >= RExC_parse
16703                     && not_posix_region_end <= posix_class_end)
16704                 {
16705                     av_undef(posix_warnings);
16706                 }
16707
16708                 RExC_parse = posix_class_end;
16709             }
16710             else if (namedclass == OOB_NAMEDCLASS) {
16711                 not_posix_region_end = posix_class_end;
16712             }
16713             else {
16714                 namedclass = OOB_NAMEDCLASS;
16715             }
16716         }
16717         else if (   RExC_parse - 1 > not_posix_region_end
16718                  && MAYBE_POSIXCC(value))
16719         {
16720             (void) handle_possible_posix(
16721                         pRExC_state,
16722                         RExC_parse - 1,  /* -1 because parse has already been
16723                                             advanced */
16724                         &not_posix_region_end,
16725                         do_posix_warnings ? &posix_warnings : NULL,
16726                         TRUE /* checking only */);
16727         }
16728         else if (  strict && ! skip_white
16729                  && (   _generic_isCC(value, _CC_VERTSPACE)
16730                      || is_VERTWS_cp_high(value)))
16731         {
16732             vFAIL("Literal vertical space in [] is illegal except under /x");
16733         }
16734         else if (value == '\\') {
16735             /* Is a backslash; get the code point of the char after it */
16736
16737             if (RExC_parse >= RExC_end) {
16738                 vFAIL("Unmatched [");
16739             }
16740
16741             if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
16742                 value = utf8n_to_uvchr((U8*)RExC_parse,
16743                                    RExC_end - RExC_parse,
16744                                    &numlen, UTF8_ALLOW_DEFAULT);
16745                 RExC_parse += numlen;
16746             }
16747             else
16748                 value = UCHARAT(RExC_parse++);
16749
16750             /* Some compilers cannot handle switching on 64-bit integer
16751              * values, therefore value cannot be an UV.  Yes, this will
16752              * be a problem later if we want switch on Unicode.
16753              * A similar issue a little bit later when switching on
16754              * namedclass. --jhi */
16755
16756             /* If the \ is escaping white space when white space is being
16757              * skipped, it means that that white space is wanted literally, and
16758              * is already in 'value'.  Otherwise, need to translate the escape
16759              * into what it signifies. */
16760             if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
16761
16762             case 'w':   namedclass = ANYOF_WORDCHAR;    break;
16763             case 'W':   namedclass = ANYOF_NWORDCHAR;   break;
16764             case 's':   namedclass = ANYOF_SPACE;       break;
16765             case 'S':   namedclass = ANYOF_NSPACE;      break;
16766             case 'd':   namedclass = ANYOF_DIGIT;       break;
16767             case 'D':   namedclass = ANYOF_NDIGIT;      break;
16768             case 'v':   namedclass = ANYOF_VERTWS;      break;
16769             case 'V':   namedclass = ANYOF_NVERTWS;     break;
16770             case 'h':   namedclass = ANYOF_HORIZWS;     break;
16771             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
16772             case 'N':  /* Handle \N{NAME} in class */
16773                 {
16774                     const char * const backslash_N_beg = RExC_parse - 2;
16775                     int cp_count;
16776
16777                     if (! grok_bslash_N(pRExC_state,
16778                                         NULL,      /* No regnode */
16779                                         &value,    /* Yes single value */
16780                                         &cp_count, /* Multiple code pt count */
16781                                         flagp,
16782                                         strict,
16783                                         depth)
16784                     ) {
16785
16786                         if (*flagp & NEED_UTF8)
16787                             FAIL("panic: grok_bslash_N set NEED_UTF8");
16788
16789                         RETURN_FAIL_ON_RESTART_FLAGP(flagp);
16790
16791                         if (cp_count < 0) {
16792                             vFAIL("\\N in a character class must be a named character: \\N{...}");
16793                         }
16794                         else if (cp_count == 0) {
16795                             ckWARNreg(RExC_parse,
16796                               "Ignoring zero length \\N{} in character class");
16797                         }
16798                         else { /* cp_count > 1 */
16799                             if (! RExC_in_multi_char_class) {
16800                                 if (invert || range || *RExC_parse == '-') {
16801                                     if (strict) {
16802                                         RExC_parse--;
16803                                         vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character");
16804                                     }
16805                                     ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
16806                                     break; /* <value> contains the first code
16807                                               point. Drop out of the switch to
16808                                               process it */
16809                                 }
16810                                 else {
16811                                     SV * multi_char_N = newSVpvn(backslash_N_beg,
16812                                                  RExC_parse - backslash_N_beg);
16813                                     multi_char_matches
16814                                         = add_multi_match(multi_char_matches,
16815                                                           multi_char_N,
16816                                                           cp_count);
16817                                 }
16818                             }
16819                         } /* End of cp_count != 1 */
16820
16821                         /* This element should not be processed further in this
16822                          * class */
16823                         element_count--;
16824                         value = save_value;
16825                         prevvalue = save_prevvalue;
16826                         continue;   /* Back to top of loop to get next char */
16827                     }
16828
16829                     /* Here, is a single code point, and <value> contains it */
16830                     unicode_range = TRUE;   /* \N{} are Unicode */
16831                 }
16832                 break;
16833             case 'p':
16834             case 'P':
16835                 {
16836                 char *e;
16837
16838                 /* \p means they want Unicode semantics */
16839                 REQUIRE_UNI_RULES(flagp, 0);
16840
16841                 if (RExC_parse >= RExC_end)
16842                     vFAIL2("Empty \\%c", (U8)value);
16843                 if (*RExC_parse == '{') {
16844                     const U8 c = (U8)value;
16845                     e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
16846                     if (!e) {
16847                         RExC_parse++;
16848                         vFAIL2("Missing right brace on \\%c{}", c);
16849                     }
16850
16851                     RExC_parse++;
16852
16853                     /* White space is allowed adjacent to the braces and after
16854                      * any '^', even when not under /x */
16855                     while (isSPACE(*RExC_parse)) {
16856                          RExC_parse++;
16857                     }
16858
16859                     if (UCHARAT(RExC_parse) == '^') {
16860
16861                         /* toggle.  (The rhs xor gets the single bit that
16862                          * differs between P and p; the other xor inverts just
16863                          * that bit) */
16864                         value ^= 'P' ^ 'p';
16865
16866                         RExC_parse++;
16867                         while (isSPACE(*RExC_parse)) {
16868                             RExC_parse++;
16869                         }
16870                     }
16871
16872                     if (e == RExC_parse)
16873                         vFAIL2("Empty \\%c{}", c);
16874
16875                     n = e - RExC_parse;
16876                     while (isSPACE(*(RExC_parse + n - 1)))
16877                         n--;
16878
16879                 }   /* The \p isn't immediately followed by a '{' */
16880                 else if (! isALPHA(*RExC_parse)) {
16881                     RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16882                     vFAIL2("Character following \\%c must be '{' or a "
16883                            "single-character Unicode property name",
16884                            (U8) value);
16885                 }
16886                 else {
16887                     e = RExC_parse;
16888                     n = 1;
16889                 }
16890                 {
16891                     char* name = RExC_parse;
16892
16893                     /* Any message returned about expanding the definition */
16894                     SV* msg = newSVpvs_flags("", SVs_TEMP);
16895
16896                     /* If set TRUE, the property is user-defined as opposed to
16897                      * official Unicode */
16898                     bool user_defined = FALSE;
16899
16900                     SV * prop_definition = parse_uniprop_string(
16901                                             name, n, UTF, FOLD,
16902                                             FALSE, /* This is compile-time */
16903                                             &user_defined,
16904                                             msg,
16905                                             0 /* Base level */
16906                                            );
16907                     if (SvCUR(msg)) {   /* Assumes any error causes a msg */
16908                         assert(prop_definition == NULL);
16909                         RExC_parse = e + 1;
16910                         if (SvUTF8(msg)) {  /* msg being UTF-8 makes the whole
16911                                                thing so, or else the display is
16912                                                mojibake */
16913                             RExC_utf8 = TRUE;
16914                         }
16915                         /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
16916                         vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
16917                                     SvCUR(msg), SvPVX(msg)));
16918                     }
16919
16920                     if (! is_invlist(prop_definition)) {
16921
16922                         /* Here, the definition isn't known, so we have gotten
16923                          * returned a string that will be evaluated if and when
16924                          * encountered at runtime.  We add it to the list of
16925                          * such properties, along with whether it should be
16926                          * complemented or not */
16927                         if (value == 'P') {
16928                             sv_catpvs(listsv, "!");
16929                         }
16930                         else {
16931                             sv_catpvs(listsv, "+");
16932                         }
16933                         sv_catsv(listsv, prop_definition);
16934
16935                         has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
16936
16937                         /* We don't know yet what this matches, so have to flag
16938                          * it */
16939                         anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
16940                     }
16941                     else {
16942                         assert (prop_definition && is_invlist(prop_definition));
16943
16944                         /* Here we do have the complete property definition
16945                          *
16946                          * Temporary workaround for [perl #133136].  For this
16947                          * precise input that is in the .t that is failing,
16948                          * load utf8.pm, which is what the test wants, so that
16949                          * that .t passes */
16950                         if (     memEQs(RExC_start, e + 1 - RExC_start,
16951                                         "foo\\p{Alnum}")
16952                             && ! hv_common(GvHVn(PL_incgv),
16953                                            NULL,
16954                                            "utf8.pm", sizeof("utf8.pm") - 1,
16955                                            0, HV_FETCH_ISEXISTS, NULL, 0))
16956                         {
16957                             require_pv("utf8.pm");
16958                         }
16959
16960                         if (! user_defined &&
16961                             /* We warn on matching an above-Unicode code point
16962                              * if the match would return true, except don't
16963                              * warn for \p{All}, which has exactly one element
16964                              * = 0 */
16965                             (_invlist_contains_cp(prop_definition, 0x110000)
16966                                 && (! (_invlist_len(prop_definition) == 1
16967                                        && *invlist_array(prop_definition) == 0))))
16968                         {
16969                             warn_super = TRUE;
16970                         }
16971
16972                         /* Invert if asking for the complement */
16973                         if (value == 'P') {
16974                             _invlist_union_complement_2nd(properties,
16975                                                           prop_definition,
16976                                                           &properties);
16977                         }
16978                         else {
16979                             _invlist_union(properties, prop_definition, &properties);
16980                         }
16981                     }
16982                 }
16983
16984                 RExC_parse = e + 1;
16985                 namedclass = ANYOF_UNIPROP;  /* no official name, but it's
16986                                                 named */
16987                 }
16988                 break;
16989             case 'n':   value = '\n';                   break;
16990             case 'r':   value = '\r';                   break;
16991             case 't':   value = '\t';                   break;
16992             case 'f':   value = '\f';                   break;
16993             case 'b':   value = '\b';                   break;
16994             case 'e':   value = ESC_NATIVE;             break;
16995             case 'a':   value = '\a';                   break;
16996             case 'o':
16997                 RExC_parse--;   /* function expects to be pointed at the 'o' */
16998                 {
16999                     const char* error_msg;
17000                     bool valid = grok_bslash_o(&RExC_parse,
17001                                                RExC_end,
17002                                                &value,
17003                                                &error_msg,
17004                                                TO_OUTPUT_WARNINGS(RExC_parse),
17005                                                strict,
17006                                                silence_non_portable,
17007                                                UTF);
17008                     if (! valid) {
17009                         vFAIL(error_msg);
17010                     }
17011                     UPDATE_WARNINGS_LOC(RExC_parse - 1);
17012                 }
17013                 non_portable_endpoint++;
17014                 break;
17015             case 'x':
17016                 RExC_parse--;   /* function expects to be pointed at the 'x' */
17017                 {
17018                     const char* error_msg;
17019                     bool valid = grok_bslash_x(&RExC_parse,
17020                                                RExC_end,
17021                                                &value,
17022                                                &error_msg,
17023                                                TO_OUTPUT_WARNINGS(RExC_parse),
17024                                                strict,
17025                                                silence_non_portable,
17026                                                UTF);
17027                     if (! valid) {
17028                         vFAIL(error_msg);
17029                     }
17030                     UPDATE_WARNINGS_LOC(RExC_parse - 1);
17031                 }
17032                 non_portable_endpoint++;
17033                 break;
17034             case 'c':
17035                 value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse));
17036                 UPDATE_WARNINGS_LOC(RExC_parse);
17037                 RExC_parse++;
17038                 non_portable_endpoint++;
17039                 break;
17040             case '0': case '1': case '2': case '3': case '4':
17041             case '5': case '6': case '7':
17042                 {
17043                     /* Take 1-3 octal digits */
17044                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
17045                     numlen = (strict) ? 4 : 3;
17046                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17047                     RExC_parse += numlen;
17048                     if (numlen != 3) {
17049                         if (strict) {
17050                             RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
17051                             vFAIL("Need exactly 3 octal digits");
17052                         }
17053                         else if (   numlen < 3 /* like \08, \178 */
17054                                  && RExC_parse < RExC_end
17055                                  && isDIGIT(*RExC_parse)
17056                                  && ckWARN(WARN_REGEXP))
17057                         {
17058                             reg_warn_non_literal_string(
17059                                  RExC_parse + 1,
17060                                  form_short_octal_warning(RExC_parse, numlen));
17061                         }
17062                     }
17063                     non_portable_endpoint++;
17064                     break;
17065                 }
17066             default:
17067                 /* Allow \_ to not give an error */
17068                 if (isWORDCHAR(value) && value != '_') {
17069                     if (strict) {
17070                         vFAIL2("Unrecognized escape \\%c in character class",
17071                                (int)value);
17072                     }
17073                     else {
17074                         ckWARN2reg(RExC_parse,
17075                             "Unrecognized escape \\%c in character class passed through",
17076                             (int)value);
17077                     }
17078                 }
17079                 break;
17080             }   /* End of switch on char following backslash */
17081         } /* end of handling backslash escape sequences */
17082
17083         /* Here, we have the current token in 'value' */
17084
17085         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
17086             U8 classnum;
17087
17088             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
17089              * literal, as is the character that began the false range, i.e.
17090              * the 'a' in the examples */
17091             if (range) {
17092                 const int w = (RExC_parse >= rangebegin)
17093                                 ? RExC_parse - rangebegin
17094                                 : 0;
17095                 if (strict) {
17096                     vFAIL2utf8f(
17097                         "False [] range \"%" UTF8f "\"",
17098                         UTF8fARG(UTF, w, rangebegin));
17099                 }
17100                 else {
17101                     ckWARN2reg(RExC_parse,
17102                         "False [] range \"%" UTF8f "\"",
17103                         UTF8fARG(UTF, w, rangebegin));
17104                     cp_list = add_cp_to_invlist(cp_list, '-');
17105                     cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
17106                                                             prevvalue);
17107                 }
17108
17109                 range = 0; /* this was not a true range */
17110                 element_count += 2; /* So counts for three values */
17111             }
17112
17113             classnum = namedclass_to_classnum(namedclass);
17114
17115             if (LOC && namedclass < ANYOF_POSIXL_MAX
17116 #ifndef HAS_ISASCII
17117                 && classnum != _CC_ASCII
17118 #endif
17119             ) {
17120                 SV* scratch_list = NULL;
17121
17122                 /* What the Posix classes (like \w, [:space:]) match in locale
17123                  * isn't knowable under locale until actual match time.  A
17124                  * special node is used for these which has extra space for a
17125                  * bitmap, with a bit reserved for each named class that is to
17126                  * be matched against.  This isn't needed for \p{} and
17127                  * pseudo-classes, as they are not affected by locale, and
17128                  * hence are dealt with separately */
17129                 POSIXL_SET(posixl, namedclass);
17130                 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
17131                 anyof_flags |= ANYOF_MATCHES_POSIXL;
17132
17133                 /* The above-Latin1 characters are not subject to locale rules.
17134                  * Just add them to the unconditionally-matched list */
17135
17136                 /* Get the list of the above-Latin1 code points this matches */
17137                 _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
17138                                         PL_XPosix_ptrs[classnum],
17139
17140                                         /* Odd numbers are complements, like
17141                                         * NDIGIT, NASCII, ... */
17142                                         namedclass % 2 != 0,
17143                                         &scratch_list);
17144                 /* Checking if 'cp_list' is NULL first saves an extra clone.
17145                  * Its reference count will be decremented at the next union,
17146                  * etc, or if this is the only instance, at the end of the
17147                  * routine */
17148                 if (! cp_list) {
17149                     cp_list = scratch_list;
17150                 }
17151                 else {
17152                     _invlist_union(cp_list, scratch_list, &cp_list);
17153                     SvREFCNT_dec_NN(scratch_list);
17154                 }
17155                 continue;   /* Go get next character */
17156             }
17157             else {
17158
17159                 /* Here, is not /l, or is a POSIX class for which /l doesn't
17160                  * matter (or is a Unicode property, which is skipped here). */
17161                 if (namedclass >= ANYOF_POSIXL_MAX) {  /* If a special class */
17162                     if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
17163
17164                         /* Here, should be \h, \H, \v, or \V.  None of /d, /i
17165                          * nor /l make a difference in what these match,
17166                          * therefore we just add what they match to cp_list. */
17167                         if (classnum != _CC_VERTSPACE) {
17168                             assert(   namedclass == ANYOF_HORIZWS
17169                                    || namedclass == ANYOF_NHORIZWS);
17170
17171                             /* It turns out that \h is just a synonym for
17172                              * XPosixBlank */
17173                             classnum = _CC_BLANK;
17174                         }
17175
17176                         _invlist_union_maybe_complement_2nd(
17177                                 cp_list,
17178                                 PL_XPosix_ptrs[classnum],
17179                                 namedclass % 2 != 0,    /* Complement if odd
17180                                                           (NHORIZWS, NVERTWS)
17181                                                         */
17182                                 &cp_list);
17183                     }
17184                 }
17185                 else if (   AT_LEAST_UNI_SEMANTICS
17186                          || classnum == _CC_ASCII
17187                          || (DEPENDS_SEMANTICS && (   classnum == _CC_DIGIT
17188                                                    || classnum == _CC_XDIGIT)))
17189                 {
17190                     /* We usually have to worry about /d affecting what POSIX
17191                      * classes match, with special code needed because we won't
17192                      * know until runtime what all matches.  But there is no
17193                      * extra work needed under /u and /a; and [:ascii:] is
17194                      * unaffected by /d; and :digit: and :xdigit: don't have
17195                      * runtime differences under /d.  So we can special case
17196                      * these, and avoid some extra work below, and at runtime.
17197                      * */
17198                     _invlist_union_maybe_complement_2nd(
17199                                                      simple_posixes,
17200                                                       ((AT_LEAST_ASCII_RESTRICTED)
17201                                                        ? PL_Posix_ptrs[classnum]
17202                                                        : PL_XPosix_ptrs[classnum]),
17203                                                      namedclass % 2 != 0,
17204                                                      &simple_posixes);
17205                 }
17206                 else {  /* Garden variety class.  If is NUPPER, NALPHA, ...
17207                            complement and use nposixes */
17208                     SV** posixes_ptr = namedclass % 2 == 0
17209                                        ? &posixes
17210                                        : &nposixes;
17211                     _invlist_union_maybe_complement_2nd(
17212                                                      *posixes_ptr,
17213                                                      PL_XPosix_ptrs[classnum],
17214                                                      namedclass % 2 != 0,
17215                                                      posixes_ptr);
17216                 }
17217             }
17218         } /* end of namedclass \blah */
17219
17220         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17221
17222         /* If 'range' is set, 'value' is the ending of a range--check its
17223          * validity.  (If value isn't a single code point in the case of a
17224          * range, we should have figured that out above in the code that
17225          * catches false ranges).  Later, we will handle each individual code
17226          * point in the range.  If 'range' isn't set, this could be the
17227          * beginning of a range, so check for that by looking ahead to see if
17228          * the next real character to be processed is the range indicator--the
17229          * minus sign */
17230
17231         if (range) {
17232 #ifdef EBCDIC
17233             /* For unicode ranges, we have to test that the Unicode as opposed
17234              * to the native values are not decreasing.  (Above 255, there is
17235              * no difference between native and Unicode) */
17236             if (unicode_range && prevvalue < 255 && value < 255) {
17237                 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
17238                     goto backwards_range;
17239                 }
17240             }
17241             else
17242 #endif
17243             if (prevvalue > value) /* b-a */ {
17244                 int w;
17245 #ifdef EBCDIC
17246               backwards_range:
17247 #endif
17248                 w = RExC_parse - rangebegin;
17249                 vFAIL2utf8f(
17250                     "Invalid [] range \"%" UTF8f "\"",
17251                     UTF8fARG(UTF, w, rangebegin));
17252                 NOT_REACHED; /* NOTREACHED */
17253             }
17254         }
17255         else {
17256             prevvalue = value; /* save the beginning of the potential range */
17257             if (! stop_at_1     /* Can't be a range if parsing just one thing */
17258                 && *RExC_parse == '-')
17259             {
17260                 char* next_char_ptr = RExC_parse + 1;
17261
17262                 /* Get the next real char after the '-' */
17263                 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
17264
17265                 /* If the '-' is at the end of the class (just before the ']',
17266                  * it is a literal minus; otherwise it is a range */
17267                 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
17268                     RExC_parse = next_char_ptr;
17269
17270                     /* a bad range like \w-, [:word:]- ? */
17271                     if (namedclass > OOB_NAMEDCLASS) {
17272                         if (strict || ckWARN(WARN_REGEXP)) {
17273                             const int w = RExC_parse >= rangebegin
17274                                           ?  RExC_parse - rangebegin
17275                                           : 0;
17276                             if (strict) {
17277                                 vFAIL4("False [] range \"%*.*s\"",
17278                                     w, w, rangebegin);
17279                             }
17280                             else {
17281                                 vWARN4(RExC_parse,
17282                                     "False [] range \"%*.*s\"",
17283                                     w, w, rangebegin);
17284                             }
17285                         }
17286                         cp_list = add_cp_to_invlist(cp_list, '-');
17287                         element_count++;
17288                     } else
17289                         range = 1;      /* yeah, it's a range! */
17290                     continue;   /* but do it the next time */
17291                 }
17292             }
17293         }
17294
17295         if (namedclass > OOB_NAMEDCLASS) {
17296             continue;
17297         }
17298
17299         /* Here, we have a single value this time through the loop, and
17300          * <prevvalue> is the beginning of the range, if any; or <value> if
17301          * not. */
17302
17303         /* non-Latin1 code point implies unicode semantics. */
17304         if (value > 255) {
17305             REQUIRE_UNI_RULES(flagp, 0);
17306         }
17307
17308         /* Ready to process either the single value, or the completed range.
17309          * For single-valued non-inverted ranges, we consider the possibility
17310          * of multi-char folds.  (We made a conscious decision to not do this
17311          * for the other cases because it can often lead to non-intuitive
17312          * results.  For example, you have the peculiar case that:
17313          *  "s s" =~ /^[^\xDF]+$/i => Y
17314          *  "ss"  =~ /^[^\xDF]+$/i => N
17315          *
17316          * See [perl #89750] */
17317         if (FOLD && allow_multi_folds && value == prevvalue) {
17318             if (    value == LATIN_SMALL_LETTER_SHARP_S
17319                 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
17320                                                         value)))
17321             {
17322                 /* Here <value> is indeed a multi-char fold.  Get what it is */
17323
17324                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17325                 STRLEN foldlen;
17326
17327                 UV folded = _to_uni_fold_flags(
17328                                 value,
17329                                 foldbuf,
17330                                 &foldlen,
17331                                 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
17332                                                    ? FOLD_FLAGS_NOMIX_ASCII
17333                                                    : 0)
17334                                 );
17335
17336                 /* Here, <folded> should be the first character of the
17337                  * multi-char fold of <value>, with <foldbuf> containing the
17338                  * whole thing.  But, if this fold is not allowed (because of
17339                  * the flags), <fold> will be the same as <value>, and should
17340                  * be processed like any other character, so skip the special
17341                  * handling */
17342                 if (folded != value) {
17343
17344                     /* Skip if we are recursed, currently parsing the class
17345                      * again.  Otherwise add this character to the list of
17346                      * multi-char folds. */
17347                     if (! RExC_in_multi_char_class) {
17348                         STRLEN cp_count = utf8_length(foldbuf,
17349                                                       foldbuf + foldlen);
17350                         SV* multi_fold = sv_2mortal(newSVpvs(""));
17351
17352                         Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
17353
17354                         multi_char_matches
17355                                         = add_multi_match(multi_char_matches,
17356                                                           multi_fold,
17357                                                           cp_count);
17358
17359                     }
17360
17361                     /* This element should not be processed further in this
17362                      * class */
17363                     element_count--;
17364                     value = save_value;
17365                     prevvalue = save_prevvalue;
17366                     continue;
17367                 }
17368             }
17369         }
17370
17371         if (strict && ckWARN(WARN_REGEXP)) {
17372             if (range) {
17373
17374                 /* If the range starts above 255, everything is portable and
17375                  * likely to be so for any forseeable character set, so don't
17376                  * warn. */
17377                 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
17378                     vWARN(RExC_parse, "Both or neither range ends should be Unicode");
17379                 }
17380                 else if (prevvalue != value) {
17381
17382                     /* Under strict, ranges that stop and/or end in an ASCII
17383                      * printable should have each end point be a portable value
17384                      * for it (preferably like 'A', but we don't warn if it is
17385                      * a (portable) Unicode name or code point), and the range
17386                      * must be be all digits or all letters of the same case.
17387                      * Otherwise, the range is non-portable and unclear as to
17388                      * what it contains */
17389                     if (             (isPRINT_A(prevvalue) || isPRINT_A(value))
17390                         && (          non_portable_endpoint
17391                             || ! (   (isDIGIT_A(prevvalue) && isDIGIT_A(value))
17392                                   || (isLOWER_A(prevvalue) && isLOWER_A(value))
17393                                   || (isUPPER_A(prevvalue) && isUPPER_A(value))
17394                     ))) {
17395                         vWARN(RExC_parse, "Ranges of ASCII printables should"
17396                                           " be some subset of \"0-9\","
17397                                           " \"A-Z\", or \"a-z\"");
17398                     }
17399                     else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
17400                         SSize_t index_start;
17401                         SSize_t index_final;
17402
17403                         /* But the nature of Unicode and languages mean we
17404                          * can't do the same checks for above-ASCII ranges,
17405                          * except in the case of digit ones.  These should
17406                          * contain only digits from the same group of 10.  The
17407                          * ASCII case is handled just above.  Hence here, the
17408                          * range could be a range of digits.  First some
17409                          * unlikely special cases.  Grandfather in that a range
17410                          * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
17411                          * if its starting value is one of the 10 digits prior
17412                          * to it.  This is because it is an alternate way of
17413                          * writing 19D1, and some people may expect it to be in
17414                          * that group.  But it is bad, because it won't give
17415                          * the expected results.  In Unicode 5.2 it was
17416                          * considered to be in that group (of 11, hence), but
17417                          * this was fixed in the next version */
17418
17419                         if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
17420                             goto warn_bad_digit_range;
17421                         }
17422                         else if (UNLIKELY(   prevvalue >= 0x1D7CE
17423                                           &&     value <= 0x1D7FF))
17424                         {
17425                             /* This is the only other case currently in Unicode
17426                              * where the algorithm below fails.  The code
17427                              * points just above are the end points of a single
17428                              * range containing only decimal digits.  It is 5
17429                              * different series of 0-9.  All other ranges of
17430                              * digits currently in Unicode are just a single
17431                              * series.  (And mktables will notify us if a later
17432                              * Unicode version breaks this.)
17433                              *
17434                              * If the range being checked is at most 9 long,
17435                              * and the digit values represented are in
17436                              * numerical order, they are from the same series.
17437                              * */
17438                             if (         value - prevvalue > 9
17439                                 ||    (((    value - 0x1D7CE) % 10)
17440                                      <= (prevvalue - 0x1D7CE) % 10))
17441                             {
17442                                 goto warn_bad_digit_range;
17443                             }
17444                         }
17445                         else {
17446
17447                             /* For all other ranges of digits in Unicode, the
17448                              * algorithm is just to check if both end points
17449                              * are in the same series, which is the same range.
17450                              * */
17451                             index_start = _invlist_search(
17452                                                     PL_XPosix_ptrs[_CC_DIGIT],
17453                                                     prevvalue);
17454
17455                             /* Warn if the range starts and ends with a digit,
17456                              * and they are not in the same group of 10. */
17457                             if (   index_start >= 0
17458                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
17459                                 && (index_final =
17460                                     _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
17461                                                     value)) != index_start
17462                                 && index_final >= 0
17463                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
17464                             {
17465                               warn_bad_digit_range:
17466                                 vWARN(RExC_parse, "Ranges of digits should be"
17467                                                   " from the same group of"
17468                                                   " 10");
17469                             }
17470                         }
17471                     }
17472                 }
17473             }
17474             if ((! range || prevvalue == value) && non_portable_endpoint) {
17475                 if (isPRINT_A(value)) {
17476                     char literal[3];
17477                     unsigned d = 0;
17478                     if (isBACKSLASHED_PUNCT(value)) {
17479                         literal[d++] = '\\';
17480                     }
17481                     literal[d++] = (char) value;
17482                     literal[d++] = '\0';
17483
17484                     vWARN4(RExC_parse,
17485                            "\"%.*s\" is more clearly written simply as \"%s\"",
17486                            (int) (RExC_parse - rangebegin),
17487                            rangebegin,
17488                            literal
17489                         );
17490                 }
17491                 else if isMNEMONIC_CNTRL(value) {
17492                     vWARN4(RExC_parse,
17493                            "\"%.*s\" is more clearly written simply as \"%s\"",
17494                            (int) (RExC_parse - rangebegin),
17495                            rangebegin,
17496                            cntrl_to_mnemonic((U8) value)
17497                         );
17498                 }
17499             }
17500         }
17501
17502         /* Deal with this element of the class */
17503
17504 #ifndef EBCDIC
17505         cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17506                                                     prevvalue, value);
17507 #else
17508         /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
17509          * that don't require special handling, we can just add the range like
17510          * we do for ASCII platforms */
17511         if ((UNLIKELY(prevvalue == 0) && value >= 255)
17512             || ! (prevvalue < 256
17513                     && (unicode_range
17514                         || (! non_portable_endpoint
17515                             && ((isLOWER_A(prevvalue) && isLOWER_A(value))
17516                                 || (isUPPER_A(prevvalue)
17517                                     && isUPPER_A(value)))))))
17518         {
17519             cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17520                                                         prevvalue, value);
17521         }
17522         else {
17523             /* Here, requires special handling.  This can be because it is a
17524              * range whose code points are considered to be Unicode, and so
17525              * must be individually translated into native, or because its a
17526              * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
17527              * EBCDIC, but we have defined them to include only the "expected"
17528              * upper or lower case ASCII alphabetics.  Subranges above 255 are
17529              * the same in native and Unicode, so can be added as a range */
17530             U8 start = NATIVE_TO_LATIN1(prevvalue);
17531             unsigned j;
17532             U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
17533             for (j = start; j <= end; j++) {
17534                 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
17535             }
17536             if (value > 255) {
17537                 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
17538                                                             256, value);
17539             }
17540         }
17541 #endif
17542
17543         range = 0; /* this range (if it was one) is done now */
17544     } /* End of loop through all the text within the brackets */
17545
17546     if (   posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
17547         output_posix_warnings(pRExC_state, posix_warnings);
17548     }
17549
17550     /* If anything in the class expands to more than one character, we have to
17551      * deal with them by building up a substitute parse string, and recursively
17552      * calling reg() on it, instead of proceeding */
17553     if (multi_char_matches) {
17554         SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
17555         I32 cp_count;
17556         STRLEN len;
17557         char *save_end = RExC_end;
17558         char *save_parse = RExC_parse;
17559         char *save_start = RExC_start;
17560         Size_t constructed_prefix_len = 0; /* This gives the length of the
17561                                               constructed portion of the
17562                                               substitute parse. */
17563         bool first_time = TRUE;     /* First multi-char occurrence doesn't get
17564                                        a "|" */
17565         I32 reg_flags;
17566
17567         assert(! invert);
17568         /* Only one level of recursion allowed */
17569         assert(RExC_copy_start_in_constructed == RExC_precomp);
17570
17571 #if 0   /* Have decided not to deal with multi-char folds in inverted classes,
17572            because too confusing */
17573         if (invert) {
17574             sv_catpvs(substitute_parse, "(?:");
17575         }
17576 #endif
17577
17578         /* Look at the longest folds first */
17579         for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
17580                         cp_count > 0;
17581                         cp_count--)
17582         {
17583
17584             if (av_exists(multi_char_matches, cp_count)) {
17585                 AV** this_array_ptr;
17586                 SV* this_sequence;
17587
17588                 this_array_ptr = (AV**) av_fetch(multi_char_matches,
17589                                                  cp_count, FALSE);
17590                 while ((this_sequence = av_pop(*this_array_ptr)) !=
17591                                                                 &PL_sv_undef)
17592                 {
17593                     if (! first_time) {
17594                         sv_catpvs(substitute_parse, "|");
17595                     }
17596                     first_time = FALSE;
17597
17598                     sv_catpv(substitute_parse, SvPVX(this_sequence));
17599                 }
17600             }
17601         }
17602
17603         /* If the character class contains anything else besides these
17604          * multi-character folds, have to include it in recursive parsing */
17605         if (element_count) {
17606             sv_catpvs(substitute_parse, "|[");
17607             constructed_prefix_len = SvCUR(substitute_parse);
17608             sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
17609
17610             /* Put in a closing ']' only if not going off the end, as otherwise
17611              * we are adding something that really isn't there */
17612             if (RExC_parse < RExC_end) {
17613                 sv_catpvs(substitute_parse, "]");
17614             }
17615         }
17616
17617         sv_catpvs(substitute_parse, ")");
17618 #if 0
17619         if (invert) {
17620             /* This is a way to get the parse to skip forward a whole named
17621              * sequence instead of matching the 2nd character when it fails the
17622              * first */
17623             sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
17624         }
17625 #endif
17626
17627         /* Set up the data structure so that any errors will be properly
17628          * reported.  See the comments at the definition of
17629          * REPORT_LOCATION_ARGS for details */
17630         RExC_copy_start_in_input = (char *) orig_parse;
17631         RExC_start = RExC_parse = SvPV(substitute_parse, len);
17632         RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
17633         RExC_end = RExC_parse + len;
17634         RExC_in_multi_char_class = 1;
17635
17636         ret = reg(pRExC_state, 1, &reg_flags, depth+1);
17637
17638         *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
17639
17640         /* And restore so can parse the rest of the pattern */
17641         RExC_parse = save_parse;
17642         RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
17643         RExC_end = save_end;
17644         RExC_in_multi_char_class = 0;
17645         SvREFCNT_dec_NN(multi_char_matches);
17646         return ret;
17647     }
17648
17649     /* If folding, we calculate all characters that could fold to or from the
17650      * ones already on the list */
17651     if (cp_foldable_list) {
17652         if (FOLD) {
17653             UV start, end;      /* End points of code point ranges */
17654
17655             SV* fold_intersection = NULL;
17656             SV** use_list;
17657
17658             /* Our calculated list will be for Unicode rules.  For locale
17659              * matching, we have to keep a separate list that is consulted at
17660              * runtime only when the locale indicates Unicode rules (and we
17661              * don't include potential matches in the ASCII/Latin1 range, as
17662              * any code point could fold to any other, based on the run-time
17663              * locale).   For non-locale, we just use the general list */
17664             if (LOC) {
17665                 use_list = &only_utf8_locale_list;
17666             }
17667             else {
17668                 use_list = &cp_list;
17669             }
17670
17671             /* Only the characters in this class that participate in folds need
17672              * be checked.  Get the intersection of this class and all the
17673              * possible characters that are foldable.  This can quickly narrow
17674              * down a large class */
17675             _invlist_intersection(PL_in_some_fold, cp_foldable_list,
17676                                   &fold_intersection);
17677
17678             /* Now look at the foldable characters in this class individually */
17679             invlist_iterinit(fold_intersection);
17680             while (invlist_iternext(fold_intersection, &start, &end)) {
17681                 UV j;
17682                 UV folded;
17683
17684                 /* Look at every character in the range */
17685                 for (j = start; j <= end; j++) {
17686                     U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17687                     STRLEN foldlen;
17688                     unsigned int k;
17689                     Size_t folds_count;
17690                     unsigned int first_fold;
17691                     const unsigned int * remaining_folds;
17692
17693                     if (j < 256) {
17694
17695                         /* Under /l, we don't know what code points below 256
17696                          * fold to, except we do know the MICRO SIGN folds to
17697                          * an above-255 character if the locale is UTF-8, so we
17698                          * add it to the special list (in *use_list)  Otherwise
17699                          * we know now what things can match, though some folds
17700                          * are valid under /d only if the target is UTF-8.
17701                          * Those go in a separate list */
17702                         if (      IS_IN_SOME_FOLD_L1(j)
17703                             && ! (LOC && j != MICRO_SIGN))
17704                         {
17705
17706                             /* ASCII is always matched; non-ASCII is matched
17707                              * only under Unicode rules (which could happen
17708                              * under /l if the locale is a UTF-8 one */
17709                             if (isASCII(j) || ! DEPENDS_SEMANTICS) {
17710                                 *use_list = add_cp_to_invlist(*use_list,
17711                                                             PL_fold_latin1[j]);
17712                             }
17713                             else if (j != PL_fold_latin1[j]) {
17714                                 upper_latin1_only_utf8_matches
17715                                         = add_cp_to_invlist(
17716                                                 upper_latin1_only_utf8_matches,
17717                                                 PL_fold_latin1[j]);
17718                             }
17719                         }
17720
17721                         if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
17722                             && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
17723                         {
17724                             add_above_Latin1_folds(pRExC_state,
17725                                                    (U8) j,
17726                                                    use_list);
17727                         }
17728                         continue;
17729                     }
17730
17731                     /* Here is an above Latin1 character.  We don't have the
17732                      * rules hard-coded for it.  First, get its fold.  This is
17733                      * the simple fold, as the multi-character folds have been
17734                      * handled earlier and separated out */
17735                     folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
17736                                                         (ASCII_FOLD_RESTRICTED)
17737                                                         ? FOLD_FLAGS_NOMIX_ASCII
17738                                                         : 0);
17739
17740                     /* Single character fold of above Latin1.  Add everything
17741                      * in its fold closure to the list that this node should
17742                      * match. */
17743                     folds_count = _inverse_folds(folded, &first_fold,
17744                                                     &remaining_folds);
17745                     for (k = 0; k <= folds_count; k++) {
17746                         UV c = (k == 0)     /* First time through use itself */
17747                                 ? folded
17748                                 : (k == 1)  /* 2nd time use, the first fold */
17749                                    ? first_fold
17750
17751                                      /* Then the remaining ones */
17752                                    : remaining_folds[k-2];
17753
17754                         /* /aa doesn't allow folds between ASCII and non- */
17755                         if ((   ASCII_FOLD_RESTRICTED
17756                             && (isASCII(c) != isASCII(j))))
17757                         {
17758                             continue;
17759                         }
17760
17761                         /* Folds under /l which cross the 255/256 boundary are
17762                          * added to a separate list.  (These are valid only
17763                          * when the locale is UTF-8.) */
17764                         if (c < 256 && LOC) {
17765                             *use_list = add_cp_to_invlist(*use_list, c);
17766                             continue;
17767                         }
17768
17769                         if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
17770                         {
17771                             cp_list = add_cp_to_invlist(cp_list, c);
17772                         }
17773                         else {
17774                             /* Similarly folds involving non-ascii Latin1
17775                              * characters under /d are added to their list */
17776                             upper_latin1_only_utf8_matches
17777                                     = add_cp_to_invlist(
17778                                                 upper_latin1_only_utf8_matches,
17779                                                 c);
17780                         }
17781                     }
17782                 }
17783             }
17784             SvREFCNT_dec_NN(fold_intersection);
17785         }
17786
17787         /* Now that we have finished adding all the folds, there is no reason
17788          * to keep the foldable list separate */
17789         _invlist_union(cp_list, cp_foldable_list, &cp_list);
17790         SvREFCNT_dec_NN(cp_foldable_list);
17791     }
17792
17793     /* And combine the result (if any) with any inversion lists from posix
17794      * classes.  The lists are kept separate up to now because we don't want to
17795      * fold the classes */
17796     if (simple_posixes) {   /* These are the classes known to be unaffected by
17797                                /a, /aa, and /d */
17798         if (cp_list) {
17799             _invlist_union(cp_list, simple_posixes, &cp_list);
17800             SvREFCNT_dec_NN(simple_posixes);
17801         }
17802         else {
17803             cp_list = simple_posixes;
17804         }
17805     }
17806     if (posixes || nposixes) {
17807         if (! DEPENDS_SEMANTICS) {
17808
17809             /* For everything but /d, we can just add the current 'posixes' and
17810              * 'nposixes' to the main list */
17811             if (posixes) {
17812                 if (cp_list) {
17813                     _invlist_union(cp_list, posixes, &cp_list);
17814                     SvREFCNT_dec_NN(posixes);
17815                 }
17816                 else {
17817                     cp_list = posixes;
17818                 }
17819             }
17820             if (nposixes) {
17821                 if (cp_list) {
17822                     _invlist_union(cp_list, nposixes, &cp_list);
17823                     SvREFCNT_dec_NN(nposixes);
17824                 }
17825                 else {
17826                     cp_list = nposixes;
17827                 }
17828             }
17829         }
17830         else {
17831             /* Under /d, things like \w match upper Latin1 characters only if
17832              * the target string is in UTF-8.  But things like \W match all the
17833              * upper Latin1 characters if the target string is not in UTF-8.
17834              *
17835              * Handle the case with something like \W separately */
17836             if (nposixes) {
17837                 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
17838
17839                 /* A complemented posix class matches all upper Latin1
17840                  * characters if not in UTF-8.  And it matches just certain
17841                  * ones when in UTF-8.  That means those certain ones are
17842                  * matched regardless, so can just be added to the
17843                  * unconditional list */
17844                 if (cp_list) {
17845                     _invlist_union(cp_list, nposixes, &cp_list);
17846                     SvREFCNT_dec_NN(nposixes);
17847                     nposixes = NULL;
17848                 }
17849                 else {
17850                     cp_list = nposixes;
17851                 }
17852
17853                 /* Likewise for 'posixes' */
17854                 _invlist_union(posixes, cp_list, &cp_list);
17855
17856                 /* Likewise for anything else in the range that matched only
17857                  * under UTF-8 */
17858                 if (upper_latin1_only_utf8_matches) {
17859                     _invlist_union(cp_list,
17860                                    upper_latin1_only_utf8_matches,
17861                                    &cp_list);
17862                     SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
17863                     upper_latin1_only_utf8_matches = NULL;
17864                 }
17865
17866                 /* If we don't match all the upper Latin1 characters regardless
17867                  * of UTF-8ness, we have to set a flag to match the rest when
17868                  * not in UTF-8 */
17869                 _invlist_subtract(only_non_utf8_list, cp_list,
17870                                   &only_non_utf8_list);
17871                 if (_invlist_len(only_non_utf8_list) != 0) {
17872                     anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
17873                 }
17874                 SvREFCNT_dec_NN(only_non_utf8_list);
17875             }
17876             else {
17877                 /* Here there were no complemented posix classes.  That means
17878                  * the upper Latin1 characters in 'posixes' match only when the
17879                  * target string is in UTF-8.  So we have to add them to the
17880                  * list of those types of code points, while adding the
17881                  * remainder to the unconditional list.
17882                  *
17883                  * First calculate what they are */
17884                 SV* nonascii_but_latin1_properties = NULL;
17885                 _invlist_intersection(posixes, PL_UpperLatin1,
17886                                       &nonascii_but_latin1_properties);
17887
17888                 /* And add them to the final list of such characters. */
17889                 _invlist_union(upper_latin1_only_utf8_matches,
17890                                nonascii_but_latin1_properties,
17891                                &upper_latin1_only_utf8_matches);
17892
17893                 /* Remove them from what now becomes the unconditional list */
17894                 _invlist_subtract(posixes, nonascii_but_latin1_properties,
17895                                   &posixes);
17896
17897                 /* And add those unconditional ones to the final list */
17898                 if (cp_list) {
17899                     _invlist_union(cp_list, posixes, &cp_list);
17900                     SvREFCNT_dec_NN(posixes);
17901                     posixes = NULL;
17902                 }
17903                 else {
17904                     cp_list = posixes;
17905                 }
17906
17907                 SvREFCNT_dec(nonascii_but_latin1_properties);
17908
17909                 /* Get rid of any characters from the conditional list that we
17910                  * now know are matched unconditionally, which may make that
17911                  * list empty */
17912                 _invlist_subtract(upper_latin1_only_utf8_matches,
17913                                   cp_list,
17914                                   &upper_latin1_only_utf8_matches);
17915                 if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
17916                     SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
17917                     upper_latin1_only_utf8_matches = NULL;
17918                 }
17919             }
17920         }
17921     }
17922
17923     /* And combine the result (if any) with any inversion list from properties.
17924      * The lists are kept separate up to now so that we can distinguish the two
17925      * in regards to matching above-Unicode.  A run-time warning is generated
17926      * if a Unicode property is matched against a non-Unicode code point. But,
17927      * we allow user-defined properties to match anything, without any warning,
17928      * and we also suppress the warning if there is a portion of the character
17929      * class that isn't a Unicode property, and which matches above Unicode, \W
17930      * or [\x{110000}] for example.
17931      * (Note that in this case, unlike the Posix one above, there is no
17932      * <upper_latin1_only_utf8_matches>, because having a Unicode property
17933      * forces Unicode semantics */
17934     if (properties) {
17935         if (cp_list) {
17936
17937             /* If it matters to the final outcome, see if a non-property
17938              * component of the class matches above Unicode.  If so, the
17939              * warning gets suppressed.  This is true even if just a single
17940              * such code point is specified, as, though not strictly correct if
17941              * another such code point is matched against, the fact that they
17942              * are using above-Unicode code points indicates they should know
17943              * the issues involved */
17944             if (warn_super) {
17945                 warn_super = ! (invert
17946                                ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
17947             }
17948
17949             _invlist_union(properties, cp_list, &cp_list);
17950             SvREFCNT_dec_NN(properties);
17951         }
17952         else {
17953             cp_list = properties;
17954         }
17955
17956         if (warn_super) {
17957             anyof_flags
17958              |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
17959
17960             /* Because an ANYOF node is the only one that warns, this node
17961              * can't be optimized into something else */
17962             optimizable = FALSE;
17963         }
17964     }
17965
17966     /* Here, we have calculated what code points should be in the character
17967      * class.
17968      *
17969      * Now we can see about various optimizations.  Fold calculation (which we
17970      * did above) needs to take place before inversion.  Otherwise /[^k]/i
17971      * would invert to include K, which under /i would match k, which it
17972      * shouldn't.  Therefore we can't invert folded locale now, as it won't be
17973      * folded until runtime */
17974
17975     /* If we didn't do folding, it's because some information isn't available
17976      * until runtime; set the run-time fold flag for these  We know to set the
17977      * flag if we have a non-NULL list for UTF-8 locales, or the class matches
17978      * at least one 0-255 range code point */
17979     if (LOC && FOLD) {
17980
17981         /* Some things on the list might be unconditionally included because of
17982          * other components.  Remove them, and clean up the list if it goes to
17983          * 0 elements */
17984         if (only_utf8_locale_list && cp_list) {
17985             _invlist_subtract(only_utf8_locale_list, cp_list,
17986                               &only_utf8_locale_list);
17987
17988             if (_invlist_len(only_utf8_locale_list) == 0) {
17989                 SvREFCNT_dec_NN(only_utf8_locale_list);
17990                 only_utf8_locale_list = NULL;
17991             }
17992         }
17993         if (    only_utf8_locale_list
17994             || (cp_list && (   _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
17995                             || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
17996         {
17997             has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
17998             anyof_flags
17999                  |= ANYOFL_FOLD
18000                  |  ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18001         }
18002         else if (cp_list) { /* Look to see if a 0-255 code point is in list */
18003             UV start, end;
18004             invlist_iterinit(cp_list);
18005             if (invlist_iternext(cp_list, &start, &end) && start < 256) {
18006                 anyof_flags |= ANYOFL_FOLD;
18007                 has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18008             }
18009             invlist_iterfinish(cp_list);
18010         }
18011     }
18012     else if (   DEPENDS_SEMANTICS
18013              && (    upper_latin1_only_utf8_matches
18014                  || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18015     {
18016         RExC_seen_d_op = TRUE;
18017         has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
18018     }
18019
18020     /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
18021      * compile time. */
18022     if (     cp_list
18023         &&   invert
18024         && ! has_runtime_dependency)
18025     {
18026         _invlist_invert(cp_list);
18027
18028         /* Clear the invert flag since have just done it here */
18029         invert = FALSE;
18030     }
18031
18032     if (ret_invlist) {
18033         *ret_invlist = cp_list;
18034
18035         return RExC_emit;
18036     }
18037
18038     /* All possible optimizations below still have these characteristics.
18039      * (Multi-char folds aren't SIMPLE, but they don't get this far in this
18040      * routine) */
18041     *flagp |= HASWIDTH|SIMPLE;
18042
18043     if (anyof_flags & ANYOF_LOCALE_FLAGS) {
18044         RExC_contains_locale = 1;
18045     }
18046
18047     /* Some character classes are equivalent to other nodes.  Such nodes take
18048      * up less room, and some nodes require fewer operations to execute, than
18049      * ANYOF nodes.  EXACTish nodes may be joinable with adjacent nodes to
18050      * improve efficiency. */
18051
18052     if (optimizable) {
18053         PERL_UINT_FAST8_T i;
18054         Size_t partial_cp_count = 0;
18055         UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
18056         UV   end[MAX_FOLD_FROMS+1] = { 0 };
18057
18058         if (cp_list) { /* Count the code points in enough ranges that we would
18059                           see all the ones possible in any fold in this version
18060                           of Unicode */
18061
18062             invlist_iterinit(cp_list);
18063             for (i = 0; i <= MAX_FOLD_FROMS; i++) {
18064                 if (! invlist_iternext(cp_list, &start[i], &end[i])) {
18065                     break;
18066                 }
18067                 partial_cp_count += end[i] - start[i] + 1;
18068             }
18069
18070             invlist_iterfinish(cp_list);
18071         }
18072
18073         /* If we know at compile time that this matches every possible code
18074          * point, any run-time dependencies don't matter */
18075         if (start[0] == 0 && end[0] == UV_MAX) {
18076             if (invert) {
18077                 ret = reganode(pRExC_state, OPFAIL, 0);
18078             }
18079             else {
18080                 ret = reg_node(pRExC_state, SANY);
18081                 MARK_NAUGHTY(1);
18082             }
18083             goto not_anyof;
18084         }
18085
18086         /* Similarly, for /l posix classes, if both a class and its
18087          * complement match, any run-time dependencies don't matter */
18088         if (posixl) {
18089             for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX;
18090                                                         namedclass += 2)
18091             {
18092                 if (   POSIXL_TEST(posixl, namedclass)      /* class */
18093                     && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
18094                 {
18095                     if (invert) {
18096                         ret = reganode(pRExC_state, OPFAIL, 0);
18097                     }
18098                     else {
18099                         ret = reg_node(pRExC_state, SANY);
18100                         MARK_NAUGHTY(1);
18101                     }
18102                     goto not_anyof;
18103                 }
18104             }
18105             /* For well-behaved locales, some classes are subsets of others,
18106              * so complementing the subset and including the non-complemented
18107              * superset should match everything, like [\D[:alnum:]], and
18108              * [[:^alpha:][:alnum:]], but some implementations of locales are
18109              * buggy, and khw thinks its a bad idea to have optimization change
18110              * behavior, even if it avoids an OS bug in a given case */
18111
18112 #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
18113
18114             /* If is a single posix /l class, can optimize to just that op.
18115              * Such a node will not match anything in the Latin1 range, as that
18116              * is not determinable until runtime, but will match whatever the
18117              * class does outside that range.  (Note that some classes won't
18118              * match anything outside the range, like [:ascii:]) */
18119             if (    isSINGLE_BIT_SET(posixl)
18120                 && (partial_cp_count == 0 || start[0] > 255))
18121             {
18122                 U8 classnum;
18123                 SV * class_above_latin1 = NULL;
18124                 bool already_inverted;
18125                 bool are_equivalent;
18126
18127                 /* Compute which bit is set, which is the same thing as, e.g.,
18128                  * ANYOF_CNTRL.  From
18129                  * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
18130                  * */
18131                 static const int MultiplyDeBruijnBitPosition2[32] =
18132                     {
18133                     0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
18134                     31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
18135                     };
18136
18137                 namedclass = MultiplyDeBruijnBitPosition2[(posixl
18138                                                           * 0x077CB531U) >> 27];
18139                 classnum = namedclass_to_classnum(namedclass);
18140
18141                 /* The named classes are such that the inverted number is one
18142                  * larger than the non-inverted one */
18143                 already_inverted = namedclass
18144                                  - classnum_to_namedclass(classnum);
18145
18146                 /* Create an inversion list of the official property, inverted
18147                  * if the constructed node list is inverted, and restricted to
18148                  * only the above latin1 code points, which are the only ones
18149                  * known at compile time */
18150                 _invlist_intersection_maybe_complement_2nd(
18151                                                     PL_AboveLatin1,
18152                                                     PL_XPosix_ptrs[classnum],
18153                                                     already_inverted,
18154                                                     &class_above_latin1);
18155                 are_equivalent = _invlistEQ(class_above_latin1, cp_list,
18156                                                                         FALSE);
18157                 SvREFCNT_dec_NN(class_above_latin1);
18158
18159                 if (are_equivalent) {
18160
18161                     /* Resolve the run-time inversion flag with this possibly
18162                      * inverted class */
18163                     invert = invert ^ already_inverted;
18164
18165                     ret = reg_node(pRExC_state,
18166                                    POSIXL + invert * (NPOSIXL - POSIXL));
18167                     FLAGS(REGNODE_p(ret)) = classnum;
18168                     goto not_anyof;
18169                 }
18170             }
18171         }
18172
18173         /* khw can't think of any other possible transformation involving
18174          * these. */
18175         if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
18176             goto is_anyof;
18177         }
18178
18179         if (! has_runtime_dependency) {
18180
18181             /* If the list is empty, nothing matches.  This happens, for
18182              * example, when a Unicode property that doesn't match anything is
18183              * the only element in the character class (perluniprops.pod notes
18184              * such properties). */
18185             if (partial_cp_count == 0) {
18186                 if (invert) {
18187                     ret = reg_node(pRExC_state, SANY);
18188                 }
18189                 else {
18190                     ret = reganode(pRExC_state, OPFAIL, 0);
18191                 }
18192
18193                 goto not_anyof;
18194             }
18195
18196             /* If matches everything but \n */
18197             if (   start[0] == 0 && end[0] == '\n' - 1
18198                 && start[1] == '\n' + 1 && end[1] == UV_MAX)
18199             {
18200                 assert (! invert);
18201                 ret = reg_node(pRExC_state, REG_ANY);
18202                 MARK_NAUGHTY(1);
18203                 goto not_anyof;
18204             }
18205         }
18206
18207         /* Next see if can optimize classes that contain just a few code points
18208          * into an EXACTish node.  The reason to do this is to let the
18209          * optimizer join this node with adjacent EXACTish ones.
18210          *
18211          * An EXACTFish node can be generated even if not under /i, and vice
18212          * versa.  But care must be taken.  An EXACTFish node has to be such
18213          * that it only matches precisely the code points in the class, but we
18214          * want to generate the least restrictive one that does that, to
18215          * increase the odds of being able to join with an adjacent node.  For
18216          * example, if the class contains [kK], we have to make it an EXACTFAA
18217          * node to prevent the KELVIN SIGN from matching.  Whether we are under
18218          * /i or not is irrelevant in this case.  Less obvious is the pattern
18219          * qr/[\x{02BC}]n/i.  U+02BC is MODIFIER LETTER APOSTROPHE. That is
18220          * supposed to match the single character U+0149 LATIN SMALL LETTER N
18221          * PRECEDED BY APOSTROPHE.  And so even though there is no simple fold
18222          * that includes \X{02BC}, there is a multi-char fold that does, and so
18223          * the node generated for it must be an EXACTFish one.  On the other
18224          * hand qr/:/i should generate a plain EXACT node since the colon
18225          * participates in no fold whatsoever, and having it EXACT tells the
18226          * optimizer the target string cannot match unless it has a colon in
18227          * it.
18228          *
18229          * We don't typically generate an EXACTish node if doing so would
18230          * require changing the pattern to UTF-8, as that affects /d and
18231          * otherwise is slower.  However, under /i, not changing to UTF-8 can
18232          * miss some potential multi-character folds.  We calculate the
18233          * EXACTish node, and then decide if something would be missed if we
18234          * don't upgrade */
18235         if (   ! posixl
18236             && ! invert
18237
18238                 /* Only try if there are no more code points in the class than
18239                  * in the max possible fold */
18240             &&   partial_cp_count > 0 && partial_cp_count <= MAX_FOLD_FROMS + 1
18241
18242             && (start[0] < 256 || UTF || FOLD))
18243         {
18244             if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches)
18245             {
18246                 /* We can always make a single code point class into an
18247                  * EXACTish node. */
18248
18249                 if (LOC) {
18250
18251                     /* Here is /l:  Use EXACTL, except /li indicates EXACTFL,
18252                      * as that means there is a fold not known until runtime so
18253                      * shows as only a single code point here. */
18254                     op = (FOLD) ? EXACTFL : EXACTL;
18255                 }
18256                 else if (! FOLD) { /* Not /l and not /i */
18257                     op = (start[0] < 256) ? EXACT : EXACT_ONLY8;
18258                 }
18259                 else if (start[0] < 256) { /* /i, not /l, and the code point is
18260                                               small */
18261
18262                     /* Under /i, it gets a little tricky.  A code point that
18263                      * doesn't participate in a fold should be an EXACT node.
18264                      * We know this one isn't the result of a simple fold, or
18265                      * there'd be more than one code point in the list, but it
18266                      * could be part of a multi- character fold.  In that case
18267                      * we better not create an EXACT node, as we would wrongly
18268                      * be telling the optimizer that this code point must be in
18269                      * the target string, and that is wrong.  This is because
18270                      * if the sequence around this code point forms a
18271                      * multi-char fold, what needs to be in the string could be
18272                      * the code point that folds to the sequence.
18273                      *
18274                      * This handles the case of below-255 code points, as we
18275                      * have an easy look up for those.  The next clause handles
18276                      * the above-256 one */
18277                     op = IS_IN_SOME_FOLD_L1(start[0])
18278                          ? EXACTFU
18279                          : EXACT;
18280                 }
18281                 else {  /* /i, larger code point.  Since we are under /i, and
18282                            have just this code point, we know that it can't
18283                            fold to something else, so PL_InMultiCharFold
18284                            applies to it */
18285                     op = _invlist_contains_cp(PL_InMultiCharFold,
18286                                               start[0])
18287                          ? EXACTFU_ONLY8
18288                          : EXACT_ONLY8;
18289                 }
18290
18291                 value = start[0];
18292             }
18293             else if (  ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
18294                      && _invlist_contains_cp(PL_in_some_fold, start[0]))
18295             {
18296                 /* Here, the only runtime dependency, if any, is from /d, and
18297                  * the class matches more than one code point, and the lowest
18298                  * code point participates in some fold.  It might be that the
18299                  * other code points are /i equivalent to this one, and hence
18300                  * they would representable by an EXACTFish node.  Above, we
18301                  * eliminated classes that contain too many code points to be
18302                  * EXACTFish, with the test for MAX_FOLD_FROMS
18303                  *
18304                  * First, special case the ASCII fold pairs, like 'B' and 'b'.
18305                  * We do this because we have EXACTFAA at our disposal for the
18306                  * ASCII range */
18307                 if (partial_cp_count == 2 && isASCII(start[0])) {
18308
18309                     /* The only ASCII characters that participate in folds are
18310                      * alphabetics */
18311                     assert(isALPHA(start[0]));
18312                     if (   end[0] == start[0]   /* First range is a single
18313                                                    character, so 2nd exists */
18314                         && isALPHA_FOLD_EQ(start[0], start[1]))
18315                     {
18316
18317                         /* Here, is part of an ASCII fold pair */
18318
18319                         if (   ASCII_FOLD_RESTRICTED
18320                             || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
18321                         {
18322                             /* If the second clause just above was true, it
18323                              * means we can't be under /i, or else the list
18324                              * would have included more than this fold pair.
18325                              * Therefore we have to exclude the possibility of
18326                              * whatever else it is that folds to these, by
18327                              * using EXACTFAA */
18328                             op = EXACTFAA;
18329                         }
18330                         else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
18331
18332                             /* Here, there's no simple fold that start[0] is part
18333                              * of, but there is a multi-character one.  If we
18334                              * are not under /i, we want to exclude that
18335                              * possibility; if under /i, we want to include it
18336                              * */
18337                             op = (FOLD) ? EXACTFU : EXACTFAA;
18338                         }
18339                         else {
18340
18341                             /* Here, the only possible fold start[0] particpates in
18342                              * is with start[1].  /i or not isn't relevant */
18343                             op = EXACTFU;
18344                         }
18345
18346                         value = toFOLD(start[0]);
18347                     }
18348                 }
18349                 else if (  ! upper_latin1_only_utf8_matches
18350                          || (   _invlist_len(upper_latin1_only_utf8_matches)
18351                                                                           == 2
18352                              && PL_fold_latin1[
18353                                invlist_highest(upper_latin1_only_utf8_matches)]
18354                              == start[0]))
18355                 {
18356                     /* Here, the smallest character is non-ascii or there are
18357                      * more than 2 code points matched by this node.  Also, we
18358                      * either don't have /d UTF-8 dependent matches, or if we
18359                      * do, they look like they could be a single character that
18360                      * is the fold of the lowest one in the always-match list.
18361                      * This test quickly excludes most of the false positives
18362                      * when there are /d UTF-8 depdendent matches.  These are
18363                      * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN
18364                      * SMALL LETTER A WITH GRAVE iff the target string is
18365                      * UTF-8.  (We don't have to worry above about exceeding
18366                      * the array bounds of PL_fold_latin1[] because any code
18367                      * point in 'upper_latin1_only_utf8_matches' is below 256.)
18368                      *
18369                      * EXACTFAA would apply only to pairs (hence exactly 2 code
18370                      * points) in the ASCII range, so we can't use it here to
18371                      * artificially restrict the fold domain, so we check if
18372                      * the class does or does not match some EXACTFish node.
18373                      * Further, if we aren't under /i, and and the folded-to
18374                      * character is part of a multi-character fold, we can't do
18375                      * this optimization, as the sequence around it could be
18376                      * that multi-character fold, and we don't here know the
18377                      * context, so we have to assume it is that multi-char
18378                      * fold, to prevent potential bugs.
18379                      *
18380                      * To do the general case, we first find the fold of the
18381                      * lowest code point (which may be higher than the lowest
18382                      * one), then find everything that folds to it.  (The data
18383                      * structure we have only maps from the folded code points,
18384                      * so we have to do the earlier step.) */
18385
18386                     Size_t foldlen;
18387                     U8 foldbuf[UTF8_MAXBYTES_CASE];
18388                     UV folded = _to_uni_fold_flags(start[0],
18389                                                         foldbuf, &foldlen, 0);
18390                     unsigned int first_fold;
18391                     const unsigned int * remaining_folds;
18392                     Size_t folds_to_this_cp_count = _inverse_folds(
18393                                                             folded,
18394                                                             &first_fold,
18395                                                             &remaining_folds);
18396                     Size_t folds_count = folds_to_this_cp_count + 1;
18397                     SV * fold_list = _new_invlist(folds_count);
18398                     unsigned int i;
18399
18400                     /* If there are UTF-8 dependent matches, create a temporary
18401                      * list of what this node matches, including them. */
18402                     SV * all_cp_list = NULL;
18403                     SV ** use_this_list = &cp_list;
18404
18405                     if (upper_latin1_only_utf8_matches) {
18406                         all_cp_list = _new_invlist(0);
18407                         use_this_list = &all_cp_list;
18408                         _invlist_union(cp_list,
18409                                        upper_latin1_only_utf8_matches,
18410                                        use_this_list);
18411                     }
18412
18413                     /* Having gotten everything that participates in the fold
18414                      * containing the lowest code point, we turn that into an
18415                      * inversion list, making sure everything is included. */
18416                     fold_list = add_cp_to_invlist(fold_list, start[0]);
18417                     fold_list = add_cp_to_invlist(fold_list, folded);
18418                     if (folds_to_this_cp_count > 0) {
18419                         fold_list = add_cp_to_invlist(fold_list, first_fold);
18420                         for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
18421                             fold_list = add_cp_to_invlist(fold_list,
18422                                                         remaining_folds[i]);
18423                         }
18424                     }
18425
18426                     /* If the fold list is identical to what's in this ANYOF
18427                      * node, the node can be represented by an EXACTFish one
18428                      * instead */
18429                     if (_invlistEQ(*use_this_list, fold_list,
18430                                    0 /* Don't complement */ )
18431                     ) {
18432
18433                         /* But, we have to be careful, as mentioned above.
18434                          * Just the right sequence of characters could match
18435                          * this if it is part of a multi-character fold.  That
18436                          * IS what we want if we are under /i.  But it ISN'T
18437                          * what we want if not under /i, as it could match when
18438                          * it shouldn't.  So, when we aren't under /i and this
18439                          * character participates in a multi-char fold, we
18440                          * don't optimize into an EXACTFish node.  So, for each
18441                          * case below we have to check if we are folding
18442                          * and if not, if it is not part of a multi-char fold.
18443                          * */
18444                         if (start[0] > 255) {    /* Highish code point */
18445                             if (FOLD || ! _invlist_contains_cp(
18446                                             PL_InMultiCharFold, folded))
18447                             {
18448                                 op = (LOC)
18449                                      ? EXACTFLU8
18450                                      : (ASCII_FOLD_RESTRICTED)
18451                                        ? EXACTFAA
18452                                        : EXACTFU_ONLY8;
18453                                 value = folded;
18454                             }
18455                         }   /* Below, the lowest code point < 256 */
18456                         else if (    FOLD
18457                                  &&  folded == 's'
18458                                  &&  DEPENDS_SEMANTICS)
18459                         {   /* An EXACTF node containing a single character
18460                                 's', can be an EXACTFU if it doesn't get
18461                                 joined with an adjacent 's' */
18462                             op = EXACTFU_S_EDGE;
18463                             value = folded;
18464                         }
18465                         else if (    FOLD
18466                                 || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
18467                         {
18468                             if (upper_latin1_only_utf8_matches) {
18469                                 op = EXACTF;
18470
18471                                 /* We can't use the fold, as that only matches
18472                                  * under UTF-8 */
18473                                 value = start[0];
18474                             }
18475                             else if (     UNLIKELY(start[0] == MICRO_SIGN)
18476                                      && ! UTF)
18477                             {   /* EXACTFUP is a special node for this
18478                                    character */
18479                                 op = (ASCII_FOLD_RESTRICTED)
18480                                      ? EXACTFAA
18481                                      : EXACTFUP;
18482                                 value = MICRO_SIGN;
18483                             }
18484                             else if (     ASCII_FOLD_RESTRICTED
18485                                      && ! isASCII(start[0]))
18486                             {   /* For ASCII under /iaa, we can use EXACTFU
18487                                    below */
18488                                 op = EXACTFAA;
18489                                 value = folded;
18490                             }
18491                             else {
18492                                 op = EXACTFU;
18493                                 value = folded;
18494                             }
18495                         }
18496                     }
18497
18498                     SvREFCNT_dec_NN(fold_list);
18499                     SvREFCNT_dec(all_cp_list);
18500                 }
18501             }
18502
18503             if (op != END) {
18504
18505                 /* Here, we have calculated what EXACTish node we would use.
18506                  * But we don't use it if it would require converting the
18507                  * pattern to UTF-8, unless not using it could cause us to miss
18508                  * some folds (hence be buggy) */
18509
18510                 if (! UTF && value > 255) {
18511                     SV * in_multis = NULL;
18512
18513                     assert(FOLD);
18514
18515                     /* If there is no code point that is part of a multi-char
18516                      * fold, then there aren't any matches, so we don't do this
18517                      * optimization.  Otherwise, it could match depending on
18518                      * the context around us, so we do upgrade */
18519                     _invlist_intersection(PL_InMultiCharFold, cp_list, &in_multis);
18520                     if (UNLIKELY(_invlist_len(in_multis) != 0)) {
18521                         REQUIRE_UTF8(flagp);
18522                     }
18523                     else {
18524                         op = END;
18525                     }
18526                 }
18527
18528                 if (op != END) {
18529                     U8 len = (UTF) ? UVCHR_SKIP(value) : 1;
18530
18531                     ret = regnode_guts(pRExC_state, op, len, "exact");
18532                     FILL_NODE(ret, op);
18533                     RExC_emit += 1 + STR_SZ(len);
18534                     STR_LEN(REGNODE_p(ret)) = len;
18535                     if (len == 1) {
18536                         *STRING(REGNODE_p(ret)) = value;
18537                     }
18538                     else {
18539                         uvchr_to_utf8((U8 *) STRING(REGNODE_p(ret)), value);
18540                     }
18541                     goto not_anyof;
18542                 }
18543             }
18544         }
18545
18546         if (! has_runtime_dependency) {
18547
18548             /* See if this can be turned into an ANYOFM node.  Think about the
18549              * bit patterns in two different bytes.  In some positions, the
18550              * bits in each will be 1; and in other positions both will be 0;
18551              * and in some positions the bit will be 1 in one byte, and 0 in
18552              * the other.  Let 'n' be the number of positions where the bits
18553              * differ.  We create a mask which has exactly 'n' 0 bits, each in
18554              * a position where the two bytes differ.  Now take the set of all
18555              * bytes that when ANDed with the mask yield the same result.  That
18556              * set has 2**n elements, and is representable by just two 8 bit
18557              * numbers: the result and the mask.  Importantly, matching the set
18558              * can be vectorized by creating a word full of the result bytes,
18559              * and a word full of the mask bytes, yielding a significant speed
18560              * up.  Here, see if this node matches such a set.  As a concrete
18561              * example consider [01], and the byte representing '0' which is
18562              * 0x30 on ASCII machines.  It has the bits 0011 0000.  Take the
18563              * mask 1111 1110.  If we AND 0x31 and 0x30 with that mask we get
18564              * 0x30.  Any other bytes ANDed yield something else.  So [01],
18565              * which is a common usage, is optimizable into ANYOFM, and can
18566              * benefit from the speed up.  We can only do this on UTF-8
18567              * invariant bytes, because they have the same bit patterns under
18568              * UTF-8 as not. */
18569             PERL_UINT_FAST8_T inverted = 0;
18570 #ifdef EBCDIC
18571             const PERL_UINT_FAST8_T max_permissible = 0xFF;
18572 #else
18573             const PERL_UINT_FAST8_T max_permissible = 0x7F;
18574 #endif
18575             /* If doesn't fit the criteria for ANYOFM, invert and try again.
18576              * If that works we will instead later generate an NANYOFM, and
18577              * invert back when through */
18578             if (invlist_highest(cp_list) > max_permissible) {
18579                 _invlist_invert(cp_list);
18580                 inverted = 1;
18581             }
18582
18583             if (invlist_highest(cp_list) <= max_permissible) {
18584                 UV this_start, this_end;
18585                 UV lowest_cp = UV_MAX;  /* inited to suppress compiler warn */
18586                 U8 bits_differing = 0;
18587                 Size_t full_cp_count = 0;
18588                 bool first_time = TRUE;
18589
18590                 /* Go through the bytes and find the bit positions that differ
18591                  * */
18592                 invlist_iterinit(cp_list);
18593                 while (invlist_iternext(cp_list, &this_start, &this_end)) {
18594                     unsigned int i = this_start;
18595
18596                     if (first_time) {
18597                         if (! UVCHR_IS_INVARIANT(i)) {
18598                             goto done_anyofm;
18599                         }
18600
18601                         first_time = FALSE;
18602                         lowest_cp = this_start;
18603
18604                         /* We have set up the code point to compare with.
18605                          * Don't compare it with itself */
18606                         i++;
18607                     }
18608
18609                     /* Find the bit positions that differ from the lowest code
18610                      * point in the node.  Keep track of all such positions by
18611                      * OR'ing */
18612                     for (; i <= this_end; i++) {
18613                         if (! UVCHR_IS_INVARIANT(i)) {
18614                             goto done_anyofm;
18615                         }
18616
18617                         bits_differing  |= i ^ lowest_cp;
18618                     }
18619
18620                     full_cp_count += this_end - this_start + 1;
18621                 }
18622                 invlist_iterfinish(cp_list);
18623
18624                 /* At the end of the loop, we count how many bits differ from
18625                  * the bits in lowest code point, call the count 'd'.  If the
18626                  * set we found contains 2**d elements, it is the closure of
18627                  * all code points that differ only in those bit positions.  To
18628                  * convince yourself of that, first note that the number in the
18629                  * closure must be a power of 2, which we test for.  The only
18630                  * way we could have that count and it be some differing set,
18631                  * is if we got some code points that don't differ from the
18632                  * lowest code point in any position, but do differ from each
18633                  * other in some other position.  That means one code point has
18634                  * a 1 in that position, and another has a 0.  But that would
18635                  * mean that one of them differs from the lowest code point in
18636                  * that position, which possibility we've already excluded.  */
18637                 if (  (inverted || full_cp_count > 1)
18638                     && full_cp_count == 1U << PL_bitcount[bits_differing])
18639                 {
18640                     U8 ANYOFM_mask;
18641
18642                     op = ANYOFM + inverted;;
18643
18644                     /* We need to make the bits that differ be 0's */
18645                     ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
18646
18647                     /* The argument is the lowest code point */
18648                     ret = reganode(pRExC_state, op, lowest_cp);
18649                     FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
18650                 }
18651             }
18652           done_anyofm:
18653
18654             if (inverted) {
18655                 _invlist_invert(cp_list);
18656             }
18657
18658             if (op != END) {
18659                 goto not_anyof;
18660             }
18661         }
18662
18663         if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) {
18664             PERL_UINT_FAST8_T type;
18665             SV * intersection = NULL;
18666             SV* d_invlist = NULL;
18667
18668             /* See if this matches any of the POSIX classes.  The POSIXA and
18669              * POSIXD ones are about the same speed as ANYOF ops, but take less
18670              * room; the ones that have above-Latin1 code point matches are
18671              * somewhat faster than ANYOF.  */
18672
18673             for (type = POSIXA; type >= POSIXD; type--) {
18674                 int posix_class;
18675
18676                 if (type == POSIXL) {   /* But not /l posix classes */
18677                     continue;
18678                 }
18679
18680                 for (posix_class = 0;
18681                      posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
18682                      posix_class++)
18683                 {
18684                     SV** our_code_points = &cp_list;
18685                     SV** official_code_points;
18686                     int try_inverted;
18687
18688                     if (type == POSIXA) {
18689                         official_code_points = &PL_Posix_ptrs[posix_class];
18690                     }
18691                     else {
18692                         official_code_points = &PL_XPosix_ptrs[posix_class];
18693                     }
18694
18695                     /* Skip non-existent classes of this type.  e.g. \v only
18696                      * has an entry in PL_XPosix_ptrs */
18697                     if (! *official_code_points) {
18698                         continue;
18699                     }
18700
18701                     /* Try both the regular class, and its inversion */
18702                     for (try_inverted = 0; try_inverted < 2; try_inverted++) {
18703                         bool this_inverted = invert ^ try_inverted;
18704
18705                         if (type != POSIXD) {
18706
18707                             /* This class that isn't /d can't match if we have
18708                              * /d dependencies */
18709                             if (has_runtime_dependency
18710                                                     & HAS_D_RUNTIME_DEPENDENCY)
18711                             {
18712                                 continue;
18713                             }
18714                         }
18715                         else /* is /d */ if (! this_inverted) {
18716
18717                             /* /d classes don't match anything non-ASCII below
18718                              * 256 unconditionally (which cp_list contains) */
18719                             _invlist_intersection(cp_list, PL_UpperLatin1,
18720                                                            &intersection);
18721                             if (_invlist_len(intersection) != 0) {
18722                                 continue;
18723                             }
18724
18725                             SvREFCNT_dec(d_invlist);
18726                             d_invlist = invlist_clone(cp_list, NULL);
18727
18728                             /* But under UTF-8 it turns into using /u rules.
18729                              * Add the things it matches under these conditions
18730                              * so that we check below that these are identical
18731                              * to what the tested class should match */
18732                             if (upper_latin1_only_utf8_matches) {
18733                                 _invlist_union(
18734                                             d_invlist,
18735                                             upper_latin1_only_utf8_matches,
18736                                             &d_invlist);
18737                             }
18738                             our_code_points = &d_invlist;
18739                         }
18740                         else {  /* POSIXD, inverted.  If this doesn't have this
18741                                    flag set, it isn't /d. */
18742                             if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
18743                             {
18744                                 continue;
18745                             }
18746                             our_code_points = &cp_list;
18747                         }
18748
18749                         /* Here, have weeded out some things.  We want to see
18750                          * if the list of characters this node contains
18751                          * ('*our_code_points') precisely matches those of the
18752                          * class we are currently checking against
18753                          * ('*official_code_points'). */
18754                         if (_invlistEQ(*our_code_points,
18755                                        *official_code_points,
18756                                        try_inverted))
18757                         {
18758                             /* Here, they precisely match.  Optimize this ANYOF
18759                              * node into its equivalent POSIX one of the
18760                              * correct type, possibly inverted */
18761                             ret = reg_node(pRExC_state, (try_inverted)
18762                                                         ? type + NPOSIXA
18763                                                                 - POSIXA
18764                                                         : type);
18765                             FLAGS(REGNODE_p(ret)) = posix_class;
18766                             SvREFCNT_dec(d_invlist);
18767                             SvREFCNT_dec(intersection);
18768                             goto not_anyof;
18769                         }
18770                     }
18771                 }
18772             }
18773             SvREFCNT_dec(d_invlist);
18774             SvREFCNT_dec(intersection);
18775         }
18776
18777         /* If didn't find an optimization and there is no need for a
18778         * bitmap, optimize to indicate that */
18779         if (     start[0] >= NUM_ANYOF_CODE_POINTS
18780             && ! LOC
18781             && ! upper_latin1_only_utf8_matches)
18782         {
18783             op = ANYOFH;
18784         }
18785     }   /* End of seeing if can optimize it into a different node */
18786
18787   is_anyof: /* It's going to be an ANYOF node. */
18788     if (op != ANYOFH) {
18789         op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY)
18790              ? ANYOFD
18791              : ((posixl)
18792                 ? ANYOFPOSIXL
18793                 : ((LOC)
18794                    ? ANYOFL
18795                    : ANYOF));
18796     }
18797
18798     ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
18799     FILL_NODE(ret, op);        /* We set the argument later */
18800     RExC_emit += 1 + regarglen[op];
18801     ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
18802
18803     /* Here, <cp_list> contains all the code points we can determine at
18804      * compile time that match under all conditions.  Go through it, and
18805      * for things that belong in the bitmap, put them there, and delete from
18806      * <cp_list>.  While we are at it, see if everything above 255 is in the
18807      * list, and if so, set a flag to speed up execution */
18808
18809     populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
18810
18811     if (posixl) {
18812         ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
18813     }
18814
18815     if (invert) {
18816         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
18817     }
18818
18819     /* Here, the bitmap has been populated with all the Latin1 code points that
18820      * always match.  Can now add to the overall list those that match only
18821      * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
18822      * */
18823     if (upper_latin1_only_utf8_matches) {
18824         if (cp_list) {
18825             _invlist_union(cp_list,
18826                            upper_latin1_only_utf8_matches,
18827                            &cp_list);
18828             SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18829         }
18830         else {
18831             cp_list = upper_latin1_only_utf8_matches;
18832         }
18833         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
18834     }
18835
18836     set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
18837                   (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
18838                    ? listsv : NULL,
18839                   only_utf8_locale_list);
18840     return ret;
18841
18842   not_anyof:
18843
18844     /* Here, the node is getting optimized into something that's not an ANYOF
18845      * one.  Finish up. */
18846
18847     Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
18848                                            RExC_parse - orig_parse);;
18849     SvREFCNT_dec(cp_list);;
18850     return ret;
18851 }
18852
18853 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
18854
18855 STATIC void
18856 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
18857                 regnode* const node,
18858                 SV* const cp_list,
18859                 SV* const runtime_defns,
18860                 SV* const only_utf8_locale_list)
18861 {
18862     /* Sets the arg field of an ANYOF-type node 'node', using information about
18863      * the node passed-in.  If there is nothing outside the node's bitmap, the
18864      * arg is set to ANYOF_ONLY_HAS_BITMAP.  Otherwise, it sets the argument to
18865      * the count returned by add_data(), having allocated and stored an array,
18866      * av, as follows:
18867      *
18868      *  av[0] stores the inversion list defining this class as far as known at
18869      *        this time, or PL_sv_undef if nothing definite is now known.
18870      *  av[1] stores the inversion list of code points that match only if the
18871      *        current locale is UTF-8, or if none, PL_sv_undef if there is an
18872      *        av[2], or no entry otherwise.
18873      *  av[2] stores the list of user-defined properties whose subroutine
18874      *        definitions aren't known at this time, or no entry if none. */
18875
18876     UV n;
18877
18878     PERL_ARGS_ASSERT_SET_ANYOF_ARG;
18879
18880     if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
18881         assert(! (ANYOF_FLAGS(node)
18882                 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
18883         ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
18884     }
18885     else {
18886         AV * const av = newAV();
18887         SV *rv;
18888
18889         if (cp_list) {
18890             av_store(av, INVLIST_INDEX, cp_list);
18891         }
18892
18893         if (only_utf8_locale_list) {
18894             av_store(av, ONLY_LOCALE_MATCHES_INDEX, only_utf8_locale_list);
18895         }
18896
18897         if (runtime_defns) {
18898             av_store(av, DEFERRED_USER_DEFINED_INDEX, SvREFCNT_inc(runtime_defns));
18899         }
18900
18901         rv = newRV_noinc(MUTABLE_SV(av));
18902         n = add_data(pRExC_state, STR_WITH_LEN("s"));
18903         RExC_rxi->data->data[n] = (void*)rv;
18904         ARG_SET(node, n);
18905     }
18906 }
18907
18908 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
18909 SV *
18910 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
18911                                         const regnode* node,
18912                                         bool doinit,
18913                                         SV** listsvp,
18914                                         SV** only_utf8_locale_ptr,
18915                                         SV** output_invlist)
18916
18917 {
18918     /* For internal core use only.
18919      * Returns the inversion list for the input 'node' in the regex 'prog'.
18920      * If <doinit> is 'true', will attempt to create the inversion list if not
18921      *    already done.
18922      * If <listsvp> is non-null, will return the printable contents of the
18923      *    property definition.  This can be used to get debugging information
18924      *    even before the inversion list exists, by calling this function with
18925      *    'doinit' set to false, in which case the components that will be used
18926      *    to eventually create the inversion list are returned  (in a printable
18927      *    form).
18928      * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
18929      *    store an inversion list of code points that should match only if the
18930      *    execution-time locale is a UTF-8 one.
18931      * If <output_invlist> is not NULL, it is where this routine is to store an
18932      *    inversion list of the code points that would be instead returned in
18933      *    <listsvp> if this were NULL.  Thus, what gets output in <listsvp>
18934      *    when this parameter is used, is just the non-code point data that
18935      *    will go into creating the inversion list.  This currently should be just
18936      *    user-defined properties whose definitions were not known at compile
18937      *    time.  Using this parameter allows for easier manipulation of the
18938      *    inversion list's data by the caller.  It is illegal to call this
18939      *    function with this parameter set, but not <listsvp>
18940      *
18941      * Tied intimately to how S_set_ANYOF_arg sets up the data structure.  Note
18942      * that, in spite of this function's name, the inversion list it returns
18943      * may include the bitmap data as well */
18944
18945     SV *si  = NULL;         /* Input initialization string */
18946     SV* invlist = NULL;
18947
18948     RXi_GET_DECL(prog, progi);
18949     const struct reg_data * const data = prog ? progi->data : NULL;
18950
18951     PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
18952     assert(! output_invlist || listsvp);
18953
18954     if (data && data->count) {
18955         const U32 n = ARG(node);
18956
18957         if (data->what[n] == 's') {
18958             SV * const rv = MUTABLE_SV(data->data[n]);
18959             AV * const av = MUTABLE_AV(SvRV(rv));
18960             SV **const ary = AvARRAY(av);
18961
18962             invlist = ary[INVLIST_INDEX];
18963
18964             if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
18965                 *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
18966             }
18967
18968             if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
18969                 si = ary[DEFERRED_USER_DEFINED_INDEX];
18970             }
18971
18972             if (doinit && (si || invlist)) {
18973                 if (si) {
18974                     bool user_defined;
18975                     SV * msg = newSVpvs_flags("", SVs_TEMP);
18976
18977                     SV * prop_definition = handle_user_defined_property(
18978                             "", 0, FALSE,   /* There is no \p{}, \P{} */
18979                             SvPVX_const(si)[1] - '0',   /* /i or not has been
18980                                                            stored here for just
18981                                                            this occasion */
18982                             TRUE,           /* run time */
18983                             si,             /* The property definition  */
18984                             &user_defined,
18985                             msg,
18986                             0               /* base level call */
18987                            );
18988
18989                     if (SvCUR(msg)) {
18990                         assert(prop_definition == NULL);
18991
18992                         Perl_croak(aTHX_ "%" UTF8f,
18993                                 UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
18994                     }
18995
18996                     if (invlist) {
18997                         _invlist_union(invlist, prop_definition, &invlist);
18998                         SvREFCNT_dec_NN(prop_definition);
18999                     }
19000                     else {
19001                         invlist = prop_definition;
19002                     }
19003
19004                     STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
19005                     STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
19006
19007                     av_store(av, INVLIST_INDEX, invlist);
19008                     av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
19009                                  ? ONLY_LOCALE_MATCHES_INDEX:
19010                                  INVLIST_INDEX);
19011                     si = NULL;
19012                 }
19013             }
19014         }
19015     }
19016
19017     /* If requested, return a printable version of what this ANYOF node matches
19018      * */
19019     if (listsvp) {
19020         SV* matches_string = NULL;
19021
19022         /* This function can be called at compile-time, before everything gets
19023          * resolved, in which case we return the currently best available
19024          * information, which is the string that will eventually be used to do
19025          * that resolving, 'si' */
19026         if (si) {
19027             /* Here, we only have 'si' (and possibly some passed-in data in
19028              * 'invlist', which is handled below)  If the caller only wants
19029              * 'si', use that.  */
19030             if (! output_invlist) {
19031                 matches_string = newSVsv(si);
19032             }
19033             else {
19034                 /* But if the caller wants an inversion list of the node, we
19035                  * need to parse 'si' and place as much as possible in the
19036                  * desired output inversion list, making 'matches_string' only
19037                  * contain the currently unresolvable things */
19038                 const char *si_string = SvPVX(si);
19039                 STRLEN remaining = SvCUR(si);
19040                 UV prev_cp = 0;
19041                 U8 count = 0;
19042
19043                 /* Ignore everything before the first new-line */
19044                 while (*si_string != '\n' && remaining > 0) {
19045                     si_string++;
19046                     remaining--;
19047                 }
19048                 assert(remaining > 0);
19049
19050                 si_string++;
19051                 remaining--;
19052
19053                 while (remaining > 0) {
19054
19055                     /* The data consists of just strings defining user-defined
19056                      * property names, but in prior incarnations, and perhaps
19057                      * somehow from pluggable regex engines, it could still
19058                      * hold hex code point definitions.  Each component of a
19059                      * range would be separated by a tab, and each range by a
19060                      * new-line.  If these are found, instead add them to the
19061                      * inversion list */
19062                     I32 grok_flags =  PERL_SCAN_SILENT_ILLDIGIT
19063                                      |PERL_SCAN_SILENT_NON_PORTABLE;
19064                     STRLEN len = remaining;
19065                     UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
19066
19067                     /* If the hex decode routine found something, it should go
19068                      * up to the next \n */
19069                     if (   *(si_string + len) == '\n') {
19070                         if (count) {    /* 2nd code point on line */
19071                             *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
19072                         }
19073                         else {
19074                             *output_invlist = add_cp_to_invlist(*output_invlist, cp);
19075                         }
19076                         count = 0;
19077                         goto prepare_for_next_iteration;
19078                     }
19079
19080                     /* If the hex decode was instead for the lower range limit,
19081                      * save it, and go parse the upper range limit */
19082                     if (*(si_string + len) == '\t') {
19083                         assert(count == 0);
19084
19085                         prev_cp = cp;
19086                         count = 1;
19087                       prepare_for_next_iteration:
19088                         si_string += len + 1;
19089                         remaining -= len + 1;
19090                         continue;
19091                     }
19092
19093                     /* Here, didn't find a legal hex number.  Just add it from
19094                      * here to the next \n */
19095
19096                     remaining -= len;
19097                     while (*(si_string + len) != '\n' && remaining > 0) {
19098                         remaining--;
19099                         len++;
19100                     }
19101                     if (*(si_string + len) == '\n') {
19102                         len++;
19103                         remaining--;
19104                     }
19105                     if (matches_string) {
19106                         sv_catpvn(matches_string, si_string, len - 1);
19107                     }
19108                     else {
19109                         matches_string = newSVpvn(si_string, len - 1);
19110                     }
19111                     si_string += len;
19112                     sv_catpvs(matches_string, " ");
19113                 } /* end of loop through the text */
19114
19115                 assert(matches_string);
19116                 if (SvCUR(matches_string)) {  /* Get rid of trailing blank */
19117                     SvCUR_set(matches_string, SvCUR(matches_string) - 1);
19118                 }
19119             } /* end of has an 'si' */
19120         }
19121
19122         /* Add the stuff that's already known */
19123         if (invlist) {
19124
19125             /* Again, if the caller doesn't want the output inversion list, put
19126              * everything in 'matches-string' */
19127             if (! output_invlist) {
19128                 if ( ! matches_string) {
19129                     matches_string = newSVpvs("\n");
19130                 }
19131                 sv_catsv(matches_string, invlist_contents(invlist,
19132                                                   TRUE /* traditional style */
19133                                                   ));
19134             }
19135             else if (! *output_invlist) {
19136                 *output_invlist = invlist_clone(invlist, NULL);
19137             }
19138             else {
19139                 _invlist_union(*output_invlist, invlist, output_invlist);
19140             }
19141         }
19142
19143         *listsvp = matches_string;
19144     }
19145
19146     return invlist;
19147 }
19148 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
19149
19150 /* reg_skipcomment()
19151
19152    Absorbs an /x style # comment from the input stream,
19153    returning a pointer to the first character beyond the comment, or if the
19154    comment terminates the pattern without anything following it, this returns
19155    one past the final character of the pattern (in other words, RExC_end) and
19156    sets the REG_RUN_ON_COMMENT_SEEN flag.
19157
19158    Note it's the callers responsibility to ensure that we are
19159    actually in /x mode
19160
19161 */
19162
19163 PERL_STATIC_INLINE char*
19164 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
19165 {
19166     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
19167
19168     assert(*p == '#');
19169
19170     while (p < RExC_end) {
19171         if (*(++p) == '\n') {
19172             return p+1;
19173         }
19174     }
19175
19176     /* we ran off the end of the pattern without ending the comment, so we have
19177      * to add an \n when wrapping */
19178     RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
19179     return p;
19180 }
19181
19182 STATIC void
19183 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
19184                                 char ** p,
19185                                 const bool force_to_xmod
19186                          )
19187 {
19188     /* If the text at the current parse position '*p' is a '(?#...)' comment,
19189      * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
19190      * is /x whitespace, advance '*p' so that on exit it points to the first
19191      * byte past all such white space and comments */
19192
19193     const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
19194
19195     PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
19196
19197     assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
19198
19199     for (;;) {
19200         if (RExC_end - (*p) >= 3
19201             && *(*p)     == '('
19202             && *(*p + 1) == '?'
19203             && *(*p + 2) == '#')
19204         {
19205             while (*(*p) != ')') {
19206                 if ((*p) == RExC_end)
19207                     FAIL("Sequence (?#... not terminated");
19208                 (*p)++;
19209             }
19210             (*p)++;
19211             continue;
19212         }
19213
19214         if (use_xmod) {
19215             const char * save_p = *p;
19216             while ((*p) < RExC_end) {
19217                 STRLEN len;
19218                 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
19219                     (*p) += len;
19220                 }
19221                 else if (*(*p) == '#') {
19222                     (*p) = reg_skipcomment(pRExC_state, (*p));
19223                 }
19224                 else {
19225                     break;
19226                 }
19227             }
19228             if (*p != save_p) {
19229                 continue;
19230             }
19231         }
19232
19233         break;
19234     }
19235
19236     return;
19237 }
19238
19239 /* nextchar()
19240
19241    Advances the parse position by one byte, unless that byte is the beginning
19242    of a '(?#...)' style comment, or is /x whitespace and /x is in effect.  In
19243    those two cases, the parse position is advanced beyond all such comments and
19244    white space.
19245
19246    This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
19247 */
19248
19249 STATIC void
19250 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
19251 {
19252     PERL_ARGS_ASSERT_NEXTCHAR;
19253
19254     if (RExC_parse < RExC_end) {
19255         assert(   ! UTF
19256                || UTF8_IS_INVARIANT(*RExC_parse)
19257                || UTF8_IS_START(*RExC_parse));
19258
19259         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
19260
19261         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
19262                                 FALSE /* Don't force /x */ );
19263     }
19264 }
19265
19266 STATIC void
19267 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
19268 {
19269     /* 'size' is the delta to add or subtract from the current memory allocated
19270      * to the regex engine being constructed */
19271
19272     PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
19273
19274     RExC_size += size;
19275
19276     Renewc(RExC_rxi,
19277            sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
19278                                                 /* +1 for REG_MAGIC */
19279            char,
19280            regexp_internal);
19281     if ( RExC_rxi == NULL )
19282         FAIL("Regexp out of space");
19283     RXi_SET(RExC_rx, RExC_rxi);
19284
19285     RExC_emit_start = RExC_rxi->program;
19286     if (size > 0) {
19287         Zero(REGNODE_p(RExC_emit), size, regnode);
19288     }
19289
19290 #ifdef RE_TRACK_PATTERN_OFFSETS
19291     Renew(RExC_offsets, 2*RExC_size+1, U32);
19292     if (size > 0) {
19293         Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
19294     }
19295     RExC_offsets[0] = RExC_size;
19296 #endif
19297 }
19298
19299 STATIC regnode_offset
19300 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
19301 {
19302     /* Allocate a regnode for 'op', with 'extra_size' extra space.  It aligns
19303      * and increments RExC_size and RExC_emit
19304      *
19305      * It returns the regnode's offset into the regex engine program */
19306
19307     const regnode_offset ret = RExC_emit;
19308
19309     GET_RE_DEBUG_FLAGS_DECL;
19310
19311     PERL_ARGS_ASSERT_REGNODE_GUTS;
19312
19313     SIZE_ALIGN(RExC_size);
19314     change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
19315     NODE_ALIGN_FILL(REGNODE_p(ret));
19316 #ifndef RE_TRACK_PATTERN_OFFSETS
19317     PERL_UNUSED_ARG(name);
19318     PERL_UNUSED_ARG(op);
19319 #else
19320     assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
19321
19322     if (RExC_offsets) {         /* MJD */
19323         MJD_OFFSET_DEBUG(
19324               ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
19325               name, __LINE__,
19326               PL_reg_name[op],
19327               (UV)(RExC_emit) > RExC_offsets[0]
19328                 ? "Overwriting end of array!\n" : "OK",
19329               (UV)(RExC_emit),
19330               (UV)(RExC_parse - RExC_start),
19331               (UV)RExC_offsets[0]));
19332         Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
19333     }
19334 #endif
19335     return(ret);
19336 }
19337
19338 /*
19339 - reg_node - emit a node
19340 */
19341 STATIC regnode_offset /* Location. */
19342 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
19343 {
19344     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
19345     regnode_offset ptr = ret;
19346
19347     PERL_ARGS_ASSERT_REG_NODE;
19348
19349     assert(regarglen[op] == 0);
19350
19351     FILL_ADVANCE_NODE(ptr, op);
19352     RExC_emit = ptr;
19353     return(ret);
19354 }
19355
19356 /*
19357 - reganode - emit a node with an argument
19358 */
19359 STATIC regnode_offset /* Location. */
19360 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
19361 {
19362     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
19363     regnode_offset ptr = ret;
19364
19365     PERL_ARGS_ASSERT_REGANODE;
19366
19367     /* ANYOF are special cased to allow non-length 1 args */
19368     assert(regarglen[op] == 1);
19369
19370     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
19371     RExC_emit = ptr;
19372     return(ret);
19373 }
19374
19375 STATIC regnode_offset
19376 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
19377 {
19378     /* emit a node with U32 and I32 arguments */
19379
19380     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
19381     regnode_offset ptr = ret;
19382
19383     PERL_ARGS_ASSERT_REG2LANODE;
19384
19385     assert(regarglen[op] == 2);
19386
19387     FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
19388     RExC_emit = ptr;
19389     return(ret);
19390 }
19391
19392 /*
19393 - reginsert - insert an operator in front of already-emitted operand
19394 *
19395 * That means that on exit 'operand' is the offset of the newly inserted
19396 * operator, and the original operand has been relocated.
19397 *
19398 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
19399 * set up NEXT_OFF() of the inserted node if needed. Something like this:
19400 *
19401 *   reginsert(pRExC, OPFAIL, orig_emit, depth+1);
19402 *   NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
19403 *
19404 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
19405 */
19406 STATIC void
19407 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
19408                   const regnode_offset operand, const U32 depth)
19409 {
19410     regnode *src;
19411     regnode *dst;
19412     regnode *place;
19413     const int offset = regarglen[(U8)op];
19414     const int size = NODE_STEP_REGNODE + offset;
19415     GET_RE_DEBUG_FLAGS_DECL;
19416
19417     PERL_ARGS_ASSERT_REGINSERT;
19418     PERL_UNUSED_CONTEXT;
19419     PERL_UNUSED_ARG(depth);
19420 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
19421     DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
19422     assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
19423                                     studying. If this is wrong then we need to adjust RExC_recurse
19424                                     below like we do with RExC_open_parens/RExC_close_parens. */
19425     change_engine_size(pRExC_state, (Ptrdiff_t) size);
19426     src = REGNODE_p(RExC_emit);
19427     RExC_emit += size;
19428     dst = REGNODE_p(RExC_emit);
19429     if (RExC_open_parens) {
19430         int paren;
19431         /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
19432         /* remember that RExC_npar is rex->nparens + 1,
19433          * iow it is 1 more than the number of parens seen in
19434          * the pattern so far. */
19435         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
19436             /* note, RExC_open_parens[0] is the start of the
19437              * regex, it can't move. RExC_close_parens[0] is the end
19438              * of the regex, it *can* move. */
19439             if ( paren && RExC_open_parens[paren] >= operand ) {
19440                 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
19441                 RExC_open_parens[paren] += size;
19442             } else {
19443                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
19444             }
19445             if ( RExC_close_parens[paren] >= operand ) {
19446                 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
19447                 RExC_close_parens[paren] += size;
19448             } else {
19449                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
19450             }
19451         }
19452     }
19453     if (RExC_end_op)
19454         RExC_end_op += size;
19455
19456     while (src > REGNODE_p(operand)) {
19457         StructCopy(--src, --dst, regnode);
19458 #ifdef RE_TRACK_PATTERN_OFFSETS
19459         if (RExC_offsets) {     /* MJD 20010112 */
19460             MJD_OFFSET_DEBUG(
19461                  ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
19462                   "reginsert",
19463                   __LINE__,
19464                   PL_reg_name[op],
19465                   (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
19466                     ? "Overwriting end of array!\n" : "OK",
19467                   (UV)REGNODE_OFFSET(src),
19468                   (UV)REGNODE_OFFSET(dst),
19469                   (UV)RExC_offsets[0]));
19470             Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
19471             Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
19472         }
19473 #endif
19474     }
19475
19476     place = REGNODE_p(operand); /* Op node, where operand used to be. */
19477 #ifdef RE_TRACK_PATTERN_OFFSETS
19478     if (RExC_offsets) {         /* MJD */
19479         MJD_OFFSET_DEBUG(
19480               ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
19481               "reginsert",
19482               __LINE__,
19483               PL_reg_name[op],
19484               (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
19485               ? "Overwriting end of array!\n" : "OK",
19486               (UV)REGNODE_OFFSET(place),
19487               (UV)(RExC_parse - RExC_start),
19488               (UV)RExC_offsets[0]));
19489         Set_Node_Offset(place, RExC_parse);
19490         Set_Node_Length(place, 1);
19491     }
19492 #endif
19493     src = NEXTOPER(place);
19494     FLAGS(place) = 0;
19495     FILL_NODE(operand, op);
19496
19497     /* Zero out any arguments in the new node */
19498     Zero(src, offset, regnode);
19499 }
19500
19501 /*
19502 - regtail - set the next-pointer at the end of a node chain of p to val.
19503 - SEE ALSO: regtail_study
19504 */
19505 STATIC void
19506 S_regtail(pTHX_ RExC_state_t * pRExC_state,
19507                 const regnode_offset p,
19508                 const regnode_offset val,
19509                 const U32 depth)
19510 {
19511     regnode_offset scan;
19512     GET_RE_DEBUG_FLAGS_DECL;
19513
19514     PERL_ARGS_ASSERT_REGTAIL;
19515 #ifndef DEBUGGING
19516     PERL_UNUSED_ARG(depth);
19517 #endif
19518
19519     /* Find last node. */
19520     scan = (regnode_offset) p;
19521     for (;;) {
19522         regnode * const temp = regnext(REGNODE_p(scan));
19523         DEBUG_PARSE_r({
19524             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
19525             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
19526             Perl_re_printf( aTHX_  "~ %s (%d) %s %s\n",
19527                 SvPV_nolen_const(RExC_mysv), scan,
19528                     (temp == NULL ? "->" : ""),
19529                     (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
19530             );
19531         });
19532         if (temp == NULL)
19533             break;
19534         scan = REGNODE_OFFSET(temp);
19535     }
19536
19537     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
19538         ARG_SET(REGNODE_p(scan), val - scan);
19539     }
19540     else {
19541         NEXT_OFF(REGNODE_p(scan)) = val - scan;
19542     }
19543 }
19544
19545 #ifdef DEBUGGING
19546 /*
19547 - regtail_study - set the next-pointer at the end of a node chain of p to val.
19548 - Look for optimizable sequences at the same time.
19549 - currently only looks for EXACT chains.
19550
19551 This is experimental code. The idea is to use this routine to perform
19552 in place optimizations on branches and groups as they are constructed,
19553 with the long term intention of removing optimization from study_chunk so
19554 that it is purely analytical.
19555
19556 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
19557 to control which is which.
19558
19559 */
19560 /* TODO: All four parms should be const */
19561
19562 STATIC U8
19563 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
19564                       const regnode_offset val, U32 depth)
19565 {
19566     regnode_offset scan;
19567     U8 exact = PSEUDO;
19568 #ifdef EXPERIMENTAL_INPLACESCAN
19569     I32 min = 0;
19570 #endif
19571     GET_RE_DEBUG_FLAGS_DECL;
19572
19573     PERL_ARGS_ASSERT_REGTAIL_STUDY;
19574
19575
19576     /* Find last node. */
19577
19578     scan = p;
19579     for (;;) {
19580         regnode * const temp = regnext(REGNODE_p(scan));
19581 #ifdef EXPERIMENTAL_INPLACESCAN
19582         if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
19583             bool unfolded_multi_char;   /* Unexamined in this routine */
19584             if (join_exact(pRExC_state, scan, &min,
19585                            &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
19586                 return EXACT;
19587         }
19588 #endif
19589         if ( exact ) {
19590             switch (OP(REGNODE_p(scan))) {
19591                 case EXACT:
19592                 case EXACT_ONLY8:
19593                 case EXACTL:
19594                 case EXACTF:
19595                 case EXACTFU_S_EDGE:
19596                 case EXACTFAA_NO_TRIE:
19597                 case EXACTFAA:
19598                 case EXACTFU:
19599                 case EXACTFU_ONLY8:
19600                 case EXACTFLU8:
19601                 case EXACTFUP:
19602                 case EXACTFL:
19603                         if( exact == PSEUDO )
19604                             exact= OP(REGNODE_p(scan));
19605                         else if ( exact != OP(REGNODE_p(scan)) )
19606                             exact= 0;
19607                 case NOTHING:
19608                     break;
19609                 default:
19610                     exact= 0;
19611             }
19612         }
19613         DEBUG_PARSE_r({
19614             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
19615             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
19616             Perl_re_printf( aTHX_  "~ %s (%d) -> %s\n",
19617                 SvPV_nolen_const(RExC_mysv),
19618                 scan,
19619                 PL_reg_name[exact]);
19620         });
19621         if (temp == NULL)
19622             break;
19623         scan = REGNODE_OFFSET(temp);
19624     }
19625     DEBUG_PARSE_r({
19626         DEBUG_PARSE_MSG("");
19627         regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
19628         Perl_re_printf( aTHX_
19629                       "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
19630                       SvPV_nolen_const(RExC_mysv),
19631                       (IV)val,
19632                       (IV)(val - scan)
19633         );
19634     });
19635     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
19636         ARG_SET(REGNODE_p(scan), val - scan);
19637     }
19638     else {
19639         NEXT_OFF(REGNODE_p(scan)) = val - scan;
19640     }
19641
19642     return exact;
19643 }
19644 #endif
19645
19646 STATIC SV*
19647 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
19648
19649     /* Returns an inversion list of all the code points matched by the
19650      * ANYOFM/NANYOFM node 'n' */
19651
19652     SV * cp_list = _new_invlist(-1);
19653     const U8 lowest = (U8) ARG(n);
19654     unsigned int i;
19655     U8 count = 0;
19656     U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
19657
19658     PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
19659
19660     /* Starting with the lowest code point, any code point that ANDed with the
19661      * mask yields the lowest code point is in the set */
19662     for (i = lowest; i <= 0xFF; i++) {
19663         if ((i & FLAGS(n)) == ARG(n)) {
19664             cp_list = add_cp_to_invlist(cp_list, i);
19665             count++;
19666
19667             /* We know how many code points (a power of two) that are in the
19668              * set.  No use looking once we've got that number */
19669             if (count >= needed) break;
19670         }
19671     }
19672
19673     if (OP(n) == NANYOFM) {
19674         _invlist_invert(cp_list);
19675     }
19676     return cp_list;
19677 }
19678
19679 /*
19680  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
19681  */
19682 #ifdef DEBUGGING
19683
19684 static void
19685 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
19686 {
19687     int bit;
19688     int set=0;
19689
19690     ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
19691
19692     for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
19693         if (flags & (1<<bit)) {
19694             if (!set++ && lead)
19695                 Perl_re_printf( aTHX_  "%s", lead);
19696             Perl_re_printf( aTHX_  "%s ", PL_reg_intflags_name[bit]);
19697         }
19698     }
19699     if (lead)  {
19700         if (set)
19701             Perl_re_printf( aTHX_  "\n");
19702         else
19703             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
19704     }
19705 }
19706
19707 static void
19708 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
19709 {
19710     int bit;
19711     int set=0;
19712     regex_charset cs;
19713
19714     ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
19715
19716     for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
19717         if (flags & (1<<bit)) {
19718             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
19719                 continue;
19720             }
19721             if (!set++ && lead)
19722                 Perl_re_printf( aTHX_  "%s", lead);
19723             Perl_re_printf( aTHX_  "%s ", PL_reg_extflags_name[bit]);
19724         }
19725     }
19726     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
19727             if (!set++ && lead) {
19728                 Perl_re_printf( aTHX_  "%s", lead);
19729             }
19730             switch (cs) {
19731                 case REGEX_UNICODE_CHARSET:
19732                     Perl_re_printf( aTHX_  "UNICODE");
19733                     break;
19734                 case REGEX_LOCALE_CHARSET:
19735                     Perl_re_printf( aTHX_  "LOCALE");
19736                     break;
19737                 case REGEX_ASCII_RESTRICTED_CHARSET:
19738                     Perl_re_printf( aTHX_  "ASCII-RESTRICTED");
19739                     break;
19740                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
19741                     Perl_re_printf( aTHX_  "ASCII-MORE_RESTRICTED");
19742                     break;
19743                 default:
19744                     Perl_re_printf( aTHX_  "UNKNOWN CHARACTER SET");
19745                     break;
19746             }
19747     }
19748     if (lead)  {
19749         if (set)
19750             Perl_re_printf( aTHX_  "\n");
19751         else
19752             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
19753     }
19754 }
19755 #endif
19756
19757 void
19758 Perl_regdump(pTHX_ const regexp *r)
19759 {
19760 #ifdef DEBUGGING
19761     int i;
19762     SV * const sv = sv_newmortal();
19763     SV *dsv= sv_newmortal();
19764     RXi_GET_DECL(r, ri);
19765     GET_RE_DEBUG_FLAGS_DECL;
19766
19767     PERL_ARGS_ASSERT_REGDUMP;
19768
19769     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
19770
19771     /* Header fields of interest. */
19772     for (i = 0; i < 2; i++) {
19773         if (r->substrs->data[i].substr) {
19774             RE_PV_QUOTED_DECL(s, 0, dsv,
19775                             SvPVX_const(r->substrs->data[i].substr),
19776                             RE_SV_DUMPLEN(r->substrs->data[i].substr),
19777                             PL_dump_re_max_len);
19778             Perl_re_printf( aTHX_
19779                           "%s %s%s at %" IVdf "..%" UVuf " ",
19780                           i ? "floating" : "anchored",
19781                           s,
19782                           RE_SV_TAIL(r->substrs->data[i].substr),
19783                           (IV)r->substrs->data[i].min_offset,
19784                           (UV)r->substrs->data[i].max_offset);
19785         }
19786         else if (r->substrs->data[i].utf8_substr) {
19787             RE_PV_QUOTED_DECL(s, 1, dsv,
19788                             SvPVX_const(r->substrs->data[i].utf8_substr),
19789                             RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
19790                             30);
19791             Perl_re_printf( aTHX_
19792                           "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
19793                           i ? "floating" : "anchored",
19794                           s,
19795                           RE_SV_TAIL(r->substrs->data[i].utf8_substr),
19796                           (IV)r->substrs->data[i].min_offset,
19797                           (UV)r->substrs->data[i].max_offset);
19798         }
19799     }
19800
19801     if (r->check_substr || r->check_utf8)
19802         Perl_re_printf( aTHX_
19803                       (const char *)
19804                       (   r->check_substr == r->substrs->data[1].substr
19805                        && r->check_utf8   == r->substrs->data[1].utf8_substr
19806                        ? "(checking floating" : "(checking anchored"));
19807     if (r->intflags & PREGf_NOSCAN)
19808         Perl_re_printf( aTHX_  " noscan");
19809     if (r->extflags & RXf_CHECK_ALL)
19810         Perl_re_printf( aTHX_  " isall");
19811     if (r->check_substr || r->check_utf8)
19812         Perl_re_printf( aTHX_  ") ");
19813
19814     if (ri->regstclass) {
19815         regprop(r, sv, ri->regstclass, NULL, NULL);
19816         Perl_re_printf( aTHX_  "stclass %s ", SvPVX_const(sv));
19817     }
19818     if (r->intflags & PREGf_ANCH) {
19819         Perl_re_printf( aTHX_  "anchored");
19820         if (r->intflags & PREGf_ANCH_MBOL)
19821             Perl_re_printf( aTHX_  "(MBOL)");
19822         if (r->intflags & PREGf_ANCH_SBOL)
19823             Perl_re_printf( aTHX_  "(SBOL)");
19824         if (r->intflags & PREGf_ANCH_GPOS)
19825             Perl_re_printf( aTHX_  "(GPOS)");
19826         Perl_re_printf( aTHX_ " ");
19827     }
19828     if (r->intflags & PREGf_GPOS_SEEN)
19829         Perl_re_printf( aTHX_  "GPOS:%" UVuf " ", (UV)r->gofs);
19830     if (r->intflags & PREGf_SKIP)
19831         Perl_re_printf( aTHX_  "plus ");
19832     if (r->intflags & PREGf_IMPLICIT)
19833         Perl_re_printf( aTHX_  "implicit ");
19834     Perl_re_printf( aTHX_  "minlen %" IVdf " ", (IV)r->minlen);
19835     if (r->extflags & RXf_EVAL_SEEN)
19836         Perl_re_printf( aTHX_  "with eval ");
19837     Perl_re_printf( aTHX_  "\n");
19838     DEBUG_FLAGS_r({
19839         regdump_extflags("r->extflags: ", r->extflags);
19840         regdump_intflags("r->intflags: ", r->intflags);
19841     });
19842 #else
19843     PERL_ARGS_ASSERT_REGDUMP;
19844     PERL_UNUSED_CONTEXT;
19845     PERL_UNUSED_ARG(r);
19846 #endif  /* DEBUGGING */
19847 }
19848
19849 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
19850 #ifdef DEBUGGING
19851
19852 #  if   _CC_WORDCHAR != 0 || _CC_DIGIT != 1        || _CC_ALPHA != 2    \
19853      || _CC_LOWER != 3    || _CC_UPPER != 4        || _CC_PUNCT != 5    \
19854      || _CC_PRINT != 6    || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8    \
19855      || _CC_CASED != 9    || _CC_SPACE != 10       || _CC_BLANK != 11   \
19856      || _CC_XDIGIT != 12  || _CC_CNTRL != 13       || _CC_ASCII != 14   \
19857      || _CC_VERTSPACE != 15
19858 #   error Need to adjust order of anyofs[]
19859 #  endif
19860 static const char * const anyofs[] = {
19861     "\\w",
19862     "\\W",
19863     "\\d",
19864     "\\D",
19865     "[:alpha:]",
19866     "[:^alpha:]",
19867     "[:lower:]",
19868     "[:^lower:]",
19869     "[:upper:]",
19870     "[:^upper:]",
19871     "[:punct:]",
19872     "[:^punct:]",
19873     "[:print:]",
19874     "[:^print:]",
19875     "[:alnum:]",
19876     "[:^alnum:]",
19877     "[:graph:]",
19878     "[:^graph:]",
19879     "[:cased:]",
19880     "[:^cased:]",
19881     "\\s",
19882     "\\S",
19883     "[:blank:]",
19884     "[:^blank:]",
19885     "[:xdigit:]",
19886     "[:^xdigit:]",
19887     "[:cntrl:]",
19888     "[:^cntrl:]",
19889     "[:ascii:]",
19890     "[:^ascii:]",
19891     "\\v",
19892     "\\V"
19893 };
19894 #endif
19895
19896 /*
19897 - regprop - printable representation of opcode, with run time support
19898 */
19899
19900 void
19901 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
19902 {
19903 #ifdef DEBUGGING
19904     dVAR;
19905     int k;
19906     RXi_GET_DECL(prog, progi);
19907     GET_RE_DEBUG_FLAGS_DECL;
19908
19909     PERL_ARGS_ASSERT_REGPROP;
19910
19911     SvPVCLEAR(sv);
19912
19913     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
19914         /* It would be nice to FAIL() here, but this may be called from
19915            regexec.c, and it would be hard to supply pRExC_state. */
19916         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
19917                                               (int)OP(o), (int)REGNODE_MAX);
19918     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
19919
19920     k = PL_regkind[OP(o)];
19921
19922     if (k == EXACT) {
19923         sv_catpvs(sv, " ");
19924         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
19925          * is a crude hack but it may be the best for now since
19926          * we have no flag "this EXACTish node was UTF-8"
19927          * --jhi */
19928         pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
19929                   PL_colors[0], PL_colors[1],
19930                   PERL_PV_ESCAPE_UNI_DETECT |
19931                   PERL_PV_ESCAPE_NONASCII   |
19932                   PERL_PV_PRETTY_ELLIPSES   |
19933                   PERL_PV_PRETTY_LTGT       |
19934                   PERL_PV_PRETTY_NOCLEAR
19935                   );
19936     } else if (k == TRIE) {
19937         /* print the details of the trie in dumpuntil instead, as
19938          * progi->data isn't available here */
19939         const char op = OP(o);
19940         const U32 n = ARG(o);
19941         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
19942                (reg_ac_data *)progi->data->data[n] :
19943                NULL;
19944         const reg_trie_data * const trie
19945             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
19946
19947         Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
19948         DEBUG_TRIE_COMPILE_r({
19949           if (trie->jump)
19950             sv_catpvs(sv, "(JUMP)");
19951           Perl_sv_catpvf(aTHX_ sv,
19952             "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
19953             (UV)trie->startstate,
19954             (IV)trie->statecount-1, /* -1 because of the unused 0 element */
19955             (UV)trie->wordcount,
19956             (UV)trie->minlen,
19957             (UV)trie->maxlen,
19958             (UV)TRIE_CHARCOUNT(trie),
19959             (UV)trie->uniquecharcount
19960           );
19961         });
19962         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
19963             sv_catpvs(sv, "[");
19964             (void) put_charclass_bitmap_innards(sv,
19965                                                 ((IS_ANYOF_TRIE(op))
19966                                                  ? ANYOF_BITMAP(o)
19967                                                  : TRIE_BITMAP(trie)),
19968                                                 NULL,
19969                                                 NULL,
19970                                                 NULL,
19971                                                 FALSE
19972                                                );
19973             sv_catpvs(sv, "]");
19974         }
19975     } else if (k == CURLY) {
19976         U32 lo = ARG1(o), hi = ARG2(o);
19977         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
19978             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
19979         Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
19980         if (hi == REG_INFTY)
19981             sv_catpvs(sv, "INFTY");
19982         else
19983             Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
19984         sv_catpvs(sv, "}");
19985     }
19986     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
19987         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
19988     else if (k == REF || k == OPEN || k == CLOSE
19989              || k == GROUPP || OP(o)==ACCEPT)
19990     {
19991         AV *name_list= NULL;
19992         U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
19993         Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno);        /* Parenth number */
19994         if ( RXp_PAREN_NAMES(prog) ) {
19995             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
19996         } else if ( pRExC_state ) {
19997             name_list= RExC_paren_name_list;
19998         }
19999         if (name_list) {
20000             if ( k != REF || (OP(o) < NREF)) {
20001                 SV **name= av_fetch(name_list, parno, 0 );
20002                 if (name)
20003                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20004             }
20005             else {
20006                 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
20007                 I32 *nums=(I32*)SvPVX(sv_dat);
20008                 SV **name= av_fetch(name_list, nums[0], 0 );
20009                 I32 n;
20010                 if (name) {
20011                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
20012                         Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
20013                                     (n ? "," : ""), (IV)nums[n]);
20014                     }
20015                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20016                 }
20017             }
20018         }
20019         if ( k == REF && reginfo) {
20020             U32 n = ARG(o);  /* which paren pair */
20021             I32 ln = prog->offs[n].start;
20022             if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
20023                 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
20024             else if (ln == prog->offs[n].end)
20025                 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
20026             else {
20027                 const char *s = reginfo->strbeg + ln;
20028                 Perl_sv_catpvf(aTHX_ sv, ": ");
20029                 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
20030                     PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
20031             }
20032         }
20033     } else if (k == GOSUB) {
20034         AV *name_list= NULL;
20035         if ( RXp_PAREN_NAMES(prog) ) {
20036             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
20037         } else if ( pRExC_state ) {
20038             name_list= RExC_paren_name_list;
20039         }
20040
20041         /* Paren and offset */
20042         Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
20043                 (int)((o + (int)ARG2L(o)) - progi->program) );
20044         if (name_list) {
20045             SV **name= av_fetch(name_list, ARG(o), 0 );
20046             if (name)
20047                 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20048         }
20049     }
20050     else if (k == LOGICAL)
20051         /* 2: embedded, otherwise 1 */
20052         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
20053     else if (k == ANYOF) {
20054         const U8 flags = ANYOF_FLAGS(o);
20055         bool do_sep = FALSE;    /* Do we need to separate various components of
20056                                    the output? */
20057         /* Set if there is still an unresolved user-defined property */
20058         SV *unresolved                = NULL;
20059
20060         /* Things that are ignored except when the runtime locale is UTF-8 */
20061         SV *only_utf8_locale_invlist = NULL;
20062
20063         /* Code points that don't fit in the bitmap */
20064         SV *nonbitmap_invlist = NULL;
20065
20066         /* And things that aren't in the bitmap, but are small enough to be */
20067         SV* bitmap_range_not_in_bitmap = NULL;
20068
20069         const bool inverted = flags & ANYOF_INVERT;
20070
20071         if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
20072             if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
20073                 sv_catpvs(sv, "{utf8-locale-reqd}");
20074             }
20075             if (flags & ANYOFL_FOLD) {
20076                 sv_catpvs(sv, "{i}");
20077             }
20078         }
20079
20080         /* If there is stuff outside the bitmap, get it */
20081         if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) {
20082             (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
20083                                                 &unresolved,
20084                                                 &only_utf8_locale_invlist,
20085                                                 &nonbitmap_invlist);
20086             /* The non-bitmap data may contain stuff that could fit in the
20087              * bitmap.  This could come from a user-defined property being
20088              * finally resolved when this call was done; or much more likely
20089              * because there are matches that require UTF-8 to be valid, and so
20090              * aren't in the bitmap.  This is teased apart later */
20091             _invlist_intersection(nonbitmap_invlist,
20092                                   PL_InBitmap,
20093                                   &bitmap_range_not_in_bitmap);
20094             /* Leave just the things that don't fit into the bitmap */
20095             _invlist_subtract(nonbitmap_invlist,
20096                               PL_InBitmap,
20097                               &nonbitmap_invlist);
20098         }
20099
20100         /* Obey this flag to add all above-the-bitmap code points */
20101         if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
20102             nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
20103                                                       NUM_ANYOF_CODE_POINTS,
20104                                                       UV_MAX);
20105         }
20106
20107         /* Ready to start outputting.  First, the initial left bracket */
20108         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
20109
20110         if (OP(o) != ANYOFH) {
20111             /* Then all the things that could fit in the bitmap */
20112             do_sep = put_charclass_bitmap_innards(sv,
20113                                                   ANYOF_BITMAP(o),
20114                                                   bitmap_range_not_in_bitmap,
20115                                                   only_utf8_locale_invlist,
20116                                                   o,
20117
20118                                                   /* Can't try inverting for a
20119                                                    * better display if there
20120                                                    * are things that haven't
20121                                                    * been resolved */
20122                                                   unresolved != NULL);
20123             SvREFCNT_dec(bitmap_range_not_in_bitmap);
20124
20125             /* If there are user-defined properties which haven't been defined
20126              * yet, output them.  If the result is not to be inverted, it is
20127              * clearest to output them in a separate [] from the bitmap range
20128              * stuff.  If the result is to be complemented, we have to show
20129              * everything in one [], as the inversion applies to the whole
20130              * thing.  Use {braces} to separate them from anything in the
20131              * bitmap and anything above the bitmap. */
20132             if (unresolved) {
20133                 if (inverted) {
20134                     if (! do_sep) { /* If didn't output anything in the bitmap
20135                                      */
20136                         sv_catpvs(sv, "^");
20137                     }
20138                     sv_catpvs(sv, "{");
20139                 }
20140                 else if (do_sep) {
20141                     Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
20142                                                       PL_colors[0]);
20143                 }
20144                 sv_catsv(sv, unresolved);
20145                 if (inverted) {
20146                     sv_catpvs(sv, "}");
20147                 }
20148                 do_sep = ! inverted;
20149             }
20150         }
20151
20152         /* And, finally, add the above-the-bitmap stuff */
20153         if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
20154             SV* contents;
20155
20156             /* See if truncation size is overridden */
20157             const STRLEN dump_len = (PL_dump_re_max_len > 256)
20158                                     ? PL_dump_re_max_len
20159                                     : 256;
20160
20161             /* This is output in a separate [] */
20162             if (do_sep) {
20163                 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
20164             }
20165
20166             /* And, for easy of understanding, it is shown in the
20167              * uncomplemented form if possible.  The one exception being if
20168              * there are unresolved items, where the inversion has to be
20169              * delayed until runtime */
20170             if (inverted && ! unresolved) {
20171                 _invlist_invert(nonbitmap_invlist);
20172                 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
20173             }
20174
20175             contents = invlist_contents(nonbitmap_invlist,
20176                                         FALSE /* output suitable for catsv */
20177                                        );
20178
20179             /* If the output is shorter than the permissible maximum, just do it. */
20180             if (SvCUR(contents) <= dump_len) {
20181                 sv_catsv(sv, contents);
20182             }
20183             else {
20184                 const char * contents_string = SvPVX(contents);
20185                 STRLEN i = dump_len;
20186
20187                 /* Otherwise, start at the permissible max and work back to the
20188                  * first break possibility */
20189                 while (i > 0 && contents_string[i] != ' ') {
20190                     i--;
20191                 }
20192                 if (i == 0) {       /* Fail-safe.  Use the max if we couldn't
20193                                        find a legal break */
20194                     i = dump_len;
20195                 }
20196
20197                 sv_catpvn(sv, contents_string, i);
20198                 sv_catpvs(sv, "...");
20199             }
20200
20201             SvREFCNT_dec_NN(contents);
20202             SvREFCNT_dec_NN(nonbitmap_invlist);
20203         }
20204
20205         /* And finally the matching, closing ']' */
20206         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
20207
20208         SvREFCNT_dec(unresolved);
20209     }
20210     else if (k == ANYOFM) {
20211         SV * cp_list = get_ANYOFM_contents(o);
20212
20213         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
20214         if (OP(o) == NANYOFM) {
20215             _invlist_invert(cp_list);
20216         }
20217
20218         put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, TRUE);
20219         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
20220
20221         SvREFCNT_dec(cp_list);
20222     }
20223     else if (k == POSIXD || k == NPOSIXD) {
20224         U8 index = FLAGS(o) * 2;
20225         if (index < C_ARRAY_LENGTH(anyofs)) {
20226             if (*anyofs[index] != '[')  {
20227                 sv_catpvs(sv, "[");
20228             }
20229             sv_catpv(sv, anyofs[index]);
20230             if (*anyofs[index] != '[')  {
20231                 sv_catpvs(sv, "]");
20232             }
20233         }
20234         else {
20235             Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
20236         }
20237     }
20238     else if (k == BOUND || k == NBOUND) {
20239         /* Must be synced with order of 'bound_type' in regcomp.h */
20240         const char * const bounds[] = {
20241             "",      /* Traditional */
20242             "{gcb}",
20243             "{lb}",
20244             "{sb}",
20245             "{wb}"
20246         };
20247         assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
20248         sv_catpv(sv, bounds[FLAGS(o)]);
20249     }
20250     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
20251         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
20252     else if (OP(o) == SBOL)
20253         Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
20254
20255     /* add on the verb argument if there is one */
20256     if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
20257         if ( ARG(o) )
20258             Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
20259                        SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
20260         else
20261             sv_catpvs(sv, ":NULL");
20262     }
20263 #else
20264     PERL_UNUSED_CONTEXT;
20265     PERL_UNUSED_ARG(sv);
20266     PERL_UNUSED_ARG(o);
20267     PERL_UNUSED_ARG(prog);
20268     PERL_UNUSED_ARG(reginfo);
20269     PERL_UNUSED_ARG(pRExC_state);
20270 #endif  /* DEBUGGING */
20271 }
20272
20273
20274
20275 SV *
20276 Perl_re_intuit_string(pTHX_ REGEXP * const r)
20277 {                               /* Assume that RE_INTUIT is set */
20278     struct regexp *const prog = ReANY(r);
20279     GET_RE_DEBUG_FLAGS_DECL;
20280
20281     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
20282     PERL_UNUSED_CONTEXT;
20283
20284     DEBUG_COMPILE_r(
20285         {
20286             const char * const s = SvPV_nolen_const(RX_UTF8(r)
20287                       ? prog->check_utf8 : prog->check_substr);
20288
20289             if (!PL_colorset) reginitcolors();
20290             Perl_re_printf( aTHX_
20291                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
20292                       PL_colors[4],
20293                       RX_UTF8(r) ? "utf8 " : "",
20294                       PL_colors[5], PL_colors[0],
20295                       s,
20296                       PL_colors[1],
20297                       (strlen(s) > PL_dump_re_max_len ? "..." : ""));
20298         } );
20299
20300     /* use UTF8 check substring if regexp pattern itself is in UTF8 */
20301     return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
20302 }
20303
20304 /*
20305    pregfree()
20306
20307    handles refcounting and freeing the perl core regexp structure. When
20308    it is necessary to actually free the structure the first thing it
20309    does is call the 'free' method of the regexp_engine associated to
20310    the regexp, allowing the handling of the void *pprivate; member
20311    first. (This routine is not overridable by extensions, which is why
20312    the extensions free is called first.)
20313
20314    See regdupe and regdupe_internal if you change anything here.
20315 */
20316 #ifndef PERL_IN_XSUB_RE
20317 void
20318 Perl_pregfree(pTHX_ REGEXP *r)
20319 {
20320     SvREFCNT_dec(r);
20321 }
20322
20323 void
20324 Perl_pregfree2(pTHX_ REGEXP *rx)
20325 {
20326     struct regexp *const r = ReANY(rx);
20327     GET_RE_DEBUG_FLAGS_DECL;
20328
20329     PERL_ARGS_ASSERT_PREGFREE2;
20330
20331     if (! r)
20332         return;
20333
20334     if (r->mother_re) {
20335         ReREFCNT_dec(r->mother_re);
20336     } else {
20337         CALLREGFREE_PVT(rx); /* free the private data */
20338         SvREFCNT_dec(RXp_PAREN_NAMES(r));
20339     }
20340     if (r->substrs) {
20341         int i;
20342         for (i = 0; i < 2; i++) {
20343             SvREFCNT_dec(r->substrs->data[i].substr);
20344             SvREFCNT_dec(r->substrs->data[i].utf8_substr);
20345         }
20346         Safefree(r->substrs);
20347     }
20348     RX_MATCH_COPY_FREE(rx);
20349 #ifdef PERL_ANY_COW
20350     SvREFCNT_dec(r->saved_copy);
20351 #endif
20352     Safefree(r->offs);
20353     SvREFCNT_dec(r->qr_anoncv);
20354     if (r->recurse_locinput)
20355         Safefree(r->recurse_locinput);
20356 }
20357
20358
20359 /*  reg_temp_copy()
20360
20361     Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
20362     except that dsv will be created if NULL.
20363
20364     This function is used in two main ways. First to implement
20365         $r = qr/....; $s = $$r;
20366
20367     Secondly, it is used as a hacky workaround to the structural issue of
20368     match results
20369     being stored in the regexp structure which is in turn stored in
20370     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
20371     could be PL_curpm in multiple contexts, and could require multiple
20372     result sets being associated with the pattern simultaneously, such
20373     as when doing a recursive match with (??{$qr})
20374
20375     The solution is to make a lightweight copy of the regexp structure
20376     when a qr// is returned from the code executed by (??{$qr}) this
20377     lightweight copy doesn't actually own any of its data except for
20378     the starp/end and the actual regexp structure itself.
20379
20380 */
20381
20382
20383 REGEXP *
20384 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
20385 {
20386     struct regexp *drx;
20387     struct regexp *const srx = ReANY(ssv);
20388     const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
20389
20390     PERL_ARGS_ASSERT_REG_TEMP_COPY;
20391
20392     if (!dsv)
20393         dsv = (REGEXP*) newSV_type(SVt_REGEXP);
20394     else {
20395         SvOK_off((SV *)dsv);
20396         if (islv) {
20397             /* For PVLVs, the head (sv_any) points to an XPVLV, while
20398              * the LV's xpvlenu_rx will point to a regexp body, which
20399              * we allocate here */
20400             REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
20401             assert(!SvPVX(dsv));
20402             ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
20403             temp->sv_any = NULL;
20404             SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
20405             SvREFCNT_dec_NN(temp);
20406             /* SvCUR still resides in the xpvlv struct, so the regexp copy-
20407                ing below will not set it. */
20408             SvCUR_set(dsv, SvCUR(ssv));
20409         }
20410     }
20411     /* This ensures that SvTHINKFIRST(sv) is true, and hence that
20412        sv_force_normal(sv) is called.  */
20413     SvFAKE_on(dsv);
20414     drx = ReANY(dsv);
20415
20416     SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
20417     SvPV_set(dsv, RX_WRAPPED(ssv));
20418     /* We share the same string buffer as the original regexp, on which we
20419        hold a reference count, incremented when mother_re is set below.
20420        The string pointer is copied here, being part of the regexp struct.
20421      */
20422     memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
20423            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
20424     if (!islv)
20425         SvLEN_set(dsv, 0);
20426     if (srx->offs) {
20427         const I32 npar = srx->nparens+1;
20428         Newx(drx->offs, npar, regexp_paren_pair);
20429         Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
20430     }
20431     if (srx->substrs) {
20432         int i;
20433         Newx(drx->substrs, 1, struct reg_substr_data);
20434         StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
20435
20436         for (i = 0; i < 2; i++) {
20437             SvREFCNT_inc_void(drx->substrs->data[i].substr);
20438             SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
20439         }
20440
20441         /* check_substr and check_utf8, if non-NULL, point to either their
20442            anchored or float namesakes, and don't hold a second reference.  */
20443     }
20444     RX_MATCH_COPIED_off(dsv);
20445 #ifdef PERL_ANY_COW
20446     drx->saved_copy = NULL;
20447 #endif
20448     drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
20449     SvREFCNT_inc_void(drx->qr_anoncv);
20450     if (srx->recurse_locinput)
20451         Newx(drx->recurse_locinput, srx->nparens + 1, char *);
20452
20453     return dsv;
20454 }
20455 #endif
20456
20457
20458 /* regfree_internal()
20459
20460    Free the private data in a regexp. This is overloadable by
20461    extensions. Perl takes care of the regexp structure in pregfree(),
20462    this covers the *pprivate pointer which technically perl doesn't
20463    know about, however of course we have to handle the
20464    regexp_internal structure when no extension is in use.
20465
20466    Note this is called before freeing anything in the regexp
20467    structure.
20468  */
20469
20470 void
20471 Perl_regfree_internal(pTHX_ REGEXP * const rx)
20472 {
20473     struct regexp *const r = ReANY(rx);
20474     RXi_GET_DECL(r, ri);
20475     GET_RE_DEBUG_FLAGS_DECL;
20476
20477     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
20478
20479     if (! ri) {
20480         return;
20481     }
20482
20483     DEBUG_COMPILE_r({
20484         if (!PL_colorset)
20485             reginitcolors();
20486         {
20487             SV *dsv= sv_newmortal();
20488             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
20489                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
20490             Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
20491                 PL_colors[4], PL_colors[5], s);
20492         }
20493     });
20494
20495 #ifdef RE_TRACK_PATTERN_OFFSETS
20496     if (ri->u.offsets)
20497         Safefree(ri->u.offsets);             /* 20010421 MJD */
20498 #endif
20499     if (ri->code_blocks)
20500         S_free_codeblocks(aTHX_ ri->code_blocks);
20501
20502     if (ri->data) {
20503         int n = ri->data->count;
20504
20505         while (--n >= 0) {
20506           /* If you add a ->what type here, update the comment in regcomp.h */
20507             switch (ri->data->what[n]) {
20508             case 'a':
20509             case 'r':
20510             case 's':
20511             case 'S':
20512             case 'u':
20513                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
20514                 break;
20515             case 'f':
20516                 Safefree(ri->data->data[n]);
20517                 break;
20518             case 'l':
20519             case 'L':
20520                 break;
20521             case 'T':
20522                 { /* Aho Corasick add-on structure for a trie node.
20523                      Used in stclass optimization only */
20524                     U32 refcount;
20525                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
20526 #ifdef USE_ITHREADS
20527                     dVAR;
20528 #endif
20529                     OP_REFCNT_LOCK;
20530                     refcount = --aho->refcount;
20531                     OP_REFCNT_UNLOCK;
20532                     if ( !refcount ) {
20533                         PerlMemShared_free(aho->states);
20534                         PerlMemShared_free(aho->fail);
20535                          /* do this last!!!! */
20536                         PerlMemShared_free(ri->data->data[n]);
20537                         /* we should only ever get called once, so
20538                          * assert as much, and also guard the free
20539                          * which /might/ happen twice. At the least
20540                          * it will make code anlyzers happy and it
20541                          * doesn't cost much. - Yves */
20542                         assert(ri->regstclass);
20543                         if (ri->regstclass) {
20544                             PerlMemShared_free(ri->regstclass);
20545                             ri->regstclass = 0;
20546                         }
20547                     }
20548                 }
20549                 break;
20550             case 't':
20551                 {
20552                     /* trie structure. */
20553                     U32 refcount;
20554                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
20555 #ifdef USE_ITHREADS
20556                     dVAR;
20557 #endif
20558                     OP_REFCNT_LOCK;
20559                     refcount = --trie->refcount;
20560                     OP_REFCNT_UNLOCK;
20561                     if ( !refcount ) {
20562                         PerlMemShared_free(trie->charmap);
20563                         PerlMemShared_free(trie->states);
20564                         PerlMemShared_free(trie->trans);
20565                         if (trie->bitmap)
20566                             PerlMemShared_free(trie->bitmap);
20567                         if (trie->jump)
20568                             PerlMemShared_free(trie->jump);
20569                         PerlMemShared_free(trie->wordinfo);
20570                         /* do this last!!!! */
20571                         PerlMemShared_free(ri->data->data[n]);
20572                     }
20573                 }
20574                 break;
20575             default:
20576                 Perl_croak(aTHX_ "panic: regfree data code '%c'",
20577                                                     ri->data->what[n]);
20578             }
20579         }
20580         Safefree(ri->data->what);
20581         Safefree(ri->data);
20582     }
20583
20584     Safefree(ri);
20585 }
20586
20587 #define av_dup_inc(s, t)        MUTABLE_AV(sv_dup_inc((const SV *)s, t))
20588 #define hv_dup_inc(s, t)        MUTABLE_HV(sv_dup_inc((const SV *)s, t))
20589 #define SAVEPVN(p, n)   ((p) ? savepvn(p, n) : NULL)
20590
20591 /*
20592    re_dup_guts - duplicate a regexp.
20593
20594    This routine is expected to clone a given regexp structure. It is only
20595    compiled under USE_ITHREADS.
20596
20597    After all of the core data stored in struct regexp is duplicated
20598    the regexp_engine.dupe method is used to copy any private data
20599    stored in the *pprivate pointer. This allows extensions to handle
20600    any duplication it needs to do.
20601
20602    See pregfree() and regfree_internal() if you change anything here.
20603 */
20604 #if defined(USE_ITHREADS)
20605 #ifndef PERL_IN_XSUB_RE
20606 void
20607 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
20608 {
20609     dVAR;
20610     I32 npar;
20611     const struct regexp *r = ReANY(sstr);
20612     struct regexp *ret = ReANY(dstr);
20613
20614     PERL_ARGS_ASSERT_RE_DUP_GUTS;
20615
20616     npar = r->nparens+1;
20617     Newx(ret->offs, npar, regexp_paren_pair);
20618     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
20619
20620     if (ret->substrs) {
20621         /* Do it this way to avoid reading from *r after the StructCopy().
20622            That way, if any of the sv_dup_inc()s dislodge *r from the L1
20623            cache, it doesn't matter.  */
20624         int i;
20625         const bool anchored = r->check_substr
20626             ? r->check_substr == r->substrs->data[0].substr
20627             : r->check_utf8   == r->substrs->data[0].utf8_substr;
20628         Newx(ret->substrs, 1, struct reg_substr_data);
20629         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
20630
20631         for (i = 0; i < 2; i++) {
20632             ret->substrs->data[i].substr =
20633                         sv_dup_inc(ret->substrs->data[i].substr, param);
20634             ret->substrs->data[i].utf8_substr =
20635                         sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
20636         }
20637
20638         /* check_substr and check_utf8, if non-NULL, point to either their
20639            anchored or float namesakes, and don't hold a second reference.  */
20640
20641         if (ret->check_substr) {
20642             if (anchored) {
20643                 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
20644
20645                 ret->check_substr = ret->substrs->data[0].substr;
20646                 ret->check_utf8   = ret->substrs->data[0].utf8_substr;
20647             } else {
20648                 assert(r->check_substr == r->substrs->data[1].substr);
20649                 assert(r->check_utf8   == r->substrs->data[1].utf8_substr);
20650
20651                 ret->check_substr = ret->substrs->data[1].substr;
20652                 ret->check_utf8   = ret->substrs->data[1].utf8_substr;
20653             }
20654         } else if (ret->check_utf8) {
20655             if (anchored) {
20656                 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
20657             } else {
20658                 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
20659             }
20660         }
20661     }
20662
20663     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
20664     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
20665     if (r->recurse_locinput)
20666         Newx(ret->recurse_locinput, r->nparens + 1, char *);
20667
20668     if (ret->pprivate)
20669         RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
20670
20671     if (RX_MATCH_COPIED(dstr))
20672         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
20673     else
20674         ret->subbeg = NULL;
20675 #ifdef PERL_ANY_COW
20676     ret->saved_copy = NULL;
20677 #endif
20678
20679     /* Whether mother_re be set or no, we need to copy the string.  We
20680        cannot refrain from copying it when the storage points directly to
20681        our mother regexp, because that's
20682                1: a buffer in a different thread
20683                2: something we no longer hold a reference on
20684                so we need to copy it locally.  */
20685     RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
20686     ret->mother_re   = NULL;
20687 }
20688 #endif /* PERL_IN_XSUB_RE */
20689
20690 /*
20691    regdupe_internal()
20692
20693    This is the internal complement to regdupe() which is used to copy
20694    the structure pointed to by the *pprivate pointer in the regexp.
20695    This is the core version of the extension overridable cloning hook.
20696    The regexp structure being duplicated will be copied by perl prior
20697    to this and will be provided as the regexp *r argument, however
20698    with the /old/ structures pprivate pointer value. Thus this routine
20699    may override any copying normally done by perl.
20700
20701    It returns a pointer to the new regexp_internal structure.
20702 */
20703
20704 void *
20705 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
20706 {
20707     dVAR;
20708     struct regexp *const r = ReANY(rx);
20709     regexp_internal *reti;
20710     int len;
20711     RXi_GET_DECL(r, ri);
20712
20713     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
20714
20715     len = ProgLen(ri);
20716
20717     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
20718           char, regexp_internal);
20719     Copy(ri->program, reti->program, len+1, regnode);
20720
20721
20722     if (ri->code_blocks) {
20723         int n;
20724         Newx(reti->code_blocks, 1, struct reg_code_blocks);
20725         Newx(reti->code_blocks->cb, ri->code_blocks->count,
20726                     struct reg_code_block);
20727         Copy(ri->code_blocks->cb, reti->code_blocks->cb,
20728              ri->code_blocks->count, struct reg_code_block);
20729         for (n = 0; n < ri->code_blocks->count; n++)
20730              reti->code_blocks->cb[n].src_regex = (REGEXP*)
20731                     sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
20732         reti->code_blocks->count = ri->code_blocks->count;
20733         reti->code_blocks->refcnt = 1;
20734     }
20735     else
20736         reti->code_blocks = NULL;
20737
20738     reti->regstclass = NULL;
20739
20740     if (ri->data) {
20741         struct reg_data *d;
20742         const int count = ri->data->count;
20743         int i;
20744
20745         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
20746                 char, struct reg_data);
20747         Newx(d->what, count, U8);
20748
20749         d->count = count;
20750         for (i = 0; i < count; i++) {
20751             d->what[i] = ri->data->what[i];
20752             switch (d->what[i]) {
20753                 /* see also regcomp.h and regfree_internal() */
20754             case 'a': /* actually an AV, but the dup function is identical.
20755                          values seem to be "plain sv's" generally. */
20756             case 'r': /* a compiled regex (but still just another SV) */
20757             case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
20758                          this use case should go away, the code could have used
20759                          'a' instead - see S_set_ANYOF_arg() for array contents. */
20760             case 'S': /* actually an SV, but the dup function is identical.  */
20761             case 'u': /* actually an HV, but the dup function is identical.
20762                          values are "plain sv's" */
20763                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
20764                 break;
20765             case 'f':
20766                 /* Synthetic Start Class - "Fake" charclass we generate to optimize
20767                  * patterns which could start with several different things. Pre-TRIE
20768                  * this was more important than it is now, however this still helps
20769                  * in some places, for instance /x?a+/ might produce a SSC equivalent
20770                  * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
20771                  * in regexec.c
20772                  */
20773                 /* This is cheating. */
20774                 Newx(d->data[i], 1, regnode_ssc);
20775                 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
20776                 reti->regstclass = (regnode*)d->data[i];
20777                 break;
20778             case 'T':
20779                 /* AHO-CORASICK fail table */
20780                 /* Trie stclasses are readonly and can thus be shared
20781                  * without duplication. We free the stclass in pregfree
20782                  * when the corresponding reg_ac_data struct is freed.
20783                  */
20784                 reti->regstclass= ri->regstclass;
20785                 /* FALLTHROUGH */
20786             case 't':
20787                 /* TRIE transition table */
20788                 OP_REFCNT_LOCK;
20789                 ((reg_trie_data*)ri->data->data[i])->refcount++;
20790                 OP_REFCNT_UNLOCK;
20791                 /* FALLTHROUGH */
20792             case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
20793             case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
20794                          is not from another regexp */
20795                 d->data[i] = ri->data->data[i];
20796                 break;
20797             default:
20798                 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
20799                                                            ri->data->what[i]);
20800             }
20801         }
20802
20803         reti->data = d;
20804     }
20805     else
20806         reti->data = NULL;
20807
20808     reti->name_list_idx = ri->name_list_idx;
20809
20810 #ifdef RE_TRACK_PATTERN_OFFSETS
20811     if (ri->u.offsets) {
20812         Newx(reti->u.offsets, 2*len+1, U32);
20813         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
20814     }
20815 #else
20816     SetProgLen(reti, len);
20817 #endif
20818
20819     return (void*)reti;
20820 }
20821
20822 #endif    /* USE_ITHREADS */
20823
20824 #ifndef PERL_IN_XSUB_RE
20825
20826 /*
20827  - regnext - dig the "next" pointer out of a node
20828  */
20829 regnode *
20830 Perl_regnext(pTHX_ regnode *p)
20831 {
20832     I32 offset;
20833
20834     if (!p)
20835         return(NULL);
20836
20837     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
20838         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
20839                                                 (int)OP(p), (int)REGNODE_MAX);
20840     }
20841
20842     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
20843     if (offset == 0)
20844         return(NULL);
20845
20846     return(p+offset);
20847 }
20848
20849 #endif
20850
20851 STATIC void
20852 S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...)
20853 {
20854     va_list args;
20855     STRLEN l1 = strlen(pat1);
20856     STRLEN l2 = strlen(pat2);
20857     char buf[512];
20858     SV *msv;
20859     const char *message;
20860
20861     PERL_ARGS_ASSERT_RE_CROAK2;
20862
20863     if (l1 > 510)
20864         l1 = 510;
20865     if (l1 + l2 > 510)
20866         l2 = 510 - l1;
20867     Copy(pat1, buf, l1 , char);
20868     Copy(pat2, buf + l1, l2 , char);
20869     buf[l1 + l2] = '\n';
20870     buf[l1 + l2 + 1] = '\0';
20871     va_start(args, pat2);
20872     msv = vmess(buf, &args);
20873     va_end(args);
20874     message = SvPV_const(msv, l1);
20875     if (l1 > 512)
20876         l1 = 512;
20877     Copy(message, buf, l1 , char);
20878     /* l1-1 to avoid \n */
20879     Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf));
20880 }
20881
20882 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
20883
20884 #ifndef PERL_IN_XSUB_RE
20885 void
20886 Perl_save_re_context(pTHX)
20887 {
20888     I32 nparens = -1;
20889     I32 i;
20890
20891     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
20892
20893     if (PL_curpm) {
20894         const REGEXP * const rx = PM_GETRE(PL_curpm);
20895         if (rx)
20896             nparens = RX_NPARENS(rx);
20897     }
20898
20899     /* RT #124109. This is a complete hack; in the SWASHNEW case we know
20900      * that PL_curpm will be null, but that utf8.pm and the modules it
20901      * loads will only use $1..$3.
20902      * The t/porting/re_context.t test file checks this assumption.
20903      */
20904     if (nparens == -1)
20905         nparens = 3;
20906
20907     for (i = 1; i <= nparens; i++) {
20908         char digits[TYPE_CHARS(long)];
20909         const STRLEN len = my_snprintf(digits, sizeof(digits),
20910                                        "%lu", (long)i);
20911         GV *const *const gvp
20912             = (GV**)hv_fetch(PL_defstash, digits, len, 0);
20913
20914         if (gvp) {
20915             GV * const gv = *gvp;
20916             if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
20917                 save_scalar(gv);
20918         }
20919     }
20920 }
20921 #endif
20922
20923 #ifdef DEBUGGING
20924
20925 STATIC void
20926 S_put_code_point(pTHX_ SV *sv, UV c)
20927 {
20928     PERL_ARGS_ASSERT_PUT_CODE_POINT;
20929
20930     if (c > 255) {
20931         Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
20932     }
20933     else if (isPRINT(c)) {
20934         const char string = (char) c;
20935
20936         /* We use {phrase} as metanotation in the class, so also escape literal
20937          * braces */
20938         if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
20939             sv_catpvs(sv, "\\");
20940         sv_catpvn(sv, &string, 1);
20941     }
20942     else if (isMNEMONIC_CNTRL(c)) {
20943         Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
20944     }
20945     else {
20946         Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
20947     }
20948 }
20949
20950 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
20951
20952 STATIC void
20953 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
20954 {
20955     /* Appends to 'sv' a displayable version of the range of code points from
20956      * 'start' to 'end'.  Mnemonics (like '\r') are used for the few controls
20957      * that have them, when they occur at the beginning or end of the range.
20958      * It uses hex to output the remaining code points, unless 'allow_literals'
20959      * is true, in which case the printable ASCII ones are output as-is (though
20960      * some of these will be escaped by put_code_point()).
20961      *
20962      * NOTE:  This is designed only for printing ranges of code points that fit
20963      *        inside an ANYOF bitmap.  Higher code points are simply suppressed
20964      */
20965
20966     const unsigned int min_range_count = 3;
20967
20968     assert(start <= end);
20969
20970     PERL_ARGS_ASSERT_PUT_RANGE;
20971
20972     while (start <= end) {
20973         UV this_end;
20974         const char * format;
20975
20976         if (end - start < min_range_count) {
20977
20978             /* Output chars individually when they occur in short ranges */
20979             for (; start <= end; start++) {
20980                 put_code_point(sv, start);
20981             }
20982             break;
20983         }
20984
20985         /* If permitted by the input options, and there is a possibility that
20986          * this range contains a printable literal, look to see if there is
20987          * one. */
20988         if (allow_literals && start <= MAX_PRINT_A) {
20989
20990             /* If the character at the beginning of the range isn't an ASCII
20991              * printable, effectively split the range into two parts:
20992              *  1) the portion before the first such printable,
20993              *  2) the rest
20994              * and output them separately. */
20995             if (! isPRINT_A(start)) {
20996                 UV temp_end = start + 1;
20997
20998                 /* There is no point looking beyond the final possible
20999                  * printable, in MAX_PRINT_A */
21000                 UV max = MIN(end, MAX_PRINT_A);
21001
21002                 while (temp_end <= max && ! isPRINT_A(temp_end)) {
21003                     temp_end++;
21004                 }
21005
21006                 /* Here, temp_end points to one beyond the first printable if
21007                  * found, or to one beyond 'max' if not.  If none found, make
21008                  * sure that we use the entire range */
21009                 if (temp_end > MAX_PRINT_A) {
21010                     temp_end = end + 1;
21011                 }
21012
21013                 /* Output the first part of the split range: the part that
21014                  * doesn't have printables, with the parameter set to not look
21015                  * for literals (otherwise we would infinitely recurse) */
21016                 put_range(sv, start, temp_end - 1, FALSE);
21017
21018                 /* The 2nd part of the range (if any) starts here. */
21019                 start = temp_end;
21020
21021                 /* We do a continue, instead of dropping down, because even if
21022                  * the 2nd part is non-empty, it could be so short that we want
21023                  * to output it as individual characters, as tested for at the
21024                  * top of this loop.  */
21025                 continue;
21026             }
21027
21028             /* Here, 'start' is a printable ASCII.  If it is an alphanumeric,
21029              * output a sub-range of just the digits or letters, then process
21030              * the remaining portion as usual. */
21031             if (isALPHANUMERIC_A(start)) {
21032                 UV mask = (isDIGIT_A(start))
21033                            ? _CC_DIGIT
21034                              : isUPPER_A(start)
21035                                ? _CC_UPPER
21036                                : _CC_LOWER;
21037                 UV temp_end = start + 1;
21038
21039                 /* Find the end of the sub-range that includes just the
21040                  * characters in the same class as the first character in it */
21041                 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
21042                     temp_end++;
21043                 }
21044                 temp_end--;
21045
21046                 /* For short ranges, don't duplicate the code above to output
21047                  * them; just call recursively */
21048                 if (temp_end - start < min_range_count) {
21049                     put_range(sv, start, temp_end, FALSE);
21050                 }
21051                 else {  /* Output as a range */
21052                     put_code_point(sv, start);
21053                     sv_catpvs(sv, "-");
21054                     put_code_point(sv, temp_end);
21055                 }
21056                 start = temp_end + 1;
21057                 continue;
21058             }
21059
21060             /* We output any other printables as individual characters */
21061             if (isPUNCT_A(start) || isSPACE_A(start)) {
21062                 while (start <= end && (isPUNCT_A(start)
21063                                         || isSPACE_A(start)))
21064                 {
21065                     put_code_point(sv, start);
21066                     start++;
21067                 }
21068                 continue;
21069             }
21070         } /* End of looking for literals */
21071
21072         /* Here is not to output as a literal.  Some control characters have
21073          * mnemonic names.  Split off any of those at the beginning and end of
21074          * the range to print mnemonically.  It isn't possible for many of
21075          * these to be in a row, so this won't overwhelm with output */
21076         if (   start <= end
21077             && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
21078         {
21079             while (isMNEMONIC_CNTRL(start) && start <= end) {
21080                 put_code_point(sv, start);
21081                 start++;
21082             }
21083
21084             /* If this didn't take care of the whole range ... */
21085             if (start <= end) {
21086
21087                 /* Look backwards from the end to find the final non-mnemonic
21088                  * */
21089                 UV temp_end = end;
21090                 while (isMNEMONIC_CNTRL(temp_end)) {
21091                     temp_end--;
21092                 }
21093
21094                 /* And separately output the interior range that doesn't start
21095                  * or end with mnemonics */
21096                 put_range(sv, start, temp_end, FALSE);
21097
21098                 /* Then output the mnemonic trailing controls */
21099                 start = temp_end + 1;
21100                 while (start <= end) {
21101                     put_code_point(sv, start);
21102                     start++;
21103                 }
21104                 break;
21105             }
21106         }
21107
21108         /* As a final resort, output the range or subrange as hex. */
21109
21110         this_end = (end < NUM_ANYOF_CODE_POINTS)
21111                     ? end
21112                     : NUM_ANYOF_CODE_POINTS - 1;
21113 #if NUM_ANYOF_CODE_POINTS > 256
21114         format = (this_end < 256)
21115                  ? "\\x%02" UVXf "-\\x%02" UVXf
21116                  : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
21117 #else
21118         format = "\\x%02" UVXf "-\\x%02" UVXf;
21119 #endif
21120         GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
21121         Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
21122         GCC_DIAG_RESTORE_STMT;
21123         break;
21124     }
21125 }
21126
21127 STATIC void
21128 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
21129 {
21130     /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
21131      * 'invlist' */
21132
21133     UV start, end;
21134     bool allow_literals = TRUE;
21135
21136     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
21137
21138     /* Generally, it is more readable if printable characters are output as
21139      * literals, but if a range (nearly) spans all of them, it's best to output
21140      * it as a single range.  This code will use a single range if all but 2
21141      * ASCII printables are in it */
21142     invlist_iterinit(invlist);
21143     while (invlist_iternext(invlist, &start, &end)) {
21144
21145         /* If the range starts beyond the final printable, it doesn't have any
21146          * in it */
21147         if (start > MAX_PRINT_A) {
21148             break;
21149         }
21150
21151         /* In both ASCII and EBCDIC, a SPACE is the lowest printable.  To span
21152          * all but two, the range must start and end no later than 2 from
21153          * either end */
21154         if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
21155             if (end > MAX_PRINT_A) {
21156                 end = MAX_PRINT_A;
21157             }
21158             if (start < ' ') {
21159                 start = ' ';
21160             }
21161             if (end - start >= MAX_PRINT_A - ' ' - 2) {
21162                 allow_literals = FALSE;
21163             }
21164             break;
21165         }
21166     }
21167     invlist_iterfinish(invlist);
21168
21169     /* Here we have figured things out.  Output each range */
21170     invlist_iterinit(invlist);
21171     while (invlist_iternext(invlist, &start, &end)) {
21172         if (start >= NUM_ANYOF_CODE_POINTS) {
21173             break;
21174         }
21175         put_range(sv, start, end, allow_literals);
21176     }
21177     invlist_iterfinish(invlist);
21178
21179     return;
21180 }
21181
21182 STATIC SV*
21183 S_put_charclass_bitmap_innards_common(pTHX_
21184         SV* invlist,            /* The bitmap */
21185         SV* posixes,            /* Under /l, things like [:word:], \S */
21186         SV* only_utf8,          /* Under /d, matches iff the target is UTF-8 */
21187         SV* not_utf8,           /* /d, matches iff the target isn't UTF-8 */
21188         SV* only_utf8_locale,   /* Under /l, matches if the locale is UTF-8 */
21189         const bool invert       /* Is the result to be inverted? */
21190 )
21191 {
21192     /* Create and return an SV containing a displayable version of the bitmap
21193      * and associated information determined by the input parameters.  If the
21194      * output would have been only the inversion indicator '^', NULL is instead
21195      * returned. */
21196
21197     dVAR;
21198     SV * output;
21199
21200     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
21201
21202     if (invert) {
21203         output = newSVpvs("^");
21204     }
21205     else {
21206         output = newSVpvs("");
21207     }
21208
21209     /* First, the code points in the bitmap that are unconditionally there */
21210     put_charclass_bitmap_innards_invlist(output, invlist);
21211
21212     /* Traditionally, these have been placed after the main code points */
21213     if (posixes) {
21214         sv_catsv(output, posixes);
21215     }
21216
21217     if (only_utf8 && _invlist_len(only_utf8)) {
21218         Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
21219         put_charclass_bitmap_innards_invlist(output, only_utf8);
21220     }
21221
21222     if (not_utf8 && _invlist_len(not_utf8)) {
21223         Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
21224         put_charclass_bitmap_innards_invlist(output, not_utf8);
21225     }
21226
21227     if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
21228         Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
21229         put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
21230
21231         /* This is the only list in this routine that can legally contain code
21232          * points outside the bitmap range.  The call just above to
21233          * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
21234          * output them here.  There's about a half-dozen possible, and none in
21235          * contiguous ranges longer than 2 */
21236         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
21237             UV start, end;
21238             SV* above_bitmap = NULL;
21239
21240             _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
21241
21242             invlist_iterinit(above_bitmap);
21243             while (invlist_iternext(above_bitmap, &start, &end)) {
21244                 UV i;
21245
21246                 for (i = start; i <= end; i++) {
21247                     put_code_point(output, i);
21248                 }
21249             }
21250             invlist_iterfinish(above_bitmap);
21251             SvREFCNT_dec_NN(above_bitmap);
21252         }
21253     }
21254
21255     if (invert && SvCUR(output) == 1) {
21256         return NULL;
21257     }
21258
21259     return output;
21260 }
21261
21262 STATIC bool
21263 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
21264                                      char *bitmap,
21265                                      SV *nonbitmap_invlist,
21266                                      SV *only_utf8_locale_invlist,
21267                                      const regnode * const node,
21268                                      const bool force_as_is_display)
21269 {
21270     /* Appends to 'sv' a displayable version of the innards of the bracketed
21271      * character class defined by the other arguments:
21272      *  'bitmap' points to the bitmap, or NULL if to ignore that.
21273      *  'nonbitmap_invlist' is an inversion list of the code points that are in
21274      *      the bitmap range, but for some reason aren't in the bitmap; NULL if
21275      *      none.  The reasons for this could be that they require some
21276      *      condition such as the target string being or not being in UTF-8
21277      *      (under /d), or because they came from a user-defined property that
21278      *      was not resolved at the time of the regex compilation (under /u)
21279      *  'only_utf8_locale_invlist' is an inversion list of the code points that
21280      *      are valid only if the runtime locale is a UTF-8 one; NULL if none
21281      *  'node' is the regex pattern ANYOF node.  It is needed only when the
21282      *      above two parameters are not null, and is passed so that this
21283      *      routine can tease apart the various reasons for them.
21284      *  'force_as_is_display' is TRUE if this routine should definitely NOT try
21285      *      to invert things to see if that leads to a cleaner display.  If
21286      *      FALSE, this routine is free to use its judgment about doing this.
21287      *
21288      * It returns TRUE if there was actually something output.  (It may be that
21289      * the bitmap, etc is empty.)
21290      *
21291      * When called for outputting the bitmap of a non-ANYOF node, just pass the
21292      * bitmap, with the succeeding parameters set to NULL, and the final one to
21293      * FALSE.
21294      */
21295
21296     /* In general, it tries to display the 'cleanest' representation of the
21297      * innards, choosing whether to display them inverted or not, regardless of
21298      * whether the class itself is to be inverted.  However,  there are some
21299      * cases where it can't try inverting, as what actually matches isn't known
21300      * until runtime, and hence the inversion isn't either. */
21301
21302     dVAR;
21303     bool inverting_allowed = ! force_as_is_display;
21304
21305     int i;
21306     STRLEN orig_sv_cur = SvCUR(sv);
21307
21308     SV* invlist;            /* Inversion list we accumulate of code points that
21309                                are unconditionally matched */
21310     SV* only_utf8 = NULL;   /* Under /d, list of matches iff the target is
21311                                UTF-8 */
21312     SV* not_utf8 =  NULL;   /* /d, list of matches iff the target isn't UTF-8
21313                              */
21314     SV* posixes = NULL;     /* Under /l, string of things like [:word:], \D */
21315     SV* only_utf8_locale = NULL;    /* Under /l, list of matches if the locale
21316                                        is UTF-8 */
21317
21318     SV* as_is_display;      /* The output string when we take the inputs
21319                                literally */
21320     SV* inverted_display;   /* The output string when we invert the inputs */
21321
21322     U8 flags = (node) ? ANYOF_FLAGS(node) : 0;
21323
21324     bool invert = cBOOL(flags & ANYOF_INVERT);  /* Is the input to be inverted
21325                                                    to match? */
21326     /* We are biased in favor of displaying things without them being inverted,
21327      * as that is generally easier to understand */
21328     const int bias = 5;
21329
21330     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
21331
21332     /* Start off with whatever code points are passed in.  (We clone, so we
21333      * don't change the caller's list) */
21334     if (nonbitmap_invlist) {
21335         assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
21336         invlist = invlist_clone(nonbitmap_invlist, NULL);
21337     }
21338     else {  /* Worst case size is every other code point is matched */
21339         invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
21340     }
21341
21342     if (flags) {
21343         if (OP(node) == ANYOFD) {
21344
21345             /* This flag indicates that the code points below 0x100 in the
21346              * nonbitmap list are precisely the ones that match only when the
21347              * target is UTF-8 (they should all be non-ASCII). */
21348             if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
21349             {
21350                 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
21351                 _invlist_subtract(invlist, only_utf8, &invlist);
21352             }
21353
21354             /* And this flag for matching all non-ASCII 0xFF and below */
21355             if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
21356             {
21357                 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
21358             }
21359         }
21360         else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
21361
21362             /* If either of these flags are set, what matches isn't
21363              * determinable except during execution, so don't know enough here
21364              * to invert */
21365             if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
21366                 inverting_allowed = FALSE;
21367             }
21368
21369             /* What the posix classes match also varies at runtime, so these
21370              * will be output symbolically. */
21371             if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
21372                 int i;
21373
21374                 posixes = newSVpvs("");
21375                 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
21376                     if (ANYOF_POSIXL_TEST(node, i)) {
21377                         sv_catpv(posixes, anyofs[i]);
21378                     }
21379                 }
21380             }
21381         }
21382     }
21383
21384     /* Accumulate the bit map into the unconditional match list */
21385     if (bitmap) {
21386         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
21387             if (BITMAP_TEST(bitmap, i)) {
21388                 int start = i++;
21389                 for (;
21390                      i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
21391                      i++)
21392                 { /* empty */ }
21393                 invlist = _add_range_to_invlist(invlist, start, i-1);
21394             }
21395         }
21396     }
21397
21398     /* Make sure that the conditional match lists don't have anything in them
21399      * that match unconditionally; otherwise the output is quite confusing.
21400      * This could happen if the code that populates these misses some
21401      * duplication. */
21402     if (only_utf8) {
21403         _invlist_subtract(only_utf8, invlist, &only_utf8);
21404     }
21405     if (not_utf8) {
21406         _invlist_subtract(not_utf8, invlist, &not_utf8);
21407     }
21408
21409     if (only_utf8_locale_invlist) {
21410
21411         /* Since this list is passed in, we have to make a copy before
21412          * modifying it */
21413         only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
21414
21415         _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
21416
21417         /* And, it can get really weird for us to try outputting an inverted
21418          * form of this list when it has things above the bitmap, so don't even
21419          * try */
21420         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
21421             inverting_allowed = FALSE;
21422         }
21423     }
21424
21425     /* Calculate what the output would be if we take the input as-is */
21426     as_is_display = put_charclass_bitmap_innards_common(invlist,
21427                                                     posixes,
21428                                                     only_utf8,
21429                                                     not_utf8,
21430                                                     only_utf8_locale,
21431                                                     invert);
21432
21433     /* If have to take the output as-is, just do that */
21434     if (! inverting_allowed) {
21435         if (as_is_display) {
21436             sv_catsv(sv, as_is_display);
21437             SvREFCNT_dec_NN(as_is_display);
21438         }
21439     }
21440     else { /* But otherwise, create the output again on the inverted input, and
21441               use whichever version is shorter */
21442
21443         int inverted_bias, as_is_bias;
21444
21445         /* We will apply our bias to whichever of the the results doesn't have
21446          * the '^' */
21447         if (invert) {
21448             invert = FALSE;
21449             as_is_bias = bias;
21450             inverted_bias = 0;
21451         }
21452         else {
21453             invert = TRUE;
21454             as_is_bias = 0;
21455             inverted_bias = bias;
21456         }
21457
21458         /* Now invert each of the lists that contribute to the output,
21459          * excluding from the result things outside the possible range */
21460
21461         /* For the unconditional inversion list, we have to add in all the
21462          * conditional code points, so that when inverted, they will be gone
21463          * from it */
21464         _invlist_union(only_utf8, invlist, &invlist);
21465         _invlist_union(not_utf8, invlist, &invlist);
21466         _invlist_union(only_utf8_locale, invlist, &invlist);
21467         _invlist_invert(invlist);
21468         _invlist_intersection(invlist, PL_InBitmap, &invlist);
21469
21470         if (only_utf8) {
21471             _invlist_invert(only_utf8);
21472             _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
21473         }
21474         else if (not_utf8) {
21475
21476             /* If a code point matches iff the target string is not in UTF-8,
21477              * then complementing the result has it not match iff not in UTF-8,
21478              * which is the same thing as matching iff it is UTF-8. */
21479             only_utf8 = not_utf8;
21480             not_utf8 = NULL;
21481         }
21482
21483         if (only_utf8_locale) {
21484             _invlist_invert(only_utf8_locale);
21485             _invlist_intersection(only_utf8_locale,
21486                                   PL_InBitmap,
21487                                   &only_utf8_locale);
21488         }
21489
21490         inverted_display = put_charclass_bitmap_innards_common(
21491                                             invlist,
21492                                             posixes,
21493                                             only_utf8,
21494                                             not_utf8,
21495                                             only_utf8_locale, invert);
21496
21497         /* Use the shortest representation, taking into account our bias
21498          * against showing it inverted */
21499         if (   inverted_display
21500             && (   ! as_is_display
21501                 || (  SvCUR(inverted_display) + inverted_bias
21502                     < SvCUR(as_is_display)    + as_is_bias)))
21503         {
21504             sv_catsv(sv, inverted_display);
21505         }
21506         else if (as_is_display) {
21507             sv_catsv(sv, as_is_display);
21508         }
21509
21510         SvREFCNT_dec(as_is_display);
21511         SvREFCNT_dec(inverted_display);
21512     }
21513
21514     SvREFCNT_dec_NN(invlist);
21515     SvREFCNT_dec(only_utf8);
21516     SvREFCNT_dec(not_utf8);
21517     SvREFCNT_dec(posixes);
21518     SvREFCNT_dec(only_utf8_locale);
21519
21520     return SvCUR(sv) > orig_sv_cur;
21521 }
21522
21523 #define CLEAR_OPTSTART                                                       \
21524     if (optstart) STMT_START {                                               \
21525         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_                                           \
21526                               " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
21527         optstart=NULL;                                                       \
21528     } STMT_END
21529
21530 #define DUMPUNTIL(b,e)                                                       \
21531                     CLEAR_OPTSTART;                                          \
21532                     node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
21533
21534 STATIC const regnode *
21535 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
21536             const regnode *last, const regnode *plast,
21537             SV* sv, I32 indent, U32 depth)
21538 {
21539     U8 op = PSEUDO;     /* Arbitrary non-END op. */
21540     const regnode *next;
21541     const regnode *optstart= NULL;
21542
21543     RXi_GET_DECL(r, ri);
21544     GET_RE_DEBUG_FLAGS_DECL;
21545
21546     PERL_ARGS_ASSERT_DUMPUNTIL;
21547
21548 #ifdef DEBUG_DUMPUNTIL
21549     Perl_re_printf( aTHX_  "--- %d : %d - %d - %d\n", indent, node-start,
21550         last ? last-start : 0, plast ? plast-start : 0);
21551 #endif
21552
21553     if (plast && plast < last)
21554         last= plast;
21555
21556     while (PL_regkind[op] != END && (!last || node < last)) {
21557         assert(node);
21558         /* While that wasn't END last time... */
21559         NODE_ALIGN(node);
21560         op = OP(node);
21561         if (op == CLOSE || op == SRCLOSE || op == WHILEM)
21562             indent--;
21563         next = regnext((regnode *)node);
21564
21565         /* Where, what. */
21566         if (OP(node) == OPTIMIZED) {
21567             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
21568                 optstart = node;
21569             else
21570                 goto after_print;
21571         } else
21572             CLEAR_OPTSTART;
21573
21574         regprop(r, sv, node, NULL, NULL);
21575         Perl_re_printf( aTHX_  "%4" IVdf ":%*s%s", (IV)(node - start),
21576                       (int)(2*indent + 1), "", SvPVX_const(sv));
21577
21578         if (OP(node) != OPTIMIZED) {
21579             if (next == NULL)           /* Next ptr. */
21580                 Perl_re_printf( aTHX_  " (0)");
21581             else if (PL_regkind[(U8)op] == BRANCH
21582                      && PL_regkind[OP(next)] != BRANCH )
21583                 Perl_re_printf( aTHX_  " (FAIL)");
21584             else
21585                 Perl_re_printf( aTHX_  " (%" IVdf ")", (IV)(next - start));
21586             Perl_re_printf( aTHX_ "\n");
21587         }
21588
21589       after_print:
21590         if (PL_regkind[(U8)op] == BRANCHJ) {
21591             assert(next);
21592             {
21593                 const regnode *nnode = (OP(next) == LONGJMP
21594                                        ? regnext((regnode *)next)
21595                                        : next);
21596                 if (last && nnode > last)
21597                     nnode = last;
21598                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
21599             }
21600         }
21601         else if (PL_regkind[(U8)op] == BRANCH) {
21602             assert(next);
21603             DUMPUNTIL(NEXTOPER(node), next);
21604         }
21605         else if ( PL_regkind[(U8)op]  == TRIE ) {
21606             const regnode *this_trie = node;
21607             const char op = OP(node);
21608             const U32 n = ARG(node);
21609             const reg_ac_data * const ac = op>=AHOCORASICK ?
21610                (reg_ac_data *)ri->data->data[n] :
21611                NULL;
21612             const reg_trie_data * const trie =
21613                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
21614 #ifdef DEBUGGING
21615             AV *const trie_words
21616                            = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
21617 #endif
21618             const regnode *nextbranch= NULL;
21619             I32 word_idx;
21620             SvPVCLEAR(sv);
21621             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
21622                 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
21623
21624                 Perl_re_indentf( aTHX_  "%s ",
21625                     indent+3,
21626                     elem_ptr
21627                     ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
21628                                 SvCUR(*elem_ptr), PL_dump_re_max_len,
21629                                 PL_colors[0], PL_colors[1],
21630                                 (SvUTF8(*elem_ptr)
21631                                  ? PERL_PV_ESCAPE_UNI
21632                                  : 0)
21633                                 | PERL_PV_PRETTY_ELLIPSES
21634                                 | PERL_PV_PRETTY_LTGT
21635                             )
21636                     : "???"
21637                 );
21638                 if (trie->jump) {
21639                     U16 dist= trie->jump[word_idx+1];
21640                     Perl_re_printf( aTHX_  "(%" UVuf ")\n",
21641                                (UV)((dist ? this_trie + dist : next) - start));
21642                     if (dist) {
21643                         if (!nextbranch)
21644                             nextbranch= this_trie + trie->jump[0];
21645                         DUMPUNTIL(this_trie + dist, nextbranch);
21646                     }
21647                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
21648                         nextbranch= regnext((regnode *)nextbranch);
21649                 } else {
21650                     Perl_re_printf( aTHX_  "\n");
21651                 }
21652             }
21653             if (last && next > last)
21654                 node= last;
21655             else
21656                 node= next;
21657         }
21658         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
21659             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
21660                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
21661         }
21662         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
21663             assert(next);
21664             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
21665         }
21666         else if ( op == PLUS || op == STAR) {
21667             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
21668         }
21669         else if (PL_regkind[(U8)op] == EXACT) {
21670             /* Literal string, where present. */
21671             node += NODE_SZ_STR(node) - 1;
21672             node = NEXTOPER(node);
21673         }
21674         else {
21675             node = NEXTOPER(node);
21676             node += regarglen[(U8)op];
21677         }
21678         if (op == CURLYX || op == OPEN || op == SROPEN)
21679             indent++;
21680     }
21681     CLEAR_OPTSTART;
21682 #ifdef DEBUG_DUMPUNTIL
21683     Perl_re_printf( aTHX_  "--- %d\n", (int)indent);
21684 #endif
21685     return node;
21686 }
21687
21688 #endif  /* DEBUGGING */
21689
21690 #ifndef PERL_IN_XSUB_RE
21691
21692 #include "uni_keywords.h"
21693
21694 void
21695 Perl_init_uniprops(pTHX)
21696 {
21697     dVAR;
21698
21699     PL_user_def_props = newHV();
21700
21701 #ifdef USE_ITHREADS
21702
21703     HvSHAREKEYS_off(PL_user_def_props);
21704     PL_user_def_props_aTHX = aTHX;
21705
21706 #endif
21707
21708     /* Set up the inversion list global variables */
21709
21710     PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
21711     PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
21712     PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
21713     PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
21714     PL_XPosix_ptrs[_CC_CASED] =  _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
21715     PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
21716     PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
21717     PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
21718     PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
21719     PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
21720     PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
21721     PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
21722     PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
21723     PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
21724     PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
21725     PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
21726
21727     PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
21728     PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
21729     PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
21730     PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
21731     PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
21732     PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
21733     PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
21734     PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
21735     PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
21736     PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
21737     PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
21738     PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
21739     PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
21740     PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
21741     PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
21742     PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
21743
21744     PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
21745     PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
21746     PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
21747     PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
21748     PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
21749
21750     PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
21751     PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
21752     PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
21753
21754     PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
21755
21756     PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
21757     PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
21758
21759     PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
21760     PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
21761
21762     PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
21763     PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
21764                                             UNI__PERL_FOLDS_TO_MULTI_CHAR]);
21765     PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
21766                                             UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
21767     PL_NonFinalFold = _new_invlist_C_array(uni_prop_ptrs[
21768                                             UNI__PERL_NON_FINAL_FOLDS]);
21769
21770     PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
21771     PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
21772     PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
21773     PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
21774     PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
21775     PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
21776     PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
21777     PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
21778
21779 #ifdef UNI_XIDC
21780     /* The below are used only by deprecated functions.  They could be removed */
21781     PL_utf8_xidcont  = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
21782     PL_utf8_idcont   = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
21783     PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
21784 #endif
21785 }
21786
21787 #if 0
21788
21789 This code was mainly added for backcompat to give a warning for non-portable
21790 code points in user-defined properties.  But experiments showed that the
21791 warning in earlier perls were only omitted on overflow, which should be an
21792 error, so there really isnt a backcompat issue, and actually adding the
21793 warning when none was present before might cause breakage, for little gain.  So
21794 khw left this code in, but not enabled.  Tests were never added.
21795
21796 embed.fnc entry:
21797 Ei      |const char *|get_extended_utf8_msg|const UV cp
21798
21799 PERL_STATIC_INLINE const char *
21800 S_get_extended_utf8_msg(pTHX_ const UV cp)
21801 {
21802     U8 dummy[UTF8_MAXBYTES + 1];
21803     HV *msgs;
21804     SV **msg;
21805
21806     uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
21807                              &msgs);
21808
21809     msg = hv_fetchs(msgs, "text", 0);
21810     assert(msg);
21811
21812     (void) sv_2mortal((SV *) msgs);
21813
21814     return SvPVX(*msg);
21815 }
21816
21817 #endif
21818
21819 SV *
21820 Perl_handle_user_defined_property(pTHX_
21821
21822     /* Parses the contents of a user-defined property definition; returning the
21823      * expanded definition if possible.  If so, the return is an inversion
21824      * list.
21825      *
21826      * If there are subroutines that are part of the expansion and which aren't
21827      * known at the time of the call to this function, this returns what
21828      * parse_uniprop_string() returned for the first one encountered.
21829      *
21830      * If an error was found, NULL is returned, and 'msg' gets a suitable
21831      * message appended to it.  (Appending allows the back trace of how we got
21832      * to the faulty definition to be displayed through nested calls of
21833      * user-defined subs.)
21834      *
21835      * The caller IS responsible for freeing any returned SV.
21836      *
21837      * The syntax of the contents is pretty much described in perlunicode.pod,
21838      * but we also allow comments on each line */
21839
21840     const char * name,          /* Name of property */
21841     const STRLEN name_len,      /* The name's length in bytes */
21842     const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
21843     const bool to_fold,         /* ? Is this under /i */
21844     const bool runtime,         /* ? Are we in compile- or run-time */
21845     SV* contents,               /* The property's definition */
21846     bool *user_defined_ptr,     /* This will be set TRUE as we wouldn't be
21847                                    getting called unless this is thought to be
21848                                    a user-defined property */
21849     SV * msg,                   /* Any error or warning msg(s) are appended to
21850                                    this */
21851     const STRLEN level)         /* Recursion level of this call */
21852 {
21853     STRLEN len;
21854     const char * string         = SvPV_const(contents, len);
21855     const char * const e        = string + len;
21856     const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
21857     const STRLEN msgs_length_on_entry = SvCUR(msg);
21858
21859     const char * s0 = string;   /* Points to first byte in the current line
21860                                    being parsed in 'string' */
21861     const char overflow_msg[] = "Code point too large in \"";
21862     SV* running_definition = NULL;
21863
21864     PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
21865
21866     *user_defined_ptr = TRUE;
21867
21868     /* Look at each line */
21869     while (s0 < e) {
21870         const char * s;     /* Current byte */
21871         char op = '+';      /* Default operation is 'union' */
21872         IV   min = 0;       /* range begin code point */
21873         IV   max = -1;      /* and range end */
21874         SV* this_definition;
21875
21876         /* Skip comment lines */
21877         if (*s0 == '#') {
21878             s0 = strchr(s0, '\n');
21879             if (s0 == NULL) {
21880                 break;
21881             }
21882             s0++;
21883             continue;
21884         }
21885
21886         /* For backcompat, allow an empty first line */
21887         if (*s0 == '\n') {
21888             s0++;
21889             continue;
21890         }
21891
21892         /* First character in the line may optionally be the operation */
21893         if (   *s0 == '+'
21894             || *s0 == '!'
21895             || *s0 == '-'
21896             || *s0 == '&')
21897         {
21898             op = *s0++;
21899         }
21900
21901         /* If the line is one or two hex digits separated by blank space, its
21902          * a range; otherwise it is either another user-defined property or an
21903          * error */
21904
21905         s = s0;
21906
21907         if (! isXDIGIT(*s)) {
21908             goto check_if_property;
21909         }
21910
21911         do { /* Each new hex digit will add 4 bits. */
21912             if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
21913                 s = strchr(s, '\n');
21914                 if (s == NULL) {
21915                     s = e;
21916                 }
21917                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
21918                 sv_catpv(msg, overflow_msg);
21919                 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
21920                                      UTF8fARG(is_contents_utf8, s - s0, s0));
21921                 sv_catpvs(msg, "\"");
21922                 goto return_msg;
21923             }
21924
21925             /* Accumulate this digit into the value */
21926             min = (min << 4) + READ_XDIGIT(s);
21927         } while (isXDIGIT(*s));
21928
21929         while (isBLANK(*s)) { s++; }
21930
21931         /* We allow comments at the end of the line */
21932         if (*s == '#') {
21933             s = strchr(s, '\n');
21934             if (s == NULL) {
21935                 s = e;
21936             }
21937             s++;
21938         }
21939         else if (s < e && *s != '\n') {
21940             if (! isXDIGIT(*s)) {
21941                 goto check_if_property;
21942             }
21943
21944             /* Look for the high point of the range */
21945             max = 0;
21946             do {
21947                 if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
21948                     s = strchr(s, '\n');
21949                     if (s == NULL) {
21950                         s = e;
21951                     }
21952                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
21953                     sv_catpv(msg, overflow_msg);
21954                     Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
21955                                       UTF8fARG(is_contents_utf8, s - s0, s0));
21956                     sv_catpvs(msg, "\"");
21957                     goto return_msg;
21958                 }
21959
21960                 max = (max << 4) + READ_XDIGIT(s);
21961             } while (isXDIGIT(*s));
21962
21963             while (isBLANK(*s)) { s++; }
21964
21965             if (*s == '#') {
21966                 s = strchr(s, '\n');
21967                 if (s == NULL) {
21968                     s = e;
21969                 }
21970             }
21971             else if (s < e && *s != '\n') {
21972                 goto check_if_property;
21973             }
21974         }
21975
21976         if (max == -1) {    /* The line only had one entry */
21977             max = min;
21978         }
21979         else if (max < min) {
21980             if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
21981             sv_catpvs(msg, "Illegal range in \"");
21982             Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
21983                                 UTF8fARG(is_contents_utf8, s - s0, s0));
21984             sv_catpvs(msg, "\"");
21985             goto return_msg;
21986         }
21987
21988 #if 0   /* See explanation at definition above of get_extended_utf8_msg() */
21989
21990         if (   UNICODE_IS_PERL_EXTENDED(min)
21991             || UNICODE_IS_PERL_EXTENDED(max))
21992         {
21993             if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
21994
21995             /* If both code points are non-portable, warn only on the lower
21996              * one. */
21997             sv_catpv(msg, get_extended_utf8_msg(
21998                                             (UNICODE_IS_PERL_EXTENDED(min))
21999                                             ? min : max));
22000             sv_catpvs(msg, " in \"");
22001             Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22002                                  UTF8fARG(is_contents_utf8, s - s0, s0));
22003             sv_catpvs(msg, "\"");
22004         }
22005
22006 #endif
22007
22008         /* Here, this line contains a legal range */
22009         this_definition = sv_2mortal(_new_invlist(2));
22010         this_definition = _add_range_to_invlist(this_definition, min, max);
22011         goto calculate;
22012
22013       check_if_property:
22014
22015         /* Here it isn't a legal range line.  See if it is a legal property
22016          * line.  First find the end of the meat of the line */
22017         s = strpbrk(s, "#\n");
22018         if (s == NULL) {
22019             s = e;
22020         }
22021
22022         /* Ignore trailing blanks in keeping with the requirements of
22023          * parse_uniprop_string() */
22024         s--;
22025         while (s > s0 && isBLANK_A(*s)) {
22026             s--;
22027         }
22028         s++;
22029
22030         this_definition = parse_uniprop_string(s0, s - s0,
22031                                                is_utf8, to_fold, runtime,
22032                                                user_defined_ptr, msg,
22033                                                (name_len == 0)
22034                                                 ? level /* Don't increase level
22035                                                            if input is empty */
22036                                                 : level + 1
22037                                               );
22038         if (this_definition == NULL) {
22039             goto return_msg;    /* 'msg' should have had the reason appended to
22040                                    it by the above call */
22041         }
22042
22043         if (! is_invlist(this_definition)) {    /* Unknown at this time */
22044             return newSVsv(this_definition);
22045         }
22046
22047         if (*s != '\n') {
22048             s = strchr(s, '\n');
22049             if (s == NULL) {
22050                 s = e;
22051             }
22052         }
22053
22054       calculate:
22055
22056         switch (op) {
22057             case '+':
22058                 _invlist_union(running_definition, this_definition,
22059                                                         &running_definition);
22060                 break;
22061             case '-':
22062                 _invlist_subtract(running_definition, this_definition,
22063                                                         &running_definition);
22064                 break;
22065             case '&':
22066                 _invlist_intersection(running_definition, this_definition,
22067                                                         &running_definition);
22068                 break;
22069             case '!':
22070                 _invlist_union_complement_2nd(running_definition,
22071                                         this_definition, &running_definition);
22072                 break;
22073             default:
22074                 Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
22075                                  __FILE__, __LINE__, op);
22076                 break;
22077         }
22078
22079         /* Position past the '\n' */
22080         s0 = s + 1;
22081     }   /* End of loop through the lines of 'contents' */
22082
22083     /* Here, we processed all the lines in 'contents' without error.  If we
22084      * didn't add any warnings, simply return success */
22085     if (msgs_length_on_entry == SvCUR(msg)) {
22086
22087         /* If the expansion was empty, the answer isn't nothing: its an empty
22088          * inversion list */
22089         if (running_definition == NULL) {
22090             running_definition = _new_invlist(1);
22091         }
22092
22093         return running_definition;
22094     }
22095
22096     /* Otherwise, add some explanatory text, but we will return success */
22097
22098   return_msg:
22099
22100     if (name_len > 0) {
22101         sv_catpvs(msg, " in expansion of ");
22102         Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
22103     }
22104
22105     return running_definition;
22106 }
22107
22108 /* As explained below, certain operations need to take place in the first
22109  * thread created.  These macros switch contexts */
22110 #ifdef USE_ITHREADS
22111 #  define DECLARATION_FOR_GLOBAL_CONTEXT                                    \
22112                                         PerlInterpreter * save_aTHX = aTHX;
22113 #  define SWITCH_TO_GLOBAL_CONTEXT                                          \
22114                            PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
22115 #  define RESTORE_CONTEXT  PERL_SET_CONTEXT((aTHX = save_aTHX));
22116 #  define CUR_CONTEXT      aTHX
22117 #  define ORIGINAL_CONTEXT save_aTHX
22118 #else
22119 #  define DECLARATION_FOR_GLOBAL_CONTEXT
22120 #  define SWITCH_TO_GLOBAL_CONTEXT          NOOP
22121 #  define RESTORE_CONTEXT                   NOOP
22122 #  define CUR_CONTEXT                       NULL
22123 #  define ORIGINAL_CONTEXT                  NULL
22124 #endif
22125
22126 STATIC void
22127 S_delete_recursion_entry(pTHX_ void *key)
22128 {
22129     /* Deletes the entry used to detect recursion when expanding user-defined
22130      * properties.  This is a function so it can be set up to be called even if
22131      * the program unexpectedly quits */
22132
22133     dVAR;
22134     SV ** current_entry;
22135     const STRLEN key_len = strlen((const char *) key);
22136     DECLARATION_FOR_GLOBAL_CONTEXT;
22137
22138     SWITCH_TO_GLOBAL_CONTEXT;
22139
22140     /* If the entry is one of these types, it is a permanent entry, and not the
22141      * one used to detect recursions.  This function should delete only the
22142      * recursion entry */
22143     current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
22144     if (     current_entry
22145         && ! is_invlist(*current_entry)
22146         && ! SvPOK(*current_entry))
22147     {
22148         (void) hv_delete(PL_user_def_props, (const char *) key, key_len,
22149                                                                     G_DISCARD);
22150     }
22151
22152     RESTORE_CONTEXT;
22153 }
22154
22155 SV *
22156 Perl_parse_uniprop_string(pTHX_
22157
22158     /* Parse the interior of a \p{}, \P{}.  Returns its definition if knowable
22159      * now.  If so, the return is an inversion list.
22160      *
22161      * If the property is user-defined, it is a subroutine, which in turn
22162      * may call other subroutines.  This function will call the whole nest of
22163      * them to get the definition they return; if some aren't known at the time
22164      * of the call to this function, the fully qualified name of the highest
22165      * level sub is returned.  It is an error to call this function at runtime
22166      * without every sub defined.
22167      *
22168      * If an error was found, NULL is returned, and 'msg' gets a suitable
22169      * message appended to it.  (Appending allows the back trace of how we got
22170      * to the faulty definition to be displayed through nested calls of
22171      * user-defined subs.)
22172      *
22173      * The caller should NOT try to free any returned inversion list.
22174      *
22175      * Other parameters will be set on return as described below */
22176
22177     const char * const name,    /* The first non-blank in the \p{}, \P{} */
22178     const Size_t name_len,      /* Its length in bytes, not including any
22179                                    trailing space */
22180     const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
22181     const bool to_fold,         /* ? Is this under /i */
22182     const bool runtime,         /* TRUE if this is being called at run time */
22183     bool *user_defined_ptr,     /* Upon return from this function it will be
22184                                    set to TRUE if any component is a
22185                                    user-defined property */
22186     SV * msg,                   /* Any error or warning msg(s) are appended to
22187                                    this */
22188    const STRLEN level)          /* Recursion level of this call */
22189 {
22190     dVAR;
22191     char* lookup_name;          /* normalized name for lookup in our tables */
22192     unsigned lookup_len;        /* Its length */
22193     bool stricter = FALSE;      /* Some properties have stricter name
22194                                    normalization rules, which we decide upon
22195                                    based on parsing */
22196
22197     /* nv= or numeric_value=, or possibly one of the cjk numeric properties
22198      * (though it requires extra effort to download them from Unicode and
22199      * compile perl to know about them) */
22200     bool is_nv_type = FALSE;
22201
22202     unsigned int i, j = 0;
22203     int equals_pos = -1;    /* Where the '=' is found, or negative if none */
22204     int slash_pos  = -1;    /* Where the '/' is found, or negative if none */
22205     int table_index = 0;    /* The entry number for this property in the table
22206                                of all Unicode property names */
22207     bool starts_with_In_or_Is = FALSE;  /* ? Does the name start with 'In' or
22208                                              'Is' */
22209     Size_t lookup_offset = 0;   /* Used to ignore the first few characters of
22210                                    the normalized name in certain situations */
22211     Size_t non_pkg_begin = 0;   /* Offset of first byte in 'name' that isn't
22212                                    part of a package name */
22213     bool could_be_user_defined = TRUE;  /* ? Could this be a user-defined
22214                                              property rather than a Unicode
22215                                              one. */
22216     SV * prop_definition = NULL;  /* The returned definition of 'name' or NULL
22217                                      if an error.  If it is an inversion list,
22218                                      it is the definition.  Otherwise it is a
22219                                      string containing the fully qualified sub
22220                                      name of 'name' */
22221     bool invert_return = FALSE; /* ? Do we need to complement the result before
22222                                      returning it */
22223
22224     PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
22225
22226     /* The input will be normalized into 'lookup_name' */
22227     Newx(lookup_name, name_len, char);
22228     SAVEFREEPV(lookup_name);
22229
22230     /* Parse the input. */
22231     for (i = 0; i < name_len; i++) {
22232         char cur = name[i];
22233
22234         /* Most of the characters in the input will be of this ilk, being parts
22235          * of a name */
22236         if (isIDCONT_A(cur)) {
22237
22238             /* Case differences are ignored.  Our lookup routine assumes
22239              * everything is lowercase, so normalize to that */
22240             if (isUPPER_A(cur)) {
22241                 lookup_name[j++] = toLOWER_A(cur);
22242                 continue;
22243             }
22244
22245             if (cur == '_') { /* Don't include these in the normalized name */
22246                 continue;
22247             }
22248
22249             lookup_name[j++] = cur;
22250
22251             /* The first character in a user-defined name must be of this type.
22252              * */
22253             if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
22254                 could_be_user_defined = FALSE;
22255             }
22256
22257             continue;
22258         }
22259
22260         /* Here, the character is not something typically in a name,  But these
22261          * two types of characters (and the '_' above) can be freely ignored in
22262          * most situations.  Later it may turn out we shouldn't have ignored
22263          * them, and we have to reparse, but we don't have enough information
22264          * yet to make that decision */
22265         if (cur == '-' || isSPACE_A(cur)) {
22266             could_be_user_defined = FALSE;
22267             continue;
22268         }
22269
22270         /* An equals sign or single colon mark the end of the first part of
22271          * the property name */
22272         if (    cur == '='
22273             || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
22274         {
22275             lookup_name[j++] = '='; /* Treat the colon as an '=' */
22276             equals_pos = j; /* Note where it occurred in the input */
22277             could_be_user_defined = FALSE;
22278             break;
22279         }
22280
22281         /* Otherwise, this character is part of the name. */
22282         lookup_name[j++] = cur;
22283
22284         /* Here it isn't a single colon, so if it is a colon, it must be a
22285          * double colon */
22286         if (cur == ':') {
22287
22288             /* A double colon should be a package qualifier.  We note its
22289              * position and continue.  Note that one could have
22290              *      pkg1::pkg2::...::foo
22291              * so that the position at the end of the loop will be just after
22292              * the final qualifier */
22293
22294             i++;
22295             non_pkg_begin = i + 1;
22296             lookup_name[j++] = ':';
22297         }
22298         else { /* Only word chars (and '::') can be in a user-defined name */
22299             could_be_user_defined = FALSE;
22300         }
22301     } /* End of parsing through the lhs of the property name (or all of it if
22302          no rhs) */
22303
22304 #define STRLENs(s)  (sizeof("" s "") - 1)
22305
22306     /* If there is a single package name 'utf8::', it is ambiguous.  It could
22307      * be for a user-defined property, or it could be a Unicode property, as
22308      * all of them are considered to be for that package.  For the purposes of
22309      * parsing the rest of the property, strip it off */
22310     if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
22311         lookup_name +=  STRLENs("utf8::");
22312         j -=  STRLENs("utf8::");
22313         equals_pos -=  STRLENs("utf8::");
22314     }
22315
22316     /* Here, we are either done with the whole property name, if it was simple;
22317      * or are positioned just after the '=' if it is compound. */
22318
22319     if (equals_pos >= 0) {
22320         assert(! stricter); /* We shouldn't have set this yet */
22321
22322         /* Space immediately after the '=' is ignored */
22323         i++;
22324         for (; i < name_len; i++) {
22325             if (! isSPACE_A(name[i])) {
22326                 break;
22327             }
22328         }
22329
22330         /* Certain properties whose values are numeric need special handling.
22331          * They may optionally be prefixed by 'is'.  Ignore that prefix for the
22332          * purposes of checking if this is one of those properties */
22333         if (memBEGINPs(lookup_name, name_len, "is")) {
22334             lookup_offset = 2;
22335         }
22336
22337         /* Then check if it is one of these specially-handled properties.  The
22338          * possibilities are hard-coded because easier this way, and the list
22339          * is unlikely to change.
22340          *
22341          * All numeric value type properties are of this ilk, and are also
22342          * special in a different way later on.  So find those first.  There
22343          * are several numeric value type properties in the Unihan DB (which is
22344          * unlikely to be compiled with perl, but we handle it here in case it
22345          * does get compiled).  They all end with 'numeric'.  The interiors
22346          * aren't checked for the precise property.  This would stop working if
22347          * a cjk property were to be created that ended with 'numeric' and
22348          * wasn't a numeric type */
22349         is_nv_type = memEQs(lookup_name + lookup_offset,
22350                        j - 1 - lookup_offset, "numericvalue")
22351                   || memEQs(lookup_name + lookup_offset,
22352                       j - 1 - lookup_offset, "nv")
22353                   || (   memENDPs(lookup_name + lookup_offset,
22354                             j - 1 - lookup_offset, "numeric")
22355                       && (   memBEGINPs(lookup_name + lookup_offset,
22356                                       j - 1 - lookup_offset, "cjk")
22357                           || memBEGINPs(lookup_name + lookup_offset,
22358                                       j - 1 - lookup_offset, "k")));
22359         if (   is_nv_type
22360             || memEQs(lookup_name + lookup_offset,
22361                       j - 1 - lookup_offset, "canonicalcombiningclass")
22362             || memEQs(lookup_name + lookup_offset,
22363                       j - 1 - lookup_offset, "ccc")
22364             || memEQs(lookup_name + lookup_offset,
22365                       j - 1 - lookup_offset, "age")
22366             || memEQs(lookup_name + lookup_offset,
22367                       j - 1 - lookup_offset, "in")
22368             || memEQs(lookup_name + lookup_offset,
22369                       j - 1 - lookup_offset, "presentin"))
22370         {
22371             unsigned int k;
22372
22373             /* Since the stuff after the '=' is a number, we can't throw away
22374              * '-' willy-nilly, as those could be a minus sign.  Other stricter
22375              * rules also apply.  However, these properties all can have the
22376              * rhs not be a number, in which case they contain at least one
22377              * alphabetic.  In those cases, the stricter rules don't apply.
22378              * But the numeric type properties can have the alphas [Ee] to
22379              * signify an exponent, and it is still a number with stricter
22380              * rules.  So look for an alpha that signifies not-strict */
22381             stricter = TRUE;
22382             for (k = i; k < name_len; k++) {
22383                 if (   isALPHA_A(name[k])
22384                     && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
22385                 {
22386                     stricter = FALSE;
22387                     break;
22388                 }
22389             }
22390         }
22391
22392         if (stricter) {
22393
22394             /* A number may have a leading '+' or '-'.  The latter is retained
22395              * */
22396             if (name[i] == '+') {
22397                 i++;
22398             }
22399             else if (name[i] == '-') {
22400                 lookup_name[j++] = '-';
22401                 i++;
22402             }
22403
22404             /* Skip leading zeros including single underscores separating the
22405              * zeros, or between the final leading zero and the first other
22406              * digit */
22407             for (; i < name_len - 1; i++) {
22408                 if (    name[i] != '0'
22409                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
22410                 {
22411                     break;
22412                 }
22413             }
22414         }
22415     }
22416     else {  /* No '=' */
22417
22418        /* Only a few properties without an '=' should be parsed with stricter
22419         * rules.  The list is unlikely to change. */
22420         if (   memBEGINPs(lookup_name, j, "perl")
22421             && memNEs(lookup_name + 4, j - 4, "space")
22422             && memNEs(lookup_name + 4, j - 4, "word"))
22423         {
22424             stricter = TRUE;
22425
22426             /* We set the inputs back to 0 and the code below will reparse,
22427              * using strict */
22428             i = j = 0;
22429         }
22430     }
22431
22432     /* Here, we have either finished the property, or are positioned to parse
22433      * the remainder, and we know if stricter rules apply.  Finish out, if not
22434      * already done */
22435     for (; i < name_len; i++) {
22436         char cur = name[i];
22437
22438         /* In all instances, case differences are ignored, and we normalize to
22439          * lowercase */
22440         if (isUPPER_A(cur)) {
22441             lookup_name[j++] = toLOWER(cur);
22442             continue;
22443         }
22444
22445         /* An underscore is skipped, but not under strict rules unless it
22446          * separates two digits */
22447         if (cur == '_') {
22448             if (    stricter
22449                 && (     i == 0 || (int) i == equals_pos || i == name_len- 1
22450                     || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
22451             {
22452                 lookup_name[j++] = '_';
22453             }
22454             continue;
22455         }
22456
22457         /* Hyphens are skipped except under strict */
22458         if (cur == '-' && ! stricter) {
22459             continue;
22460         }
22461
22462         /* XXX Bug in documentation.  It says white space skipped adjacent to
22463          * non-word char.  Maybe we should, but shouldn't skip it next to a dot
22464          * in a number */
22465         if (isSPACE_A(cur) && ! stricter) {
22466             continue;
22467         }
22468
22469         lookup_name[j++] = cur;
22470
22471         /* Unless this is a non-trailing slash, we are done with it */
22472         if (i >= name_len - 1 || cur != '/') {
22473             continue;
22474         }
22475
22476         slash_pos = j;
22477
22478         /* A slash in the 'numeric value' property indicates that what follows
22479          * is a denominator.  It can have a leading '+' and '0's that should be
22480          * skipped.  But we have never allowed a negative denominator, so treat
22481          * a minus like every other character.  (No need to rule out a second
22482          * '/', as that won't match anything anyway */
22483         if (is_nv_type) {
22484             i++;
22485             if (i < name_len && name[i] == '+') {
22486                 i++;
22487             }
22488
22489             /* Skip leading zeros including underscores separating digits */
22490             for (; i < name_len - 1; i++) {
22491                 if (   name[i] != '0'
22492                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
22493                 {
22494                     break;
22495                 }
22496             }
22497
22498             /* Store the first real character in the denominator */
22499             lookup_name[j++] = name[i];
22500         }
22501     }
22502
22503     /* Here are completely done parsing the input 'name', and 'lookup_name'
22504      * contains a copy, normalized.
22505      *
22506      * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
22507      * different from without the underscores.  */
22508     if (  (   UNLIKELY(memEQs(lookup_name, j, "l"))
22509            || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
22510         && UNLIKELY(name[name_len-1] == '_'))
22511     {
22512         lookup_name[j++] = '&';
22513     }
22514
22515     /* If the original input began with 'In' or 'Is', it could be a subroutine
22516      * call to a user-defined property instead of a Unicode property name. */
22517     if (    non_pkg_begin + name_len > 2
22518         &&  name[non_pkg_begin+0] == 'I'
22519         && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
22520     {
22521         starts_with_In_or_Is = TRUE;
22522     }
22523     else {
22524         could_be_user_defined = FALSE;
22525     }
22526
22527     if (could_be_user_defined) {
22528         CV* user_sub;
22529
22530         /* Here, the name could be for a user defined property, which are
22531          * implemented as subs. */
22532         user_sub = get_cvn_flags(name, name_len, 0);
22533         if (user_sub) {
22534
22535             /* Here, there is a sub by the correct name.  Normally we call it
22536              * to get the property definition */
22537             dSP;
22538             SV * user_sub_sv = MUTABLE_SV(user_sub);
22539             SV * error;     /* Any error returned by calling 'user_sub' */
22540             SV * fq_name;   /* Fully qualified property name */
22541             SV * placeholder;
22542             char to_fold_string[] = "0:";   /* The 0 gets overwritten with the
22543                                                actual value */
22544             SV ** saved_user_prop_ptr;      /* Hash entry for this property */
22545
22546             /* How many times to retry when another thread is in the middle of
22547              * expanding the same definition we want */
22548             PERL_INT_FAST8_T retry_countdown = 10;
22549
22550             DECLARATION_FOR_GLOBAL_CONTEXT;
22551
22552             /* If we get here, we know this property is user-defined */
22553             *user_defined_ptr = TRUE;
22554
22555             /* We refuse to call a tainted subroutine; returning an error
22556              * instead */
22557             if (TAINT_get) {
22558                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22559                 sv_catpvs(msg, "Insecure user-defined property");
22560                 goto append_name_to_msg;
22561             }
22562
22563             /* In principal, we only call each subroutine property definition
22564              * once during the life of the program.  This guarantees that the
22565              * property definition never changes.  The results of the single
22566              * sub call are stored in a hash, which is used instead for future
22567              * references to this property.  The property definition is thus
22568              * immutable.  But, to allow the user to have a /i-dependent
22569              * definition, we call the sub once for non-/i, and once for /i,
22570              * should the need arise, passing the /i status as a parameter.
22571              *
22572              * We start by constructing the hash key name, consisting of the
22573              * fully qualified subroutine name */
22574             fq_name = sv_2mortal(newSV(10));    /* 10 is just a guess */
22575             (void) cv_name(user_sub, fq_name, 0);
22576
22577             /* But precede the sub name in the key with the /i status, so that
22578              * there is a key for /i and a different key for non-/i */
22579             to_fold_string[0] = to_fold + '0';
22580             sv_insert(fq_name, 0, 0, to_fold_string, 2);
22581
22582             /* We only call the sub once throughout the life of the program
22583              * (with the /i, non-/i exception noted above).  That means the
22584              * hash must be global and accessible to all threads.  It is
22585              * created at program start-up, before any threads are created, so
22586              * is accessible to all children.  But this creates some
22587              * complications.
22588              *
22589              * 1) The keys can't be shared, or else problems arise; sharing is
22590              *    turned off at hash creation time
22591              * 2) All SVs in it are there for the remainder of the life of the
22592              *    program, and must be created in the same interpreter context
22593              *    as the hash, or else they will be freed from the wrong pool
22594              *    at global destruction time.  This is handled by switching to
22595              *    the hash's context to create each SV going into it, and then
22596              *    immediately switching back
22597              * 3) All accesses to the hash must be controlled by a mutex, to
22598              *    prevent two threads from getting an unstable state should
22599              *    they simultaneously be accessing it.  The code below is
22600              *    crafted so that the mutex is locked whenever there is an
22601              *    access and unlocked only when the next stable state is
22602              *    achieved.
22603              *
22604              * The hash stores either the definition of the property if it was
22605              * valid, or, if invalid, the error message that was raised.  We
22606              * use the type of SV to distinguish.
22607              *
22608              * There's also the need to guard against the definition expansion
22609              * from infinitely recursing.  This is handled by storing the aTHX
22610              * of the expanding thread during the expansion.  Again the SV type
22611              * is used to distinguish this from the other two cases.  If we
22612              * come to here and the hash entry for this property is our aTHX,
22613              * it means we have recursed, and the code assumes that we would
22614              * infinitely recurse, so instead stops and raises an error.
22615              * (Any recursion has always been treated as infinite recursion in
22616              * this feature.)
22617              *
22618              * If instead, the entry is for a different aTHX, it means that
22619              * that thread has gotten here first, and hasn't finished expanding
22620              * the definition yet.  We just have to wait until it is done.  We
22621              * sleep and retry a few times, returning an error if the other
22622              * thread doesn't complete. */
22623
22624           re_fetch:
22625             USER_PROP_MUTEX_LOCK;
22626
22627             /* If we have an entry for this key, the subroutine has already
22628              * been called once with this /i status. */
22629             saved_user_prop_ptr = hv_fetch(PL_user_def_props,
22630                                            SvPVX(fq_name), SvCUR(fq_name), 0);
22631             if (saved_user_prop_ptr) {
22632
22633                 /* If the saved result is an inversion list, it is the valid
22634                  * definition of this property */
22635                 if (is_invlist(*saved_user_prop_ptr)) {
22636                     prop_definition = *saved_user_prop_ptr;
22637
22638                     /* The SV in the hash won't be removed until global
22639                      * destruction, so it is stable and we can unlock */
22640                     USER_PROP_MUTEX_UNLOCK;
22641
22642                     /* The caller shouldn't try to free this SV */
22643                     return prop_definition;
22644                 }
22645
22646                 /* Otherwise, if it is a string, it is the error message
22647                  * that was returned when we first tried to evaluate this
22648                  * property.  Fail, and append the message */
22649                 if (SvPOK(*saved_user_prop_ptr)) {
22650                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22651                     sv_catsv(msg, *saved_user_prop_ptr);
22652
22653                     /* The SV in the hash won't be removed until global
22654                      * destruction, so it is stable and we can unlock */
22655                     USER_PROP_MUTEX_UNLOCK;
22656
22657                     return NULL;
22658                 }
22659
22660                 assert(SvIOK(*saved_user_prop_ptr));
22661
22662                 /* Here, we have an unstable entry in the hash.  Either another
22663                  * thread is in the middle of expanding the property's
22664                  * definition, or we are ourselves recursing.  We use the aTHX
22665                  * in it to distinguish */
22666                 if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
22667
22668                     /* Here, it's another thread doing the expanding.  We've
22669                      * looked as much as we are going to at the contents of the
22670                      * hash entry.  It's safe to unlock. */
22671                     USER_PROP_MUTEX_UNLOCK;
22672
22673                     /* Retry a few times */
22674                     if (retry_countdown-- > 0) {
22675                         PerlProc_sleep(1);
22676                         goto re_fetch;
22677                     }
22678
22679                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22680                     sv_catpvs(msg, "Timeout waiting for another thread to "
22681                                    "define");
22682                     goto append_name_to_msg;
22683                 }
22684
22685                 /* Here, we are recursing; don't dig any deeper */
22686                 USER_PROP_MUTEX_UNLOCK;
22687
22688                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22689                 sv_catpvs(msg,
22690                           "Infinite recursion in user-defined property");
22691                 goto append_name_to_msg;
22692             }
22693
22694             /* Here, this thread has exclusive control, and there is no entry
22695              * for this property in the hash.  So we have the go ahead to
22696              * expand the definition ourselves. */
22697
22698             ENTER;
22699
22700             /* Create a temporary placeholder in the hash to detect recursion
22701              * */
22702             SWITCH_TO_GLOBAL_CONTEXT;
22703             placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
22704             (void) hv_store_ent(PL_user_def_props, fq_name, placeholder, 0);
22705             RESTORE_CONTEXT;
22706
22707             /* Now that we have a placeholder, we can let other threads
22708              * continue */
22709             USER_PROP_MUTEX_UNLOCK;
22710
22711             /* Make sure the placeholder always gets destroyed */
22712             SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(fq_name));
22713
22714             PUSHMARK(SP);
22715             SAVETMPS;
22716
22717             /* Call the user's function, with the /i status as a parameter.
22718              * Note that we have gone to a lot of trouble to keep this call
22719              * from being within the locked mutex region. */
22720             XPUSHs(boolSV(to_fold));
22721             PUTBACK;
22722
22723             (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
22724
22725             SPAGAIN;
22726
22727             error = ERRSV;
22728             if (SvTRUE(error)) {
22729                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22730                 sv_catpvs(msg, "Error \"");
22731                 sv_catsv(msg, error);
22732                 sv_catpvs(msg, "\"");
22733                 if (name_len > 0) {
22734                     sv_catpvs(msg, " in expansion of ");
22735                     Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
22736                                                                   name_len,
22737                                                                   name));
22738                 }
22739
22740                 (void) POPs;
22741                 prop_definition = NULL;
22742             }
22743             else {  /* G_SCALAR guarantees a single return value */
22744
22745                 /* The contents is supposed to be the expansion of the property
22746                  * definition.  Call a function to check for valid syntax and
22747                  * handle it */
22748                 prop_definition = handle_user_defined_property(name, name_len,
22749                                                     is_utf8, to_fold, runtime,
22750                                                     POPs, user_defined_ptr,
22751                                                     msg,
22752                                                     level);
22753             }
22754
22755             /* Here, we have the results of the expansion.  Replace the
22756              * placeholder with them.  We need exclusive access to the hash,
22757              * and we can't let anyone else in, between when we delete the
22758              * placeholder and add the permanent entry */
22759             USER_PROP_MUTEX_LOCK;
22760
22761             S_delete_recursion_entry(aTHX_ SvPVX(fq_name));
22762
22763             if (! prop_definition || is_invlist(prop_definition)) {
22764
22765                 /* If we got success we use the inversion list defining the
22766                  * property; otherwise use the error message */
22767                 SWITCH_TO_GLOBAL_CONTEXT;
22768                 (void) hv_store_ent(PL_user_def_props,
22769                                     fq_name,
22770                                     ((prop_definition)
22771                                      ? newSVsv(prop_definition)
22772                                      : newSVsv(msg)),
22773                                     0);
22774                 RESTORE_CONTEXT;
22775             }
22776
22777             /* All done, and the hash now has a permanent entry for this
22778              * property.  Give up exclusive control */
22779             USER_PROP_MUTEX_UNLOCK;
22780
22781             FREETMPS;
22782             LEAVE;
22783
22784             if (prop_definition) {
22785
22786                 /* If the definition is for something not known at this time,
22787                  * we toss it, and go return the main property name, as that's
22788                  * the one the user will be aware of */
22789                 if (! is_invlist(prop_definition)) {
22790                     SvREFCNT_dec_NN(prop_definition);
22791                     goto definition_deferred;
22792                 }
22793
22794                 sv_2mortal(prop_definition);
22795             }
22796
22797             /* And return */
22798             return prop_definition;
22799
22800         }   /* End of calling the subroutine for the user-defined property */
22801     }       /* End of it could be a user-defined property */
22802
22803     /* Here it wasn't a user-defined property that is known at this time.  See
22804      * if it is a Unicode property */
22805
22806     lookup_len = j;     /* This is a more mnemonic name than 'j' */
22807
22808     /* Get the index into our pointer table of the inversion list corresponding
22809      * to the property */
22810     table_index = match_uniprop((U8 *) lookup_name, lookup_len);
22811
22812     /* If it didn't find the property ... */
22813     if (table_index == 0) {
22814
22815         /* Try again stripping off any initial 'In' or 'Is' */
22816         if (starts_with_In_or_Is) {
22817             lookup_name += 2;
22818             lookup_len -= 2;
22819             equals_pos -= 2;
22820             slash_pos -= 2;
22821
22822             table_index = match_uniprop((U8 *) lookup_name, lookup_len);
22823         }
22824
22825         if (table_index == 0) {
22826             char * canonical;
22827
22828             /* Here, we didn't find it.  If not a numeric type property, and
22829              * can't be a user-defined one, it isn't a legal property */
22830             if (! is_nv_type) {
22831                 if (! could_be_user_defined) {
22832                     goto failed;
22833                 }
22834
22835                 /* Here, the property name is legal as a user-defined one.   At
22836                  * compile time, it might just be that the subroutine for that
22837                  * property hasn't been encountered yet, but at runtime, it's
22838                  * an error to try to use an undefined one */
22839                 if (runtime) {
22840                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22841                     sv_catpvs(msg, "Unknown user-defined property name");
22842                     goto append_name_to_msg;
22843                 }
22844
22845                 goto definition_deferred;
22846             } /* End of isn't a numeric type property */
22847
22848             /* The numeric type properties need more work to decide.  What we
22849              * do is make sure we have the number in canonical form and look
22850              * that up. */
22851
22852             if (slash_pos < 0) {    /* No slash */
22853
22854                 /* When it isn't a rational, take the input, convert it to a
22855                  * NV, then create a canonical string representation of that
22856                  * NV. */
22857
22858                 NV value;
22859
22860                 /* Get the value */
22861                 if (my_atof3(lookup_name + equals_pos, &value,
22862                              lookup_len - equals_pos)
22863                           != lookup_name + lookup_len)
22864                 {
22865                     goto failed;
22866                 }
22867
22868                 /* If the value is an integer, the canonical value is integral
22869                  * */
22870                 if (Perl_ceil(value) == value) {
22871                     canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
22872                                             equals_pos, lookup_name, value);
22873                 }
22874                 else {  /* Otherwise, it is %e with a known precision */
22875                     char * exp_ptr;
22876
22877                     canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
22878                                                 equals_pos, lookup_name,
22879                                                 PL_E_FORMAT_PRECISION, value);
22880
22881                     /* The exponent generated is expecting two digits, whereas
22882                      * %e on some systems will generate three.  Remove leading
22883                      * zeros in excess of 2 from the exponent.  We start
22884                      * looking for them after the '=' */
22885                     exp_ptr = strchr(canonical + equals_pos, 'e');
22886                     if (exp_ptr) {
22887                         char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
22888                         SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
22889
22890                         assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
22891
22892                         if (excess_exponent_len > 0) {
22893                             SSize_t leading_zeros = strspn(cur_ptr, "0");
22894                             SSize_t excess_leading_zeros
22895                                     = MIN(leading_zeros, excess_exponent_len);
22896                             if (excess_leading_zeros > 0) {
22897                                 Move(cur_ptr + excess_leading_zeros,
22898                                      cur_ptr,
22899                                      strlen(cur_ptr) - excess_leading_zeros
22900                                        + 1,  /* Copy the NUL as well */
22901                                      char);
22902                             }
22903                         }
22904                     }
22905                 }
22906             }
22907             else {  /* Has a slash.  Create a rational in canonical form  */
22908                 UV numerator, denominator, gcd, trial;
22909                 const char * end_ptr;
22910                 const char * sign = "";
22911
22912                 /* We can't just find the numerator, denominator, and do the
22913                  * division, then use the method above, because that is
22914                  * inexact.  And the input could be a rational that is within
22915                  * epsilon (given our precision) of a valid rational, and would
22916                  * then incorrectly compare valid.
22917                  *
22918                  * We're only interested in the part after the '=' */
22919                 const char * this_lookup_name = lookup_name + equals_pos;
22920                 lookup_len -= equals_pos;
22921                 slash_pos -= equals_pos;
22922
22923                 /* Handle any leading minus */
22924                 if (this_lookup_name[0] == '-') {
22925                     sign = "-";
22926                     this_lookup_name++;
22927                     lookup_len--;
22928                     slash_pos--;
22929                 }
22930
22931                 /* Convert the numerator to numeric */
22932                 end_ptr = this_lookup_name + slash_pos;
22933                 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
22934                     goto failed;
22935                 }
22936
22937                 /* It better have included all characters before the slash */
22938                 if (*end_ptr != '/') {
22939                     goto failed;
22940                 }
22941
22942                 /* Set to look at just the denominator */
22943                 this_lookup_name += slash_pos;
22944                 lookup_len -= slash_pos;
22945                 end_ptr = this_lookup_name + lookup_len;
22946
22947                 /* Convert the denominator to numeric */
22948                 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
22949                     goto failed;
22950                 }
22951
22952                 /* It better be the rest of the characters, and don't divide by
22953                  * 0 */
22954                 if (   end_ptr != this_lookup_name + lookup_len
22955                     || denominator == 0)
22956                 {
22957                     goto failed;
22958                 }
22959
22960                 /* Get the greatest common denominator using
22961                    http://en.wikipedia.org/wiki/Euclidean_algorithm */
22962                 gcd = numerator;
22963                 trial = denominator;
22964                 while (trial != 0) {
22965                     UV temp = trial;
22966                     trial = gcd % trial;
22967                     gcd = temp;
22968                 }
22969
22970                 /* If already in lowest possible terms, we have already tried
22971                  * looking this up */
22972                 if (gcd == 1) {
22973                     goto failed;
22974                 }
22975
22976                 /* Reduce the rational, which should put it in canonical form
22977                  * */
22978                 numerator /= gcd;
22979                 denominator /= gcd;
22980
22981                 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
22982                         equals_pos, lookup_name, sign, numerator, denominator);
22983             }
22984
22985             /* Here, we have the number in canonical form.  Try that */
22986             table_index = match_uniprop((U8 *) canonical, strlen(canonical));
22987             if (table_index == 0) {
22988                 goto failed;
22989             }
22990         }   /* End of still didn't find the property in our table */
22991     }       /* End of       didn't find the property in our table */
22992
22993     /* Here, we have a non-zero return, which is an index into a table of ptrs.
22994      * A negative return signifies that the real index is the absolute value,
22995      * but the result needs to be inverted */
22996     if (table_index < 0) {
22997         invert_return = TRUE;
22998         table_index = -table_index;
22999     }
23000
23001     /* Out-of band indices indicate a deprecated property.  The proper index is
23002      * modulo it with the table size.  And dividing by the table size yields
23003      * an offset into a table constructed by regen/mk_invlists.pl to contain
23004      * the corresponding warning message */
23005     if (table_index > MAX_UNI_KEYWORD_INDEX) {
23006         Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
23007         table_index %= MAX_UNI_KEYWORD_INDEX;
23008         Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
23009                 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
23010                 (int) name_len, name, deprecated_property_msgs[warning_offset]);
23011     }
23012
23013     /* In a few properties, a different property is used under /i.  These are
23014      * unlikely to change, so are hard-coded here. */
23015     if (to_fold) {
23016         if (   table_index == UNI_XPOSIXUPPER
23017             || table_index == UNI_XPOSIXLOWER
23018             || table_index == UNI_TITLE)
23019         {
23020             table_index = UNI_CASED;
23021         }
23022         else if (   table_index == UNI_UPPERCASELETTER
23023                  || table_index == UNI_LOWERCASELETTER
23024 #  ifdef UNI_TITLECASELETTER   /* Missing from early Unicodes */
23025                  || table_index == UNI_TITLECASELETTER
23026 #  endif
23027         ) {
23028             table_index = UNI_CASEDLETTER;
23029         }
23030         else if (  table_index == UNI_POSIXUPPER
23031                 || table_index == UNI_POSIXLOWER)
23032         {
23033             table_index = UNI_POSIXALPHA;
23034         }
23035     }
23036
23037     /* Create and return the inversion list */
23038     prop_definition =_new_invlist_C_array(uni_prop_ptrs[table_index]);
23039     if (invert_return) {
23040         _invlist_invert(prop_definition);
23041     }
23042     sv_2mortal(prop_definition);
23043     return prop_definition;
23044
23045
23046   failed:
23047     if (non_pkg_begin != 0) {
23048         if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23049         sv_catpvs(msg, "Illegal user-defined property name");
23050     }
23051     else {
23052         if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23053         sv_catpvs(msg, "Can't find Unicode property definition");
23054     }
23055     /* FALLTHROUGH */
23056
23057   append_name_to_msg:
23058     {
23059         const char * prefix = (runtime && level == 0) ?  " \\p{" : " \"";
23060         const char * suffix = (runtime && level == 0) ?  "}" : "\"";
23061
23062         sv_catpv(msg, prefix);
23063         Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
23064         sv_catpv(msg, suffix);
23065     }
23066
23067     return NULL;
23068
23069   definition_deferred:
23070
23071     /* Here it could yet to be defined, so defer evaluation of this
23072      * until its needed at runtime. */
23073     prop_definition = newSVpvs_flags("", SVs_TEMP);
23074
23075     /* To avoid any ambiguity, the package is always specified.
23076      * Use the current one if it wasn't included in our input */
23077     if (non_pkg_begin == 0) {
23078         const HV * pkg = (IN_PERL_COMPILETIME)
23079                          ? PL_curstash
23080                          : CopSTASH(PL_curcop);
23081         const char* pkgname = HvNAME(pkg);
23082
23083         Perl_sv_catpvf(aTHX_ prop_definition, "%" UTF8f,
23084                       UTF8fARG(is_utf8, strlen(pkgname), pkgname));
23085         sv_catpvs(prop_definition, "::");
23086     }
23087
23088     Perl_sv_catpvf(aTHX_ prop_definition, "%" UTF8f,
23089                          UTF8fARG(is_utf8, name_len, name));
23090     sv_catpvs(prop_definition, "\n");
23091
23092     *user_defined_ptr = TRUE;
23093     return prop_definition;
23094 }
23095
23096 #endif
23097
23098 /*
23099  * ex: set ts=8 sts=4 sw=4 et:
23100  */