This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regcomp.c: Move some code to within a block
[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
74 /* Note on debug output:
75  *
76  * This is set up so that -Dr turns on debugging like all other flags that are
77  * enabled by -DDEBUGGING.  -Drv gives more verbose output.  This applies to
78  * all regular expressions encountered in a program, and gives a huge amount of
79  * output for all but the shortest programs.
80  *
81  * The ability to output pattern debugging information lexically, and with much
82  * finer grained control was added, with 'use re qw(Debug ....);' available even
83  * in non-DEBUGGING builds.  This is accomplished by copying the contents of
84  * regcomp.c to ext/re/re_comp.c, and regexec.c is copied to ext/re/re_exec.c.
85  * Those files are compiled and linked into the perl executable, and they are
86  * compiled essentially as if DEBUGGING were enabled, and controlled by calls
87  * to re.pm.
88  *
89  * That would normally mean linking errors when two functions of the same name
90  * are attempted to be placed into the same executable.  That is solved in one
91  * of four ways:
92  *  1)  Static functions aren't known outside the file they are in, so for the
93  *      many functions of that type in this file, it just isn't a problem.
94  *  2)  Most externally known functions are enclosed in
95  *          #ifndef PERL_IN_XSUB_RE
96  *          ...
97  *          #endif
98  *      blocks, so there is only one defintion for them in the whole
99  *      executable, the one in regcomp.c (or regexec.c).  The implication of
100  *      that is any debugging info that comes from them is controlled only by
101  *      -Dr.  Further, any static function they call will also be the version
102  *      in regcomp.c (or regexec.c), so its debugging will also be by -Dr.
103  *  3)  About a dozen external functions are re-#defined in ext/re/re_top.h, to
104  *      have different names, so that what gets loaded in the executable is
105  *      'Perl_foo' from regcomp.c (and regexec.c), and the identical function
106  *      from re_comp.c (and re_exec.c), but with the name 'my_foo'  Debugging
107  *      in the 'Perl_foo' versions is controlled by -Dr, but the 'my_foo'
108  *      versions and their callees are under control of re.pm.   The catch is
109  *      that references to all these go through the regexp_engine structure,
110  *      which is initialized in regcomp.h to the Perl_foo versions, and
111  *      substituted out in lexical scopes where 'use re' is in effect to the
112  *      'my_foo' ones.   That structure is public API, so it would be a hard
113  *      sell to add any additional members.
114  *  4)  For functions in regcomp.c and re_comp.c that are called only from,
115  *      respectively, regexec.c and re_exec.c, they can have two different
116  *      names, depending on #ifdef'ing PERL_IN_XSUB_RE, in both regexec.c and
117  *      embed.fnc.
118  *
119  * The bottom line is that if you add code to one of the public functions
120  * listed in ext/re/re_top.h, debugging automagically works.  But if you write
121  * a new function that needs to do debugging or there is a chain of calls from
122  * it that need to do debugging, all functions in the chain should use options
123  * 2) or 4) above.
124  *
125  * A function may have to be split so that debugging stuff is static, but it
126  * calls out to some other function that only gets compiled in regcomp.c to
127  * access data that we don't want to duplicate.
128  */
129
130 #include "EXTERN.h"
131 #define PERL_IN_REGCOMP_C
132 #include "perl.h"
133
134 #define REG_COMP_C
135 #ifdef PERL_IN_XSUB_RE
136 #  include "re_comp.h"
137 EXTERN_C const struct regexp_engine my_reg_engine;
138 EXTERN_C const struct regexp_engine wild_reg_engine;
139 #else
140 #  include "regcomp.h"
141 #endif
142
143 #include "invlist_inline.h"
144 #include "unicode_constants.h"
145
146 #ifndef STATIC
147 #define STATIC  static
148 #endif
149
150 /* this is a chain of data about sub patterns we are processing that
151    need to be handled separately/specially in study_chunk. Its so
152    we can simulate recursion without losing state.  */
153 struct scan_frame;
154 typedef struct scan_frame {
155     regnode *last_regnode;      /* last node to process in this frame */
156     regnode *next_regnode;      /* next node to process when last is reached */
157     U32 prev_recursed_depth;
158     I32 stopparen;              /* what stopparen do we use */
159     bool in_gosub;              /* this or an outer frame is for GOSUB */
160
161     struct scan_frame *this_prev_frame; /* this previous frame */
162     struct scan_frame *prev_frame;      /* previous frame */
163     struct scan_frame *next_frame;      /* next frame */
164 } scan_frame;
165
166 /* Certain characters are output as a sequence with the first being a
167  * backslash. */
168 #define isBACKSLASHED_PUNCT(c)  memCHRs("-[]\\^", c)
169
170
171 struct RExC_state_t {
172     U32         flags;                  /* RXf_* are we folding, multilining? */
173     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
174     char        *precomp;               /* uncompiled string. */
175     char        *precomp_end;           /* pointer to end of uncompiled string. */
176     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
177     regexp      *rx;                    /* perl core regexp structure */
178     regexp_internal     *rxi;           /* internal data for regexp object
179                                            pprivate field */
180     char        *start;                 /* Start of input for compile */
181     char        *end;                   /* End of input for compile */
182     char        *parse;                 /* Input-scan pointer. */
183     char        *copy_start;            /* start of copy of input within
184                                            constructed parse string */
185     char        *save_copy_start;       /* Provides one level of saving
186                                            and restoring 'copy_start' */
187     char        *copy_start_in_input;   /* Position in input string
188                                            corresponding to copy_start */
189     SSize_t     whilem_seen;            /* number of WHILEM in this expr */
190     regnode     *emit_start;            /* Start of emitted-code area */
191     regnode_offset emit;                /* Code-emit pointer */
192     I32         naughty;                /* How bad is this pattern? */
193     I32         sawback;                /* Did we see \1, ...? */
194     SSize_t     size;                   /* Number of regnode equivalents in
195                                            pattern */
196     Size_t      sets_depth;              /* Counts recursion depth of already-
197                                            compiled regex set patterns */
198     U32         seen;
199
200     I32      parens_buf_size;           /* #slots malloced open/close_parens */
201     regnode_offset *open_parens;        /* offsets to open parens */
202     regnode_offset *close_parens;       /* offsets to close parens */
203     HV          *paren_names;           /* Paren names */
204
205     /* position beyond 'precomp' of the warning message furthest away from
206      * 'precomp'.  During the parse, no warnings are raised for any problems
207      * earlier in the parse than this position.  This works if warnings are
208      * raised the first time a given spot is parsed, and if only one
209      * independent warning is raised for any given spot */
210     Size_t      latest_warn_offset;
211
212     I32         npar;                   /* Capture buffer count so far in the
213                                            parse, (OPEN) plus one. ("par" 0 is
214                                            the whole pattern)*/
215     I32         total_par;              /* During initial parse, is either 0,
216                                            or -1; the latter indicating a
217                                            reparse is needed.  After that pass,
218                                            it is what 'npar' became after the
219                                            pass.  Hence, it being > 0 indicates
220                                            we are in a reparse situation */
221     I32         nestroot;               /* root parens we are in - used by
222                                            accept */
223     I32         seen_zerolen;
224     regnode     *end_op;                /* END node in program */
225     I32         utf8;           /* whether the pattern is utf8 or not */
226     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
227                                 /* XXX use this for future optimisation of case
228                                  * where pattern must be upgraded to utf8. */
229     I32         uni_semantics;  /* If a d charset modifier should use unicode
230                                    rules, even if the pattern is not in
231                                    utf8 */
232
233     I32         recurse_count;          /* Number of recurse regops we have generated */
234     regnode     **recurse;              /* Recurse regops */
235     U8          *study_chunk_recursed;  /* bitmap of which subs we have moved
236                                            through */
237     U32         study_chunk_recursed_bytes;  /* bytes in bitmap */
238     I32         in_lookaround;
239     I32         contains_locale;
240     I32         override_recoding;
241     I32         recode_x_to_native;
242     I32         in_multi_char_class;
243     int         code_index;             /* next code_blocks[] slot */
244     struct reg_code_blocks *code_blocks;/* positions of literal (?{})
245                                             within pattern */
246     SSize_t     maxlen;                        /* mininum possible number of chars in string to match */
247     scan_frame *frame_head;
248     scan_frame *frame_last;
249     U32         frame_count;
250     AV         *warn_text;
251     HV         *unlexed_names;
252     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
253 #ifdef DEBUGGING
254     const char  *lastparse;
255     I32         lastnum;
256     U32         study_chunk_recursed_count;
257     AV          *paren_name_list;       /* idx -> name */
258     SV          *mysv1;
259     SV          *mysv2;
260
261 #define RExC_lastparse  (pRExC_state->lastparse)
262 #define RExC_lastnum    (pRExC_state->lastnum)
263 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
264 #define RExC_study_chunk_recursed_count    (pRExC_state->study_chunk_recursed_count)
265 #define RExC_mysv       (pRExC_state->mysv1)
266 #define RExC_mysv1      (pRExC_state->mysv1)
267 #define RExC_mysv2      (pRExC_state->mysv2)
268
269 #endif
270     bool        seen_d_op;
271     bool        strict;
272     bool        study_started;
273     bool        in_script_run;
274     bool        use_BRANCHJ;
275     bool        sWARN_EXPERIMENTAL__VLB;
276     bool        sWARN_EXPERIMENTAL__REGEX_SETS;
277 };
278
279 #define RExC_flags      (pRExC_state->flags)
280 #define RExC_pm_flags   (pRExC_state->pm_flags)
281 #define RExC_precomp    (pRExC_state->precomp)
282 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
283 #define RExC_copy_start_in_constructed  (pRExC_state->copy_start)
284 #define RExC_save_copy_start_in_constructed  (pRExC_state->save_copy_start)
285 #define RExC_precomp_end (pRExC_state->precomp_end)
286 #define RExC_rx_sv      (pRExC_state->rx_sv)
287 #define RExC_rx         (pRExC_state->rx)
288 #define RExC_rxi        (pRExC_state->rxi)
289 #define RExC_start      (pRExC_state->start)
290 #define RExC_end        (pRExC_state->end)
291 #define RExC_parse      (pRExC_state->parse)
292 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
293 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
294 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
295                                                    under /d from /u ? */
296
297 #ifdef RE_TRACK_PATTERN_OFFSETS
298 #  define RExC_offsets  (RExC_rxi->u.offsets) /* I am not like the
299                                                          others */
300 #endif
301 #define RExC_emit       (pRExC_state->emit)
302 #define RExC_emit_start (pRExC_state->emit_start)
303 #define RExC_sawback    (pRExC_state->sawback)
304 #define RExC_seen       (pRExC_state->seen)
305 #define RExC_size       (pRExC_state->size)
306 #define RExC_maxlen        (pRExC_state->maxlen)
307 #define RExC_npar       (pRExC_state->npar)
308 #define RExC_total_parens       (pRExC_state->total_par)
309 #define RExC_parens_buf_size    (pRExC_state->parens_buf_size)
310 #define RExC_nestroot   (pRExC_state->nestroot)
311 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
312 #define RExC_utf8       (pRExC_state->utf8)
313 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
314 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
315 #define RExC_open_parens        (pRExC_state->open_parens)
316 #define RExC_close_parens       (pRExC_state->close_parens)
317 #define RExC_end_op     (pRExC_state->end_op)
318 #define RExC_paren_names        (pRExC_state->paren_names)
319 #define RExC_recurse    (pRExC_state->recurse)
320 #define RExC_recurse_count      (pRExC_state->recurse_count)
321 #define RExC_sets_depth         (pRExC_state->sets_depth)
322 #define RExC_study_chunk_recursed        (pRExC_state->study_chunk_recursed)
323 #define RExC_study_chunk_recursed_bytes  \
324                                    (pRExC_state->study_chunk_recursed_bytes)
325 #define RExC_in_lookaround      (pRExC_state->in_lookaround)
326 #define RExC_contains_locale    (pRExC_state->contains_locale)
327 #define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
328
329 #ifdef EBCDIC
330 #  define SET_recode_x_to_native(x)                                         \
331                     STMT_START { RExC_recode_x_to_native = (x); } STMT_END
332 #else
333 #  define SET_recode_x_to_native(x) NOOP
334 #endif
335
336 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
337 #define RExC_frame_head (pRExC_state->frame_head)
338 #define RExC_frame_last (pRExC_state->frame_last)
339 #define RExC_frame_count (pRExC_state->frame_count)
340 #define RExC_strict (pRExC_state->strict)
341 #define RExC_study_started      (pRExC_state->study_started)
342 #define RExC_warn_text (pRExC_state->warn_text)
343 #define RExC_in_script_run      (pRExC_state->in_script_run)
344 #define RExC_use_BRANCHJ        (pRExC_state->use_BRANCHJ)
345 #define RExC_warned_WARN_EXPERIMENTAL__VLB (pRExC_state->sWARN_EXPERIMENTAL__VLB)
346 #define RExC_warned_WARN_EXPERIMENTAL__REGEX_SETS (pRExC_state->sWARN_EXPERIMENTAL__REGEX_SETS)
347 #define RExC_unlexed_names (pRExC_state->unlexed_names)
348
349 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
350  * a flag to disable back-off on the fixed/floating substrings - if it's
351  * a high complexity pattern we assume the benefit of avoiding a full match
352  * is worth the cost of checking for the substrings even if they rarely help.
353  */
354 #define RExC_naughty    (pRExC_state->naughty)
355 #define TOO_NAUGHTY (10)
356 #define MARK_NAUGHTY(add) \
357     if (RExC_naughty < TOO_NAUGHTY) \
358         RExC_naughty += (add)
359 #define MARK_NAUGHTY_EXP(exp, add) \
360     if (RExC_naughty < TOO_NAUGHTY) \
361         RExC_naughty += RExC_naughty / (exp) + (add)
362
363 #define isNON_BRACE_QUANTIFIER(c)   ((c) == '*' || (c) == '+' || (c) == '?')
364 #define isQUANTIFIER(s,e)  (   isNON_BRACE_QUANTIFIER(*s)                      \
365                             || ((*s) == '{' && regcurly(s, e, NULL)))
366
367 /*
368  * Flags to be passed up and down.
369  */
370 #define HASWIDTH        0x01    /* Known to not match null strings, could match
371                                    non-null ones. */
372 #define SIMPLE          0x02    /* Exactly one character wide */
373                                 /* (or LNBREAK as a special case) */
374 #define POSTPONED       0x08    /* (?1),(?&name), (??{...}) or similar */
375 #define TRYAGAIN        0x10    /* Weeded out a declaration. */
376 #define RESTART_PARSE   0x20    /* Need to redo the parse */
377 #define NEED_UTF8       0x40    /* In conjunction with RESTART_PARSE, need to
378                                    calcuate sizes as UTF-8 */
379
380 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
381
382 /* whether trie related optimizations are enabled */
383 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
384 #define TRIE_STUDY_OPT
385 #define FULL_TRIE_STUDY
386 #define TRIE_STCLASS
387 #endif
388
389
390
391 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
392 #define PBITVAL(paren) (1 << ((paren) & 7))
393 #define PAREN_OFFSET(depth) \
394     (RExC_study_chunk_recursed + (depth) * RExC_study_chunk_recursed_bytes)
395 #define PAREN_TEST(depth, paren) \
396     (PBYTE(PAREN_OFFSET(depth), paren) & PBITVAL(paren))
397 #define PAREN_SET(depth, paren) \
398     (PBYTE(PAREN_OFFSET(depth), paren) |= PBITVAL(paren))
399 #define PAREN_UNSET(depth, paren) \
400     (PBYTE(PAREN_OFFSET(depth), paren) &= ~PBITVAL(paren))
401
402 #define REQUIRE_UTF8(flagp) STMT_START {                                   \
403                                      if (!UTF) {                           \
404                                          *flagp = RESTART_PARSE|NEED_UTF8; \
405                                          return 0;                         \
406                                      }                                     \
407                              } STMT_END
408
409 /* /u is to be chosen if we are supposed to use Unicode rules, or if the
410  * pattern is in UTF-8.  This latter condition is in case the outermost rules
411  * are locale.  See GH #17278 */
412 #define toUSE_UNI_CHARSET_NOT_DEPENDS (RExC_uni_semantics || UTF)
413
414 /* Change from /d into /u rules, and restart the parse.  RExC_uni_semantics is
415  * a flag that indicates we need to override /d with /u as a result of
416  * something in the pattern.  It should only be used in regards to calling
417  * set_regex_charset() or get_regex_charset() */
418 #define REQUIRE_UNI_RULES(flagp, restart_retval)                            \
419     STMT_START {                                                            \
420             if (DEPENDS_SEMANTICS) {                                        \
421                 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);      \
422                 RExC_uni_semantics = 1;                                     \
423                 if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) {           \
424                     /* No need to restart the parse if we haven't seen      \
425                      * anything that differs between /u and /d, and no need \
426                      * to restart immediately if we're going to reparse     \
427                      * anyway to count parens */                            \
428                     *flagp |= RESTART_PARSE;                                \
429                     return restart_retval;                                  \
430                 }                                                           \
431             }                                                               \
432     } STMT_END
433
434 #define REQUIRE_BRANCHJ(flagp, restart_retval)                              \
435     STMT_START {                                                            \
436                 RExC_use_BRANCHJ = 1;                                       \
437                 *flagp |= RESTART_PARSE;                                    \
438                 return restart_retval;                                      \
439     } STMT_END
440
441 /* Until we have completed the parse, we leave RExC_total_parens at 0 or
442  * less.  After that, it must always be positive, because the whole re is
443  * considered to be surrounded by virtual parens.  Setting it to negative
444  * indicates there is some construct that needs to know the actual number of
445  * parens to be properly handled.  And that means an extra pass will be
446  * required after we've counted them all */
447 #define ALL_PARENS_COUNTED (RExC_total_parens > 0)
448 #define REQUIRE_PARENS_PASS                                                 \
449     STMT_START {  /* No-op if have completed a pass */                      \
450                     if (! ALL_PARENS_COUNTED) RExC_total_parens = -1;       \
451     } STMT_END
452 #define IN_PARENS_PASS (RExC_total_parens < 0)
453
454
455 /* This is used to return failure (zero) early from the calling function if
456  * various flags in 'flags' are set.  Two flags always cause a return:
457  * 'RESTART_PARSE' and 'NEED_UTF8'.   'extra' can be used to specify any
458  * additional flags that should cause a return; 0 if none.  If the return will
459  * be done, '*flagp' is first set to be all of the flags that caused the
460  * return. */
461 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra)                  \
462     STMT_START {                                                            \
463             if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) {              \
464                 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra));     \
465                 return 0;                                                   \
466             }                                                               \
467     } STMT_END
468
469 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
470
471 #define RETURN_FAIL_ON_RESTART(flags,flagp)                                 \
472                         RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
473 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp)                                 \
474                                     if (MUST_RESTART(*(flagp))) return 0
475
476 /* This converts the named class defined in regcomp.h to its equivalent class
477  * number defined in handy.h. */
478 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
479 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
480
481 #define _invlist_union_complement_2nd(a, b, output) \
482                         _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
483 #define _invlist_intersection_complement_2nd(a, b, output) \
484                  _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
485
486 /* We add a marker if we are deferring expansion of a property that is both
487  * 1) potentiallly user-defined; and
488  * 2) could also be an official Unicode property.
489  *
490  * Without this marker, any deferred expansion can only be for a user-defined
491  * one.  This marker shouldn't conflict with any that could be in a legal name,
492  * and is appended to its name to indicate this.  There is a string and
493  * character form */
494 #define DEFERRED_COULD_BE_OFFICIAL_MARKERs  "~"
495 #define DEFERRED_COULD_BE_OFFICIAL_MARKERc  '~'
496
497 /* What is infinity for optimization purposes */
498 #define OPTIMIZE_INFTY  SSize_t_MAX
499
500 /* About scan_data_t.
501
502   During optimisation we recurse through the regexp program performing
503   various inplace (keyhole style) optimisations. In addition study_chunk
504   and scan_commit populate this data structure with information about
505   what strings MUST appear in the pattern. We look for the longest
506   string that must appear at a fixed location, and we look for the
507   longest string that may appear at a floating location. So for instance
508   in the pattern:
509
510     /FOO[xX]A.*B[xX]BAR/
511
512   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
513   strings (because they follow a .* construct). study_chunk will identify
514   both FOO and BAR as being the longest fixed and floating strings respectively.
515
516   The strings can be composites, for instance
517
518      /(f)(o)(o)/
519
520   will result in a composite fixed substring 'foo'.
521
522   For each string some basic information is maintained:
523
524   - min_offset
525     This is the position the string must appear at, or not before.
526     It also implicitly (when combined with minlenp) tells us how many
527     characters must match before the string we are searching for.
528     Likewise when combined with minlenp and the length of the string it
529     tells us how many characters must appear after the string we have
530     found.
531
532   - max_offset
533     Only used for floating strings. This is the rightmost point that
534     the string can appear at. If set to OPTIMIZE_INFTY it indicates that the
535     string can occur infinitely far to the right.
536     For fixed strings, it is equal to min_offset.
537
538   - minlenp
539     A pointer to the minimum number of characters of the pattern that the
540     string was found inside. This is important as in the case of positive
541     lookahead or positive lookbehind we can have multiple patterns
542     involved. Consider
543
544     /(?=FOO).*F/
545
546     The minimum length of the pattern overall is 3, the minimum length
547     of the lookahead part is 3, but the minimum length of the part that
548     will actually match is 1. So 'FOO's minimum length is 3, but the
549     minimum length for the F is 1. This is important as the minimum length
550     is used to determine offsets in front of and behind the string being
551     looked for.  Since strings can be composites this is the length of the
552     pattern at the time it was committed with a scan_commit. Note that
553     the length is calculated by study_chunk, so that the minimum lengths
554     are not known until the full pattern has been compiled, thus the
555     pointer to the value.
556
557   - lookbehind
558
559     In the case of lookbehind the string being searched for can be
560     offset past the start point of the final matching string.
561     If this value was just blithely removed from the min_offset it would
562     invalidate some of the calculations for how many chars must match
563     before or after (as they are derived from min_offset and minlen and
564     the length of the string being searched for).
565     When the final pattern is compiled and the data is moved from the
566     scan_data_t structure into the regexp structure the information
567     about lookbehind is factored in, with the information that would
568     have been lost precalculated in the end_shift field for the
569     associated string.
570
571   The fields pos_min and pos_delta are used to store the minimum offset
572   and the delta to the maximum offset at the current point in the pattern.
573
574 */
575
576 struct scan_data_substrs {
577     SV      *str;       /* longest substring found in pattern */
578     SSize_t min_offset; /* earliest point in string it can appear */
579     SSize_t max_offset; /* latest point in string it can appear */
580     SSize_t *minlenp;   /* pointer to the minlen relevant to the string */
581     SSize_t lookbehind; /* is the pos of the string modified by LB */
582     I32 flags;          /* per substring SF_* and SCF_* flags */
583 };
584
585 typedef struct scan_data_t {
586     /*I32 len_min;      unused */
587     /*I32 len_delta;    unused */
588     SSize_t pos_min;
589     SSize_t pos_delta;
590     SV *last_found;
591     SSize_t last_end;       /* min value, <0 unless valid. */
592     SSize_t last_start_min;
593     SSize_t last_start_max;
594     U8      cur_is_floating; /* whether the last_* values should be set as
595                               * the next fixed (0) or floating (1)
596                               * substring */
597
598     /* [0] is longest fixed substring so far, [1] is longest float so far */
599     struct scan_data_substrs  substrs[2];
600
601     I32 flags;             /* common SF_* and SCF_* flags */
602     I32 whilem_c;
603     SSize_t *last_closep;
604     regnode_ssc *start_class;
605 } scan_data_t;
606
607 /*
608  * Forward declarations for pregcomp()'s friends.
609  */
610
611 static const scan_data_t zero_scan_data = {
612     0, 0, NULL, 0, 0, 0, 0,
613     {
614         { NULL, 0, 0, 0, 0, 0 },
615         { NULL, 0, 0, 0, 0, 0 },
616     },
617     0, 0, NULL, NULL
618 };
619
620 /* study flags */
621
622 #define SF_BEFORE_SEOL          0x0001
623 #define SF_BEFORE_MEOL          0x0002
624 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
625
626 #define SF_IS_INF               0x0040
627 #define SF_HAS_PAR              0x0080
628 #define SF_IN_PAR               0x0100
629 #define SF_HAS_EVAL             0x0200
630
631
632 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
633  * longest substring in the pattern. When it is not set the optimiser keeps
634  * track of position, but does not keep track of the actual strings seen,
635  *
636  * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
637  * /foo/i will not.
638  *
639  * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
640  * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
641  * turned off because of the alternation (BRANCH). */
642 #define SCF_DO_SUBSTR           0x0400
643
644 #define SCF_DO_STCLASS_AND      0x0800
645 #define SCF_DO_STCLASS_OR       0x1000
646 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
647 #define SCF_WHILEM_VISITED_POS  0x2000
648
649 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
650 #define SCF_SEEN_ACCEPT         0x8000
651 #define SCF_TRIE_DOING_RESTUDY 0x10000
652 #define SCF_IN_DEFINE          0x20000
653
654
655
656
657 #define UTF cBOOL(RExC_utf8)
658
659 /* The enums for all these are ordered so things work out correctly */
660 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
661 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags)                    \
662                                                      == REGEX_DEPENDS_CHARSET)
663 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
664 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags)                \
665                                                      >= REGEX_UNICODE_CHARSET)
666 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags)                      \
667                                             == REGEX_ASCII_RESTRICTED_CHARSET)
668 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags)             \
669                                             >= REGEX_ASCII_RESTRICTED_CHARSET)
670 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags)                 \
671                                         == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
672
673 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
674
675 /* For programs that want to be strictly Unicode compatible by dying if any
676  * attempt is made to match a non-Unicode code point against a Unicode
677  * property.  */
678 #define ALWAYS_WARN_SUPER  ckDEAD(packWARN(WARN_NON_UNICODE))
679
680 #define OOB_NAMEDCLASS          -1
681
682 /* There is no code point that is out-of-bounds, so this is problematic.  But
683  * its only current use is to initialize a variable that is always set before
684  * looked at. */
685 #define OOB_UNICODE             0xDEADBEEF
686
687 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
688
689
690 /* length of regex to show in messages that don't mark a position within */
691 #define RegexLengthToShowInErrorMessages 127
692
693 /*
694  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
695  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
696  * op/pragma/warn/regcomp.
697  */
698 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
699 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
700
701 #define REPORT_LOCATION " in regex; marked by " MARKER1    \
702                         " in m/%" UTF8f MARKER2 "%" UTF8f "/"
703
704 /* The code in this file in places uses one level of recursion with parsing
705  * rebased to an alternate string constructed by us in memory.  This can take
706  * the form of something that is completely different from the input, or
707  * something that uses the input as part of the alternate.  In the first case,
708  * there should be no possibility of an error, as we are in complete control of
709  * the alternate string.  But in the second case we don't completely control
710  * the input portion, so there may be errors in that.  Here's an example:
711  *      /[abc\x{DF}def]/ui
712  * is handled specially because \x{df} folds to a sequence of more than one
713  * character: 'ss'.  What is done is to create and parse an alternate string,
714  * which looks like this:
715  *      /(?:\x{DF}|[abc\x{DF}def])/ui
716  * where it uses the input unchanged in the middle of something it constructs,
717  * which is a branch for the DF outside the character class, and clustering
718  * parens around the whole thing. (It knows enough to skip the DF inside the
719  * class while in this substitute parse.) 'abc' and 'def' may have errors that
720  * need to be reported.  The general situation looks like this:
721  *
722  *                                       |<------- identical ------>|
723  *              sI                       tI               xI       eI
724  * Input:       ---------------------------------------------------------------
725  * Constructed:         ---------------------------------------------------
726  *                      sC               tC               xC       eC     EC
727  *                                       |<------- identical ------>|
728  *
729  * sI..eI   is the portion of the input pattern we are concerned with here.
730  * sC..EC   is the constructed substitute parse string.
731  *  sC..tC  is constructed by us
732  *  tC..eC  is an exact duplicate of the portion of the input pattern tI..eI.
733  *          In the diagram, these are vertically aligned.
734  *  eC..EC  is also constructed by us.
735  * xC       is the position in the substitute parse string where we found a
736  *          problem.
737  * xI       is the position in the original pattern corresponding to xC.
738  *
739  * We want to display a message showing the real input string.  Thus we need to
740  * translate from xC to xI.  We know that xC >= tC, since the portion of the
741  * string sC..tC has been constructed by us, and so shouldn't have errors.  We
742  * get:
743  *      xI = tI + (xC - tC)
744  *
745  * When the substitute parse is constructed, the code needs to set:
746  *      RExC_start (sC)
747  *      RExC_end (eC)
748  *      RExC_copy_start_in_input  (tI)
749  *      RExC_copy_start_in_constructed (tC)
750  * and restore them when done.
751  *
752  * During normal processing of the input pattern, both
753  * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
754  * sI, so that xC equals xI.
755  */
756
757 #define sI              RExC_precomp
758 #define eI              RExC_precomp_end
759 #define sC              RExC_start
760 #define eC              RExC_end
761 #define tI              RExC_copy_start_in_input
762 #define tC              RExC_copy_start_in_constructed
763 #define xI(xC)          (tI + (xC - tC))
764 #define xI_offset(xC)   (xI(xC) - sI)
765
766 #define REPORT_LOCATION_ARGS(xC)                                            \
767     UTF8fARG(UTF,                                                           \
768              (xI(xC) > eI) /* Don't run off end */                          \
769               ? eI - sI   /* Length before the <--HERE */                   \
770               : ((xI_offset(xC) >= 0)                                       \
771                  ? xI_offset(xC)                                            \
772                  : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %"    \
773                                     IVdf " trying to output message for "   \
774                                     " pattern %.*s",                        \
775                                     __FILE__, __LINE__, (IV) xI_offset(xC), \
776                                     ((int) (eC - sC)), sC), 0)),            \
777              sI),         /* The input pattern printed up to the <--HERE */ \
778     UTF8fARG(UTF,                                                           \
779              (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */    \
780              (xI(xC) > eI) ? eI : xI(xC))     /* pattern after <--HERE */
781
782 /* Used to point after bad bytes for an error message, but avoid skipping
783  * past a nul byte. */
784 #define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1)
785
786 /* Set up to clean up after our imminent demise */
787 #define PREPARE_TO_DIE                                                      \
788     STMT_START {                                                            \
789         if (RExC_rx_sv)                                                     \
790             SAVEFREESV(RExC_rx_sv);                                         \
791         if (RExC_open_parens)                                               \
792             SAVEFREEPV(RExC_open_parens);                                   \
793         if (RExC_close_parens)                                              \
794             SAVEFREEPV(RExC_close_parens);                                  \
795     } STMT_END
796
797 /*
798  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
799  * arg. Show regex, up to a maximum length. If it's too long, chop and add
800  * "...".
801  */
802 #define _FAIL(code) STMT_START {                                        \
803     const char *ellipses = "";                                          \
804     IV len = RExC_precomp_end - RExC_precomp;                           \
805                                                                         \
806     PREPARE_TO_DIE;                                                     \
807     if (len > RegexLengthToShowInErrorMessages) {                       \
808         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
809         len = RegexLengthToShowInErrorMessages - 10;                    \
810         ellipses = "...";                                               \
811     }                                                                   \
812     code;                                                               \
813 } STMT_END
814
815 #define FAIL(msg) _FAIL(                            \
816     Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/",         \
817             msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
818
819 #define FAIL2(msg,arg) _FAIL(                       \
820     Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/",       \
821             arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
822
823 #define FAIL3(msg,arg1,arg2) _FAIL(                         \
824     Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/",       \
825      arg1, arg2, UTF8fARG(UTF, len, RExC_precomp), ellipses))
826
827 /*
828  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
829  */
830 #define Simple_vFAIL(m) STMT_START {                                    \
831     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
832             m, REPORT_LOCATION_ARGS(RExC_parse));                       \
833 } STMT_END
834
835 /*
836  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
837  */
838 #define vFAIL(m) STMT_START {                           \
839     PREPARE_TO_DIE;                                     \
840     Simple_vFAIL(m);                                    \
841 } STMT_END
842
843 /*
844  * Like Simple_vFAIL(), but accepts two arguments.
845  */
846 #define Simple_vFAIL2(m,a1) STMT_START {                        \
847     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1,                \
848                       REPORT_LOCATION_ARGS(RExC_parse));        \
849 } STMT_END
850
851 /*
852  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
853  */
854 #define vFAIL2(m,a1) STMT_START {                       \
855     PREPARE_TO_DIE;                                     \
856     Simple_vFAIL2(m, a1);                               \
857 } STMT_END
858
859
860 /*
861  * Like Simple_vFAIL(), but accepts three arguments.
862  */
863 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
864     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2,            \
865             REPORT_LOCATION_ARGS(RExC_parse));                  \
866 } STMT_END
867
868 /*
869  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
870  */
871 #define vFAIL3(m,a1,a2) STMT_START {                    \
872     PREPARE_TO_DIE;                                     \
873     Simple_vFAIL3(m, a1, a2);                           \
874 } STMT_END
875
876 /*
877  * Like Simple_vFAIL(), but accepts four arguments.
878  */
879 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
880     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2, a3,        \
881             REPORT_LOCATION_ARGS(RExC_parse));                  \
882 } STMT_END
883
884 #define vFAIL4(m,a1,a2,a3) STMT_START {                 \
885     PREPARE_TO_DIE;                                     \
886     Simple_vFAIL4(m, a1, a2, a3);                       \
887 } STMT_END
888
889 /* A specialized version of vFAIL2 that works with UTF8f */
890 #define vFAIL2utf8f(m, a1) STMT_START {             \
891     PREPARE_TO_DIE;                                 \
892     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1,  \
893             REPORT_LOCATION_ARGS(RExC_parse));      \
894 } STMT_END
895
896 #define vFAIL3utf8f(m, a1, a2) STMT_START {             \
897     PREPARE_TO_DIE;                                     \
898     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2,  \
899             REPORT_LOCATION_ARGS(RExC_parse));          \
900 } STMT_END
901
902 /* Setting this to NULL is a signal to not output warnings */
903 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE                               \
904     STMT_START {                                                            \
905       RExC_save_copy_start_in_constructed  = RExC_copy_start_in_constructed;\
906       RExC_copy_start_in_constructed = NULL;                                \
907     } STMT_END
908 #define RESTORE_WARNINGS                                                    \
909     RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed
910
911 /* Since a warning can be generated multiple times as the input is reparsed, we
912  * output it the first time we come to that point in the parse, but suppress it
913  * otherwise.  'RExC_copy_start_in_constructed' being NULL is a flag to not
914  * generate any warnings */
915 #define TO_OUTPUT_WARNINGS(loc)                                         \
916   (   RExC_copy_start_in_constructed                                    \
917    && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
918
919 /* After we've emitted a warning, we save the position in the input so we don't
920  * output it again */
921 #define UPDATE_WARNINGS_LOC(loc)                                        \
922     STMT_START {                                                        \
923         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
924             RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc)))         \
925                                                        - RExC_precomp;  \
926         }                                                               \
927     } STMT_END
928
929 /* 'warns' is the output of the packWARNx macro used in 'code' */
930 #define _WARN_HELPER(loc, warns, code)                                  \
931     STMT_START {                                                        \
932         if (! RExC_copy_start_in_constructed) {                         \
933             Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none"  \
934                               " expected at '%s'",                      \
935                               __FILE__, __LINE__, loc);                 \
936         }                                                               \
937         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
938             if (ckDEAD(warns))                                          \
939                 PREPARE_TO_DIE;                                         \
940             code;                                                       \
941             UPDATE_WARNINGS_LOC(loc);                                   \
942         }                                                               \
943     } STMT_END
944
945 /* m is not necessarily a "literal string", in this macro */
946 #define warn_non_literal_string(loc, packed_warn, m)                    \
947     _WARN_HELPER(loc, packed_warn,                                      \
948                       Perl_warner(aTHX_ packed_warn,                    \
949                                        "%s" REPORT_LOCATION,            \
950                                   m, REPORT_LOCATION_ARGS(loc)))
951 #define reg_warn_non_literal_string(loc, m)                             \
952                 warn_non_literal_string(loc, packWARN(WARN_REGEXP), m)
953
954 #define ckWARN2_non_literal_string(loc, packwarn, m, a1)                    \
955     STMT_START {                                                            \
956                 char * format;                                              \
957                 Size_t format_size = strlen(m) + strlen(REPORT_LOCATION)+ 1;\
958                 Newx(format, format_size, char);                            \
959                 my_strlcpy(format, m, format_size);                         \
960                 my_strlcat(format, REPORT_LOCATION, format_size);           \
961                 SAVEFREEPV(format);                                         \
962                 _WARN_HELPER(loc, packwarn,                                 \
963                       Perl_ck_warner(aTHX_ packwarn,                        \
964                                         format,                             \
965                                         a1, REPORT_LOCATION_ARGS(loc)));    \
966     } STMT_END
967
968 #define ckWARNreg(loc,m)                                                \
969     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
970                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
971                                           m REPORT_LOCATION,            \
972                                           REPORT_LOCATION_ARGS(loc)))
973
974 #define vWARN(loc, m)                                                   \
975     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
976                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
977                                        m REPORT_LOCATION,               \
978                                        REPORT_LOCATION_ARGS(loc)))      \
979
980 #define vWARN_dep(loc, m)                                               \
981     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
982                       Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),      \
983                                        m REPORT_LOCATION,               \
984                                        REPORT_LOCATION_ARGS(loc)))
985
986 #define ckWARNdep(loc,m)                                                \
987     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
988                       Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
989                                             m REPORT_LOCATION,          \
990                                             REPORT_LOCATION_ARGS(loc)))
991
992 #define ckWARNregdep(loc,m)                                                 \
993     _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP),              \
994                       Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED,     \
995                                                       WARN_REGEXP),         \
996                                              m REPORT_LOCATION,             \
997                                              REPORT_LOCATION_ARGS(loc)))
998
999 #define ckWARN2reg_d(loc,m, a1)                                             \
1000     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
1001                       Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP),         \
1002                                             m REPORT_LOCATION,              \
1003                                             a1, REPORT_LOCATION_ARGS(loc)))
1004
1005 #define ckWARN2reg(loc, m, a1)                                              \
1006     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
1007                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
1008                                           m REPORT_LOCATION,                \
1009                                           a1, REPORT_LOCATION_ARGS(loc)))
1010
1011 #define vWARN3(loc, m, a1, a2)                                              \
1012     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
1013                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),              \
1014                                        m REPORT_LOCATION,                   \
1015                                        a1, a2, REPORT_LOCATION_ARGS(loc)))
1016
1017 #define ckWARN3reg(loc, m, a1, a2)                                          \
1018     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
1019                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
1020                                           m REPORT_LOCATION,                \
1021                                           a1, a2,                           \
1022                                           REPORT_LOCATION_ARGS(loc)))
1023
1024 #define vWARN4(loc, m, a1, a2, a3)                                      \
1025     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
1026                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
1027                                        m REPORT_LOCATION,               \
1028                                        a1, a2, a3,                      \
1029                                        REPORT_LOCATION_ARGS(loc)))
1030
1031 #define ckWARN4reg(loc, m, a1, a2, a3)                                  \
1032     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
1033                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
1034                                           m REPORT_LOCATION,            \
1035                                           a1, a2, a3,                   \
1036                                           REPORT_LOCATION_ARGS(loc)))
1037
1038 #define vWARN5(loc, m, a1, a2, a3, a4)                                  \
1039     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
1040                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
1041                                        m REPORT_LOCATION,               \
1042                                        a1, a2, a3, a4,                  \
1043                                        REPORT_LOCATION_ARGS(loc)))
1044
1045 #define ckWARNexperimental(loc, class, m)                               \
1046     STMT_START {                                                        \
1047         if (! RExC_warned_ ## class) { /* warn once per compilation */  \
1048             RExC_warned_ ## class = 1;                                  \
1049             _WARN_HELPER(loc, packWARN(class),                          \
1050                       Perl_ck_warner_d(aTHX_ packWARN(class),           \
1051                                             m REPORT_LOCATION,          \
1052                                             REPORT_LOCATION_ARGS(loc)));\
1053         }                                                               \
1054     } STMT_END
1055
1056 /* Convert between a pointer to a node and its offset from the beginning of the
1057  * program */
1058 #define REGNODE_p(offset)    (RExC_emit_start + (offset))
1059 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
1060
1061 /* Macros for recording node offsets.   20001227 mjd@plover.com
1062  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
1063  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
1064  * Element 0 holds the number n.
1065  * Position is 1 indexed.
1066  */
1067 #ifndef RE_TRACK_PATTERN_OFFSETS
1068 #define Set_Node_Offset_To_R(offset,byte)
1069 #define Set_Node_Offset(node,byte)
1070 #define Set_Cur_Node_Offset
1071 #define Set_Node_Length_To_R(node,len)
1072 #define Set_Node_Length(node,len)
1073 #define Set_Node_Cur_Length(node,start)
1074 #define Node_Offset(n)
1075 #define Node_Length(n)
1076 #define Set_Node_Offset_Length(node,offset,len)
1077 #define ProgLen(ri) ri->u.proglen
1078 #define SetProgLen(ri,x) ri->u.proglen = x
1079 #define Track_Code(code)
1080 #else
1081 #define ProgLen(ri) ri->u.offsets[0]
1082 #define SetProgLen(ri,x) ri->u.offsets[0] = x
1083 #define Set_Node_Offset_To_R(offset,byte) STMT_START {                  \
1084         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
1085                     __LINE__, (int)(offset), (int)(byte)));             \
1086         if((offset) < 0) {                                              \
1087             Perl_croak(aTHX_ "value of node is %d in Offset macro",     \
1088                                          (int)(offset));                \
1089         } else {                                                        \
1090             RExC_offsets[2*(offset)-1] = (byte);                        \
1091         }                                                               \
1092 } STMT_END
1093
1094 #define Set_Node_Offset(node,byte)                                      \
1095     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
1096 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
1097
1098 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
1099         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
1100                 __LINE__, (int)(node), (int)(len)));                    \
1101         if((node) < 0) {                                                \
1102             Perl_croak(aTHX_ "value of node is %d in Length macro",     \
1103                                          (int)(node));                  \
1104         } else {                                                        \
1105             RExC_offsets[2*(node)] = (len);                             \
1106         }                                                               \
1107 } STMT_END
1108
1109 #define Set_Node_Length(node,len) \
1110     Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1111 #define Set_Node_Cur_Length(node, start)                \
1112     Set_Node_Length(node, RExC_parse - start)
1113
1114 /* Get offsets and lengths */
1115 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1116 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1117
1118 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
1119     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset));       \
1120     Set_Node_Length_To_R(REGNODE_OFFSET(node), (len));  \
1121 } STMT_END
1122
1123 #define Track_Code(code) STMT_START { code } STMT_END
1124 #endif
1125
1126 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1127 #define EXPERIMENTAL_INPLACESCAN
1128 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1129
1130 #ifdef DEBUGGING
1131 int
1132 Perl_re_printf(pTHX_ const char *fmt, ...)
1133 {
1134     va_list ap;
1135     int result;
1136     PerlIO *f= Perl_debug_log;
1137     PERL_ARGS_ASSERT_RE_PRINTF;
1138     va_start(ap, fmt);
1139     result = PerlIO_vprintf(f, fmt, ap);
1140     va_end(ap);
1141     return result;
1142 }
1143
1144 int
1145 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1146 {
1147     va_list ap;
1148     int result;
1149     PerlIO *f= Perl_debug_log;
1150     PERL_ARGS_ASSERT_RE_INDENTF;
1151     va_start(ap, depth);
1152     PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1153     result = PerlIO_vprintf(f, fmt, ap);
1154     va_end(ap);
1155     return result;
1156 }
1157 #endif /* DEBUGGING */
1158
1159 #define DEBUG_RExC_seen()                                                   \
1160         DEBUG_OPTIMISE_MORE_r({                                             \
1161             Perl_re_printf( aTHX_ "RExC_seen: ");                           \
1162                                                                             \
1163             if (RExC_seen & REG_ZERO_LEN_SEEN)                              \
1164                 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN ");                \
1165                                                                             \
1166             if (RExC_seen & REG_LOOKBEHIND_SEEN)                            \
1167                 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN ");              \
1168                                                                             \
1169             if (RExC_seen & REG_GPOS_SEEN)                                  \
1170                 Perl_re_printf( aTHX_ "REG_GPOS_SEEN ");                    \
1171                                                                             \
1172             if (RExC_seen & REG_RECURSE_SEEN)                               \
1173                 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN ");                 \
1174                                                                             \
1175             if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)                    \
1176                 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN ");      \
1177                                                                             \
1178             if (RExC_seen & REG_VERBARG_SEEN)                               \
1179                 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN ");                 \
1180                                                                             \
1181             if (RExC_seen & REG_CUTGROUP_SEEN)                              \
1182                 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN ");                \
1183                                                                             \
1184             if (RExC_seen & REG_RUN_ON_COMMENT_SEEN)                        \
1185                 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN ");          \
1186                                                                             \
1187             if (RExC_seen & REG_UNFOLDED_MULTI_SEEN)                        \
1188                 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN ");          \
1189                                                                             \
1190             if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)                  \
1191                 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN ");    \
1192                                                                             \
1193             Perl_re_printf( aTHX_ "\n");                                    \
1194         });
1195
1196 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1197   if ((flags) & flag) Perl_re_printf( aTHX_  "%s ", #flag)
1198
1199
1200 #ifdef DEBUGGING
1201 static void
1202 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1203                                     const char *close_str)
1204 {
1205     if (!flags)
1206         return;
1207
1208     Perl_re_printf( aTHX_  "%s", open_str);
1209     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1210     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1211     DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1212     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1213     DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1214     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1215     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1216     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1217     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1218     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1219     DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1220     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1221     DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1222     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1223     DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1224     Perl_re_printf( aTHX_  "%s", close_str);
1225 }
1226
1227
1228 static void
1229 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1230                     U32 depth, int is_inf)
1231 {
1232     DECLARE_AND_GET_RE_DEBUG_FLAGS;
1233
1234     DEBUG_OPTIMISE_MORE_r({
1235         if (!data)
1236             return;
1237         Perl_re_indentf(aTHX_  "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1238             depth,
1239             where,
1240             (IV)data->pos_min,
1241             (IV)data->pos_delta,
1242             (UV)data->flags
1243         );
1244
1245         S_debug_show_study_flags(aTHX_ data->flags," [","]");
1246
1247         Perl_re_printf( aTHX_
1248             " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1249             (IV)data->whilem_c,
1250             (IV)(data->last_closep ? *((data)->last_closep) : -1),
1251             is_inf ? "INF " : ""
1252         );
1253
1254         if (data->last_found) {
1255             int i;
1256             Perl_re_printf(aTHX_
1257                 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1258                     SvPVX_const(data->last_found),
1259                     (IV)data->last_end,
1260                     (IV)data->last_start_min,
1261                     (IV)data->last_start_max
1262             );
1263
1264             for (i = 0; i < 2; i++) {
1265                 Perl_re_printf(aTHX_
1266                     " %s%s: '%s' @ %" IVdf "/%" IVdf,
1267                     data->cur_is_floating == i ? "*" : "",
1268                     i ? "Float" : "Fixed",
1269                     SvPVX_const(data->substrs[i].str),
1270                     (IV)data->substrs[i].min_offset,
1271                     (IV)data->substrs[i].max_offset
1272                 );
1273                 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1274             }
1275         }
1276
1277         Perl_re_printf( aTHX_ "\n");
1278     });
1279 }
1280
1281
1282 static void
1283 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1284                 regnode *scan, U32 depth, U32 flags)
1285 {
1286     DECLARE_AND_GET_RE_DEBUG_FLAGS;
1287
1288     DEBUG_OPTIMISE_r({
1289         regnode *Next;
1290
1291         if (!scan)
1292             return;
1293         Next = regnext(scan);
1294         regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1295         Perl_re_indentf( aTHX_   "%s>%3d: %s (%d)",
1296             depth,
1297             str,
1298             REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1299             Next ? (REG_NODE_NUM(Next)) : 0 );
1300         S_debug_show_study_flags(aTHX_ flags," [ ","]");
1301         Perl_re_printf( aTHX_  "\n");
1302    });
1303 }
1304
1305
1306 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1307                     S_debug_studydata(aTHX_ where, data, depth, is_inf)
1308
1309 #  define DEBUG_PEEP(str, scan, depth, flags)   \
1310                     S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1311
1312 #else
1313 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1314 #  define DEBUG_PEEP(str, scan, depth, flags)         NOOP
1315 #endif
1316
1317
1318 /* =========================================================
1319  * BEGIN edit_distance stuff.
1320  *
1321  * This calculates how many single character changes of any type are needed to
1322  * transform a string into another one.  It is taken from version 3.1 of
1323  *
1324  * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1325  */
1326
1327 /* Our unsorted dictionary linked list.   */
1328 /* Note we use UVs, not chars. */
1329
1330 struct dictionary{
1331   UV key;
1332   UV value;
1333   struct dictionary* next;
1334 };
1335 typedef struct dictionary item;
1336
1337
1338 PERL_STATIC_INLINE item*
1339 push(UV key, item* curr)
1340 {
1341     item* head;
1342     Newx(head, 1, item);
1343     head->key = key;
1344     head->value = 0;
1345     head->next = curr;
1346     return head;
1347 }
1348
1349
1350 PERL_STATIC_INLINE item*
1351 find(item* head, UV key)
1352 {
1353     item* iterator = head;
1354     while (iterator){
1355         if (iterator->key == key){
1356             return iterator;
1357         }
1358         iterator = iterator->next;
1359     }
1360
1361     return NULL;
1362 }
1363
1364 PERL_STATIC_INLINE item*
1365 uniquePush(item* head, UV key)
1366 {
1367     item* iterator = head;
1368
1369     while (iterator){
1370         if (iterator->key == key) {
1371             return head;
1372         }
1373         iterator = iterator->next;
1374     }
1375
1376     return push(key, head);
1377 }
1378
1379 PERL_STATIC_INLINE void
1380 dict_free(item* head)
1381 {
1382     item* iterator = head;
1383
1384     while (iterator) {
1385         item* temp = iterator;
1386         iterator = iterator->next;
1387         Safefree(temp);
1388     }
1389
1390     head = NULL;
1391 }
1392
1393 /* End of Dictionary Stuff */
1394
1395 /* All calculations/work are done here */
1396 STATIC int
1397 S_edit_distance(const UV* src,
1398                 const UV* tgt,
1399                 const STRLEN x,             /* length of src[] */
1400                 const STRLEN y,             /* length of tgt[] */
1401                 const SSize_t maxDistance
1402 )
1403 {
1404     item *head = NULL;
1405     UV swapCount, swapScore, targetCharCount, i, j;
1406     UV *scores;
1407     UV score_ceil = x + y;
1408
1409     PERL_ARGS_ASSERT_EDIT_DISTANCE;
1410
1411     /* intialize matrix start values */
1412     Newx(scores, ( (x + 2) * (y + 2)), UV);
1413     scores[0] = score_ceil;
1414     scores[1 * (y + 2) + 0] = score_ceil;
1415     scores[0 * (y + 2) + 1] = score_ceil;
1416     scores[1 * (y + 2) + 1] = 0;
1417     head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1418
1419     /* work loops    */
1420     /* i = src index */
1421     /* j = tgt index */
1422     for (i=1;i<=x;i++) {
1423         if (i < x)
1424             head = uniquePush(head, src[i]);
1425         scores[(i+1) * (y + 2) + 1] = i;
1426         scores[(i+1) * (y + 2) + 0] = score_ceil;
1427         swapCount = 0;
1428
1429         for (j=1;j<=y;j++) {
1430             if (i == 1) {
1431                 if(j < y)
1432                 head = uniquePush(head, tgt[j]);
1433                 scores[1 * (y + 2) + (j + 1)] = j;
1434                 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1435             }
1436
1437             targetCharCount = find(head, tgt[j-1])->value;
1438             swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1439
1440             if (src[i-1] != tgt[j-1]){
1441                 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));
1442             }
1443             else {
1444                 swapCount = j;
1445                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1446             }
1447         }
1448
1449         find(head, src[i-1])->value = i;
1450     }
1451
1452     {
1453         IV score = scores[(x+1) * (y + 2) + (y + 1)];
1454         dict_free(head);
1455         Safefree(scores);
1456         return (maxDistance != 0 && maxDistance < score)?(-1):score;
1457     }
1458 }
1459
1460 /* END of edit_distance() stuff
1461  * ========================================================= */
1462
1463 /* Mark that we cannot extend a found fixed substring at this point.
1464    Update the longest found anchored substring or the longest found
1465    floating substrings if needed. */
1466
1467 STATIC void
1468 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1469                     SSize_t *minlenp, int is_inf)
1470 {
1471     const STRLEN l = CHR_SVLEN(data->last_found);
1472     SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1473     const STRLEN old_l = CHR_SVLEN(longest_sv);
1474     DECLARE_AND_GET_RE_DEBUG_FLAGS;
1475
1476     PERL_ARGS_ASSERT_SCAN_COMMIT;
1477
1478     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1479         const U8 i = data->cur_is_floating;
1480         SvSetMagicSV(longest_sv, data->last_found);
1481         data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1482
1483         if (!i) /* fixed */
1484             data->substrs[0].max_offset = data->substrs[0].min_offset;
1485         else { /* float */
1486             data->substrs[1].max_offset =
1487                       (is_inf)
1488                        ? OPTIMIZE_INFTY
1489                        : (l
1490                           ? data->last_start_max
1491                           /* temporary underflow guard for 5.32 */
1492                           : data->pos_delta < 0 ? OPTIMIZE_INFTY
1493                           : (data->pos_delta > OPTIMIZE_INFTY - data->pos_min
1494                                          ? OPTIMIZE_INFTY
1495                                          : data->pos_min + data->pos_delta));
1496         }
1497
1498         data->substrs[i].flags &= ~SF_BEFORE_EOL;
1499         data->substrs[i].flags |= data->flags & SF_BEFORE_EOL;
1500         data->substrs[i].minlenp = minlenp;
1501         data->substrs[i].lookbehind = 0;
1502     }
1503
1504     SvCUR_set(data->last_found, 0);
1505     {
1506         SV * const sv = data->last_found;
1507         if (SvUTF8(sv) && SvMAGICAL(sv)) {
1508             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1509             if (mg)
1510                 mg->mg_len = 0;
1511         }
1512     }
1513     data->last_end = -1;
1514     data->flags &= ~SF_BEFORE_EOL;
1515     DEBUG_STUDYDATA("commit", data, 0, is_inf);
1516 }
1517
1518 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1519  * list that describes which code points it matches */
1520
1521 STATIC void
1522 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1523 {
1524     /* Set the SSC 'ssc' to match an empty string or any code point */
1525
1526     PERL_ARGS_ASSERT_SSC_ANYTHING;
1527
1528     assert(is_ANYOF_SYNTHETIC(ssc));
1529
1530     /* mortalize so won't leak */
1531     ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1532     ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING;  /* Plus matches empty */
1533 }
1534
1535 STATIC int
1536 S_ssc_is_anything(const regnode_ssc *ssc)
1537 {
1538     /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1539      * point; FALSE otherwise.  Thus, this is used to see if using 'ssc' buys
1540      * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1541      * in any way, so there's no point in using it */
1542
1543     UV start, end;
1544     bool ret;
1545
1546     PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1547
1548     assert(is_ANYOF_SYNTHETIC(ssc));
1549
1550     if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1551         return FALSE;
1552     }
1553
1554     /* See if the list consists solely of the range 0 - Infinity */
1555     invlist_iterinit(ssc->invlist);
1556     ret = invlist_iternext(ssc->invlist, &start, &end)
1557           && start == 0
1558           && end == UV_MAX;
1559
1560     invlist_iterfinish(ssc->invlist);
1561
1562     if (ret) {
1563         return TRUE;
1564     }
1565
1566     /* If e.g., both \w and \W are set, matches everything */
1567     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1568         int i;
1569         for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1570             if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1571                 return TRUE;
1572             }
1573         }
1574     }
1575
1576     return FALSE;
1577 }
1578
1579 STATIC void
1580 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1581 {
1582     /* Initializes the SSC 'ssc'.  This includes setting it to match an empty
1583      * string, any code point, or any posix class under locale */
1584
1585     PERL_ARGS_ASSERT_SSC_INIT;
1586
1587     Zero(ssc, 1, regnode_ssc);
1588     set_ANYOF_SYNTHETIC(ssc);
1589     ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1590     ssc_anything(ssc);
1591
1592     /* If any portion of the regex is to operate under locale rules that aren't
1593      * fully known at compile time, initialization includes it.  The reason
1594      * this isn't done for all regexes is that the optimizer was written under
1595      * the assumption that locale was all-or-nothing.  Given the complexity and
1596      * lack of documentation in the optimizer, and that there are inadequate
1597      * test cases for locale, many parts of it may not work properly, it is
1598      * safest to avoid locale unless necessary. */
1599     if (RExC_contains_locale) {
1600         ANYOF_POSIXL_SETALL(ssc);
1601     }
1602     else {
1603         ANYOF_POSIXL_ZERO(ssc);
1604     }
1605 }
1606
1607 STATIC int
1608 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1609                         const regnode_ssc *ssc)
1610 {
1611     /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1612      * to the list of code points matched, and locale posix classes; hence does
1613      * not check its flags) */
1614
1615     UV start, end;
1616     bool ret;
1617
1618     PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1619
1620     assert(is_ANYOF_SYNTHETIC(ssc));
1621
1622     invlist_iterinit(ssc->invlist);
1623     ret = invlist_iternext(ssc->invlist, &start, &end)
1624           && start == 0
1625           && end == UV_MAX;
1626
1627     invlist_iterfinish(ssc->invlist);
1628
1629     if (! ret) {
1630         return FALSE;
1631     }
1632
1633     if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1634         return FALSE;
1635     }
1636
1637     return TRUE;
1638 }
1639
1640 #define INVLIST_INDEX 0
1641 #define ONLY_LOCALE_MATCHES_INDEX 1
1642 #define DEFERRED_USER_DEFINED_INDEX 2
1643
1644 STATIC SV*
1645 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1646                                const regnode_charclass* const node)
1647 {
1648     /* Returns a mortal inversion list defining which code points are matched
1649      * by 'node', which is of type ANYOF.  Handles complementing the result if
1650      * appropriate.  If some code points aren't knowable at this time, the
1651      * returned list must, and will, contain every code point that is a
1652      * possibility. */
1653
1654     SV* invlist = NULL;
1655     SV* only_utf8_locale_invlist = NULL;
1656     unsigned int i;
1657     const U32 n = ARG(node);
1658     bool new_node_has_latin1 = FALSE;
1659     const U8 flags = (inRANGE(OP(node), ANYOFH, ANYOFRb))
1660                       ? 0
1661                       : ANYOF_FLAGS(node);
1662
1663     PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1664
1665     /* Look at the data structure created by S_set_ANYOF_arg() */
1666     if (n != ANYOF_ONLY_HAS_BITMAP) {
1667         SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1668         AV * const av = MUTABLE_AV(SvRV(rv));
1669         SV **const ary = AvARRAY(av);
1670         assert(RExC_rxi->data->what[n] == 's');
1671
1672         if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1673
1674             /* Here there are things that won't be known until runtime -- we
1675              * have to assume it could be anything */
1676             invlist = sv_2mortal(_new_invlist(1));
1677             return _add_range_to_invlist(invlist, 0, UV_MAX);
1678         }
1679         else if (ary[INVLIST_INDEX]) {
1680
1681             /* Use the node's inversion list */
1682             invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1683         }
1684
1685         /* Get the code points valid only under UTF-8 locales */
1686         if (   (flags & ANYOFL_FOLD)
1687             &&  av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1688         {
1689             only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1690         }
1691     }
1692
1693     if (! invlist) {
1694         invlist = sv_2mortal(_new_invlist(0));
1695     }
1696
1697     /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1698      * code points, and an inversion list for the others, but if there are code
1699      * points that should match only conditionally on the target string being
1700      * UTF-8, those are placed in the inversion list, and not the bitmap.
1701      * Since there are circumstances under which they could match, they are
1702      * included in the SSC.  But if the ANYOF node is to be inverted, we have
1703      * to exclude them here, so that when we invert below, the end result
1704      * actually does include them.  (Think about "\xe0" =~ /[^\xc0]/di;).  We
1705      * have to do this here before we add the unconditionally matched code
1706      * points */
1707     if (flags & ANYOF_INVERT) {
1708         _invlist_intersection_complement_2nd(invlist,
1709                                              PL_UpperLatin1,
1710                                              &invlist);
1711     }
1712
1713     /* Add in the points from the bit map */
1714     if (! inRANGE(OP(node), ANYOFH, ANYOFRb)) {
1715         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1716             if (ANYOF_BITMAP_TEST(node, i)) {
1717                 unsigned int start = i++;
1718
1719                 for (;    i < NUM_ANYOF_CODE_POINTS
1720                        && ANYOF_BITMAP_TEST(node, i); ++i)
1721                 {
1722                     /* empty */
1723                 }
1724                 invlist = _add_range_to_invlist(invlist, start, i-1);
1725                 new_node_has_latin1 = TRUE;
1726             }
1727         }
1728     }
1729
1730     /* If this can match all upper Latin1 code points, have to add them
1731      * as well.  But don't add them if inverting, as when that gets done below,
1732      * it would exclude all these characters, including the ones it shouldn't
1733      * that were added just above */
1734     if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD
1735         && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1736     {
1737         _invlist_union(invlist, PL_UpperLatin1, &invlist);
1738     }
1739
1740     /* Similarly for these */
1741     if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1742         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1743     }
1744
1745     if (flags & ANYOF_INVERT) {
1746         _invlist_invert(invlist);
1747     }
1748     else if (flags & ANYOFL_FOLD) {
1749         if (new_node_has_latin1) {
1750
1751             /* Under /li, any 0-255 could fold to any other 0-255, depending on
1752              * the locale.  We can skip this if there are no 0-255 at all. */
1753             _invlist_union(invlist, PL_Latin1, &invlist);
1754
1755             invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1756             invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1757         }
1758         else {
1759             if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1760                 invlist = add_cp_to_invlist(invlist, 'I');
1761             }
1762             if (_invlist_contains_cp(invlist,
1763                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1764             {
1765                 invlist = add_cp_to_invlist(invlist, 'i');
1766             }
1767         }
1768     }
1769
1770     /* Similarly add the UTF-8 locale possible matches.  These have to be
1771      * deferred until after the non-UTF-8 locale ones are taken care of just
1772      * above, or it leads to wrong results under ANYOF_INVERT */
1773     if (only_utf8_locale_invlist) {
1774         _invlist_union_maybe_complement_2nd(invlist,
1775                                             only_utf8_locale_invlist,
1776                                             flags & ANYOF_INVERT,
1777                                             &invlist);
1778     }
1779
1780     return invlist;
1781 }
1782
1783 /* These two functions currently do the exact same thing */
1784 #define ssc_init_zero           ssc_init
1785
1786 #define ssc_add_cp(ssc, cp)   ssc_add_range((ssc), (cp), (cp))
1787 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1788
1789 /* 'AND' a given class with another one.  Can create false positives.  'ssc'
1790  * should not be inverted.  'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1791  * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1792
1793 STATIC void
1794 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1795                 const regnode_charclass *and_with)
1796 {
1797     /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1798      * another SSC or a regular ANYOF class.  Can create false positives. */
1799
1800     SV* anded_cp_list;
1801     U8  and_with_flags = inRANGE(OP(and_with), ANYOFH, ANYOFRb)
1802                           ? 0
1803                           : ANYOF_FLAGS(and_with);
1804     U8  anded_flags;
1805
1806     PERL_ARGS_ASSERT_SSC_AND;
1807
1808     assert(is_ANYOF_SYNTHETIC(ssc));
1809
1810     /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1811      * the code point inversion list and just the relevant flags */
1812     if (is_ANYOF_SYNTHETIC(and_with)) {
1813         anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1814         anded_flags = and_with_flags;
1815
1816         /* XXX This is a kludge around what appears to be deficiencies in the
1817          * optimizer.  If we make S_ssc_anything() add in the WARN_SUPER flag,
1818          * there are paths through the optimizer where it doesn't get weeded
1819          * out when it should.  And if we don't make some extra provision for
1820          * it like the code just below, it doesn't get added when it should.
1821          * This solution is to add it only when AND'ing, which is here, and
1822          * only when what is being AND'ed is the pristine, original node
1823          * matching anything.  Thus it is like adding it to ssc_anything() but
1824          * only when the result is to be AND'ed.  Probably the same solution
1825          * could be adopted for the same problem we have with /l matching,
1826          * which is solved differently in S_ssc_init(), and that would lead to
1827          * fewer false positives than that solution has.  But if this solution
1828          * creates bugs, the consequences are only that a warning isn't raised
1829          * that should be; while the consequences for having /l bugs is
1830          * incorrect matches */
1831         if (ssc_is_anything((regnode_ssc *)and_with)) {
1832             anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1833         }
1834     }
1835     else {
1836         anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1837         if (OP(and_with) == ANYOFD) {
1838             anded_flags = and_with_flags & ANYOF_COMMON_FLAGS;
1839         }
1840         else {
1841             anded_flags = and_with_flags
1842             &( ANYOF_COMMON_FLAGS
1843               |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1844               |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1845             if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) {
1846                 anded_flags &=
1847                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1848             }
1849         }
1850     }
1851
1852     ANYOF_FLAGS(ssc) &= anded_flags;
1853
1854     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1855      * C2 is the list of code points in 'and-with'; P2, its posix classes.
1856      * 'and_with' may be inverted.  When not inverted, we have the situation of
1857      * computing:
1858      *  (C1 | P1) & (C2 | P2)
1859      *                     =  (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1860      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1861      *                    <=  ((C1 & C2) |       P2)) | ( P1       | (P1 & P2))
1862      *                    <=  ((C1 & C2) | P1 | P2)
1863      * Alternatively, the last few steps could be:
1864      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1865      *                    <=  ((C1 & C2) |  C1      ) | (      C2  | (P1 & P2))
1866      *                    <=  (C1 | C2 | (P1 & P2))
1867      * We favor the second approach if either P1 or P2 is non-empty.  This is
1868      * because these components are a barrier to doing optimizations, as what
1869      * they match cannot be known until the moment of matching as they are
1870      * dependent on the current locale, 'AND"ing them likely will reduce or
1871      * eliminate them.
1872      * But we can do better if we know that C1,P1 are in their initial state (a
1873      * frequent occurrence), each matching everything:
1874      *  (<everything>) & (C2 | P2) =  C2 | P2
1875      * Similarly, if C2,P2 are in their initial state (again a frequent
1876      * occurrence), the result is a no-op
1877      *  (C1 | P1) & (<everything>) =  C1 | P1
1878      *
1879      * Inverted, we have
1880      *  (C1 | P1) & ~(C2 | P2)  =  (C1 | P1) & (~C2 & ~P2)
1881      *                          =  (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1882      *                         <=  (C1 & ~C2) | (P1 & ~P2)
1883      * */
1884
1885     if ((and_with_flags & ANYOF_INVERT)
1886         && ! is_ANYOF_SYNTHETIC(and_with))
1887     {
1888         unsigned int i;
1889
1890         ssc_intersection(ssc,
1891                          anded_cp_list,
1892                          FALSE /* Has already been inverted */
1893                          );
1894
1895         /* If either P1 or P2 is empty, the intersection will be also; can skip
1896          * the loop */
1897         if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) {
1898             ANYOF_POSIXL_ZERO(ssc);
1899         }
1900         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1901
1902             /* Note that the Posix class component P from 'and_with' actually
1903              * looks like:
1904              *      P = Pa | Pb | ... | Pn
1905              * where each component is one posix class, such as in [\w\s].
1906              * Thus
1907              *      ~P = ~(Pa | Pb | ... | Pn)
1908              *         = ~Pa & ~Pb & ... & ~Pn
1909              *        <= ~Pa | ~Pb | ... | ~Pn
1910              * The last is something we can easily calculate, but unfortunately
1911              * is likely to have many false positives.  We could do better
1912              * in some (but certainly not all) instances if two classes in
1913              * P have known relationships.  For example
1914              *      :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1915              * So
1916              *      :lower: & :print: = :lower:
1917              * And similarly for classes that must be disjoint.  For example,
1918              * since \s and \w can have no elements in common based on rules in
1919              * the POSIX standard,
1920              *      \w & ^\S = nothing
1921              * Unfortunately, some vendor locales do not meet the Posix
1922              * standard, in particular almost everything by Microsoft.
1923              * The loop below just changes e.g., \w into \W and vice versa */
1924
1925             regnode_charclass_posixl temp;
1926             int add = 1;    /* To calculate the index of the complement */
1927
1928             Zero(&temp, 1, regnode_charclass_posixl);
1929             ANYOF_POSIXL_ZERO(&temp);
1930             for (i = 0; i < ANYOF_MAX; i++) {
1931                 assert(i % 2 != 0
1932                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1933                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1934
1935                 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1936                     ANYOF_POSIXL_SET(&temp, i + add);
1937                 }
1938                 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1939             }
1940             ANYOF_POSIXL_AND(&temp, ssc);
1941
1942         } /* else ssc already has no posixes */
1943     } /* else: Not inverted.  This routine is a no-op if 'and_with' is an SSC
1944          in its initial state */
1945     else if (! is_ANYOF_SYNTHETIC(and_with)
1946              || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1947     {
1948         /* But if 'ssc' is in its initial state, the result is just 'and_with';
1949          * copy it over 'ssc' */
1950         if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1951             if (is_ANYOF_SYNTHETIC(and_with)) {
1952                 StructCopy(and_with, ssc, regnode_ssc);
1953             }
1954             else {
1955                 ssc->invlist = anded_cp_list;
1956                 ANYOF_POSIXL_ZERO(ssc);
1957                 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1958                     ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1959                 }
1960             }
1961         }
1962         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1963                  || (and_with_flags & ANYOF_MATCHES_POSIXL))
1964         {
1965             /* One or the other of P1, P2 is non-empty. */
1966             if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1967                 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1968             }
1969             ssc_union(ssc, anded_cp_list, FALSE);
1970         }
1971         else { /* P1 = P2 = empty */
1972             ssc_intersection(ssc, anded_cp_list, FALSE);
1973         }
1974     }
1975 }
1976
1977 STATIC void
1978 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1979                const regnode_charclass *or_with)
1980 {
1981     /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1982      * another SSC or a regular ANYOF class.  Can create false positives if
1983      * 'or_with' is to be inverted. */
1984
1985     SV* ored_cp_list;
1986     U8 ored_flags;
1987     U8  or_with_flags = inRANGE(OP(or_with), ANYOFH, ANYOFRb)
1988                          ? 0
1989                          : ANYOF_FLAGS(or_with);
1990
1991     PERL_ARGS_ASSERT_SSC_OR;
1992
1993     assert(is_ANYOF_SYNTHETIC(ssc));
1994
1995     /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1996      * the code point inversion list and just the relevant flags */
1997     if (is_ANYOF_SYNTHETIC(or_with)) {
1998         ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1999         ored_flags = or_with_flags;
2000     }
2001     else {
2002         ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
2003         ored_flags = or_with_flags & ANYOF_COMMON_FLAGS;
2004         if (OP(or_with) != ANYOFD) {
2005             ored_flags
2006             |= or_with_flags
2007              & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2008                 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
2009             if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) {
2010                 ored_flags |=
2011                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
2012             }
2013         }
2014     }
2015
2016     ANYOF_FLAGS(ssc) |= ored_flags;
2017
2018     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
2019      * C2 is the list of code points in 'or-with'; P2, its posix classes.
2020      * 'or_with' may be inverted.  When not inverted, we have the simple
2021      * situation of computing:
2022      *  (C1 | P1) | (C2 | P2)  =  (C1 | C2) | (P1 | P2)
2023      * If P1|P2 yields a situation with both a class and its complement are
2024      * set, like having both \w and \W, this matches all code points, and we
2025      * can delete these from the P component of the ssc going forward.  XXX We
2026      * might be able to delete all the P components, but I (khw) am not certain
2027      * about this, and it is better to be safe.
2028      *
2029      * Inverted, we have
2030      *  (C1 | P1) | ~(C2 | P2)  =  (C1 | P1) | (~C2 & ~P2)
2031      *                         <=  (C1 | P1) | ~C2
2032      *                         <=  (C1 | ~C2) | P1
2033      * (which results in actually simpler code than the non-inverted case)
2034      * */
2035
2036     if ((or_with_flags & ANYOF_INVERT)
2037         && ! is_ANYOF_SYNTHETIC(or_with))
2038     {
2039         /* We ignore P2, leaving P1 going forward */
2040     }   /* else  Not inverted */
2041     else if (or_with_flags & ANYOF_MATCHES_POSIXL) {
2042         ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
2043         if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2044             unsigned int i;
2045             for (i = 0; i < ANYOF_MAX; i += 2) {
2046                 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
2047                 {
2048                     ssc_match_all_cp(ssc);
2049                     ANYOF_POSIXL_CLEAR(ssc, i);
2050                     ANYOF_POSIXL_CLEAR(ssc, i+1);
2051                 }
2052             }
2053         }
2054     }
2055
2056     ssc_union(ssc,
2057               ored_cp_list,
2058               FALSE /* Already has been inverted */
2059               );
2060 }
2061
2062 STATIC void
2063 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
2064 {
2065     PERL_ARGS_ASSERT_SSC_UNION;
2066
2067     assert(is_ANYOF_SYNTHETIC(ssc));
2068
2069     _invlist_union_maybe_complement_2nd(ssc->invlist,
2070                                         invlist,
2071                                         invert2nd,
2072                                         &ssc->invlist);
2073 }
2074
2075 STATIC void
2076 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
2077                          SV* const invlist,
2078                          const bool invert2nd)
2079 {
2080     PERL_ARGS_ASSERT_SSC_INTERSECTION;
2081
2082     assert(is_ANYOF_SYNTHETIC(ssc));
2083
2084     _invlist_intersection_maybe_complement_2nd(ssc->invlist,
2085                                                invlist,
2086                                                invert2nd,
2087                                                &ssc->invlist);
2088 }
2089
2090 STATIC void
2091 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
2092 {
2093     PERL_ARGS_ASSERT_SSC_ADD_RANGE;
2094
2095     assert(is_ANYOF_SYNTHETIC(ssc));
2096
2097     ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
2098 }
2099
2100 STATIC void
2101 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2102 {
2103     /* AND just the single code point 'cp' into the SSC 'ssc' */
2104
2105     SV* cp_list = _new_invlist(2);
2106
2107     PERL_ARGS_ASSERT_SSC_CP_AND;
2108
2109     assert(is_ANYOF_SYNTHETIC(ssc));
2110
2111     cp_list = add_cp_to_invlist(cp_list, cp);
2112     ssc_intersection(ssc, cp_list,
2113                      FALSE /* Not inverted */
2114                      );
2115     SvREFCNT_dec_NN(cp_list);
2116 }
2117
2118 STATIC void
2119 S_ssc_clear_locale(regnode_ssc *ssc)
2120 {
2121     /* Set the SSC 'ssc' to not match any locale things */
2122     PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2123
2124     assert(is_ANYOF_SYNTHETIC(ssc));
2125
2126     ANYOF_POSIXL_ZERO(ssc);
2127     ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2128 }
2129
2130 STATIC bool
2131 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2132 {
2133     /* The synthetic start class is used to hopefully quickly winnow down
2134      * places where a pattern could start a match in the target string.  If it
2135      * doesn't really narrow things down that much, there isn't much point to
2136      * having the overhead of using it.  This function uses some very crude
2137      * heuristics to decide if to use the ssc or not.
2138      *
2139      * It returns TRUE if 'ssc' rules out more than half what it considers to
2140      * be the "likely" possible matches, but of course it doesn't know what the
2141      * actual things being matched are going to be; these are only guesses
2142      *
2143      * For /l matches, it assumes that the only likely matches are going to be
2144      *      in the 0-255 range, uniformly distributed, so half of that is 127
2145      * For /a and /d matches, it assumes that the likely matches will be just
2146      *      the ASCII range, so half of that is 63
2147      * For /u and there isn't anything matching above the Latin1 range, it
2148      *      assumes that that is the only range likely to be matched, and uses
2149      *      half that as the cut-off: 127.  If anything matches above Latin1,
2150      *      it assumes that all of Unicode could match (uniformly), except for
2151      *      non-Unicode code points and things in the General Category "Other"
2152      *      (unassigned, private use, surrogates, controls and formats).  This
2153      *      is a much large number. */
2154
2155     U32 count = 0;      /* Running total of number of code points matched by
2156                            'ssc' */
2157     UV start, end;      /* Start and end points of current range in inversion
2158                            XXX outdated.  UTF-8 locales are common, what about invert? list */
2159     const U32 max_code_points = (LOC)
2160                                 ?  256
2161                                 : ((  ! UNI_SEMANTICS
2162                                     ||  invlist_highest(ssc->invlist) < 256)
2163                                   ? 128
2164                                   : NON_OTHER_COUNT);
2165     const U32 max_match = max_code_points / 2;
2166
2167     PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2168
2169     invlist_iterinit(ssc->invlist);
2170     while (invlist_iternext(ssc->invlist, &start, &end)) {
2171         if (start >= max_code_points) {
2172             break;
2173         }
2174         end = MIN(end, max_code_points - 1);
2175         count += end - start + 1;
2176         if (count >= max_match) {
2177             invlist_iterfinish(ssc->invlist);
2178             return FALSE;
2179         }
2180     }
2181
2182     return TRUE;
2183 }
2184
2185
2186 STATIC void
2187 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2188 {
2189     /* The inversion list in the SSC is marked mortal; now we need a more
2190      * permanent copy, which is stored the same way that is done in a regular
2191      * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2192      * map */
2193
2194     SV* invlist = invlist_clone(ssc->invlist, NULL);
2195
2196     PERL_ARGS_ASSERT_SSC_FINALIZE;
2197
2198     assert(is_ANYOF_SYNTHETIC(ssc));
2199
2200     /* The code in this file assumes that all but these flags aren't relevant
2201      * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2202      * by the time we reach here */
2203     assert(! (ANYOF_FLAGS(ssc)
2204         & ~( ANYOF_COMMON_FLAGS
2205             |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2206             |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2207
2208     populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2209
2210     set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2211     SvREFCNT_dec(invlist);
2212
2213     /* Make sure is clone-safe */
2214     ssc->invlist = NULL;
2215
2216     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2217         ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2218         OP(ssc) = ANYOFPOSIXL;
2219     }
2220     else if (RExC_contains_locale) {
2221         OP(ssc) = ANYOFL;
2222     }
2223
2224     assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2225 }
2226
2227 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2228 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
2229 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2230 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list         \
2231                                ? (TRIE_LIST_CUR( idx ) - 1)           \
2232                                : 0 )
2233
2234
2235 #ifdef DEBUGGING
2236 /*
2237    dump_trie(trie,widecharmap,revcharmap)
2238    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2239    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2240
2241    These routines dump out a trie in a somewhat readable format.
2242    The _interim_ variants are used for debugging the interim
2243    tables that are used to generate the final compressed
2244    representation which is what dump_trie expects.
2245
2246    Part of the reason for their existence is to provide a form
2247    of documentation as to how the different representations function.
2248
2249 */
2250
2251 /*
2252   Dumps the final compressed table form of the trie to Perl_debug_log.
2253   Used for debugging make_trie().
2254 */
2255
2256 STATIC void
2257 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2258             AV *revcharmap, U32 depth)
2259 {
2260     U32 state;
2261     SV *sv=sv_newmortal();
2262     int colwidth= widecharmap ? 6 : 4;
2263     U16 word;
2264     DECLARE_AND_GET_RE_DEBUG_FLAGS;
2265
2266     PERL_ARGS_ASSERT_DUMP_TRIE;
2267
2268     Perl_re_indentf( aTHX_  "Char : %-6s%-6s%-4s ",
2269         depth+1, "Match","Base","Ofs" );
2270
2271     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2272         SV ** const tmp = av_fetch( revcharmap, state, 0);
2273         if ( tmp ) {
2274             Perl_re_printf( aTHX_  "%*s",
2275                 colwidth,
2276                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2277                             PL_colors[0], PL_colors[1],
2278                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2279                             PERL_PV_ESCAPE_FIRSTCHAR
2280                 )
2281             );
2282         }
2283     }
2284     Perl_re_printf( aTHX_  "\n");
2285     Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2286
2287     for( state = 0 ; state < trie->uniquecharcount ; state++ )
2288         Perl_re_printf( aTHX_  "%.*s", colwidth, "--------");
2289     Perl_re_printf( aTHX_  "\n");
2290
2291     for( state = 1 ; state < trie->statecount ; state++ ) {
2292         const U32 base = trie->states[ state ].trans.base;
2293
2294         Perl_re_indentf( aTHX_  "#%4" UVXf "|", depth+1, (UV)state);
2295
2296         if ( trie->states[ state ].wordnum ) {
2297             Perl_re_printf( aTHX_  " W%4X", trie->states[ state ].wordnum );
2298         } else {
2299             Perl_re_printf( aTHX_  "%6s", "" );
2300         }
2301
2302         Perl_re_printf( aTHX_  " @%4" UVXf " ", (UV)base );
2303
2304         if ( base ) {
2305             U32 ofs = 0;
2306
2307             while( ( base + ofs  < trie->uniquecharcount ) ||
2308                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
2309                      && trie->trans[ base + ofs - trie->uniquecharcount ].check
2310                                                                     != state))
2311                     ofs++;
2312
2313             Perl_re_printf( aTHX_  "+%2" UVXf "[ ", (UV)ofs);
2314
2315             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2316                 if ( ( base + ofs >= trie->uniquecharcount )
2317                         && ( base + ofs - trie->uniquecharcount
2318                                                         < trie->lasttrans )
2319                         && trie->trans[ base + ofs
2320                                     - trie->uniquecharcount ].check == state )
2321                 {
2322                    Perl_re_printf( aTHX_  "%*" UVXf, colwidth,
2323                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2324                    );
2325                 } else {
2326                     Perl_re_printf( aTHX_  "%*s", colwidth,"   ." );
2327                 }
2328             }
2329
2330             Perl_re_printf( aTHX_  "]");
2331
2332         }
2333         Perl_re_printf( aTHX_  "\n" );
2334     }
2335     Perl_re_indentf( aTHX_  "word_info N:(prev,len)=",
2336                                 depth);
2337     for (word=1; word <= trie->wordcount; word++) {
2338         Perl_re_printf( aTHX_  " %d:(%d,%d)",
2339             (int)word, (int)(trie->wordinfo[word].prev),
2340             (int)(trie->wordinfo[word].len));
2341     }
2342     Perl_re_printf( aTHX_  "\n" );
2343 }
2344 /*
2345   Dumps a fully constructed but uncompressed trie in list form.
2346   List tries normally only are used for construction when the number of
2347   possible chars (trie->uniquecharcount) is very high.
2348   Used for debugging make_trie().
2349 */
2350 STATIC void
2351 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2352                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
2353                          U32 depth)
2354 {
2355     U32 state;
2356     SV *sv=sv_newmortal();
2357     int colwidth= widecharmap ? 6 : 4;
2358     DECLARE_AND_GET_RE_DEBUG_FLAGS;
2359
2360     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2361
2362     /* print out the table precompression.  */
2363     Perl_re_indentf( aTHX_  "State :Word | Transition Data\n",
2364             depth+1 );
2365     Perl_re_indentf( aTHX_  "%s",
2366             depth+1, "------:-----+-----------------\n" );
2367
2368     for( state=1 ; state < next_alloc ; state ++ ) {
2369         U16 charid;
2370
2371         Perl_re_indentf( aTHX_  " %4" UVXf " :",
2372             depth+1, (UV)state  );
2373         if ( ! trie->states[ state ].wordnum ) {
2374             Perl_re_printf( aTHX_  "%5s| ","");
2375         } else {
2376             Perl_re_printf( aTHX_  "W%4x| ",
2377                 trie->states[ state ].wordnum
2378             );
2379         }
2380         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2381             SV ** const tmp = av_fetch( revcharmap,
2382                                         TRIE_LIST_ITEM(state, charid).forid, 0);
2383             if ( tmp ) {
2384                 Perl_re_printf( aTHX_  "%*s:%3X=%4" UVXf " | ",
2385                     colwidth,
2386                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2387                               colwidth,
2388                               PL_colors[0], PL_colors[1],
2389                               (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2390                               | PERL_PV_ESCAPE_FIRSTCHAR
2391                     ) ,
2392                     TRIE_LIST_ITEM(state, charid).forid,
2393                     (UV)TRIE_LIST_ITEM(state, charid).newstate
2394                 );
2395                 if (!(charid % 10))
2396                     Perl_re_printf( aTHX_  "\n%*s| ",
2397                         (int)((depth * 2) + 14), "");
2398             }
2399         }
2400         Perl_re_printf( aTHX_  "\n");
2401     }
2402 }
2403
2404 /*
2405   Dumps a fully constructed but uncompressed trie in table form.
2406   This is the normal DFA style state transition table, with a few
2407   twists to facilitate compression later.
2408   Used for debugging make_trie().
2409 */
2410 STATIC void
2411 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2412                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
2413                           U32 depth)
2414 {
2415     U32 state;
2416     U16 charid;
2417     SV *sv=sv_newmortal();
2418     int colwidth= widecharmap ? 6 : 4;
2419     DECLARE_AND_GET_RE_DEBUG_FLAGS;
2420
2421     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2422
2423     /*
2424        print out the table precompression so that we can do a visual check
2425        that they are identical.
2426      */
2427
2428     Perl_re_indentf( aTHX_  "Char : ", depth+1 );
2429
2430     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2431         SV ** const tmp = av_fetch( revcharmap, charid, 0);
2432         if ( tmp ) {
2433             Perl_re_printf( aTHX_  "%*s",
2434                 colwidth,
2435                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2436                             PL_colors[0], PL_colors[1],
2437                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2438                             PERL_PV_ESCAPE_FIRSTCHAR
2439                 )
2440             );
2441         }
2442     }
2443
2444     Perl_re_printf( aTHX_ "\n");
2445     Perl_re_indentf( aTHX_  "State+-", depth+1 );
2446
2447     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2448         Perl_re_printf( aTHX_  "%.*s", colwidth,"--------");
2449     }
2450
2451     Perl_re_printf( aTHX_  "\n" );
2452
2453     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2454
2455         Perl_re_indentf( aTHX_  "%4" UVXf " : ",
2456             depth+1,
2457             (UV)TRIE_NODENUM( state ) );
2458
2459         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2460             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2461             if (v)
2462                 Perl_re_printf( aTHX_  "%*" UVXf, colwidth, v );
2463             else
2464                 Perl_re_printf( aTHX_  "%*s", colwidth, "." );
2465         }
2466         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2467             Perl_re_printf( aTHX_  " (%4" UVXf ")\n",
2468                                             (UV)trie->trans[ state ].check );
2469         } else {
2470             Perl_re_printf( aTHX_  " (%4" UVXf ") W%4X\n",
2471                                             (UV)trie->trans[ state ].check,
2472             trie->states[ TRIE_NODENUM( state ) ].wordnum );
2473         }
2474     }
2475 }
2476
2477 #endif
2478
2479
2480 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2481   startbranch: the first branch in the whole branch sequence
2482   first      : start branch of sequence of branch-exact nodes.
2483                May be the same as startbranch
2484   last       : Thing following the last branch.
2485                May be the same as tail.
2486   tail       : item following the branch sequence
2487   count      : words in the sequence
2488   flags      : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2489   depth      : indent depth
2490
2491 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2492
2493 A trie is an N'ary tree where the branches are determined by digital
2494 decomposition of the key. IE, at the root node you look up the 1st character and
2495 follow that branch repeat until you find the end of the branches. Nodes can be
2496 marked as "accepting" meaning they represent a complete word. Eg:
2497
2498   /he|she|his|hers/
2499
2500 would convert into the following structure. Numbers represent states, letters
2501 following numbers represent valid transitions on the letter from that state, if
2502 the number is in square brackets it represents an accepting state, otherwise it
2503 will be in parenthesis.
2504
2505       +-h->+-e->[3]-+-r->(8)-+-s->[9]
2506       |    |
2507       |   (2)
2508       |    |
2509      (1)   +-i->(6)-+-s->[7]
2510       |
2511       +-s->(3)-+-h->(4)-+-e->[5]
2512
2513       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2514
2515 This shows that when matching against the string 'hers' we will begin at state 1
2516 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2517 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2518 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2519 single traverse. We store a mapping from accepting to state to which word was
2520 matched, and then when we have multiple possibilities we try to complete the
2521 rest of the regex in the order in which they occurred in the alternation.
2522
2523 The only prior NFA like behaviour that would be changed by the TRIE support is
2524 the silent ignoring of duplicate alternations which are of the form:
2525
2526  / (DUPE|DUPE) X? (?{ ... }) Y /x
2527
2528 Thus EVAL blocks following a trie may be called a different number of times with
2529 and without the optimisation. With the optimisations dupes will be silently
2530 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2531 the following demonstrates:
2532
2533  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2534
2535 which prints out 'word' three times, but
2536
2537  'words'=~/(word|word|word)(?{ print $1 })S/
2538
2539 which doesnt print it out at all. This is due to other optimisations kicking in.
2540
2541 Example of what happens on a structural level:
2542
2543 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2544
2545    1: CURLYM[1] {1,32767}(18)
2546    5:   BRANCH(8)
2547    6:     EXACT <ac>(16)
2548    8:   BRANCH(11)
2549    9:     EXACT <ad>(16)
2550   11:   BRANCH(14)
2551   12:     EXACT <ab>(16)
2552   16:   SUCCEED(0)
2553   17:   NOTHING(18)
2554   18: END(0)
2555
2556 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2557 and should turn into:
2558
2559    1: CURLYM[1] {1,32767}(18)
2560    5:   TRIE(16)
2561         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2562           <ac>
2563           <ad>
2564           <ab>
2565   16:   SUCCEED(0)
2566   17:   NOTHING(18)
2567   18: END(0)
2568
2569 Cases where tail != last would be like /(?foo|bar)baz/:
2570
2571    1: BRANCH(4)
2572    2:   EXACT <foo>(8)
2573    4: BRANCH(7)
2574    5:   EXACT <bar>(8)
2575    7: TAIL(8)
2576    8: EXACT <baz>(10)
2577   10: END(0)
2578
2579 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2580 and would end up looking like:
2581
2582     1: TRIE(8)
2583       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2584         <foo>
2585         <bar>
2586    7: TAIL(8)
2587    8: EXACT <baz>(10)
2588   10: END(0)
2589
2590     d = uvchr_to_utf8_flags(d, uv, 0);
2591
2592 is the recommended Unicode-aware way of saying
2593
2594     *(d++) = uv;
2595 */
2596
2597 #define TRIE_STORE_REVCHAR(val)                                            \
2598     STMT_START {                                                           \
2599         if (UTF) {                                                         \
2600             SV *zlopp = newSV(UTF8_MAXBYTES);                              \
2601             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
2602             unsigned char *const kapow = uvchr_to_utf8(flrbbbbb, val);     \
2603             *kapow = '\0';                                                 \
2604             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
2605             SvPOK_on(zlopp);                                               \
2606             SvUTF8_on(zlopp);                                              \
2607             av_push(revcharmap, zlopp);                                    \
2608         } else {                                                           \
2609             char ooooff = (char)val;                                           \
2610             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
2611         }                                                                  \
2612         } STMT_END
2613
2614 /* This gets the next character from the input, folding it if not already
2615  * folded. */
2616 #define TRIE_READ_CHAR STMT_START {                                           \
2617     wordlen++;                                                                \
2618     if ( UTF ) {                                                              \
2619         /* if it is UTF then it is either already folded, or does not need    \
2620          * folding */                                                         \
2621         uvc = valid_utf8_to_uvchr( (const U8*) uc, &len);                     \
2622     }                                                                         \
2623     else if (folder == PL_fold_latin1) {                                      \
2624         /* This folder implies Unicode rules, which in the range expressible  \
2625          *  by not UTF is the lower case, with the two exceptions, one of     \
2626          *  which should have been taken care of before calling this */       \
2627         assert(*uc != LATIN_SMALL_LETTER_SHARP_S);                            \
2628         uvc = toLOWER_L1(*uc);                                                \
2629         if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU;         \
2630         len = 1;                                                              \
2631     } else {                                                                  \
2632         /* raw data, will be folded later if needed */                        \
2633         uvc = (U32)*uc;                                                       \
2634         len = 1;                                                              \
2635     }                                                                         \
2636 } STMT_END
2637
2638
2639
2640 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
2641     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
2642         U32 ging = TRIE_LIST_LEN( state ) * 2;                  \
2643         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2644         TRIE_LIST_LEN( state ) = ging;                          \
2645     }                                                           \
2646     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
2647     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
2648     TRIE_LIST_CUR( state )++;                                   \
2649 } STMT_END
2650
2651 #define TRIE_LIST_NEW(state) STMT_START {                       \
2652     Newx( trie->states[ state ].trans.list,                     \
2653         4, reg_trie_trans_le );                                 \
2654      TRIE_LIST_CUR( state ) = 1;                                \
2655      TRIE_LIST_LEN( state ) = 4;                                \
2656 } STMT_END
2657
2658 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
2659     U16 dupe= trie->states[ state ].wordnum;                    \
2660     regnode * const noper_next = regnext( noper );              \
2661                                                                 \
2662     DEBUG_r({                                                   \
2663         /* store the word for dumping */                        \
2664         SV* tmp;                                                \
2665         if (OP(noper) != NOTHING)                               \
2666             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
2667         else                                                    \
2668             tmp = newSVpvn_utf8( "", 0, UTF );                  \
2669         av_push( trie_words, tmp );                             \
2670     });                                                         \
2671                                                                 \
2672     curword++;                                                  \
2673     trie->wordinfo[curword].prev   = 0;                         \
2674     trie->wordinfo[curword].len    = wordlen;                   \
2675     trie->wordinfo[curword].accept = state;                     \
2676                                                                 \
2677     if ( noper_next < tail ) {                                  \
2678         if (!trie->jump)                                        \
2679             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2680                                                  sizeof(U16) ); \
2681         trie->jump[curword] = (U16)(noper_next - convert);      \
2682         if (!jumper)                                            \
2683             jumper = noper_next;                                \
2684         if (!nextbranch)                                        \
2685             nextbranch= regnext(cur);                           \
2686     }                                                           \
2687                                                                 \
2688     if ( dupe ) {                                               \
2689         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
2690         /* chain, so that when the bits of chain are later    */\
2691         /* linked together, the dups appear in the chain      */\
2692         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2693         trie->wordinfo[dupe].prev = curword;                    \
2694     } else {                                                    \
2695         /* we haven't inserted this word yet.                */ \
2696         trie->states[ state ].wordnum = curword;                \
2697     }                                                           \
2698 } STMT_END
2699
2700
2701 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
2702      ( ( base + charid >=  ucharcount                                   \
2703          && base + charid < ubound                                      \
2704          && state == trie->trans[ base - ucharcount + charid ].check    \
2705          && trie->trans[ base - ucharcount + charid ].next )            \
2706            ? trie->trans[ base - ucharcount + charid ].next             \
2707            : ( state==1 ? special : 0 )                                 \
2708       )
2709
2710 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder)           \
2711 STMT_START {                                                \
2712     TRIE_BITMAP_SET(trie, uvc);                             \
2713     /* store the folded codepoint */                        \
2714     if ( folder )                                           \
2715         TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);           \
2716                                                             \
2717     if ( !UTF ) {                                           \
2718         /* store first byte of utf8 representation of */    \
2719         /* variant codepoints */                            \
2720         if (! UVCHR_IS_INVARIANT(uvc)) {                    \
2721             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));   \
2722         }                                                   \
2723     }                                                       \
2724 } STMT_END
2725 #define MADE_TRIE       1
2726 #define MADE_JUMP_TRIE  2
2727 #define MADE_EXACT_TRIE 4
2728
2729 STATIC I32
2730 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2731                   regnode *first, regnode *last, regnode *tail,
2732                   U32 word_count, U32 flags, U32 depth)
2733 {
2734     /* first pass, loop through and scan words */
2735     reg_trie_data *trie;
2736     HV *widecharmap = NULL;
2737     AV *revcharmap = newAV();
2738     regnode *cur;
2739     STRLEN len = 0;
2740     UV uvc = 0;
2741     U16 curword = 0;
2742     U32 next_alloc = 0;
2743     regnode *jumper = NULL;
2744     regnode *nextbranch = NULL;
2745     regnode *convert = NULL;
2746     U32 *prev_states; /* temp array mapping each state to previous one */
2747     /* we just use folder as a flag in utf8 */
2748     const U8 * folder = NULL;
2749
2750     /* in the below add_data call we are storing either 'tu' or 'tuaa'
2751      * which stands for one trie structure, one hash, optionally followed
2752      * by two arrays */
2753 #ifdef DEBUGGING
2754     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2755     AV *trie_words = NULL;
2756     /* along with revcharmap, this only used during construction but both are
2757      * useful during debugging so we store them in the struct when debugging.
2758      */
2759 #else
2760     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2761     STRLEN trie_charcount=0;
2762 #endif
2763     SV *re_trie_maxbuff;
2764     DECLARE_AND_GET_RE_DEBUG_FLAGS;
2765
2766     PERL_ARGS_ASSERT_MAKE_TRIE;
2767 #ifndef DEBUGGING
2768     PERL_UNUSED_ARG(depth);
2769 #endif
2770
2771     switch (flags) {
2772         case EXACT: case EXACT_REQ8: case EXACTL: break;
2773         case EXACTFAA:
2774         case EXACTFUP:
2775         case EXACTFU:
2776         case EXACTFLU8: folder = PL_fold_latin1; break;
2777         case EXACTF:  folder = PL_fold; break;
2778         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2779     }
2780
2781     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2782     trie->refcount = 1;
2783     trie->startstate = 1;
2784     trie->wordcount = word_count;
2785     RExC_rxi->data->data[ data_slot ] = (void*)trie;
2786     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2787     if (flags == EXACT || flags == EXACT_REQ8 || flags == EXACTL)
2788         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2789     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2790                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
2791
2792     DEBUG_r({
2793         trie_words = newAV();
2794     });
2795
2796     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD);
2797     assert(re_trie_maxbuff);
2798     if (!SvIOK(re_trie_maxbuff)) {
2799         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2800     }
2801     DEBUG_TRIE_COMPILE_r({
2802         Perl_re_indentf( aTHX_
2803           "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2804           depth+1,
2805           REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2806           REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2807     });
2808
2809    /* Find the node we are going to overwrite */
2810     if ( first == startbranch && OP( last ) != BRANCH ) {
2811         /* whole branch chain */
2812         convert = first;
2813     } else {
2814         /* branch sub-chain */
2815         convert = NEXTOPER( first );
2816     }
2817
2818     /*  -- First loop and Setup --
2819
2820        We first traverse the branches and scan each word to determine if it
2821        contains widechars, and how many unique chars there are, this is
2822        important as we have to build a table with at least as many columns as we
2823        have unique chars.
2824
2825        We use an array of integers to represent the character codes 0..255
2826        (trie->charmap) and we use a an HV* to store Unicode characters. We use
2827        the native representation of the character value as the key and IV's for
2828        the coded index.
2829
2830        *TODO* If we keep track of how many times each character is used we can
2831        remap the columns so that the table compression later on is more
2832        efficient in terms of memory by ensuring the most common value is in the
2833        middle and the least common are on the outside.  IMO this would be better
2834        than a most to least common mapping as theres a decent chance the most
2835        common letter will share a node with the least common, meaning the node
2836        will not be compressible. With a middle is most common approach the worst
2837        case is when we have the least common nodes twice.
2838
2839      */
2840
2841     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2842         regnode *noper = NEXTOPER( cur );
2843         const U8 *uc;
2844         const U8 *e;
2845         int foldlen = 0;
2846         U32 wordlen      = 0;         /* required init */
2847         STRLEN minchars = 0;
2848         STRLEN maxchars = 0;
2849         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2850                                                bitmap?*/
2851
2852         if (OP(noper) == NOTHING) {
2853             /* skip past a NOTHING at the start of an alternation
2854              * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2855              *
2856              * If the next node is not something we are supposed to process
2857              * we will just ignore it due to the condition guarding the
2858              * next block.
2859              */
2860
2861             regnode *noper_next= regnext(noper);
2862             if (noper_next < tail)
2863                 noper= noper_next;
2864         }
2865
2866         if (    noper < tail
2867             && (    OP(noper) == flags
2868                 || (flags == EXACT && OP(noper) == EXACT_REQ8)
2869                 || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
2870                                          || OP(noper) == EXACTFUP))))
2871         {
2872             uc= (U8*)STRING(noper);
2873             e= uc + STR_LEN(noper);
2874         } else {
2875             trie->minlen= 0;
2876             continue;
2877         }
2878
2879
2880         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2881             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2882                                           regardless of encoding */
2883             if (OP( noper ) == EXACTFUP) {
2884                 /* false positives are ok, so just set this */
2885                 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2886             }
2887         }
2888
2889         for ( ; uc < e ; uc += len ) {  /* Look at each char in the current
2890                                            branch */
2891             TRIE_CHARCOUNT(trie)++;
2892             TRIE_READ_CHAR;
2893
2894             /* TRIE_READ_CHAR returns the current character, or its fold if /i
2895              * is in effect.  Under /i, this character can match itself, or
2896              * anything that folds to it.  If not under /i, it can match just
2897              * itself.  Most folds are 1-1, for example k, K, and KELVIN SIGN
2898              * all fold to k, and all are single characters.   But some folds
2899              * expand to more than one character, so for example LATIN SMALL
2900              * LIGATURE FFI folds to the three character sequence 'ffi'.  If
2901              * the string beginning at 'uc' is 'ffi', it could be matched by
2902              * three characters, or just by the one ligature character. (It
2903              * could also be matched by two characters: LATIN SMALL LIGATURE FF
2904              * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2905              * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2906              * match.)  The trie needs to know the minimum and maximum number
2907              * of characters that could match so that it can use size alone to
2908              * quickly reject many match attempts.  The max is simple: it is
2909              * the number of folded characters in this branch (since a fold is
2910              * never shorter than what folds to it. */
2911
2912             maxchars++;
2913
2914             /* And the min is equal to the max if not under /i (indicated by
2915              * 'folder' being NULL), or there are no multi-character folds.  If
2916              * there is a multi-character fold, the min is incremented just
2917              * once, for the character that folds to the sequence.  Each
2918              * character in the sequence needs to be added to the list below of
2919              * characters in the trie, but we count only the first towards the
2920              * min number of characters needed.  This is done through the
2921              * variable 'foldlen', which is returned by the macros that look
2922              * for these sequences as the number of bytes the sequence
2923              * occupies.  Each time through the loop, we decrement 'foldlen' by
2924              * how many bytes the current char occupies.  Only when it reaches
2925              * 0 do we increment 'minchars' or look for another multi-character
2926              * sequence. */
2927             if (folder == NULL) {
2928                 minchars++;
2929             }
2930             else if (foldlen > 0) {
2931                 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2932             }
2933             else {
2934                 minchars++;
2935
2936                 /* See if *uc is the beginning of a multi-character fold.  If
2937                  * so, we decrement the length remaining to look at, to account
2938                  * for the current character this iteration.  (We can use 'uc'
2939                  * instead of the fold returned by TRIE_READ_CHAR because the
2940                  * macro is smart enough to account for any unfolded
2941                  * characters. */
2942                 if (UTF) {
2943                     if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2944                         foldlen -= UTF8SKIP(uc);
2945                     }
2946                 }
2947                 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2948                     foldlen--;
2949                 }
2950             }
2951
2952             /* The current character (and any potential folds) should be added
2953              * to the possible matching characters for this position in this
2954              * branch */
2955             if ( uvc < 256 ) {
2956                 if ( folder ) {
2957                     U8 folded= folder[ (U8) uvc ];
2958                     if ( !trie->charmap[ folded ] ) {
2959                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
2960                         TRIE_STORE_REVCHAR( folded );
2961                     }
2962                 }
2963                 if ( !trie->charmap[ uvc ] ) {
2964                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2965                     TRIE_STORE_REVCHAR( uvc );
2966                 }
2967                 if ( set_bit ) {
2968                     /* store the codepoint in the bitmap, and its folded
2969                      * equivalent. */
2970                     TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2971                     set_bit = 0; /* We've done our bit :-) */
2972                 }
2973             } else {
2974
2975                 /* XXX We could come up with the list of code points that fold
2976                  * to this using PL_utf8_foldclosures, except not for
2977                  * multi-char folds, as there may be multiple combinations
2978                  * there that could work, which needs to wait until runtime to
2979                  * resolve (The comment about LIGATURE FFI above is such an
2980                  * example */
2981
2982                 SV** svpp;
2983                 if ( !widecharmap )
2984                     widecharmap = newHV();
2985
2986                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2987
2988                 if ( !svpp )
2989                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2990
2991                 if ( !SvTRUE( *svpp ) ) {
2992                     sv_setiv( *svpp, ++trie->uniquecharcount );
2993                     TRIE_STORE_REVCHAR(uvc);
2994                 }
2995             }
2996         } /* end loop through characters in this branch of the trie */
2997
2998         /* We take the min and max for this branch and combine to find the min
2999          * and max for all branches processed so far */
3000         if( cur == first ) {
3001             trie->minlen = minchars;
3002             trie->maxlen = maxchars;
3003         } else if (minchars < trie->minlen) {
3004             trie->minlen = minchars;
3005         } else if (maxchars > trie->maxlen) {
3006             trie->maxlen = maxchars;
3007         }
3008     } /* end first pass */
3009     DEBUG_TRIE_COMPILE_r(
3010         Perl_re_indentf( aTHX_
3011                 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
3012                 depth+1,
3013                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
3014                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
3015                 (int)trie->minlen, (int)trie->maxlen )
3016     );
3017
3018     /*
3019         We now know what we are dealing with in terms of unique chars and
3020         string sizes so we can calculate how much memory a naive
3021         representation using a flat table  will take. If it's over a reasonable
3022         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
3023         conservative but potentially much slower representation using an array
3024         of lists.
3025
3026         At the end we convert both representations into the same compressed
3027         form that will be used in regexec.c for matching with. The latter
3028         is a form that cannot be used to construct with but has memory
3029         properties similar to the list form and access properties similar
3030         to the table form making it both suitable for fast searches and
3031         small enough that its feasable to store for the duration of a program.
3032
3033         See the comment in the code where the compressed table is produced
3034         inplace from the flat tabe representation for an explanation of how
3035         the compression works.
3036
3037     */
3038
3039
3040     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
3041     prev_states[1] = 0;
3042
3043     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
3044                                                     > SvIV(re_trie_maxbuff) )
3045     {
3046         /*
3047             Second Pass -- Array Of Lists Representation
3048
3049             Each state will be represented by a list of charid:state records
3050             (reg_trie_trans_le) the first such element holds the CUR and LEN
3051             points of the allocated array. (See defines above).
3052
3053             We build the initial structure using the lists, and then convert
3054             it into the compressed table form which allows faster lookups
3055             (but cant be modified once converted).
3056         */
3057
3058         STRLEN transcount = 1;
3059
3060         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using list compiler\n",
3061             depth+1));
3062
3063         trie->states = (reg_trie_state *)
3064             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3065                                   sizeof(reg_trie_state) );
3066         TRIE_LIST_NEW(1);
3067         next_alloc = 2;
3068
3069         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3070
3071             regnode *noper   = NEXTOPER( cur );
3072             U32 state        = 1;         /* required init */
3073             U16 charid       = 0;         /* sanity init */
3074             U32 wordlen      = 0;         /* required init */
3075
3076             if (OP(noper) == NOTHING) {
3077                 regnode *noper_next= regnext(noper);
3078                 if (noper_next < tail)
3079                     noper= noper_next;
3080                 /* we will undo this assignment if noper does not
3081                  * point at a trieable type in the else clause of
3082                  * the following statement. */
3083             }
3084
3085             if (    noper < tail
3086                 && (    OP(noper) == flags
3087                     || (flags == EXACT && OP(noper) == EXACT_REQ8)
3088                     || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
3089                                              || OP(noper) == EXACTFUP))))
3090             {
3091                 const U8 *uc= (U8*)STRING(noper);
3092                 const U8 *e= uc + STR_LEN(noper);
3093
3094                 for ( ; uc < e ; uc += len ) {
3095
3096                     TRIE_READ_CHAR;
3097
3098                     if ( uvc < 256 ) {
3099                         charid = trie->charmap[ uvc ];
3100                     } else {
3101                         SV** const svpp = hv_fetch( widecharmap,
3102                                                     (char*)&uvc,
3103                                                     sizeof( UV ),
3104                                                     0);
3105                         if ( !svpp ) {
3106                             charid = 0;
3107                         } else {
3108                             charid=(U16)SvIV( *svpp );
3109                         }
3110                     }
3111                     /* charid is now 0 if we dont know the char read, or
3112                      * nonzero if we do */
3113                     if ( charid ) {
3114
3115                         U16 check;
3116                         U32 newstate = 0;
3117
3118                         charid--;
3119                         if ( !trie->states[ state ].trans.list ) {
3120                             TRIE_LIST_NEW( state );
3121                         }
3122                         for ( check = 1;
3123                               check <= TRIE_LIST_USED( state );
3124                               check++ )
3125                         {
3126                             if ( TRIE_LIST_ITEM( state, check ).forid
3127                                                                     == charid )
3128                             {
3129                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3130                                 break;
3131                             }
3132                         }
3133                         if ( ! newstate ) {
3134                             newstate = next_alloc++;
3135                             prev_states[newstate] = state;
3136                             TRIE_LIST_PUSH( state, charid, newstate );
3137                             transcount++;
3138                         }
3139                         state = newstate;
3140                     } else {
3141                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3142                     }
3143                 }
3144             } else {
3145                 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3146                  * on a trieable type. So we need to reset noper back to point at the first regop
3147                  * in the branch before we call TRIE_HANDLE_WORD()
3148                 */
3149                 noper= NEXTOPER(cur);
3150             }
3151             TRIE_HANDLE_WORD(state);
3152
3153         } /* end second pass */
3154
3155         /* next alloc is the NEXT state to be allocated */
3156         trie->statecount = next_alloc;
3157         trie->states = (reg_trie_state *)
3158             PerlMemShared_realloc( trie->states,
3159                                    next_alloc
3160                                    * sizeof(reg_trie_state) );
3161
3162         /* and now dump it out before we compress it */
3163         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3164                                                          revcharmap, next_alloc,
3165                                                          depth+1)
3166         );
3167
3168         trie->trans = (reg_trie_trans *)
3169             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3170         {
3171             U32 state;
3172             U32 tp = 0;
3173             U32 zp = 0;
3174
3175
3176             for( state=1 ; state < next_alloc ; state ++ ) {
3177                 U32 base=0;
3178
3179                 /*
3180                 DEBUG_TRIE_COMPILE_MORE_r(
3181                     Perl_re_printf( aTHX_  "tp: %d zp: %d ",tp,zp)
3182                 );
3183                 */
3184
3185                 if (trie->states[state].trans.list) {
3186                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3187                     U16 maxid=minid;
3188                     U16 idx;
3189
3190                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3191                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3192                         if ( forid < minid ) {
3193                             minid=forid;
3194                         } else if ( forid > maxid ) {
3195                             maxid=forid;
3196                         }
3197                     }
3198                     if ( transcount < tp + maxid - minid + 1) {
3199                         transcount *= 2;
3200                         trie->trans = (reg_trie_trans *)
3201                             PerlMemShared_realloc( trie->trans,
3202                                                      transcount
3203                                                      * sizeof(reg_trie_trans) );
3204                         Zero( trie->trans + (transcount / 2),
3205                               transcount / 2,
3206                               reg_trie_trans );
3207                     }
3208                     base = trie->uniquecharcount + tp - minid;
3209                     if ( maxid == minid ) {
3210                         U32 set = 0;
3211                         for ( ; zp < tp ; zp++ ) {
3212                             if ( ! trie->trans[ zp ].next ) {
3213                                 base = trie->uniquecharcount + zp - minid;
3214                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3215                                                                    1).newstate;
3216                                 trie->trans[ zp ].check = state;
3217                                 set = 1;
3218                                 break;
3219                             }
3220                         }
3221                         if ( !set ) {
3222                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3223                                                                    1).newstate;
3224                             trie->trans[ tp ].check = state;
3225                             tp++;
3226                             zp = tp;
3227                         }
3228                     } else {
3229                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3230                             const U32 tid = base
3231                                            - trie->uniquecharcount
3232                                            + TRIE_LIST_ITEM( state, idx ).forid;
3233                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3234                                                                 idx ).newstate;
3235                             trie->trans[ tid ].check = state;
3236                         }
3237                         tp += ( maxid - minid + 1 );
3238                     }
3239                     Safefree(trie->states[ state ].trans.list);
3240                 }
3241                 /*
3242                 DEBUG_TRIE_COMPILE_MORE_r(
3243                     Perl_re_printf( aTHX_  " base: %d\n",base);
3244                 );
3245                 */
3246                 trie->states[ state ].trans.base=base;
3247             }
3248             trie->lasttrans = tp + 1;
3249         }
3250     } else {
3251         /*
3252            Second Pass -- Flat Table Representation.
3253
3254            we dont use the 0 slot of either trans[] or states[] so we add 1 to
3255            each.  We know that we will need Charcount+1 trans at most to store
3256            the data (one row per char at worst case) So we preallocate both
3257            structures assuming worst case.
3258
3259            We then construct the trie using only the .next slots of the entry
3260            structs.
3261
3262            We use the .check field of the first entry of the node temporarily
3263            to make compression both faster and easier by keeping track of how
3264            many non zero fields are in the node.
3265
3266            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3267            transition.
3268
3269            There are two terms at use here: state as a TRIE_NODEIDX() which is
3270            a number representing the first entry of the node, and state as a
3271            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3272            and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3273            if there are 2 entrys per node. eg:
3274
3275              A B       A B
3276           1. 2 4    1. 3 7
3277           2. 0 3    3. 0 5
3278           3. 0 0    5. 0 0
3279           4. 0 0    7. 0 0
3280
3281            The table is internally in the right hand, idx form. However as we
3282            also have to deal with the states array which is indexed by nodenum
3283            we have to use TRIE_NODENUM() to convert.
3284
3285         */
3286         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using table compiler\n",
3287             depth+1));
3288
3289         trie->trans = (reg_trie_trans *)
3290             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3291                                   * trie->uniquecharcount + 1,
3292                                   sizeof(reg_trie_trans) );
3293         trie->states = (reg_trie_state *)
3294             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3295                                   sizeof(reg_trie_state) );
3296         next_alloc = trie->uniquecharcount + 1;
3297
3298
3299         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3300
3301             regnode *noper   = NEXTOPER( cur );
3302
3303             U32 state        = 1;         /* required init */
3304
3305             U16 charid       = 0;         /* sanity init */
3306             U32 accept_state = 0;         /* sanity init */
3307
3308             U32 wordlen      = 0;         /* required init */
3309
3310             if (OP(noper) == NOTHING) {
3311                 regnode *noper_next= regnext(noper);
3312                 if (noper_next < tail)
3313                     noper= noper_next;
3314                 /* we will undo this assignment if noper does not
3315                  * point at a trieable type in the else clause of
3316                  * the following statement. */
3317             }
3318
3319             if (    noper < tail
3320                 && (    OP(noper) == flags
3321                     || (flags == EXACT && OP(noper) == EXACT_REQ8)
3322                     || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
3323                                              || OP(noper) == EXACTFUP))))
3324             {
3325                 const U8 *uc= (U8*)STRING(noper);
3326                 const U8 *e= uc + STR_LEN(noper);
3327
3328                 for ( ; uc < e ; uc += len ) {
3329
3330                     TRIE_READ_CHAR;
3331
3332                     if ( uvc < 256 ) {
3333                         charid = trie->charmap[ uvc ];
3334                     } else {
3335                         SV* const * const svpp = hv_fetch( widecharmap,
3336                                                            (char*)&uvc,
3337                                                            sizeof( UV ),
3338                                                            0);
3339                         charid = svpp ? (U16)SvIV(*svpp) : 0;
3340                     }
3341                     if ( charid ) {
3342                         charid--;
3343                         if ( !trie->trans[ state + charid ].next ) {
3344                             trie->trans[ state + charid ].next = next_alloc;
3345                             trie->trans[ state ].check++;
3346                             prev_states[TRIE_NODENUM(next_alloc)]
3347                                     = TRIE_NODENUM(state);
3348                             next_alloc += trie->uniquecharcount;
3349                         }
3350                         state = trie->trans[ state + charid ].next;
3351                     } else {
3352                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3353                     }
3354                     /* charid is now 0 if we dont know the char read, or
3355                      * nonzero if we do */
3356                 }
3357             } else {
3358                 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3359                  * on a trieable type. So we need to reset noper back to point at the first regop
3360                  * in the branch before we call TRIE_HANDLE_WORD().
3361                 */
3362                 noper= NEXTOPER(cur);
3363             }
3364             accept_state = TRIE_NODENUM( state );
3365             TRIE_HANDLE_WORD(accept_state);
3366
3367         } /* end second pass */
3368
3369         /* and now dump it out before we compress it */
3370         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3371                                                           revcharmap,
3372                                                           next_alloc, depth+1));
3373
3374         {
3375         /*
3376            * Inplace compress the table.*
3377
3378            For sparse data sets the table constructed by the trie algorithm will
3379            be mostly 0/FAIL transitions or to put it another way mostly empty.
3380            (Note that leaf nodes will not contain any transitions.)
3381
3382            This algorithm compresses the tables by eliminating most such
3383            transitions, at the cost of a modest bit of extra work during lookup:
3384
3385            - Each states[] entry contains a .base field which indicates the
3386            index in the state[] array wheres its transition data is stored.
3387
3388            - If .base is 0 there are no valid transitions from that node.
3389
3390            - If .base is nonzero then charid is added to it to find an entry in
3391            the trans array.
3392
3393            -If trans[states[state].base+charid].check!=state then the
3394            transition is taken to be a 0/Fail transition. Thus if there are fail
3395            transitions at the front of the node then the .base offset will point
3396            somewhere inside the previous nodes data (or maybe even into a node
3397            even earlier), but the .check field determines if the transition is
3398            valid.
3399
3400            XXX - wrong maybe?
3401            The following process inplace converts the table to the compressed
3402            table: We first do not compress the root node 1,and mark all its
3403            .check pointers as 1 and set its .base pointer as 1 as well. This
3404            allows us to do a DFA construction from the compressed table later,
3405            and ensures that any .base pointers we calculate later are greater
3406            than 0.
3407
3408            - We set 'pos' to indicate the first entry of the second node.
3409
3410            - We then iterate over the columns of the node, finding the first and
3411            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3412            and set the .check pointers accordingly, and advance pos
3413            appropriately and repreat for the next node. Note that when we copy
3414            the next pointers we have to convert them from the original
3415            NODEIDX form to NODENUM form as the former is not valid post
3416            compression.
3417
3418            - If a node has no transitions used we mark its base as 0 and do not
3419            advance the pos pointer.
3420
3421            - If a node only has one transition we use a second pointer into the
3422            structure to fill in allocated fail transitions from other states.
3423            This pointer is independent of the main pointer and scans forward
3424            looking for null transitions that are allocated to a state. When it
3425            finds one it writes the single transition into the "hole".  If the
3426            pointer doesnt find one the single transition is appended as normal.
3427
3428            - Once compressed we can Renew/realloc the structures to release the
3429            excess space.
3430
3431            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3432            specifically Fig 3.47 and the associated pseudocode.
3433
3434            demq
3435         */
3436         const U32 laststate = TRIE_NODENUM( next_alloc );
3437         U32 state, charid;
3438         U32 pos = 0, zp=0;
3439         trie->statecount = laststate;
3440
3441         for ( state = 1 ; state < laststate ; state++ ) {
3442             U8 flag = 0;
3443             const U32 stateidx = TRIE_NODEIDX( state );
3444             const U32 o_used = trie->trans[ stateidx ].check;
3445             U32 used = trie->trans[ stateidx ].check;
3446             trie->trans[ stateidx ].check = 0;
3447
3448             for ( charid = 0;
3449                   used && charid < trie->uniquecharcount;
3450                   charid++ )
3451             {
3452                 if ( flag || trie->trans[ stateidx + charid ].next ) {
3453                     if ( trie->trans[ stateidx + charid ].next ) {
3454                         if (o_used == 1) {
3455                             for ( ; zp < pos ; zp++ ) {
3456                                 if ( ! trie->trans[ zp ].next ) {
3457                                     break;
3458                                 }
3459                             }
3460                             trie->states[ state ].trans.base
3461                                                     = zp
3462                                                       + trie->uniquecharcount
3463                                                       - charid ;
3464                             trie->trans[ zp ].next
3465                                 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3466                                                              + charid ].next );
3467                             trie->trans[ zp ].check = state;
3468                             if ( ++zp > pos ) pos = zp;
3469                             break;
3470                         }
3471                         used--;
3472                     }
3473                     if ( !flag ) {
3474                         flag = 1;
3475                         trie->states[ state ].trans.base
3476                                        = pos + trie->uniquecharcount - charid ;
3477                     }
3478                     trie->trans[ pos ].next
3479                         = SAFE_TRIE_NODENUM(
3480                                        trie->trans[ stateidx + charid ].next );
3481                     trie->trans[ pos ].check = state;
3482                     pos++;
3483                 }
3484             }
3485         }
3486         trie->lasttrans = pos + 1;
3487         trie->states = (reg_trie_state *)
3488             PerlMemShared_realloc( trie->states, laststate
3489                                    * sizeof(reg_trie_state) );
3490         DEBUG_TRIE_COMPILE_MORE_r(
3491             Perl_re_indentf( aTHX_  "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3492                 depth+1,
3493                 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3494                        + 1 ),
3495                 (IV)next_alloc,
3496                 (IV)pos,
3497                 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3498             );
3499
3500         } /* end table compress */
3501     }
3502     DEBUG_TRIE_COMPILE_MORE_r(
3503             Perl_re_indentf( aTHX_  "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3504                 depth+1,
3505                 (UV)trie->statecount,
3506                 (UV)trie->lasttrans)
3507     );
3508     /* resize the trans array to remove unused space */
3509     trie->trans = (reg_trie_trans *)
3510         PerlMemShared_realloc( trie->trans, trie->lasttrans
3511                                * sizeof(reg_trie_trans) );
3512
3513     {   /* Modify the program and insert the new TRIE node */
3514         U8 nodetype =(U8) flags;
3515         char *str=NULL;
3516
3517 #ifdef DEBUGGING
3518         regnode *optimize = NULL;
3519 #ifdef RE_TRACK_PATTERN_OFFSETS
3520
3521         U32 mjd_offset = 0;
3522         U32 mjd_nodelen = 0;
3523 #endif /* RE_TRACK_PATTERN_OFFSETS */
3524 #endif /* DEBUGGING */
3525         /*
3526            This means we convert either the first branch or the first Exact,
3527            depending on whether the thing following (in 'last') is a branch
3528            or not and whther first is the startbranch (ie is it a sub part of
3529            the alternation or is it the whole thing.)
3530            Assuming its a sub part we convert the EXACT otherwise we convert
3531            the whole branch sequence, including the first.
3532          */
3533         /* Find the node we are going to overwrite */
3534         if ( first != startbranch || OP( last ) == BRANCH ) {
3535             /* branch sub-chain */
3536             NEXT_OFF( first ) = (U16)(last - first);
3537 #ifdef RE_TRACK_PATTERN_OFFSETS
3538             DEBUG_r({
3539                 mjd_offset= Node_Offset((convert));
3540                 mjd_nodelen= Node_Length((convert));
3541             });
3542 #endif
3543             /* whole branch chain */
3544         }
3545 #ifdef RE_TRACK_PATTERN_OFFSETS
3546         else {
3547             DEBUG_r({
3548                 const  regnode *nop = NEXTOPER( convert );
3549                 mjd_offset= Node_Offset((nop));
3550                 mjd_nodelen= Node_Length((nop));
3551             });
3552         }
3553         DEBUG_OPTIMISE_r(
3554             Perl_re_indentf( aTHX_  "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3555                 depth+1,
3556                 (UV)mjd_offset, (UV)mjd_nodelen)
3557         );
3558 #endif
3559         /* But first we check to see if there is a common prefix we can
3560            split out as an EXACT and put in front of the TRIE node.  */
3561         trie->startstate= 1;
3562         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
3563             /* we want to find the first state that has more than
3564              * one transition, if that state is not the first state
3565              * then we have a common prefix which we can remove.
3566              */
3567             U32 state;
3568             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3569                 U32 ofs = 0;
3570                 I32 first_ofs = -1; /* keeps track of the ofs of the first
3571                                        transition, -1 means none */
3572                 U32 count = 0;
3573                 const U32 base = trie->states[ state ].trans.base;
3574
3575                 /* does this state terminate an alternation? */
3576                 if ( trie->states[state].wordnum )
3577                         count = 1;
3578
3579                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3580                     if ( ( base + ofs >= trie->uniquecharcount ) &&
3581                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3582                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3583                     {
3584                         if ( ++count > 1 ) {
3585                             /* we have more than one transition */
3586                             SV **tmp;
3587                             U8 *ch;
3588                             /* if this is the first state there is no common prefix
3589                              * to extract, so we can exit */
3590                             if ( state == 1 ) break;
3591                             tmp = av_fetch( revcharmap, ofs, 0);
3592                             ch = (U8*)SvPV_nolen_const( *tmp );
3593
3594                             /* if we are on count 2 then we need to initialize the
3595                              * bitmap, and store the previous char if there was one
3596                              * in it*/
3597                             if ( count == 2 ) {
3598                                 /* clear the bitmap */
3599                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3600                                 DEBUG_OPTIMISE_r(
3601                                     Perl_re_indentf( aTHX_  "New Start State=%" UVuf " Class: [",
3602                                         depth+1,
3603                                         (UV)state));
3604                                 if (first_ofs >= 0) {
3605                                     SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3606                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3607
3608                                     TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3609                                     DEBUG_OPTIMISE_r(
3610                                         Perl_re_printf( aTHX_  "%s", (char*)ch)
3611                                     );
3612                                 }
3613                             }
3614                             /* store the current firstchar in the bitmap */
3615                             TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3616                             DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3617                         }
3618                         first_ofs = ofs;
3619                     }
3620                 }
3621                 if ( count == 1 ) {
3622                     /* This state has only one transition, its transition is part
3623                      * of a common prefix - we need to concatenate the char it
3624                      * represents to what we have so far. */
3625                     SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3626                     STRLEN len;
3627                     char *ch = SvPV( *tmp, len );
3628                     DEBUG_OPTIMISE_r({
3629                         SV *sv=sv_newmortal();
3630                         Perl_re_indentf( aTHX_  "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3631                             depth+1,
3632                             (UV)state, (UV)first_ofs,
3633                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3634                                 PL_colors[0], PL_colors[1],
3635                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3636                                 PERL_PV_ESCAPE_FIRSTCHAR
3637                             )
3638                         );
3639                     });
3640                     if ( state==1 ) {
3641                         OP( convert ) = nodetype;
3642                         str=STRING(convert);
3643                         setSTR_LEN(convert, 0);
3644                     }
3645                     assert( ( STR_LEN(convert) + len ) < 256 );
3646                     setSTR_LEN(convert, (U8)(STR_LEN(convert) + len));
3647                     while (len--)
3648                         *str++ = *ch++;
3649                 } else {
3650 #ifdef DEBUGGING
3651                     if (state>1)
3652                         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3653 #endif
3654                     break;
3655                 }
3656             }
3657             trie->prefixlen = (state-1);
3658             if (str) {
3659                 regnode *n = convert+NODE_SZ_STR(convert);
3660                 assert( NODE_SZ_STR(convert) <= U16_MAX );
3661                 NEXT_OFF(convert) = (U16)(NODE_SZ_STR(convert));
3662                 trie->startstate = state;
3663                 trie->minlen -= (state - 1);
3664                 trie->maxlen -= (state - 1);
3665 #ifdef DEBUGGING
3666                /* At least the UNICOS C compiler choked on this
3667                 * being argument to DEBUG_r(), so let's just have
3668                 * it right here. */
3669                if (
3670 #ifdef PERL_EXT_RE_BUILD
3671                    1
3672 #else
3673                    DEBUG_r_TEST
3674 #endif
3675                    ) {
3676                    regnode *fix = convert;
3677                    U32 word = trie->wordcount;
3678 #ifdef RE_TRACK_PATTERN_OFFSETS
3679                    mjd_nodelen++;
3680 #endif
3681                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3682                    while( ++fix < n ) {
3683                        Set_Node_Offset_Length(fix, 0, 0);
3684                    }
3685                    while (word--) {
3686                        SV ** const tmp = av_fetch( trie_words, word, 0 );
3687                        if (tmp) {
3688                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
3689                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3690                            else
3691                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3692                        }
3693                    }
3694                }
3695 #endif
3696                 if (trie->maxlen) {
3697                     convert = n;
3698                 } else {
3699                     NEXT_OFF(convert) = (U16)(tail - convert);
3700                     DEBUG_r(optimize= n);
3701                 }
3702             }
3703         }
3704         if (!jumper)
3705             jumper = last;
3706         if ( trie->maxlen ) {
3707             NEXT_OFF( convert ) = (U16)(tail - convert);
3708             ARG_SET( convert, data_slot );
3709             /* Store the offset to the first unabsorbed branch in
3710                jump[0], which is otherwise unused by the jump logic.
3711                We use this when dumping a trie and during optimisation. */
3712             if (trie->jump)
3713                 trie->jump[0] = (U16)(nextbranch - convert);
3714
3715             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3716              *   and there is a bitmap
3717              *   and the first "jump target" node we found leaves enough room
3718              * then convert the TRIE node into a TRIEC node, with the bitmap
3719              * embedded inline in the opcode - this is hypothetically faster.
3720              */
3721             if ( !trie->states[trie->startstate].wordnum
3722                  && trie->bitmap
3723                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3724             {
3725                 OP( convert ) = TRIEC;
3726                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3727                 PerlMemShared_free(trie->bitmap);
3728                 trie->bitmap= NULL;
3729             } else
3730                 OP( convert ) = TRIE;
3731
3732             /* store the type in the flags */
3733             convert->flags = nodetype;
3734             DEBUG_r({
3735             optimize = convert
3736                       + NODE_STEP_REGNODE
3737                       + regarglen[ OP( convert ) ];
3738             });
3739             /* XXX We really should free up the resource in trie now,
3740                    as we won't use them - (which resources?) dmq */
3741         }
3742         /* needed for dumping*/
3743         DEBUG_r(if (optimize) {
3744             regnode *opt = convert;
3745
3746             while ( ++opt < optimize) {
3747                 Set_Node_Offset_Length(opt, 0, 0);
3748             }
3749             /*
3750                 Try to clean up some of the debris left after the
3751                 optimisation.
3752              */
3753             while( optimize < jumper ) {
3754                 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3755                 OP( optimize ) = OPTIMIZED;
3756                 Set_Node_Offset_Length(optimize, 0, 0);
3757                 optimize++;
3758             }
3759             Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3760         });
3761     } /* end node insert */
3762
3763     /*  Finish populating the prev field of the wordinfo array.  Walk back
3764      *  from each accept state until we find another accept state, and if
3765      *  so, point the first word's .prev field at the second word. If the
3766      *  second already has a .prev field set, stop now. This will be the
3767      *  case either if we've already processed that word's accept state,
3768      *  or that state had multiple words, and the overspill words were
3769      *  already linked up earlier.
3770      */
3771     {
3772         U16 word;
3773         U32 state;
3774         U16 prev;
3775
3776         for (word=1; word <= trie->wordcount; word++) {
3777             prev = 0;
3778             if (trie->wordinfo[word].prev)
3779                 continue;
3780             state = trie->wordinfo[word].accept;
3781             while (state) {
3782                 state = prev_states[state];
3783                 if (!state)
3784                     break;
3785                 prev = trie->states[state].wordnum;
3786                 if (prev)
3787                     break;
3788             }
3789             trie->wordinfo[word].prev = prev;
3790         }
3791         Safefree(prev_states);
3792     }
3793
3794
3795     /* and now dump out the compressed format */
3796     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3797
3798     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3799 #ifdef DEBUGGING
3800     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3801     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3802 #else
3803     SvREFCNT_dec_NN(revcharmap);
3804 #endif
3805     return trie->jump
3806            ? MADE_JUMP_TRIE
3807            : trie->startstate>1
3808              ? MADE_EXACT_TRIE
3809              : MADE_TRIE;
3810 }
3811
3812 STATIC regnode *
3813 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3814 {
3815 /* The Trie is constructed and compressed now so we can build a fail array if
3816  * it's needed
3817
3818    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3819    3.32 in the
3820    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3821    Ullman 1985/88
3822    ISBN 0-201-10088-6
3823
3824    We find the fail state for each state in the trie, this state is the longest
3825    proper suffix of the current state's 'word' that is also a proper prefix of
3826    another word in our trie. State 1 represents the word '' and is thus the
3827    default fail state. This allows the DFA not to have to restart after its
3828    tried and failed a word at a given point, it simply continues as though it
3829    had been matching the other word in the first place.
3830    Consider
3831       'abcdgu'=~/abcdefg|cdgu/
3832    When we get to 'd' we are still matching the first word, we would encounter
3833    'g' which would fail, which would bring us to the state representing 'd' in
3834    the second word where we would try 'g' and succeed, proceeding to match
3835    'cdgu'.
3836  */
3837  /* add a fail transition */
3838     const U32 trie_offset = ARG(source);
3839     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3840     U32 *q;
3841     const U32 ucharcount = trie->uniquecharcount;
3842     const U32 numstates = trie->statecount;
3843     const U32 ubound = trie->lasttrans + ucharcount;
3844     U32 q_read = 0;
3845     U32 q_write = 0;
3846     U32 charid;
3847     U32 base = trie->states[ 1 ].trans.base;
3848     U32 *fail;
3849     reg_ac_data *aho;
3850     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3851     regnode *stclass;
3852     DECLARE_AND_GET_RE_DEBUG_FLAGS;
3853
3854     PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3855     PERL_UNUSED_CONTEXT;
3856 #ifndef DEBUGGING
3857     PERL_UNUSED_ARG(depth);
3858 #endif
3859
3860     if ( OP(source) == TRIE ) {
3861         struct regnode_1 *op = (struct regnode_1 *)
3862             PerlMemShared_calloc(1, sizeof(struct regnode_1));
3863         StructCopy(source, op, struct regnode_1);
3864         stclass = (regnode *)op;
3865     } else {
3866         struct regnode_charclass *op = (struct regnode_charclass *)
3867             PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3868         StructCopy(source, op, struct regnode_charclass);
3869         stclass = (regnode *)op;
3870     }
3871     OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3872
3873     ARG_SET( stclass, data_slot );
3874     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3875     RExC_rxi->data->data[ data_slot ] = (void*)aho;
3876     aho->trie=trie_offset;
3877     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3878     Copy( trie->states, aho->states, numstates, reg_trie_state );
3879     Newx( q, numstates, U32);
3880     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3881     aho->refcount = 1;
3882     fail = aho->fail;
3883     /* initialize fail[0..1] to be 1 so that we always have
3884        a valid final fail state */
3885     fail[ 0 ] = fail[ 1 ] = 1;
3886
3887     for ( charid = 0; charid < ucharcount ; charid++ ) {
3888         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3889         if ( newstate ) {
3890             q[ q_write ] = newstate;
3891             /* set to point at the root */
3892             fail[ q[ q_write++ ] ]=1;
3893         }
3894     }
3895     while ( q_read < q_write) {
3896         const U32 cur = q[ q_read++ % numstates ];
3897         base = trie->states[ cur ].trans.base;
3898
3899         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3900             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3901             if (ch_state) {
3902                 U32 fail_state = cur;
3903                 U32 fail_base;
3904                 do {
3905                     fail_state = fail[ fail_state ];
3906                     fail_base = aho->states[ fail_state ].trans.base;
3907                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3908
3909                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3910                 fail[ ch_state ] = fail_state;
3911                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3912                 {
3913                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
3914                 }
3915                 q[ q_write++ % numstates] = ch_state;
3916             }
3917         }
3918     }
3919     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3920        when we fail in state 1, this allows us to use the
3921        charclass scan to find a valid start char. This is based on the principle
3922        that theres a good chance the string being searched contains lots of stuff
3923        that cant be a start char.
3924      */
3925     fail[ 0 ] = fail[ 1 ] = 0;
3926     DEBUG_TRIE_COMPILE_r({
3927         Perl_re_indentf( aTHX_  "Stclass Failtable (%" UVuf " states): 0",
3928                       depth, (UV)numstates
3929         );
3930         for( q_read=1; q_read<numstates; q_read++ ) {
3931             Perl_re_printf( aTHX_  ", %" UVuf, (UV)fail[q_read]);
3932         }
3933         Perl_re_printf( aTHX_  "\n");
3934     });
3935     Safefree(q);
3936     /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3937     return stclass;
3938 }
3939
3940
3941 /* The below joins as many adjacent EXACTish nodes as possible into a single
3942  * one.  The regop may be changed if the node(s) contain certain sequences that
3943  * require special handling.  The joining is only done if:
3944  * 1) there is room in the current conglomerated node to entirely contain the
3945  *    next one.
3946  * 2) they are compatible node types
3947  *
3948  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3949  * these get optimized out
3950  *
3951  * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3952  * as possible, even if that means splitting an existing node so that its first
3953  * part is moved to the preceding node.  This would maximise the efficiency of
3954  * memEQ during matching.
3955  *
3956  * If a node is to match under /i (folded), the number of characters it matches
3957  * can be different than its character length if it contains a multi-character
3958  * fold.  *min_subtract is set to the total delta number of characters of the
3959  * input nodes.
3960  *
3961  * And *unfolded_multi_char is set to indicate whether or not the node contains
3962  * an unfolded multi-char fold.  This happens when it won't be known until
3963  * runtime whether the fold is valid or not; namely
3964  *  1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3965  *      target string being matched against turns out to be UTF-8 is that fold
3966  *      valid; or
3967  *  2) for EXACTFL nodes whose folding rules depend on the locale in force at
3968  *      runtime.
3969  * (Multi-char folds whose components are all above the Latin1 range are not
3970  * run-time locale dependent, and have already been folded by the time this
3971  * function is called.)
3972  *
3973  * This is as good a place as any to discuss the design of handling these
3974  * multi-character fold sequences.  It's been wrong in Perl for a very long
3975  * time.  There are three code points in Unicode whose multi-character folds
3976  * were long ago discovered to mess things up.  The previous designs for
3977  * dealing with these involved assigning a special node for them.  This
3978  * approach doesn't always work, as evidenced by this example:
3979  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
3980  * Both sides fold to "sss", but if the pattern is parsed to create a node that
3981  * would match just the \xDF, it won't be able to handle the case where a
3982  * successful match would have to cross the node's boundary.  The new approach
3983  * that hopefully generally solves the problem generates an EXACTFUP node
3984  * that is "sss" in this case.
3985  *
3986  * It turns out that there are problems with all multi-character folds, and not
3987  * just these three.  Now the code is general, for all such cases.  The
3988  * approach taken is:
3989  * 1)   This routine examines each EXACTFish node that could contain multi-
3990  *      character folded sequences.  Since a single character can fold into
3991  *      such a sequence, the minimum match length for this node is less than
3992  *      the number of characters in the node.  This routine returns in
3993  *      *min_subtract how many characters to subtract from the actual
3994  *      length of the string to get a real minimum match length; it is 0 if
3995  *      there are no multi-char foldeds.  This delta is used by the caller to
3996  *      adjust the min length of the match, and the delta between min and max,
3997  *      so that the optimizer doesn't reject these possibilities based on size
3998  *      constraints.
3999  *
4000  * 2)   For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
4001  *      under /u, we fold it to 'ss' in regatom(), and in this routine, after
4002  *      joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
4003  *      EXACTFU nodes.  The node type of such nodes is then changed to
4004  *      EXACTFUP, indicating it is problematic, and needs careful handling.
4005  *      (The procedures in step 1) above are sufficient to handle this case in
4006  *      UTF-8 encoded nodes.)  The reason this is problematic is that this is
4007  *      the only case where there is a possible fold length change in non-UTF-8
4008  *      patterns.  By reserving a special node type for problematic cases, the
4009  *      far more common regular EXACTFU nodes can be processed faster.
4010  *      regexec.c takes advantage of this.
4011  *
4012  *      EXACTFUP has been created as a grab-bag for (hopefully uncommon)
4013  *      problematic cases.   These all only occur when the pattern is not
4014  *      UTF-8.  In addition to the 'ss' sequence where there is a possible fold
4015  *      length change, it handles the situation where the string cannot be
4016  *      entirely folded.  The strings in an EXACTFish node are folded as much
4017  *      as possible during compilation in regcomp.c.  This saves effort in
4018  *      regex matching.  By using an EXACTFUP node when it is not possible to
4019  *      fully fold at compile time, regexec.c can know that everything in an
4020  *      EXACTFU node is folded, so folding can be skipped at runtime.  The only
4021  *      case where folding in EXACTFU nodes can't be done at compile time is
4022  *      the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8.  This
4023  *      is because its fold requires UTF-8 to represent.  Thus EXACTFUP nodes
4024  *      handle two very different cases.  Alternatively, there could have been
4025  *      a node type where there are length changes, one for unfolded, and one
4026  *      for both.  If yet another special case needed to be created, the number
4027  *      of required node types would have to go to 7.  khw figures that even
4028  *      though there are plenty of node types to spare, that the maintenance
4029  *      cost wasn't worth the small speedup of doing it that way, especially
4030  *      since he thinks the MICRO SIGN is rarely encountered in practice.
4031  *
4032  *      There are other cases where folding isn't done at compile time, but
4033  *      none of them are under /u, and hence not for EXACTFU nodes.  The folds
4034  *      in EXACTFL nodes aren't known until runtime, and vary as the locale
4035  *      changes.  Some folds in EXACTF depend on if the runtime target string
4036  *      is UTF-8 or not.  (regatom() will create an EXACTFU node even under /di
4037  *      when no fold in it depends on the UTF-8ness of the target string.)
4038  *
4039  * 3)   A problem remains for unfolded multi-char folds. (These occur when the
4040  *      validity of the fold won't be known until runtime, and so must remain
4041  *      unfolded for now.  This happens for the sharp s in EXACTF and EXACTFAA
4042  *      nodes when the pattern isn't in UTF-8.  (Note, BTW, that there cannot
4043  *      be an EXACTF node with a UTF-8 pattern.)  They also occur for various
4044  *      folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
4045  *      The reason this is a problem is that the optimizer part of regexec.c
4046  *      (probably unwittingly, in Perl_regexec_flags()) makes an assumption
4047  *      that a character in the pattern corresponds to at most a single
4048  *      character in the target string.  (And I do mean character, and not byte
4049  *      here, unlike other parts of the documentation that have never been
4050  *      updated to account for multibyte Unicode.)  Sharp s in EXACTF and
4051  *      EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
4052  *      nodes it can match "\x{17F}\x{17F}".  These, along with other ones in
4053  *      EXACTFL nodes, violate the assumption, and they are the only instances
4054  *      where it is violated.  I'm reluctant to try to change the assumption,
4055  *      as the code involved is impenetrable to me (khw), so instead the code
4056  *      here punts.  This routine examines EXACTFL nodes, and (when the pattern
4057  *      isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
4058  *      boolean indicating whether or not the node contains such a fold.  When
4059  *      it is true, the caller sets a flag that later causes the optimizer in
4060  *      this file to not set values for the floating and fixed string lengths,
4061  *      and thus avoids the optimizer code in regexec.c that makes the invalid
4062  *      assumption.  Thus, there is no optimization based on string lengths for
4063  *      EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
4064  *      EXACTF and EXACTFAA nodes that contain the sharp s.  (The reason the
4065  *      assumption is wrong only in these cases is that all other non-UTF-8
4066  *      folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
4067  *      their expanded versions.  (Again, we can't prefold sharp s to 'ss' in
4068  *      EXACTF nodes because we don't know at compile time if it actually
4069  *      matches 'ss' or not.  For EXACTF nodes it will match iff the target
4070  *      string is in UTF-8.  This is in contrast to EXACTFU nodes, where it
4071  *      always matches; and EXACTFAA where it never does.  In an EXACTFAA node
4072  *      in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
4073  *      problem; but in a non-UTF8 pattern, folding it to that above-Latin1
4074  *      string would require the pattern to be forced into UTF-8, the overhead
4075  *      of which we want to avoid.  Similarly the unfolded multi-char folds in
4076  *      EXACTFL nodes will match iff the locale at the time of match is a UTF-8
4077  *      locale.)
4078  *
4079  *      Similarly, the code that generates tries doesn't currently handle
4080  *      not-already-folded multi-char folds, and it looks like a pain to change
4081  *      that.  Therefore, trie generation of EXACTFAA nodes with the sharp s
4082  *      doesn't work.  Instead, such an EXACTFAA is turned into a new regnode,
4083  *      EXACTFAA_NO_TRIE, which the trie code knows not to handle.  Most people
4084  *      using /iaa matching will be doing so almost entirely with ASCII
4085  *      strings, so this should rarely be encountered in practice */
4086
4087 STATIC U32
4088 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
4089                    UV *min_subtract, bool *unfolded_multi_char,
4090                    U32 flags, regnode *val, U32 depth)
4091 {
4092     /* Merge several consecutive EXACTish nodes into one. */
4093
4094     regnode *n = regnext(scan);
4095     U32 stringok = 1;
4096     regnode *next = scan + NODE_SZ_STR(scan);
4097     U32 merged = 0;
4098     U32 stopnow = 0;
4099 #ifdef DEBUGGING
4100     regnode *stop = scan;
4101     DECLARE_AND_GET_RE_DEBUG_FLAGS;
4102 #else
4103     PERL_UNUSED_ARG(depth);
4104 #endif
4105
4106     PERL_ARGS_ASSERT_JOIN_EXACT;
4107 #ifndef EXPERIMENTAL_INPLACESCAN
4108     PERL_UNUSED_ARG(flags);
4109     PERL_UNUSED_ARG(val);
4110 #endif
4111     DEBUG_PEEP("join", scan, depth, 0);
4112
4113     assert(PL_regkind[OP(scan)] == EXACT);
4114
4115     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
4116      * EXACT ones that are mergeable to the current one. */
4117     while (    n
4118            && (    PL_regkind[OP(n)] == NOTHING
4119                || (stringok && PL_regkind[OP(n)] == EXACT))
4120            && NEXT_OFF(n)
4121            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
4122     {
4123
4124         if (OP(n) == TAIL || n > next)
4125             stringok = 0;
4126         if (PL_regkind[OP(n)] == NOTHING) {
4127             DEBUG_PEEP("skip:", n, depth, 0);
4128             NEXT_OFF(scan) += NEXT_OFF(n);
4129             next = n + NODE_STEP_REGNODE;
4130 #ifdef DEBUGGING
4131             if (stringok)
4132                 stop = n;
4133 #endif
4134             n = regnext(n);
4135         }
4136         else if (stringok) {
4137             const unsigned int oldl = STR_LEN(scan);
4138             regnode * const nnext = regnext(n);
4139
4140             /* XXX I (khw) kind of doubt that this works on platforms (should
4141              * Perl ever run on one) where U8_MAX is above 255 because of lots
4142              * of other assumptions */
4143             /* Don't join if the sum can't fit into a single node */
4144             if (oldl + STR_LEN(n) > U8_MAX)
4145                 break;
4146
4147             /* Joining something that requires UTF-8 with something that
4148              * doesn't, means the result requires UTF-8. */
4149             if (OP(scan) == EXACT && (OP(n) == EXACT_REQ8)) {
4150                 OP(scan) = EXACT_REQ8;
4151             }
4152             else if (OP(scan) == EXACT_REQ8 && (OP(n) == EXACT)) {
4153                 ;   /* join is compatible, no need to change OP */
4154             }
4155             else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_REQ8)) {
4156                 OP(scan) = EXACTFU_REQ8;
4157             }
4158             else if ((OP(scan) == EXACTFU_REQ8) && (OP(n) == EXACTFU)) {
4159                 ;   /* join is compatible, no need to change OP */
4160             }
4161             else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
4162                 ;   /* join is compatible, no need to change OP */
4163             }
4164             else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
4165
4166                  /* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
4167                   * which can join with EXACTFU ones.  We check for this case
4168                   * here.  These need to be resolved to either EXACTFU or
4169                   * EXACTF at joining time.  They have nothing in them that
4170                   * would forbid them from being the more desirable EXACTFU
4171                   * nodes except that they begin and/or end with a single [Ss].
4172                   * The reason this is problematic is because they could be
4173                   * joined in this loop with an adjacent node that ends and/or
4174                   * begins with [Ss] which would then form the sequence 'ss',
4175                   * which matches differently under /di than /ui, in which case
4176                   * EXACTFU can't be used.  If the 'ss' sequence doesn't get
4177                   * formed, the nodes get absorbed into any adjacent EXACTFU
4178                   * node.  And if the only adjacent node is EXACTF, they get
4179                   * absorbed into that, under the theory that a longer node is
4180                   * better than two shorter ones, even if one is EXACTFU.  Note
4181                   * that EXACTFU_REQ8 is generated only for UTF-8 patterns,
4182                   * and the EXACTFU_S_EDGE ones only for non-UTF-8.  */
4183
4184                 if (STRING(n)[STR_LEN(n)-1] == 's') {
4185
4186                     /* Here the joined node would end with 's'.  If the node
4187                      * following the combination is an EXACTF one, it's better to
4188                      * join this trailing edge 's' node with that one, leaving the
4189                      * current one in 'scan' be the more desirable EXACTFU */
4190                     if (OP(nnext) == EXACTF) {
4191                         break;
4192                     }
4193
4194                     OP(scan) = EXACTFU_S_EDGE;
4195
4196                 }   /* Otherwise, the beginning 's' of the 2nd node just
4197                        becomes an interior 's' in 'scan' */
4198             }
4199             else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
4200                 ;   /* join is compatible, no need to change OP */
4201             }
4202             else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
4203
4204                 /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
4205                  * nodes.  But the latter nodes can be also joined with EXACTFU
4206                  * ones, and that is a better outcome, so if the node following
4207                  * 'n' is EXACTFU, quit now so that those two can be joined
4208                  * later */
4209                 if (OP(nnext) == EXACTFU) {
4210                     break;
4211                 }
4212
4213                 /* The join is compatible, and the combined node will be
4214                  * EXACTF.  (These don't care if they begin or end with 's' */
4215             }
4216             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
4217                 if (   STRING(scan)[STR_LEN(scan)-1] == 's'
4218                     && STRING(n)[0] == 's')
4219                 {
4220                     /* When combined, we have the sequence 'ss', which means we
4221                      * have to remain /di */
4222                     OP(scan) = EXACTF;
4223                 }
4224             }
4225             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
4226                 if (STRING(n)[0] == 's') {
4227                     ;   /* Here the join is compatible and the combined node
4228                            starts with 's', no need to change OP */
4229                 }
4230                 else {  /* Now the trailing 's' is in the interior */
4231                     OP(scan) = EXACTFU;
4232                 }
4233             }
4234             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
4235
4236                 /* The join is compatible, and the combined node will be
4237                  * EXACTF.  (These don't care if they begin or end with 's' */
4238                 OP(scan) = EXACTF;
4239             }
4240             else if (OP(scan) != OP(n)) {
4241
4242                 /* The only other compatible joinings are the same node type */
4243                 break;
4244             }
4245
4246             DEBUG_PEEP("merg", n, depth, 0);
4247             merged++;
4248
4249             NEXT_OFF(scan) += NEXT_OFF(n);
4250             assert( ( STR_LEN(scan) + STR_LEN(n) ) < 256 );
4251             setSTR_LEN(scan, (U8)(STR_LEN(scan) + STR_LEN(n)));
4252             next = n + NODE_SZ_STR(n);
4253             /* Now we can overwrite *n : */
4254             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
4255 #ifdef DEBUGGING
4256             stop = next - 1;
4257 #endif
4258             n = nnext;
4259             if (stopnow) break;
4260         }
4261
4262 #ifdef EXPERIMENTAL_INPLACESCAN
4263         if (flags && !NEXT_OFF(n)) {
4264             DEBUG_PEEP("atch", val, depth, 0);
4265             if (reg_off_by_arg[OP(n)]) {
4266                 ARG_SET(n, val - n);
4267             }
4268             else {
4269                 NEXT_OFF(n) = val - n;
4270             }
4271             stopnow = 1;
4272         }
4273 #endif
4274     }
4275
4276     /* This temporary node can now be turned into EXACTFU, and must, as
4277      * regexec.c doesn't handle it */
4278     if (OP(scan) == EXACTFU_S_EDGE) {
4279         OP(scan) = EXACTFU;
4280     }
4281
4282     *min_subtract = 0;
4283     *unfolded_multi_char = FALSE;
4284
4285     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
4286      * can now analyze for sequences of problematic code points.  (Prior to
4287      * this final joining, sequences could have been split over boundaries, and
4288      * hence missed).  The sequences only happen in folding, hence for any
4289      * non-EXACT EXACTish node */
4290     if (OP(scan) != EXACT && OP(scan) != EXACT_REQ8 && OP(scan) != EXACTL) {
4291         U8* s0 = (U8*) STRING(scan);
4292         U8* s = s0;
4293         U8* s_end = s0 + STR_LEN(scan);
4294
4295         int total_count_delta = 0;  /* Total delta number of characters that
4296                                        multi-char folds expand to */
4297
4298         /* One pass is made over the node's string looking for all the
4299          * possibilities.  To avoid some tests in the loop, there are two main
4300          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4301          * non-UTF-8 */
4302         if (UTF) {
4303             U8* folded = NULL;
4304
4305             if (OP(scan) == EXACTFL) {
4306                 U8 *d;
4307
4308                 /* An EXACTFL node would already have been changed to another
4309                  * node type unless there is at least one character in it that
4310                  * is problematic; likely a character whose fold definition
4311                  * won't be known until runtime, and so has yet to be folded.
4312                  * For all but the UTF-8 locale, folds are 1-1 in length, but
4313                  * to handle the UTF-8 case, we need to create a temporary
4314                  * folded copy using UTF-8 locale rules in order to analyze it.
4315                  * This is because our macros that look to see if a sequence is
4316                  * a multi-char fold assume everything is folded (otherwise the
4317                  * tests in those macros would be too complicated and slow).
4318                  * Note that here, the non-problematic folds will have already
4319                  * been done, so we can just copy such characters.  We actually
4320                  * don't completely fold the EXACTFL string.  We skip the
4321                  * unfolded multi-char folds, as that would just create work
4322                  * below to figure out the size they already are */
4323
4324                 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4325                 d = folded;
4326                 while (s < s_end) {
4327                     STRLEN s_len = UTF8SKIP(s);
4328                     if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4329                         Copy(s, d, s_len, U8);
4330                         d += s_len;
4331                     }
4332                     else if (is_FOLDS_TO_MULTI_utf8(s)) {
4333                         *unfolded_multi_char = TRUE;
4334                         Copy(s, d, s_len, U8);
4335                         d += s_len;
4336                     }
4337                     else if (isASCII(*s)) {
4338                         *(d++) = toFOLD(*s);
4339                     }
4340                     else {
4341                         STRLEN len;
4342                         _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4343                         d += len;
4344                     }
4345                     s += s_len;
4346                 }
4347
4348                 /* Point the remainder of the routine to look at our temporary
4349                  * folded copy */
4350                 s = folded;
4351                 s_end = d;
4352             } /* End of creating folded copy of EXACTFL string */
4353
4354             /* Examine the string for a multi-character fold sequence.  UTF-8
4355              * patterns have all characters pre-folded by the time this code is
4356              * executed */
4357             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4358                                      length sequence we are looking for is 2 */
4359             {
4360                 int count = 0;  /* How many characters in a multi-char fold */
4361                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4362                 if (! len) {    /* Not a multi-char fold: get next char */
4363                     s += UTF8SKIP(s);
4364                     continue;
4365                 }
4366
4367                 { /* Here is a generic multi-char fold. */
4368                     U8* multi_end  = s + len;
4369
4370                     /* Count how many characters are in it.  In the case of
4371                      * /aa, no folds which contain ASCII code points are
4372                      * allowed, so check for those, and skip if found. */
4373                     if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4374                         count = utf8_length(s, multi_end);
4375                         s = multi_end;
4376                     }
4377                     else {
4378                         while (s < multi_end) {
4379                             if (isASCII(*s)) {
4380                                 s++;
4381                                 goto next_iteration;
4382                             }
4383                             else {
4384                                 s += UTF8SKIP(s);
4385                             }
4386                             count++;
4387                         }
4388                     }
4389                 }
4390
4391                 /* The delta is how long the sequence is minus 1 (1 is how long
4392                  * the character that folds to the sequence is) */
4393                 total_count_delta += count - 1;
4394               next_iteration: ;
4395             }
4396
4397             /* We created a temporary folded copy of the string in EXACTFL
4398              * nodes.  Therefore we need to be sure it doesn't go below zero,
4399              * as the real string could be shorter */
4400             if (OP(scan) == EXACTFL) {
4401                 int total_chars = utf8_length((U8*) STRING(scan),
4402                                            (U8*) STRING(scan) + STR_LEN(scan));
4403                 if (total_count_delta > total_chars) {
4404                     total_count_delta = total_chars;
4405                 }
4406             }
4407
4408             *min_subtract += total_count_delta;
4409             Safefree(folded);
4410         }
4411         else if (OP(scan) == EXACTFAA) {
4412
4413             /* Non-UTF-8 pattern, EXACTFAA node.  There can't be a multi-char
4414              * fold to the ASCII range (and there are no existing ones in the
4415              * upper latin1 range).  But, as outlined in the comments preceding
4416              * this function, we need to flag any occurrences of the sharp s.
4417              * This character forbids trie formation (because of added
4418              * complexity) */
4419 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
4420    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
4421                                       || UNICODE_DOT_DOT_VERSION > 0)
4422             while (s < s_end) {
4423                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4424                     OP(scan) = EXACTFAA_NO_TRIE;
4425                     *unfolded_multi_char = TRUE;
4426                     break;
4427                 }
4428                 s++;
4429             }
4430         }
4431         else if (OP(scan) != EXACTFAA_NO_TRIE) {
4432
4433             /* Non-UTF-8 pattern, not EXACTFAA node.  Look for the multi-char
4434              * folds that are all Latin1.  As explained in the comments
4435              * preceding this function, we look also for the sharp s in EXACTF
4436              * and EXACTFL nodes; it can be in the final position.  Otherwise
4437              * we can stop looking 1 byte earlier because have to find at least
4438              * two characters for a multi-fold */
4439             const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4440                               ? s_end
4441                               : s_end -1;
4442
4443             while (s < upper) {
4444                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4445                 if (! len) {    /* Not a multi-char fold. */
4446                     if (*s == LATIN_SMALL_LETTER_SHARP_S
4447                         && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4448                     {
4449                         *unfolded_multi_char = TRUE;
4450                     }
4451                     s++;
4452                     continue;
4453                 }
4454
4455                 if (len == 2
4456                     && isALPHA_FOLD_EQ(*s, 's')
4457                     && isALPHA_FOLD_EQ(*(s+1), 's'))
4458                 {
4459
4460                     /* EXACTF nodes need to know that the minimum length
4461                      * changed so that a sharp s in the string can match this
4462                      * ss in the pattern, but they remain EXACTF nodes, as they
4463                      * won't match this unless the target string is in UTF-8,
4464                      * which we don't know until runtime.  EXACTFL nodes can't
4465                      * transform into EXACTFU nodes */
4466                     if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4467                         OP(scan) = EXACTFUP;
4468                     }
4469                 }
4470
4471                 *min_subtract += len - 1;
4472                 s += len;
4473             }
4474 #endif
4475         }
4476     }
4477
4478 #ifdef DEBUGGING
4479     /* Allow dumping but overwriting the collection of skipped
4480      * ops and/or strings with fake optimized ops */
4481     n = scan + NODE_SZ_STR(scan);
4482     while (n <= stop) {
4483         OP(n) = OPTIMIZED;
4484         FLAGS(n) = 0;
4485         NEXT_OFF(n) = 0;
4486         n++;
4487     }
4488 #endif
4489     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4490     return stopnow;
4491 }
4492
4493 /* REx optimizer.  Converts nodes into quicker variants "in place".
4494    Finds fixed substrings.  */
4495
4496 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4497    to the position after last scanned or to NULL. */
4498
4499 #define INIT_AND_WITHP \
4500     assert(!and_withp); \
4501     Newx(and_withp, 1, regnode_ssc); \
4502     SAVEFREEPV(and_withp)
4503
4504
4505 static void
4506 S_unwind_scan_frames(pTHX_ const void *p)
4507 {
4508     scan_frame *f= (scan_frame *)p;
4509     do {
4510         scan_frame *n= f->next_frame;
4511         Safefree(f);
4512         f= n;
4513     } while (f);
4514 }
4515
4516 /* Follow the next-chain of the current node and optimize away
4517    all the NOTHINGs from it.
4518  */
4519 STATIC void
4520 S_rck_elide_nothing(pTHX_ regnode *node)
4521 {
4522     PERL_ARGS_ASSERT_RCK_ELIDE_NOTHING;
4523
4524     if (OP(node) != CURLYX) {
4525         const int max = (reg_off_by_arg[OP(node)]
4526                         ? I32_MAX
4527                           /* I32 may be smaller than U16 on CRAYs! */
4528                         : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4529         int off = (reg_off_by_arg[OP(node)] ? ARG(node) : NEXT_OFF(node));
4530         int noff;
4531         regnode *n = node;
4532
4533         /* Skip NOTHING and LONGJMP. */
4534         while (
4535             (n = regnext(n))
4536             && (
4537                 (PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4538                 || ((OP(n) == LONGJMP) && (noff = ARG(n)))
4539             )
4540             && off + noff < max
4541         ) {
4542             off += noff;
4543         }
4544         if (reg_off_by_arg[OP(node)])
4545             ARG(node) = off;
4546         else
4547             NEXT_OFF(node) = off;
4548     }
4549     return;
4550 }
4551
4552 /* the return from this sub is the minimum length that could possibly match */
4553 STATIC SSize_t
4554 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4555                         SSize_t *minlenp, SSize_t *deltap,
4556                         regnode *last,
4557                         scan_data_t *data,
4558                         I32 stopparen,
4559                         U32 recursed_depth,
4560                         regnode_ssc *and_withp,
4561                         U32 flags, U32 depth, bool was_mutate_ok)
4562                         /* scanp: Start here (read-write). */
4563                         /* deltap: Write maxlen-minlen here. */
4564                         /* last: Stop before this one. */
4565                         /* data: string data about the pattern */
4566                         /* stopparen: treat close N as END */
4567                         /* recursed: which subroutines have we recursed into */
4568                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4569 {
4570     SSize_t final_minlen;
4571     /* There must be at least this number of characters to match */
4572     SSize_t min = 0;
4573     I32 pars = 0, code;
4574     regnode *scan = *scanp, *next;
4575     SSize_t delta = 0;
4576     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4577     int is_inf_internal = 0;            /* The studied chunk is infinite */
4578     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4579     scan_data_t data_fake;
4580     SV *re_trie_maxbuff = NULL;
4581     regnode *first_non_open = scan;
4582     SSize_t stopmin = OPTIMIZE_INFTY;
4583     scan_frame *frame = NULL;
4584     DECLARE_AND_GET_RE_DEBUG_FLAGS;
4585
4586     PERL_ARGS_ASSERT_STUDY_CHUNK;
4587     RExC_study_started= 1;
4588
4589     Zero(&data_fake, 1, scan_data_t);
4590
4591     if ( depth == 0 ) {
4592         while (first_non_open && OP(first_non_open) == OPEN)
4593             first_non_open=regnext(first_non_open);
4594     }
4595
4596
4597   fake_study_recurse:
4598     DEBUG_r(
4599         RExC_study_chunk_recursed_count++;
4600     );
4601     DEBUG_OPTIMISE_MORE_r(
4602     {
4603         Perl_re_indentf( aTHX_  "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4604             depth, (long)stopparen,
4605             (unsigned long)RExC_study_chunk_recursed_count,
4606             (unsigned long)depth, (unsigned long)recursed_depth,
4607             scan,
4608             last);
4609         if (recursed_depth) {
4610             U32 i;
4611             U32 j;
4612             for ( j = 0 ; j < recursed_depth ; j++ ) {
4613                 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4614                     if (PAREN_TEST(j, i) && (!j || !PAREN_TEST(j - 1, i))) {
4615                         Perl_re_printf( aTHX_ " %d",(int)i);
4616                         break;
4617                     }
4618                 }
4619                 if ( j + 1 < recursed_depth ) {
4620                     Perl_re_printf( aTHX_  ",");
4621                 }
4622             }
4623         }
4624         Perl_re_printf( aTHX_ "\n");
4625     }
4626     );
4627     while ( scan && OP(scan) != END && scan < last ){
4628         UV min_subtract = 0;    /* How mmany chars to subtract from the minimum
4629                                    node length to get a real minimum (because
4630                                    the folded version may be shorter) */
4631         bool unfolded_multi_char = FALSE;
4632         /* avoid mutating ops if we are anywhere within the recursed or
4633          * enframed handling for a GOSUB: the outermost level will handle it.
4634          */
4635         bool mutate_ok = was_mutate_ok && !(frame && frame->in_gosub);
4636         /* Peephole optimizer: */
4637         DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4638         DEBUG_PEEP("Peep", scan, depth, flags);
4639
4640
4641         /* The reason we do this here is that we need to deal with things like
4642          * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4643          * parsing code, as each (?:..) is handled by a different invocation of
4644          * reg() -- Yves
4645          */
4646         if (PL_regkind[OP(scan)] == EXACT
4647             && OP(scan) != LEXACT
4648             && OP(scan) != LEXACT_REQ8
4649             && mutate_ok
4650         ) {
4651             join_exact(pRExC_state, scan, &min_subtract, &unfolded_multi_char,
4652                     0, NULL, depth + 1);
4653         }
4654
4655         /* Follow the next-chain of the current node and optimize
4656            away all the NOTHINGs from it.
4657          */
4658         rck_elide_nothing(scan);
4659
4660         /* The principal pseudo-switch.  Cannot be a switch, since we look into
4661          * several different things.  */
4662         if ( OP(scan) == DEFINEP ) {
4663             SSize_t minlen = 0;
4664             SSize_t deltanext = 0;
4665             SSize_t fake_last_close = 0;
4666             I32 f = SCF_IN_DEFINE;
4667
4668             StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4669             scan = regnext(scan);
4670             assert( OP(scan) == IFTHEN );
4671             DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4672
4673             data_fake.last_closep= &fake_last_close;
4674             minlen = *minlenp;
4675             next = regnext(scan);
4676             scan = NEXTOPER(NEXTOPER(scan));
4677             DEBUG_PEEP("scan", scan, depth, flags);
4678             DEBUG_PEEP("next", next, depth, flags);
4679
4680             /* we suppose the run is continuous, last=next...
4681              * NOTE we dont use the return here! */
4682             /* DEFINEP study_chunk() recursion */
4683             (void)study_chunk(pRExC_state, &scan, &minlen,
4684                               &deltanext, next, &data_fake, stopparen,
4685                               recursed_depth, NULL, f, depth+1, mutate_ok);
4686
4687             scan = next;
4688         } else
4689         if (
4690             OP(scan) == BRANCH  ||
4691             OP(scan) == BRANCHJ ||
4692             OP(scan) == IFTHEN
4693         ) {
4694             next = regnext(scan);
4695             code = OP(scan);
4696
4697             /* The op(next)==code check below is to see if we
4698              * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4699              * IFTHEN is special as it might not appear in pairs.
4700              * Not sure whether BRANCH-BRANCHJ is possible, regardless
4701              * we dont handle it cleanly. */
4702             if (OP(next) == code || code == IFTHEN) {
4703                 /* NOTE - There is similar code to this block below for
4704                  * handling TRIE nodes on a re-study.  If you change stuff here
4705                  * check there too. */
4706                 SSize_t max1 = 0, min1 = OPTIMIZE_INFTY, num = 0;
4707                 regnode_ssc accum;
4708                 regnode * const startbranch=scan;
4709
4710                 if (flags & SCF_DO_SUBSTR) {
4711                     /* Cannot merge strings after this. */
4712                     scan_commit(pRExC_state, data, minlenp, is_inf);
4713                 }
4714
4715                 if (flags & SCF_DO_STCLASS)
4716                     ssc_init_zero(pRExC_state, &accum);
4717
4718                 while (OP(scan) == code) {
4719                     SSize_t deltanext, minnext, fake;
4720                     I32 f = 0;
4721                     regnode_ssc this_class;
4722
4723                     DEBUG_PEEP("Branch", scan, depth, flags);
4724
4725                     num++;
4726                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4727                     if (data) {
4728                         data_fake.whilem_c = data->whilem_c;
4729                         data_fake.last_closep = data->last_closep;
4730                     }
4731                     else
4732                         data_fake.last_closep = &fake;
4733
4734                     data_fake.pos_delta = delta;
4735                     next = regnext(scan);
4736
4737                     scan = NEXTOPER(scan); /* everything */
4738                     if (code != BRANCH)    /* everything but BRANCH */
4739                         scan = NEXTOPER(scan);
4740
4741                     if (flags & SCF_DO_STCLASS) {
4742                         ssc_init(pRExC_state, &this_class);
4743                         data_fake.start_class = &this_class;
4744                         f = SCF_DO_STCLASS_AND;
4745                     }
4746                     if (flags & SCF_WHILEM_VISITED_POS)
4747                         f |= SCF_WHILEM_VISITED_POS;
4748
4749                     /* we suppose the run is continuous, last=next...*/
4750                     /* recurse study_chunk() for each BRANCH in an alternation */
4751                     minnext = study_chunk(pRExC_state, &scan, minlenp,
4752                                       &deltanext, next, &data_fake, stopparen,
4753                                       recursed_depth, NULL, f, depth+1,
4754                                       mutate_ok);
4755
4756                     if (min1 > minnext)
4757                         min1 = minnext;
4758                     if (deltanext == OPTIMIZE_INFTY) {
4759                         is_inf = is_inf_internal = 1;
4760                         max1 = OPTIMIZE_INFTY;
4761                     } else if (max1 < minnext + deltanext)
4762                         max1 = minnext + deltanext;
4763                     scan = next;
4764                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4765                         pars++;
4766                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4767                         if ( stopmin > minnext)
4768                             stopmin = min + min1;
4769                         flags &= ~SCF_DO_SUBSTR;
4770                         if (data)
4771                             data->flags |= SCF_SEEN_ACCEPT;
4772                     }
4773                     if (data) {
4774                         if (data_fake.flags & SF_HAS_EVAL)
4775                             data->flags |= SF_HAS_EVAL;
4776                         data->whilem_c = data_fake.whilem_c;
4777                     }
4778                     if (flags & SCF_DO_STCLASS)
4779                         ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4780                 }
4781                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4782                     min1 = 0;
4783                 if (flags & SCF_DO_SUBSTR) {
4784                     data->pos_min += min1;
4785                     if (data->pos_delta >= OPTIMIZE_INFTY - (max1 - min1))
4786                         data->pos_delta = OPTIMIZE_INFTY;
4787                     else
4788                         data->pos_delta += max1 - min1;
4789                     if (max1 != min1 || is_inf)
4790                         data->cur_is_floating = 1;
4791                 }
4792                 min += min1;
4793                 if (delta == OPTIMIZE_INFTY
4794                  || OPTIMIZE_INFTY - delta - (max1 - min1) < 0)
4795                     delta = OPTIMIZE_INFTY;
4796                 else
4797                     delta += max1 - min1;
4798                 if (flags & SCF_DO_STCLASS_OR) {
4799                     ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4800                     if (min1) {
4801                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4802                         flags &= ~SCF_DO_STCLASS;
4803                     }
4804                 }
4805                 else if (flags & SCF_DO_STCLASS_AND) {
4806                     if (min1) {
4807                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4808                         flags &= ~SCF_DO_STCLASS;
4809                     }
4810                     else {
4811                         /* Switch to OR mode: cache the old value of
4812                          * data->start_class */
4813                         INIT_AND_WITHP;
4814                         StructCopy(data->start_class, and_withp, regnode_ssc);
4815                         flags &= ~SCF_DO_STCLASS_AND;
4816                         StructCopy(&accum, data->start_class, regnode_ssc);
4817                         flags |= SCF_DO_STCLASS_OR;
4818                     }
4819                 }
4820
4821                 if (PERL_ENABLE_TRIE_OPTIMISATION
4822                     && OP(startbranch) == BRANCH
4823                     && mutate_ok
4824                 ) {
4825                 /* demq.
4826
4827                    Assuming this was/is a branch we are dealing with: 'scan'
4828                    now points at the item that follows the branch sequence,
4829                    whatever it is. We now start at the beginning of the
4830                    sequence and look for subsequences of
4831
4832                    BRANCH->EXACT=>x1
4833                    BRANCH->EXACT=>x2
4834                    tail
4835
4836                    which would be constructed from a pattern like
4837                    /A|LIST|OF|WORDS/
4838
4839                    If we can find such a subsequence we need to turn the first
4840                    element into a trie and then add the subsequent branch exact
4841                    strings to the trie.
4842
4843                    We have two cases
4844
4845                      1. patterns where the whole set of branches can be
4846                         converted.
4847
4848                      2. patterns where only a subset can be converted.
4849
4850                    In case 1 we can replace the whole set with a single regop
4851                    for the trie. In case 2 we need to keep the start and end
4852                    branches so
4853
4854                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4855                      becomes BRANCH TRIE; BRANCH X;
4856
4857                   There is an additional case, that being where there is a
4858                   common prefix, which gets split out into an EXACT like node
4859                   preceding the TRIE node.
4860
4861                   If x(1..n)==tail then we can do a simple trie, if not we make
4862                   a "jump" trie, such that when we match the appropriate word
4863                   we "jump" to the appropriate tail node. Essentially we turn
4864                   a nested if into a case structure of sorts.
4865
4866                 */
4867
4868                     int made=0;
4869                     if (!re_trie_maxbuff) {
4870                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4871                         if (!SvIOK(re_trie_maxbuff))
4872                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4873                     }
4874                     if ( SvIV(re_trie_maxbuff)>=0  ) {
4875                         regnode *cur;
4876                         regnode *first = (regnode *)NULL;
4877                         regnode *prev = (regnode *)NULL;
4878                         regnode *tail = scan;
4879                         U8 trietype = 0;
4880                         U32 count=0;
4881
4882                         /* var tail is used because there may be a TAIL
4883                            regop in the way. Ie, the exacts will point to the
4884                            thing following the TAIL, but the last branch will
4885                            point at the TAIL. So we advance tail. If we
4886                            have nested (?:) we may have to move through several
4887                            tails.
4888                          */
4889
4890                         while ( OP( tail ) == TAIL ) {
4891                             /* this is the TAIL generated by (?:) */
4892                             tail = regnext( tail );
4893                         }
4894
4895
4896                         DEBUG_TRIE_COMPILE_r({
4897                             regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4898                             Perl_re_indentf( aTHX_  "%s %" UVuf ":%s\n",
4899                               depth+1,
4900                               "Looking for TRIE'able sequences. Tail node is ",
4901                               (UV) REGNODE_OFFSET(tail),
4902                               SvPV_nolen_const( RExC_mysv )
4903                             );
4904                         });
4905
4906                         /*
4907
4908                             Step through the branches
4909                                 cur represents each branch,
4910                                 noper is the first thing to be matched as part
4911                                       of that branch
4912                                 noper_next is the regnext() of that node.
4913
4914                             We normally handle a case like this
4915                             /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4916                             support building with NOJUMPTRIE, which restricts
4917                             the trie logic to structures like /FOO|BAR/.
4918
4919                             If noper is a trieable nodetype then the branch is
4920                             a possible optimization target. If we are building
4921                             under NOJUMPTRIE then we require that noper_next is
4922                             the same as scan (our current position in the regex
4923                             program).
4924
4925                             Once we have two or more consecutive such branches
4926                             we can create a trie of the EXACT's contents and
4927                             stitch it in place into the program.
4928
4929                             If the sequence represents all of the branches in
4930                             the alternation we replace the entire thing with a
4931                             single TRIE node.
4932
4933                             Otherwise when it is a subsequence we need to
4934                             stitch it in place and replace only the relevant
4935                             branches. This means the first branch has to remain
4936                             as it is used by the alternation logic, and its
4937                             next pointer, and needs to be repointed at the item
4938                             on the branch chain following the last branch we
4939                             have optimized away.
4940
4941                             This could be either a BRANCH, in which case the
4942                             subsequence is internal, or it could be the item
4943                             following the branch sequence in which case the
4944                             subsequence is at the end (which does not
4945                             necessarily mean the first node is the start of the
4946                             alternation).
4947
4948                             TRIE_TYPE(X) is a define which maps the optype to a
4949                             trietype.
4950
4951                                 optype          |  trietype
4952                                 ----------------+-----------
4953                                 NOTHING         | NOTHING
4954                                 EXACT           | EXACT
4955                                 EXACT_REQ8     | EXACT
4956                                 EXACTFU         | EXACTFU
4957                                 EXACTFU_REQ8   | EXACTFU
4958                                 EXACTFUP        | EXACTFU
4959                                 EXACTFAA        | EXACTFAA
4960                                 EXACTL          | EXACTL
4961                                 EXACTFLU8       | EXACTFLU8
4962
4963
4964                         */
4965 #define TRIE_TYPE(X) ( ( NOTHING == (X) )                                   \
4966                        ? NOTHING                                            \
4967                        : ( EXACT == (X) || EXACT_REQ8 == (X) )             \
4968                          ? EXACT                                            \
4969                          : (     EXACTFU == (X)                             \
4970                               || EXACTFU_REQ8 == (X)                       \
4971                               || EXACTFUP == (X) )                          \
4972                            ? EXACTFU                                        \
4973                            : ( EXACTFAA == (X) )                            \
4974                              ? EXACTFAA                                     \
4975                              : ( EXACTL == (X) )                            \
4976                                ? EXACTL                                     \
4977                                : ( EXACTFLU8 == (X) )                       \
4978                                  ? EXACTFLU8                                \
4979                                  : 0 )
4980
4981                         /* dont use tail as the end marker for this traverse */
4982                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4983                             regnode * const noper = NEXTOPER( cur );
4984                             U8 noper_type = OP( noper );
4985                             U8 noper_trietype = TRIE_TYPE( noper_type );
4986 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4987                             regnode * const noper_next = regnext( noper );
4988                             U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4989                             U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
4990 #endif
4991
4992                             DEBUG_TRIE_COMPILE_r({
4993                                 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4994                                 Perl_re_indentf( aTHX_  "- %d:%s (%d)",
4995                                    depth+1,
4996                                    REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4997
4998                                 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4999                                 Perl_re_printf( aTHX_  " -> %d:%s",
5000                                     REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
5001
5002                                 if ( noper_next ) {
5003                                   regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
5004                                   Perl_re_printf( aTHX_ "\t=> %d:%s\t",
5005                                     REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
5006                                 }
5007                                 Perl_re_printf( aTHX_  "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
5008                                    REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5009                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
5010                                 );
5011                             });
5012
5013                             /* Is noper a trieable nodetype that can be merged
5014                              * with the current trie (if there is one)? */
5015                             if ( noper_trietype
5016                                   &&
5017                                   (
5018                                         ( noper_trietype == NOTHING )
5019                                         || ( trietype == NOTHING )
5020                                         || ( trietype == noper_trietype )
5021                                   )
5022 #ifdef NOJUMPTRIE
5023                                   && noper_next >= tail
5024 #endif
5025                                   && count < U16_MAX)
5026                             {
5027                                 /* Handle mergable triable node Either we are
5028                                  * the first node in a new trieable sequence,
5029                                  * in which case we do some bookkeeping,
5030                                  * otherwise we update the end pointer. */
5031                                 if ( !first ) {
5032                                     first = cur;
5033                                     if ( noper_trietype == NOTHING ) {
5034 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
5035                                         regnode * const noper_next = regnext( noper );
5036                                         U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
5037                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
5038 #endif
5039
5040                                         if ( noper_next_trietype ) {
5041                                             trietype = noper_next_trietype;
5042                                         } else if (noper_next_type)  {
5043                                             /* a NOTHING regop is 1 regop wide.
5044                                              * We need at least two for a trie
5045                                              * so we can't merge this in */
5046                                             first = NULL;
5047                                         }
5048                                     } else {
5049                                         trietype = noper_trietype;
5050                                     }
5051                                 } else {
5052                                     if ( trietype == NOTHING )
5053                                         trietype = noper_trietype;
5054                                     prev = cur;
5055                                 }
5056                                 if (first)
5057                                     count++;
5058                             } /* end handle mergable triable node */
5059                             else {
5060                                 /* handle unmergable node -
5061                                  * noper may either be a triable node which can
5062                                  * not be tried together with the current trie,
5063                                  * or a non triable node */
5064                                 if ( prev ) {
5065                                     /* If last is set and trietype is not
5066                                      * NOTHING then we have found at least two
5067                                      * triable branch sequences in a row of a
5068                                      * similar trietype so we can turn them
5069                                      * into a trie. If/when we allow NOTHING to
5070                                      * start a trie sequence this condition
5071                                      * will be required, and it isn't expensive
5072                                      * so we leave it in for now. */
5073                                     if ( trietype && trietype != NOTHING )
5074                                         make_trie( pRExC_state,
5075                                                 startbranch, first, cur, tail,
5076                                                 count, trietype, depth+1 );
5077                                     prev = NULL; /* note: we clear/update
5078                                                     first, trietype etc below,
5079                                                     so we dont do it here */
5080                                 }
5081                                 if ( noper_trietype
5082 #ifdef NOJUMPTRIE
5083                                      && noper_next >= tail
5084 #endif
5085                                 ){
5086                                     /* noper is triable, so we can start a new
5087                                      * trie sequence */
5088                                     count = 1;
5089                                     first = cur;
5090                                     trietype = noper_trietype;
5091                                 } else if (first) {
5092                                     /* if we already saw a first but the
5093                                      * current node is not triable then we have
5094                                      * to reset the first information. */
5095                                     count = 0;
5096                                     first = NULL;
5097                                     trietype = 0;
5098                                 }
5099                             } /* end handle unmergable node */
5100                         } /* loop over branches */
5101                         DEBUG_TRIE_COMPILE_r({
5102                             regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5103                             Perl_re_indentf( aTHX_  "- %s (%d) <SCAN FINISHED> ",
5104                               depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5105                             Perl_re_printf( aTHX_  "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
5106                                REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5107                                PL_reg_name[trietype]
5108                             );
5109
5110                         });
5111                         if ( prev && trietype ) {
5112                             if ( trietype != NOTHING ) {
5113                                 /* the last branch of the sequence was part of
5114                                  * a trie, so we have to construct it here
5115                                  * outside of the loop */
5116                                 made= make_trie( pRExC_state, startbranch,
5117                                                  first, scan, tail, count,
5118                                                  trietype, depth+1 );
5119 #ifdef TRIE_STUDY_OPT
5120                                 if ( ((made == MADE_EXACT_TRIE &&
5121                                      startbranch == first)
5122                                      || ( first_non_open == first )) &&
5123                                      depth==0 ) {
5124                                     flags |= SCF_TRIE_RESTUDY;
5125                                     if ( startbranch == first
5126                                          && scan >= tail )
5127                                     {
5128                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
5129                                     }
5130                                 }
5131 #endif
5132                             } else {
5133                                 /* at this point we know whatever we have is a
5134                                  * NOTHING sequence/branch AND if 'startbranch'
5135                                  * is 'first' then we can turn the whole thing
5136                                  * into a NOTHING
5137                                  */
5138                                 if ( startbranch == first ) {
5139                                     regnode *opt;
5140                                     /* the entire thing is a NOTHING sequence,
5141                                      * something like this: (?:|) So we can
5142                                      * turn it into a plain NOTHING op. */
5143                                     DEBUG_TRIE_COMPILE_r({
5144                                         regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5145                                         Perl_re_indentf( aTHX_  "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
5146                                           depth+1,
5147                                           SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5148
5149                                     });
5150                                     OP(startbranch)= NOTHING;
5151                                     NEXT_OFF(startbranch)= tail - startbranch;
5152                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
5153                                         OP(opt)= OPTIMIZED;
5154                                 }
5155                             }
5156                         } /* end if ( prev) */
5157                     } /* TRIE_MAXBUF is non zero */
5158                 } /* do trie */
5159
5160             }
5161             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
5162                 scan = NEXTOPER(NEXTOPER(scan));
5163             } else                      /* single branch is optimized. */
5164                 scan = NEXTOPER(scan);
5165             continue;
5166         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
5167             I32 paren = 0;
5168             regnode *start = NULL;
5169             regnode *end = NULL;
5170             U32 my_recursed_depth= recursed_depth;
5171
5172             if (OP(scan) != SUSPEND) { /* GOSUB */
5173                 /* Do setup, note this code has side effects beyond
5174                  * the rest of this block. Specifically setting
5175                  * RExC_recurse[] must happen at least once during
5176                  * study_chunk(). */
5177                 paren = ARG(scan);
5178                 RExC_recurse[ARG2L(scan)] = scan;
5179                 start = REGNODE_p(RExC_open_parens[paren]);
5180                 end   = REGNODE_p(RExC_close_parens[paren]);
5181
5182                 /* NOTE we MUST always execute the above code, even
5183                  * if we do nothing with a GOSUB */
5184                 if (
5185                     ( flags & SCF_IN_DEFINE )
5186                     ||
5187                     (
5188                         (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
5189                         &&
5190                         ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
5191                     )
5192                 ) {
5193                     /* no need to do anything here if we are in a define. */
5194                     /* or we are after some kind of infinite construct
5195                      * so we can skip recursing into this item.
5196                      * Since it is infinite we will not change the maxlen
5197                      * or delta, and if we miss something that might raise
5198                      * the minlen it will merely pessimise a little.
5199                      *
5200                      * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
5201                      * might result in a minlen of 1 and not of 4,
5202                      * but this doesn't make us mismatch, just try a bit
5203                      * harder than we should.
5204                      *
5205                      * However we must assume this GOSUB is infinite, to
5206                      * avoid wrongly applying other optimizations in the
5207                      * enclosing scope - see GH 18096, for example.
5208                      */
5209                     is_inf = is_inf_internal = 1;
5210                     scan= regnext(scan);
5211                     continue;
5212                 }
5213
5214                 if (
5215                     !recursed_depth
5216                     || !PAREN_TEST(recursed_depth - 1, paren)
5217                 ) {
5218                     /* it is quite possible that there are more efficient ways
5219                      * to do this. We maintain a bitmap per level of recursion
5220                      * of which patterns we have entered so we can detect if a
5221                      * pattern creates a possible infinite loop. When we
5222                      * recurse down a level we copy the previous levels bitmap
5223                      * down. When we are at recursion level 0 we zero the top
5224                      * level bitmap. It would be nice to implement a different
5225                      * more efficient way of doing this. In particular the top
5226                      * level bitmap may be unnecessary.
5227                      */
5228                     if (!recursed_depth) {
5229                         Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
5230                     } else {
5231                         Copy(PAREN_OFFSET(recursed_depth - 1),
5232                              PAREN_OFFSET(recursed_depth),
5233                              RExC_study_chunk_recursed_bytes, U8);
5234                     }
5235                     /* we havent recursed into this paren yet, so recurse into it */
5236                     DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
5237                     PAREN_SET(recursed_depth, paren);
5238                     my_recursed_depth= recursed_depth + 1;
5239                 } else {
5240                     DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
5241                     /* some form of infinite recursion, assume infinite length
5242                      * */
5243                     if (flags & SCF_DO_SUBSTR) {
5244                         scan_commit(pRExC_state, data, minlenp, is_inf);
5245                         data->cur_is_floating = 1;
5246                     }
5247                     is_inf = is_inf_internal = 1;
5248                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5249                         ssc_anything(data->start_class);
5250                     flags &= ~SCF_DO_STCLASS;
5251
5252                     start= NULL; /* reset start so we dont recurse later on. */
5253                 }
5254             } else {
5255                 paren = stopparen;
5256                 start = scan + 2;
5257                 end = regnext(scan);
5258             }
5259             if (start) {
5260                 scan_frame *newframe;
5261                 assert(end);
5262                 if (!RExC_frame_last) {
5263                     Newxz(newframe, 1, scan_frame);
5264                     SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
5265                     RExC_frame_head= newframe;
5266                     RExC_frame_count++;
5267                 } else if (!RExC_frame_last->next_frame) {
5268                     Newxz(newframe, 1, scan_frame);
5269                     RExC_frame_last->next_frame= newframe;
5270                     newframe->prev_frame= RExC_frame_last;
5271                     RExC_frame_count++;
5272                 } else {
5273                     newframe= RExC_frame_last->next_frame;
5274                 }
5275                 RExC_frame_last= newframe;
5276
5277                 newframe->next_regnode = regnext(scan);
5278                 newframe->last_regnode = last;
5279                 newframe->stopparen = stopparen;
5280                 newframe->prev_recursed_depth = recursed_depth;
5281                 newframe->this_prev_frame= frame;
5282                 newframe->in_gosub = (
5283                     (frame && frame->in_gosub) || OP(scan) == GOSUB
5284                 );
5285
5286                 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
5287                 DEBUG_PEEP("fnew", scan, depth, flags);
5288
5289                 frame = newframe;
5290                 scan =  start;
5291                 stopparen = paren;
5292                 last = end;
5293                 depth = depth + 1;
5294                 recursed_depth= my_recursed_depth;
5295
5296                 continue;
5297             }
5298         }
5299         else if (PL_regkind[OP(scan)] == EXACT && ! isEXACTFish(OP(scan))) {
5300             SSize_t bytelen = STR_LEN(scan), charlen;
5301             UV uc;
5302             assert(bytelen);
5303             if (UTF) {
5304                 const U8 * const s = (U8*)STRING(scan);
5305                 uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
5306                 charlen = utf8_length(s, s + bytelen);
5307             } else {
5308                 uc = *((U8*)STRING(scan));
5309                 charlen = bytelen;
5310             }
5311             min += charlen;
5312             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5313                 /* The code below prefers earlier match for fixed
5314                    offset, later match for variable offset.  */
5315                 if (data->last_end == -1) { /* Update the start info. */
5316                     data->last_start_min = data->pos_min;
5317                     data->last_start_max =
5318                         is_inf ? OPTIMIZE_INFTY
5319                         : (data->pos_delta > OPTIMIZE_INFTY - data->pos_min)
5320                             ? OPTIMIZE_INFTY : data->pos_min + data->pos_delta;
5321                 }
5322                 sv_catpvn(data->last_found, STRING(scan), bytelen);
5323                 if (UTF)
5324                     SvUTF8_on(data->last_found);
5325                 {
5326                     SV * const sv = data->last_found;
5327                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5328                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5329                     if (mg && mg->mg_len >= 0)
5330                         mg->mg_len += charlen;
5331                 }
5332                 data->last_end = data->pos_min + charlen;
5333                 data->pos_min += charlen; /* As in the first entry. */
5334                 data->flags &= ~SF_BEFORE_EOL;
5335             }
5336
5337             /* ANDing the code point leaves at most it, and not in locale, and
5338              * can't match null string */
5339             if (flags & SCF_DO_STCLASS_AND) {
5340                 ssc_cp_and(data->start_class, uc);
5341                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5342                 ssc_clear_locale(data->start_class);
5343             }
5344             else if (flags & SCF_DO_STCLASS_OR) {
5345                 ssc_add_cp(data->start_class, uc);
5346                 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5347
5348                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5349                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5350             }
5351             flags &= ~SCF_DO_STCLASS;
5352         }
5353         else if (PL_regkind[OP(scan)] == EXACT) {
5354             /* But OP != EXACT!, so is EXACTFish */
5355             SSize_t bytelen = STR_LEN(scan), charlen;
5356             const U8 * s = (U8*)STRING(scan);
5357
5358             /* Replace a length 1 ASCII fold pair node with an ANYOFM node,
5359              * with the mask set to the complement of the bit that differs
5360              * between upper and lower case, and the lowest code point of the
5361              * pair (which the '&' forces) */
5362             if (     bytelen == 1
5363                 &&   isALPHA_A(*s)
5364                 &&  (         OP(scan) == EXACTFAA
5365                      || (     OP(scan) == EXACTFU
5366                          && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(*s)))
5367                 &&   mutate_ok
5368             ) {
5369                 U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
5370
5371                 OP(scan) = ANYOFM;
5372                 ARG_SET(scan, *s & mask);
5373                 FLAGS(scan) = mask;
5374                 /* we're not EXACTFish any more, so restudy */
5375                 continue;
5376             }
5377
5378             /* Search for fixed substrings supports EXACT only. */
5379             if (flags & SCF_DO_SUBSTR) {
5380                 assert(data);
5381                 scan_commit(pRExC_state, data, minlenp, is_inf);
5382             }
5383             charlen = UTF ? (SSize_t) utf8_length(s, s + bytelen) : bytelen;
5384             if (unfolded_multi_char) {
5385                 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5386             }
5387             min += charlen - min_subtract;
5388             assert (min >= 0);
5389             if ((SSize_t)min_subtract < OPTIMIZE_INFTY
5390                 && delta < OPTIMIZE_INFTY - (SSize_t)min_subtract
5391             ) {
5392                 delta += min_subtract;
5393             } else {
5394                 delta = OPTIMIZE_INFTY;
5395             }
5396             if (flags & SCF_DO_SUBSTR) {
5397                 data->pos_min += charlen - min_subtract;
5398                 if (data->pos_min < 0) {
5399                     data->pos_min = 0;
5400                 }
5401                 if ((SSize_t)min_subtract < OPTIMIZE_INFTY
5402                     && data->pos_delta < OPTIMIZE_INFTY - (SSize_t)min_subtract
5403                 ) {
5404                     data->pos_delta += min_subtract;
5405                 } else {
5406                     data->pos_delta = OPTIMIZE_INFTY;
5407                 }
5408                 if (min_subtract) {
5409                     data->cur_is_floating = 1; /* float */
5410                 }
5411             }
5412
5413             if (flags & SCF_DO_STCLASS) {
5414                 SV* EXACTF_invlist = make_exactf_invlist(pRExC_state, scan);
5415
5416                 assert(EXACTF_invlist);
5417                 if (flags & SCF_DO_STCLASS_AND) {
5418                     if (OP(scan) != EXACTFL)
5419                         ssc_clear_locale(data->start_class);
5420                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5421                     ANYOF_POSIXL_ZERO(data->start_class);
5422                     ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5423                 }
5424                 else {  /* SCF_DO_STCLASS_OR */
5425                     ssc_union(data->start_class, EXACTF_invlist, FALSE);
5426                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5427
5428                     /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5429                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5430                 }
5431                 flags &= ~SCF_DO_STCLASS;
5432                 SvREFCNT_dec(EXACTF_invlist);
5433             }
5434         }
5435         else if (REGNODE_VARIES(OP(scan))) {
5436             SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5437             I32 fl = 0, f = flags;
5438             regnode * const oscan = scan;
5439             regnode_ssc this_class;
5440             regnode_ssc *oclass = NULL;
5441             I32 next_is_eval = 0;
5442
5443             switch (PL_regkind[OP(scan)]) {
5444             case WHILEM:                /* End of (?:...)* . */
5445                 scan = NEXTOPER(scan);
5446                 goto finish;
5447             case PLUS:
5448                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5449                     next = NEXTOPER(scan);
5450                     if (   (     PL_regkind[OP(next)] == EXACT
5451                             && ! isEXACTFish(OP(next)))
5452                         || (flags & SCF_DO_STCLASS))
5453                     {
5454                         mincount = 1;
5455                         maxcount = REG_INFTY;
5456                         next = regnext(scan);
5457                         scan = NEXTOPER(scan);
5458                         goto do_curly;
5459                     }
5460                 }
5461                 if (flags & SCF_DO_SUBSTR)
5462                     data->pos_min++;
5463                 /* This will bypass the formal 'min += minnext * mincount'
5464                  * calculation in the do_curly path, so assumes min width
5465                  * of the PLUS payload is exactly one. */
5466                 min++;
5467                 /* FALLTHROUGH */
5468             case STAR:
5469                 next = NEXTOPER(scan);
5470
5471                 /* This temporary node can now be turned into EXACTFU, and
5472                  * must, as regexec.c doesn't handle it */
5473                 if (OP(next) == EXACTFU_S_EDGE && mutate_ok) {
5474                     OP(next) = EXACTFU;
5475                 }
5476
5477                 if (     STR_LEN(next) == 1
5478                     &&   isALPHA_A(* STRING(next))
5479                     && (         OP(next) == EXACTFAA
5480                         || (     OP(next) == EXACTFU
5481                             && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))
5482                     &&   mutate_ok
5483                 ) {
5484                     /* These differ in just one bit */
5485                     U8 mask = ~ ('A' ^ 'a');
5486
5487                     assert(isALPHA_A(* STRING(next)));
5488
5489                     /* Then replace it by an ANYOFM node, with
5490                     * the mask set to the complement of the
5491                     * bit that differs between upper and lower
5492                     * case, and the lowest code point of the
5493                     * pair (which the '&' forces) */
5494                     OP(next) = ANYOFM;
5495                     ARG_SET(next, *STRING(next) & mask);
5496                     FLAGS(next) = mask;
5497                 }
5498
5499                 if (flags & SCF_DO_STCLASS) {
5500                     mincount = 0;
5501                     maxcount = REG_INFTY;
5502                     next = regnext(scan);
5503                     scan = NEXTOPER(scan);
5504                     goto do_curly;
5505                 }
5506                 if (flags & SCF_DO_SUBSTR) {
5507                     scan_commit(pRExC_state, data, minlenp, is_inf);
5508                     /* Cannot extend fixed substrings */
5509                     data->cur_is_floating = 1; /* float */
5510                 }
5511                 is_inf = is_inf_internal = 1;
5512                 scan = regnext(scan);
5513                 goto optimize_curly_tail;
5514             case CURLY:
5515                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5516                     && (scan->flags == stopparen))
5517                 {
5518                     mincount = 1;
5519                     maxcount = 1;
5520                 } else {
5521                     mincount = ARG1(scan);
5522                     maxcount = ARG2(scan);
5523                 }
5524                 next = regnext(scan);
5525                 if (OP(scan) == CURLYX) {
5526                     I32 lp = (data ? *(data->last_closep) : 0);
5527                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5528                 }
5529                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5530                 next_is_eval = (OP(scan) == EVAL);
5531               do_curly:
5532                 if (flags & SCF_DO_SUBSTR) {
5533                     if (mincount == 0)
5534                         scan_commit(pRExC_state, data, minlenp, is_inf);
5535                     /* Cannot extend fixed substrings */
5536                     pos_before = data->pos_min;
5537                 }
5538                 if (data) {
5539                     fl = data->flags;
5540                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5541                     if (is_inf)
5542                         data->flags |= SF_IS_INF;
5543                 }
5544                 if (flags & SCF_DO_STCLASS) {
5545                     ssc_init(pRExC_state, &this_class);
5546                     oclass = data->start_class;
5547                     data->start_class = &this_class;
5548                     f |= SCF_DO_STCLASS_AND;
5549                     f &= ~SCF_DO_STCLASS_OR;
5550                 }
5551                 /* Exclude from super-linear cache processing any {n,m}
5552                    regops for which the combination of input pos and regex
5553                    pos is not enough information to determine if a match
5554                    will be possible.
5555
5556                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
5557                    regex pos at the \s*, the prospects for a match depend not
5558                    only on the input position but also on how many (bar\s*)
5559                    repeats into the {4,8} we are. */
5560                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5561                     f &= ~SCF_WHILEM_VISITED_POS;
5562
5563                 /* This will finish on WHILEM, setting scan, or on NULL: */
5564                 /* recurse study_chunk() on loop bodies */
5565                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5566                                   last, data, stopparen, recursed_depth, NULL,
5567                                   (mincount == 0
5568                                    ? (f & ~SCF_DO_SUBSTR)
5569                                    : f)
5570                                   , depth+1, mutate_ok);
5571
5572                 if (flags & SCF_DO_STCLASS)
5573                     data->start_class = oclass;
5574                 if (mincount == 0 || minnext == 0) {
5575                     if (flags & SCF_DO_STCLASS_OR) {
5576                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5577                     }
5578                     else if (flags & SCF_DO_STCLASS_AND) {
5579                         /* Switch to OR mode: cache the old value of
5580                          * data->start_class */
5581                         INIT_AND_WITHP;
5582                         StructCopy(data->start_class, and_withp, regnode_ssc);
5583                         flags &= ~SCF_DO_STCLASS_AND;
5584                         StructCopy(&this_class, data->start_class, regnode_ssc);
5585                         flags |= SCF_DO_STCLASS_OR;
5586                         ANYOF_FLAGS(data->start_class)
5587                                                 |= SSC_MATCHES_EMPTY_STRING;
5588                     }
5589                 } else {                /* Non-zero len */
5590                     if (flags & SCF_DO_STCLASS_OR) {
5591                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5592                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5593                     }
5594                     else if (flags & SCF_DO_STCLASS_AND)
5595                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5596                     flags &= ~SCF_DO_STCLASS;
5597                 }
5598                 if (!scan)              /* It was not CURLYX, but CURLY. */
5599                     scan = next;
5600                 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5601                     /* ? quantifier ok, except for (?{ ... }) */
5602                     && (next_is_eval || !(mincount == 0 && maxcount == 1))
5603                     && (minnext == 0) && (deltanext == 0)
5604                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5605                     && maxcount <= REG_INFTY/3) /* Complement check for big
5606                                                    count */
5607                 {
5608                     _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5609                         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5610                             "Quantifier unexpected on zero-length expression "
5611                             "in regex m/%" UTF8f "/",
5612                              UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5613                                   RExC_precomp)));
5614                 }
5615
5616                 if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext )
5617                     || min >= SSize_t_MAX - minnext * mincount )
5618                 {
5619                     FAIL("Regexp out of space");
5620                 }
5621
5622                 min += minnext * mincount;
5623                 is_inf_internal |= deltanext == OPTIMIZE_INFTY
5624                          || (maxcount == REG_INFTY && minnext + deltanext > 0);
5625                 is_inf |= is_inf_internal;
5626                 if (is_inf) {
5627                     delta = OPTIMIZE_INFTY;
5628                 } else {
5629                     delta += (minnext + deltanext) * maxcount
5630                              - minnext * mincount;
5631                 }
5632                 /* Try powerful optimization CURLYX => CURLYN. */
5633                 if (  OP(oscan) == CURLYX && data
5634                       && data->flags & SF_IN_PAR
5635                       && !(data->flags & SF_HAS_EVAL)
5636                       && !deltanext && minnext == 1
5637                       && mutate_ok
5638                 ) {
5639                     /* Try to optimize to CURLYN.  */
5640                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5641                     regnode * const nxt1 = nxt;
5642 #ifdef DEBUGGING
5643                     regnode *nxt2;
5644 #endif
5645
5646                     /* Skip open. */
5647                     nxt = regnext(nxt);
5648                     if (!REGNODE_SIMPLE(OP(nxt))
5649                         && !(PL_regkind[OP(nxt)] == EXACT
5650                              && STR_LEN(nxt) == 1))
5651                         goto nogo;
5652 #ifdef DEBUGGING
5653                     nxt2 = nxt;
5654 #endif
5655                     nxt = regnext(nxt);
5656                     if (OP(nxt) != CLOSE)
5657                         goto nogo;
5658                     if (RExC_open_parens) {
5659
5660                         /*open->CURLYM*/
5661                         RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5662
5663                         /*close->while*/
5664                         RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5665                     }
5666                     /* Now we know that nxt2 is the only contents: */
5667                     oscan->flags = (U8)ARG(nxt);
5668                     OP(oscan) = CURLYN;
5669                     OP(nxt1) = NOTHING; /* was OPEN. */
5670
5671 #ifdef DEBUGGING
5672                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5673                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5674                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5675                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
5676                     OP(nxt + 1) = OPTIMIZED; /* was count. */
5677                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5678 #endif
5679                 }
5680               nogo:
5681
5682                 /* Try optimization CURLYX => CURLYM. */
5683                 if (  OP(oscan) == CURLYX && data
5684                       && !(data->flags & SF_HAS_PAR)
5685                       && !(data->flags & SF_HAS_EVAL)
5686                       && !deltanext     /* atom is fixed width */
5687                       && minnext != 0   /* CURLYM can't handle zero width */
5688                          /* Nor characters whose fold at run-time may be
5689                           * multi-character */
5690                       && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5691                       && mutate_ok
5692                 ) {
5693                     /* XXXX How to optimize if data == 0? */
5694                     /* Optimize to a simpler form.  */
5695                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5696                     regnode *nxt2;
5697
5698                     OP(oscan) = CURLYM;
5699                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5700                             && (OP(nxt2) != WHILEM))
5701                         nxt = nxt2;
5702                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
5703                     /* Need to optimize away parenths. */
5704                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5705                         /* Set the parenth number.  */
5706                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5707
5708                         oscan->flags = (U8)ARG(nxt);
5709                         if (RExC_open_parens) {
5710                              /*open->CURLYM*/
5711                             RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5712
5713                             /*close->NOTHING*/
5714                             RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5715                                                          + 1;
5716                         }
5717                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
5718                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
5719
5720 #ifdef DEBUGGING
5721                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5722                         OP(nxt + 1) = OPTIMIZED; /* was count. */
5723                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5724                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5725 #endif
5726 #if 0
5727                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
5728                             regnode *nnxt = regnext(nxt1);
5729                             if (nnxt == nxt) {
5730                                 if (reg_off_by_arg[OP(nxt1)])
5731                                     ARG_SET(nxt1, nxt2 - nxt1);
5732                                 else if (nxt2 - nxt1 < U16_MAX)
5733                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
5734                                 else
5735                                     OP(nxt) = NOTHING;  /* Cannot beautify */
5736                             }
5737                             nxt1 = nnxt;
5738                         }
5739 #endif
5740                         /* Optimize again: */
5741                         /* recurse study_chunk() on optimised CURLYX => CURLYM */
5742                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5743                                     NULL, stopparen, recursed_depth, NULL, 0,
5744                                     depth+1, mutate_ok);
5745                     }
5746                     else
5747                         oscan->flags = 0;
5748                 }
5749                 else if ((OP(oscan) == CURLYX)
5750                          && (flags & SCF_WHILEM_VISITED_POS)
5751                          /* See the comment on a similar expression above.
5752                             However, this time it's not a subexpression
5753                             we care about, but the expression itself. */
5754                          && (maxcount == REG_INFTY)
5755                          && data) {
5756                     /* This stays as CURLYX, we can put the count/of pair. */
5757                     /* Find WHILEM (as in regexec.c) */
5758                     regnode *nxt = oscan + NEXT_OFF(oscan);
5759
5760                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5761                         nxt += ARG(nxt);
5762                     nxt = PREVOPER(nxt);
5763                     if (nxt->flags & 0xf) {
5764                         /* we've already set whilem count on this node */
5765                     } else if (++data->whilem_c < 16) {
5766                         assert(data->whilem_c <= RExC_whilem_seen);
5767                         nxt->flags = (U8)(data->whilem_c
5768                             | (RExC_whilem_seen << 4)); /* On WHILEM */
5769                     }
5770                 }
5771                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5772                     pars++;
5773                 if (flags & SCF_DO_SUBSTR) {
5774                     SV *last_str = NULL;
5775                     STRLEN last_chrs = 0;
5776                     int counted = mincount != 0;
5777
5778                     if (data->last_end > 0 && mincount != 0) { /* Ends with a
5779                                                                   string. */
5780                         SSize_t b = pos_before >= data->last_start_min
5781                             ? pos_before : data->last_start_min;
5782                         STRLEN l;
5783                         const char * const s = SvPV_const(data->last_found, l);
5784                         SSize_t old = b - data->last_start_min;
5785                         assert(old >= 0);
5786
5787                         if (UTF)
5788                             old = utf8_hop_forward((U8*)s, old,
5789                                                (U8 *) SvEND(data->last_found))
5790                                 - (U8*)s;
5791                         l -= old;
5792                         /* Get the added string: */
5793                         last_str = newSVpvn_utf8(s  + old, l, UTF);
5794                         last_chrs = UTF ? utf8_length((U8*)(s + old),
5795                                             (U8*)(s + old + l)) : l;
5796                         if (deltanext == 0 && pos_before == b) {
5797                             /* What was added is a constant string */
5798                             if (mincount > 1) {
5799
5800                                 SvGROW(last_str, (mincount * l) + 1);
5801                                 repeatcpy(SvPVX(last_str) + l,
5802                                           SvPVX_const(last_str), l,
5803                                           mincount - 1);
5804                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5805                                 /* Add additional parts. */
5806                                 SvCUR_set(data->last_found,
5807                                           SvCUR(data->last_found) - l);
5808                                 sv_catsv(data->last_found, last_str);
5809                                 {
5810                                     SV * sv = data->last_found;
5811                                     MAGIC *mg =
5812                                         SvUTF8(sv) && SvMAGICAL(sv) ?
5813                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5814                                     if (mg && mg->mg_len >= 0)
5815                                         mg->mg_len += last_chrs * (mincount-1);
5816                                 }
5817                                 last_chrs *= mincount;
5818                                 data->last_end += l * (mincount - 1);
5819                             }
5820                         } else {
5821                             /* start offset must point into the last copy */
5822                             data->last_start_min += minnext * (mincount - 1);
5823                             data->last_start_max =
5824                               is_inf
5825                                ? OPTIMIZE_INFTY
5826                                : data->last_start_max +
5827                                  (maxcount - 1) * (minnext + data->pos_delta);
5828                         }
5829                     }
5830                     /* It is counted once already... */
5831                     data->pos_min += minnext * (mincount - counted);
5832 #if 0
5833 Perl_re_printf( aTHX_  "counted=%" UVuf " deltanext=%" UVuf
5834                               " OPTIMIZE_INFTY=%" UVuf " minnext=%" UVuf
5835                               " maxcount=%" UVuf " mincount=%" UVuf
5836                               " data->pos_delta=%" UVuf "\n",
5837     (UV)counted, (UV)deltanext, (UV)OPTIMIZE_INFTY, (UV)minnext, (UV)maxcount,
5838     (UV)mincount, (UV)data->pos_delta);
5839 if (deltanext != OPTIMIZE_INFTY)
5840 Perl_re_printf( aTHX_  "LHS=%" UVuf " RHS=%" UVuf "\n",
5841     (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5842           - minnext * mincount), (UV)(OPTIMIZE_INFTY - data->pos_delta));
5843 #endif
5844                     if (deltanext == OPTIMIZE_INFTY
5845                         || data->pos_delta == OPTIMIZE_INFTY
5846                         || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= OPTIMIZE_INFTY - data->pos_delta)
5847                         data->pos_delta = OPTIMIZE_INFTY;
5848                     else
5849                         data->pos_delta += - counted * deltanext +
5850                         (minnext + deltanext) * maxcount - minnext * mincount;
5851                     if (mincount != maxcount) {
5852                          /* Cannot extend fixed substrings found inside
5853                             the group.  */
5854                         scan_commit(pRExC_state, data, minlenp, is_inf);
5855                         if (mincount && last_str) {
5856                             SV * const sv = data->last_found;
5857                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5858                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5859
5860                             if (mg)
5861                                 mg->mg_len = -1;
5862                             sv_setsv(sv, last_str);
5863                             data->last_end = data->pos_min;
5864                             data->last_start_min = data->pos_min - last_chrs;
5865                             data->last_start_max = is_inf
5866                                 ? OPTIMIZE_INFTY
5867                                 : data->pos_min + data->pos_delta - last_chrs;
5868                         }
5869                         data->cur_is_floating = 1; /* float */
5870                     }
5871                     SvREFCNT_dec(last_str);
5872                 }
5873                 if (data && (fl & SF_HAS_EVAL))
5874                     data->flags |= SF_HAS_EVAL;
5875               optimize_curly_tail:
5876                 rck_elide_nothing(oscan);
5877                 continue;
5878
5879             default:
5880                 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5881                                                                     OP(scan));
5882             case REF:
5883             case CLUMP:
5884                 if (flags & SCF_DO_SUBSTR) {
5885                     /* Cannot expect anything... */
5886                     scan_commit(pRExC_state, data, minlenp, is_inf);
5887                     data->cur_is_floating = 1; /* float */
5888                 }
5889                 is_inf = is_inf_internal = 1;
5890                 if (flags & SCF_DO_STCLASS_OR) {
5891                     if (OP(scan) == CLUMP) {
5892                         /* Actually is any start char, but very few code points
5893                          * aren't start characters */
5894                         ssc_match_all_cp(data->start_class);
5895                     }
5896                     else {
5897                         ssc_anything(data->start_class);
5898                     }
5899                 }
5900                 flags &= ~SCF_DO_STCLASS;
5901                 break;
5902             }
5903         }
5904         else if (OP(scan) == LNBREAK) {
5905             if (flags & SCF_DO_STCLASS) {
5906                 if (flags & SCF_DO_STCLASS_AND) {
5907                     ssc_intersection(data->start_class,
5908                                     PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5909                     ssc_clear_locale(data->start_class);
5910                     ANYOF_FLAGS(data->start_class)
5911                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5912                 }
5913                 else if (flags & SCF_DO_STCLASS_OR) {
5914                     ssc_union(data->start_class,
5915                               PL_XPosix_ptrs[_CC_VERTSPACE],
5916                               FALSE);
5917                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5918
5919                     /* See commit msg for
5920                      * 749e076fceedeb708a624933726e7989f2302f6a */
5921                     ANYOF_FLAGS(data->start_class)
5922                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5923                 }
5924                 flags &= ~SCF_DO_STCLASS;
5925             }
5926             min++;
5927             if (delta != OPTIMIZE_INFTY)
5928                 delta++;    /* Because of the 2 char string cr-lf */
5929             if (flags & SCF_DO_SUBSTR) {
5930                 /* Cannot expect anything... */
5931                 scan_commit(pRExC_state, data, minlenp, is_inf);
5932                 data->pos_min += 1;
5933                 if (data->pos_delta != OPTIMIZE_INFTY) {
5934                     data->pos_delta += 1;
5935                 }
5936                 data->cur_is_floating = 1; /* float */
5937             }
5938         }
5939         else if (REGNODE_SIMPLE(OP(scan))) {
5940
5941             if (flags & SCF_DO_SUBSTR) {
5942                 scan_commit(pRExC_state, data, minlenp, is_inf);
5943                 data->pos_min++;
5944             }
5945             min++;
5946             if (flags & SCF_DO_STCLASS) {
5947                 bool invert = 0;
5948                 SV* my_invlist = NULL;
5949                 U8 namedclass;
5950
5951                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5952                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5953
5954                 /* Some of the logic below assumes that switching
5955                    locale on will only add false positives. */
5956                 switch (OP(scan)) {
5957
5958                 default:
5959 #ifdef DEBUGGING
5960                    Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5961                                                                      OP(scan));
5962 #endif
5963                 case SANY:
5964                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5965                         ssc_match_all_cp(data->start_class);
5966                     break;
5967
5968                 case REG_ANY:
5969                     {
5970                         SV* REG_ANY_invlist = _new_invlist(2);
5971                         REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5972                                                             '\n');
5973                         if (flags & SCF_DO_STCLASS_OR) {
5974                             ssc_union(data->start_class,
5975                                       REG_ANY_invlist,
5976                                       TRUE /* TRUE => invert, hence all but \n
5977                                             */
5978                                       );
5979                         }
5980                         else if (flags & SCF_DO_STCLASS_AND) {
5981                             ssc_intersection(data->start_class,
5982                                              REG_ANY_invlist,
5983                                              TRUE  /* TRUE => invert */
5984                                              );
5985                             ssc_clear_locale(data->start_class);
5986                         }
5987                         SvREFCNT_dec_NN(REG_ANY_invlist);
5988                     }
5989                     break;
5990
5991                 case ANYOFD:
5992                 case ANYOFL:
5993                 case ANYOFPOSIXL:
5994                 case ANYOFH:
5995                 case ANYOFHb:
5996                 case ANYOFHr:
5997                 case ANYOFHs:
5998                 case ANYOF:
5999                     if (flags & SCF_DO_STCLASS_AND)
6000                         ssc_and(pRExC_state, data->start_class,
6001                                 (regnode_charclass *) scan);
6002                     else
6003                         ssc_or(pRExC_state, data->start_class,
6004                                                           (regnode_charclass *) scan);
6005                     break;
6006
6007                 case NANYOFM: /* NANYOFM already contains the inversion of the
6008                                  input ANYOF data, so, unlike things like
6009                                  NPOSIXA, don't change 'invert' to TRUE */
6010                     /* FALLTHROUGH */
6011                 case ANYOFM:
6012                   {
6013                     SV* cp_list = get_ANYOFM_contents(scan);
6014
6015                     if (flags & SCF_DO_STCLASS_OR) {
6016                         ssc_union(data->start_class, cp_list, invert);
6017                     }
6018                     else if (flags & SCF_DO_STCLASS_AND) {
6019                         ssc_intersection(data->start_class, cp_list, invert);
6020                     }
6021
6022                     SvREFCNT_dec_NN(cp_list);
6023                     break;
6024                   }
6025
6026                 case ANYOFR:
6027                 case ANYOFRb:
6028                   {
6029                     SV* cp_list = NULL;
6030
6031                     cp_list = _add_range_to_invlist(cp_list,
6032                                         ANYOFRbase(scan),
6033                                         ANYOFRbase(scan) + ANYOFRdelta(scan));
6034
6035                     if (flags & SCF_DO_STCLASS_OR) {
6036                         ssc_union(data->start_class, cp_list, invert);
6037                     }
6038                     else if (flags & SCF_DO_STCLASS_AND) {
6039                         ssc_intersection(data->start_class, cp_list, invert);
6040                     }
6041
6042                     SvREFCNT_dec_NN(cp_list);
6043                     break;
6044                   }
6045
6046                 case NPOSIXL:
6047                     invert = 1;
6048                     /* FALLTHROUGH */
6049
6050                 case POSIXL:
6051                     namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
6052                     if (flags & SCF_DO_STCLASS_AND) {
6053                         bool was_there = cBOOL(
6054                                           ANYOF_POSIXL_TEST(data->start_class,
6055                                                                  namedclass));
6056                         ANYOF_POSIXL_ZERO(data->start_class);
6057                         if (was_there) {    /* Do an AND */
6058                             ANYOF_POSIXL_SET(data->start_class, namedclass);
6059                         }
6060                         /* No individual code points can now match */
6061                         data->start_class->invlist
6062                                                 = sv_2mortal(_new_invlist(0));
6063                     }
6064                     else {
6065                         int complement = namedclass + ((invert) ? -1 : 1);
6066
6067                         assert(flags & SCF_DO_STCLASS_OR);
6068
6069                         /* If the complement of this class was already there,
6070                          * the result is that they match all code points,
6071                          * (\d + \D == everything).  Remove the classes from
6072                          * future consideration.  Locale is not relevant in
6073                          * this case */
6074                         if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
6075                             ssc_match_all_cp(data->start_class);
6076                             ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
6077                             ANYOF_POSIXL_CLEAR(data->start_class, complement);
6078                         }
6079                         else {  /* The usual case; just add this class to the
6080                                    existing set */
6081                             ANYOF_POSIXL_SET(data->start_class, namedclass);
6082                         }
6083                     }
6084                     break;
6085
6086                 case NPOSIXA:   /* For these, we always know the exact set of
6087                                    what's matched */
6088                     invert = 1;
6089                     /* FALLTHROUGH */
6090                 case POSIXA:
6091                     my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
6092                     goto join_posix_and_ascii;
6093
6094                 case NPOSIXD:
6095                 case NPOSIXU:
6096                     invert = 1;
6097                     /* FALLTHROUGH */
6098                 case POSIXD:
6099                 case POSIXU:
6100                     my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
6101
6102                     /* NPOSIXD matches all upper Latin1 code points unless the
6103                      * target string being matched is UTF-8, which is
6104                      * unknowable until match time.  Since we are going to
6105                      * invert, we want to get rid of all of them so that the
6106                      * inversion will match all */
6107                     if (OP(scan) == NPOSIXD) {
6108                         _invlist_subtract(my_invlist, PL_UpperLatin1,
6109                                           &my_invlist);
6110                     }
6111
6112                   join_posix_and_ascii:
6113
6114                     if (flags & SCF_DO_STCLASS_AND) {
6115                         ssc_intersection(data->start_class, my_invlist, invert);
6116                         ssc_clear_locale(data->start_class);
6117                     }
6118                     else {
6119                         assert(flags & SCF_DO_STCLASS_OR);
6120                         ssc_union(data->start_class, my_invlist, invert);
6121                     }
6122                     SvREFCNT_dec(my_invlist);
6123                 }
6124                 if (flags & SCF_DO_STCLASS_OR)
6125                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6126                 flags &= ~SCF_DO_STCLASS;
6127             }
6128         }
6129         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
6130             data->flags |= (OP(scan) == MEOL
6131                             ? SF_BEFORE_MEOL
6132                             : SF_BEFORE_SEOL);
6133             scan_commit(pRExC_state, data, minlenp, is_inf);
6134
6135         }
6136         else if (  PL_regkind[OP(scan)] == BRANCHJ
6137                  /* Lookbehind, or need to calculate parens/evals/stclass: */
6138                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
6139                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
6140         {
6141             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6142                 || OP(scan) == UNLESSM )
6143             {
6144                 /* Negative Lookahead/lookbehind
6145                    In this case we can't do fixed string optimisation.
6146                 */
6147
6148                 SSize_t deltanext, minnext, fake = 0;
6149                 regnode *nscan;
6150                 regnode_ssc intrnl;
6151                 int f = 0;
6152
6153                 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6154                 if (data) {
6155                     data_fake.whilem_c = data->whilem_c;
6156                     data_fake.last_closep = data->last_closep;
6157                 }
6158                 else
6159                     data_fake.last_closep = &fake;
6160                 data_fake.pos_delta = delta;
6161                 if ( flags & SCF_DO_STCLASS && !scan->flags
6162                      && OP(scan) == IFMATCH ) { /* Lookahead */
6163                     ssc_init(pRExC_state, &intrnl);
6164                     data_fake.start_class = &intrnl;
6165                     f |= SCF_DO_STCLASS_AND;
6166                 }
6167                 if (flags & SCF_WHILEM_VISITED_POS)
6168                     f |= SCF_WHILEM_VISITED_POS;
6169                 next = regnext(scan);
6170                 nscan = NEXTOPER(NEXTOPER(scan));
6171
6172                 /* recurse study_chunk() for lookahead body */
6173                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
6174                                       last, &data_fake, stopparen,
6175                                       recursed_depth, NULL, f, depth+1,
6176                                       mutate_ok);
6177                 if (scan->flags) {
6178                     if (   deltanext < 0
6179                         || deltanext > (I32) U8_MAX
6180                         || minnext > (I32)U8_MAX
6181                         || minnext + deltanext > (I32)U8_MAX)
6182                     {
6183                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
6184                               (UV)U8_MAX);
6185                     }
6186
6187                     /* The 'next_off' field has been repurposed to count the
6188                      * additional starting positions to try beyond the initial
6189                      * one.  (This leaves it at 0 for non-variable length
6190                      * matches to avoid breakage for those not using this
6191                      * extension) */
6192                     if (deltanext) {
6193                         scan->next_off = deltanext;
6194                         ckWARNexperimental(RExC_parse,
6195                             WARN_EXPERIMENTAL__VLB,
6196                             "Variable length lookbehind is experimental");
6197                     }
6198                     scan->flags = (U8)minnext + deltanext;
6199                 }
6200                 if (data) {
6201                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6202                         pars++;
6203                     if (data_fake.flags & SF_HAS_EVAL)
6204                         data->flags |= SF_HAS_EVAL;
6205                     data->whilem_c = data_fake.whilem_c;
6206                 }
6207                 if (f & SCF_DO_STCLASS_AND) {
6208                     if (flags & SCF_DO_STCLASS_OR) {
6209                         /* OR before, AND after: ideally we would recurse with
6210                          * data_fake to get the AND applied by study of the
6211                          * remainder of the pattern, and then derecurse;
6212                          * *** HACK *** for now just treat as "no information".
6213                          * See [perl #56690].
6214                          */
6215                         ssc_init(pRExC_state, data->start_class);
6216                     }  else {
6217                         /* AND before and after: combine and continue.  These
6218                          * assertions are zero-length, so can match an EMPTY
6219                          * string */
6220                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6221                         ANYOF_FLAGS(data->start_class)
6222                                                    |= SSC_MATCHES_EMPTY_STRING;
6223                     }
6224                 }
6225             }
6226 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6227             else {
6228                 /* Positive Lookahead/lookbehind
6229                    In this case we can do fixed string optimisation,
6230                    but we must be careful about it. Note in the case of
6231                    lookbehind the positions will be offset by the minimum
6232                    length of the pattern, something we won't know about
6233                    until after the recurse.
6234                 */
6235                 SSize_t deltanext, fake = 0;
6236                 regnode *nscan;
6237                 regnode_ssc intrnl;
6238                 int f = 0;
6239                 /* We use SAVEFREEPV so that when the full compile
6240                     is finished perl will clean up the allocated
6241                     minlens when it's all done. This way we don't
6242                     have to worry about freeing them when we know
6243                     they wont be used, which would be a pain.
6244                  */
6245                 SSize_t *minnextp;
6246                 Newx( minnextp, 1, SSize_t );
6247                 SAVEFREEPV(minnextp);
6248
6249                 if (data) {
6250                     StructCopy(data, &data_fake, scan_data_t);
6251                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
6252                         f |= SCF_DO_SUBSTR;
6253                         if (scan->flags)
6254                             scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
6255                         data_fake.last_found=newSVsv(data->last_found);
6256                     }
6257                 }
6258                 else
6259                     data_fake.last_closep = &fake;
6260                 data_fake.flags = 0;
6261                 data_fake.substrs[0].flags = 0;
6262                 data_fake.substrs[1].flags = 0;
6263                 data_fake.pos_delta = delta;
6264                 if (is_inf)
6265                     data_fake.flags |= SF_IS_INF;
6266                 if ( flags & SCF_DO_STCLASS && !scan->flags
6267                      && OP(scan) == IFMATCH ) { /* Lookahead */
6268                     ssc_init(pRExC_state, &intrnl);
6269                     data_fake.start_class = &intrnl;
6270                     f |= SCF_DO_STCLASS_AND;
6271                 }
6272                 if (flags & SCF_WHILEM_VISITED_POS)
6273                     f |= SCF_WHILEM_VISITED_POS;
6274                 next = regnext(scan);
6275                 nscan = NEXTOPER(NEXTOPER(scan));
6276
6277                 /* positive lookahead study_chunk() recursion */
6278                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
6279                                         &deltanext, last, &data_fake,
6280                                         stopparen, recursed_depth, NULL,
6281                                         f, depth+1, mutate_ok);
6282                 if (scan->flags) {
6283                     assert(0);  /* This code has never been tested since this
6284                                    is normally not compiled */
6285                     if (   deltanext < 0
6286                         || deltanext > (I32) U8_MAX
6287                         || *minnextp > (I32)U8_MAX
6288                         || *minnextp + deltanext > (I32)U8_MAX)
6289                     {
6290                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
6291                               (UV)U8_MAX);
6292                     }
6293
6294                     if (deltanext) {
6295                         scan->next_off = deltanext;
6296                     }
6297                     scan->flags = (U8)*minnextp + deltanext;
6298                 }
6299
6300                 *minnextp += min;
6301
6302                 if (f & SCF_DO_STCLASS_AND) {
6303                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6304                     ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
6305                 }
6306                 if (data) {
6307                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6308                         pars++;
6309                     if (data_fake.flags & SF_HAS_EVAL)
6310                         data->flags |= SF_HAS_EVAL;
6311                     data->whilem_c = data_fake.whilem_c;
6312                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
6313                         int i;
6314                         if (RExC_rx->minlen<*minnextp)
6315                             RExC_rx->minlen=*minnextp;
6316                         scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
6317                         SvREFCNT_dec_NN(data_fake.last_found);
6318
6319                         for (i = 0; i < 2; i++) {
6320                             if (data_fake.substrs[i].minlenp != minlenp) {
6321                                 data->substrs[i].min_offset =
6322                                             data_fake.substrs[i].min_offset;
6323                                 data->substrs[i].max_offset =
6324                                             data_fake.substrs[i].max_offset;
6325                                 data->substrs[i].minlenp =
6326                                             data_fake.substrs[i].minlenp;
6327                                 data->substrs[i].lookbehind += scan->flags;
6328                             }
6329                         }
6330                     }
6331                 }
6332             }
6333 #endif
6334         }
6335         else if (OP(scan) == OPEN) {
6336             if (stopparen != (I32)ARG(scan))
6337                 pars++;
6338         }
6339         else if (OP(scan) == CLOSE) {
6340             if (stopparen == (I32)ARG(scan)) {
6341                 break;
6342             }
6343             if ((I32)ARG(scan) == is_par) {
6344                 next = regnext(scan);
6345
6346                 if ( next && (OP(next) != WHILEM) && next < last)
6347                     is_par = 0;         /* Disable optimization */
6348             }
6349             if (data)
6350                 *(data->last_closep) = ARG(scan);
6351         }
6352         else if (OP(scan) == EVAL) {
6353             if (data)
6354                 data->flags |= SF_HAS_EVAL;
6355         }
6356         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
6357             if (flags & SCF_DO_SUBSTR) {
6358                 scan_commit(pRExC_state, data, minlenp, is_inf);
6359                 flags &= ~SCF_DO_SUBSTR;
6360             }
6361             if (OP(scan)==ACCEPT) {
6362                 /* m{(*ACCEPT)x} does not have to start with 'x' */
6363                 flags &= ~SCF_DO_STCLASS;
6364                 if (data) {
6365                     data->flags |= SCF_SEEN_ACCEPT;
6366                     if (stopmin > min)
6367                         stopmin = min;
6368                 }
6369             }
6370         }
6371         else if (OP(scan) == COMMIT) {
6372             /* gh18770: m{abc(*COMMIT)xyz} must fail on "abc abcxyz", so we
6373              * must not end up with "abcxyz" as a fixed substring else we'll
6374              * skip straight to attempting to match at offset 4.
6375              */
6376             if (flags & SCF_DO_SUBSTR) {
6377                 scan_commit(pRExC_state, data, minlenp, is_inf);
6378                 flags &= ~SCF_DO_SUBSTR;
6379             }
6380         }
6381         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
6382         {
6383                 if (flags & SCF_DO_SUBSTR) {
6384                     scan_commit(pRExC_state, data, minlenp, is_inf);
6385                     data->cur_is_floating = 1; /* float */
6386                 }
6387                 is_inf = is_inf_internal = 1;
6388                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
6389                     ssc_anything(data->start_class);
6390                 flags &= ~SCF_DO_STCLASS;
6391         }
6392         else if (OP(scan) == GPOS) {
6393             if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
6394                 !(delta || is_inf || (data && data->pos_delta)))
6395             {
6396                 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
6397                     RExC_rx->intflags |= PREGf_ANCH_GPOS;
6398                 if (RExC_rx->gofs < (STRLEN)min)
6399                     RExC_rx->gofs = min;
6400             } else {
6401                 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
6402                 RExC_rx->gofs = 0;
6403             }
6404         }
6405 #ifdef TRIE_STUDY_OPT
6406 #ifdef FULL_TRIE_STUDY
6407         else if (PL_regkind[OP(scan)] == TRIE) {
6408             /* NOTE - There is similar code to this block above for handling
6409                BRANCH nodes on the initial study.  If you change stuff here
6410                check there too. */
6411             regnode *trie_node= scan;
6412             regnode *tail= regnext(scan);
6413             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6414             SSize_t max1 = 0, min1 = OPTIMIZE_INFTY;
6415             regnode_ssc accum;
6416
6417             if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
6418                 /* Cannot merge strings after this. */
6419                 scan_commit(pRExC_state, data, minlenp, is_inf);
6420             }
6421             if (flags & SCF_DO_STCLASS)
6422                 ssc_init_zero(pRExC_state, &accum);
6423
6424             if (!trie->jump) {
6425                 min1= trie->minlen;
6426                 max1= trie->maxlen;
6427             } else {
6428                 const regnode *nextbranch= NULL;
6429                 U32 word;
6430
6431                 for ( word=1 ; word <= trie->wordcount ; word++)
6432                 {
6433                     SSize_t deltanext=0, minnext=0, f = 0, fake;
6434                     regnode_ssc this_class;
6435
6436                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6437                     if (data) {
6438                         data_fake.whilem_c = data->whilem_c;
6439                         data_fake.last_closep = data->last_closep;
6440                     }
6441                     else
6442                         data_fake.last_closep = &fake;
6443                     data_fake.pos_delta = delta;
6444                     if (flags & SCF_DO_STCLASS) {
6445                         ssc_init(pRExC_state, &this_class);
6446                         data_fake.start_class = &this_class;
6447                         f = SCF_DO_STCLASS_AND;
6448                     }
6449                     if (flags & SCF_WHILEM_VISITED_POS)
6450                         f |= SCF_WHILEM_VISITED_POS;
6451
6452                     if (trie->jump[word]) {
6453                         if (!nextbranch)
6454                             nextbranch = trie_node + trie->jump[0];
6455                         scan= trie_node + trie->jump[word];
6456                         /* We go from the jump point to the branch that follows
6457                            it. Note this means we need the vestigal unused
6458                            branches even though they arent otherwise used. */
6459                         /* optimise study_chunk() for TRIE */
6460                         minnext = study_chunk(pRExC_state, &scan, minlenp,
6461                             &deltanext, (regnode *)nextbranch, &data_fake,
6462                             stopparen, recursed_depth, NULL, f, depth+1,
6463                             mutate_ok);
6464                     }
6465                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6466                         nextbranch= regnext((regnode*)nextbranch);
6467
6468                     if (min1 > (SSize_t)(minnext + trie->minlen))
6469                         min1 = minnext + trie->minlen;
6470                     if (deltanext == OPTIMIZE_INFTY) {
6471                         is_inf = is_inf_internal = 1;
6472                         max1 = OPTIMIZE_INFTY;
6473                     } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6474                         max1 = minnext + deltanext + trie->maxlen;
6475
6476                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6477                         pars++;
6478                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
6479                         if ( stopmin > min + min1)
6480                             stopmin = min + min1;
6481                         flags &= ~SCF_DO_SUBSTR;
6482                         if (data)
6483                             data->flags |= SCF_SEEN_ACCEPT;
6484                     }
6485                     if (data) {
6486                         if (data_fake.flags & SF_HAS_EVAL)
6487                             data->flags |= SF_HAS_EVAL;
6488                         data->whilem_c = data_fake.whilem_c;
6489                     }
6490                     if (flags & SCF_DO_STCLASS)
6491                         ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6492                 }
6493             }
6494             if (flags & SCF_DO_SUBSTR) {
6495                 data->pos_min += min1;
6496                 data->pos_delta += max1 - min1;
6497                 if (max1 != min1 || is_inf)
6498                     data->cur_is_floating = 1; /* float */
6499             }
6500             min += min1;
6501             if (delta != OPTIMIZE_INFTY) {
6502                 if (OPTIMIZE_INFTY - (max1 - min1) >= delta)
6503                     delta += max1 - min1;
6504                 else
6505                     delta = OPTIMIZE_INFTY;
6506             }
6507             if (flags & SCF_DO_STCLASS_OR) {
6508                 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6509                 if (min1) {
6510                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6511                     flags &= ~SCF_DO_STCLASS;
6512                 }
6513             }
6514             else if (flags & SCF_DO_STCLASS_AND) {
6515                 if (min1) {
6516                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6517                     flags &= ~SCF_DO_STCLASS;
6518                 }
6519                 else {
6520                     /* Switch to OR mode: cache the old value of
6521                      * data->start_class */
6522                     INIT_AND_WITHP;
6523                     StructCopy(data->start_class, and_withp, regnode_ssc);
6524                     flags &= ~SCF_DO_STCLASS_AND;
6525                     StructCopy(&accum, data->start_class, regnode_ssc);
6526                     flags |= SCF_DO_STCLASS_OR;
6527                 }
6528             }
6529             scan= tail;
6530             continue;
6531         }
6532 #else
6533         else if (PL_regkind[OP(scan)] == TRIE) {
6534             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6535             U8*bang=NULL;
6536
6537             min += trie->minlen;
6538             delta += (trie->maxlen - trie->minlen);
6539             flags &= ~SCF_DO_STCLASS; /* xxx */
6540             if (flags & SCF_DO_SUBSTR) {
6541                 /* Cannot expect anything... */
6542                 scan_commit(pRExC_state, data, minlenp, is_inf);
6543                 data->pos_min += trie->minlen;
6544                 data->pos_delta += (trie->maxlen - trie->minlen);
6545                 if (trie->maxlen != trie->minlen)
6546                     data->cur_is_floating = 1; /* float */
6547             }
6548             if (trie->jump) /* no more substrings -- for now /grr*/
6549                flags &= ~SCF_DO_SUBSTR;
6550         }
6551
6552 #endif /* old or new */
6553 #endif /* TRIE_STUDY_OPT */
6554
6555         else if (OP(scan) == REGEX_SET) {
6556             Perl_croak(aTHX_ "panic: %s regnode should be resolved"
6557                              " before optimization", PL_reg_name[REGEX_SET]);
6558         }
6559
6560         /* Else: zero-length, ignore. */
6561         scan = regnext(scan);
6562     }
6563
6564   finish:
6565     if (frame) {
6566         /* we need to unwind recursion. */
6567         depth = depth - 1;
6568
6569         DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6570         DEBUG_PEEP("fend", scan, depth, flags);
6571
6572         /* restore previous context */
6573         last = frame->last_regnode;
6574         scan = frame->next_regnode;
6575         stopparen = frame->stopparen;
6576         recursed_depth = frame->prev_recursed_depth;
6577
6578         RExC_frame_last = frame->prev_frame;
6579         frame = frame->this_prev_frame;
6580         goto fake_study_recurse;
6581     }
6582
6583     assert(!frame);
6584     DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6585
6586     *scanp = scan;
6587     *deltap = is_inf_internal ? OPTIMIZE_INFTY : delta;
6588
6589     if (flags & SCF_DO_SUBSTR && is_inf)
6590         data->pos_delta = OPTIMIZE_INFTY - data->pos_min;
6591     if (is_par > (I32)U8_MAX)
6592         is_par = 0;
6593     if (is_par && pars==1 && data) {
6594         data->flags |= SF_IN_PAR;
6595         data->flags &= ~SF_HAS_PAR;
6596     }
6597     else if (pars && data) {
6598         data->flags |= SF_HAS_PAR;
6599         data->flags &= ~SF_IN_PAR;
6600     }
6601     if (flags & SCF_DO_STCLASS_OR)
6602         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6603     if (flags & SCF_TRIE_RESTUDY)
6604         data->flags |=  SCF_TRIE_RESTUDY;
6605
6606     DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6607
6608     final_minlen = min < stopmin
6609             ? min : stopmin;
6610
6611     if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6612         if (final_minlen > OPTIMIZE_INFTY - delta)
6613             RExC_maxlen = OPTIMIZE_INFTY;
6614         else if (RExC_maxlen < final_minlen + delta)
6615             RExC_maxlen = final_minlen + delta;
6616     }
6617     return final_minlen;
6618 }
6619
6620 STATIC U32
6621 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6622 {
6623     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6624
6625     PERL_ARGS_ASSERT_ADD_DATA;
6626
6627     Renewc(RExC_rxi->data,
6628            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6629            char, struct reg_data);
6630     if(count)
6631         Renew(RExC_rxi->data->what, count + n, U8);
6632     else
6633         Newx(RExC_rxi->data->what, n, U8);
6634     RExC_rxi->data->count = count + n;
6635     Copy(s, RExC_rxi->data->what + count, n, U8);
6636     return count;
6637 }
6638
6639 /*XXX: todo make this not included in a non debugging perl, but appears to be
6640  * used anyway there, in 'use re' */
6641 #ifndef PERL_IN_XSUB_RE
6642 void
6643 Perl_reginitcolors(pTHX)
6644 {
6645     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6646     if (s) {
6647         char *t = savepv(s);
6648         int i = 0;
6649         PL_colors[0] = t;
6650         while (++i < 6) {
6651             t = strchr(t, '\t');
6652             if (t) {
6653                 *t = '\0';
6654                 PL_colors[i] = ++t;
6655             }
6656             else
6657                 PL_colors[i] = t = (char *)"";
6658         }
6659     } else {
6660         int i = 0;
6661         while (i < 6)
6662             PL_colors[i++] = (char *)"";
6663     }
6664     PL_colorset = 1;
6665 }
6666 #endif
6667
6668
6669 #ifdef TRIE_STUDY_OPT
6670 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething)            \
6671     STMT_START {                                            \
6672         if (                                                \
6673               (data.flags & SCF_TRIE_RESTUDY)               \
6674               && ! restudied++                              \
6675         ) {                                                 \
6676             dOsomething;                                    \
6677             goto reStudy;                                   \
6678         }                                                   \
6679     } STMT_END
6680 #else
6681 #define CHECK_RESTUDY_GOTO_butfirst
6682 #endif
6683
6684 /*
6685  * pregcomp - compile a regular expression into internal code
6686  *
6687  * Decides which engine's compiler to call based on the hint currently in
6688  * scope
6689  */
6690
6691 #ifndef PERL_IN_XSUB_RE
6692
6693 /* return the currently in-scope regex engine (or the default if none)  */
6694
6695 regexp_engine const *
6696 Perl_current_re_engine(pTHX)
6697 {
6698     if (IN_PERL_COMPILETIME) {
6699         HV * const table = GvHV(PL_hintgv);
6700         SV **ptr;
6701
6702         if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6703             return &PL_core_reg_engine;
6704         ptr = hv_fetchs(table, "regcomp", FALSE);
6705         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6706             return &PL_core_reg_engine;
6707         return INT2PTR(regexp_engine*, SvIV(*ptr));
6708     }
6709     else {
6710         SV *ptr;
6711         if (!PL_curcop->cop_hints_hash)
6712             return &PL_core_reg_engine;
6713         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6714         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6715             return &PL_core_reg_engine;
6716         return INT2PTR(regexp_engine*, SvIV(ptr));
6717     }
6718 }
6719
6720
6721 REGEXP *
6722 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6723 {
6724     regexp_engine const *eng = current_re_engine();
6725     DECLARE_AND_GET_RE_DEBUG_FLAGS;
6726
6727     PERL_ARGS_ASSERT_PREGCOMP;
6728
6729     /* Dispatch a request to compile a regexp to correct regexp engine. */
6730     DEBUG_COMPILE_r({
6731         Perl_re_printf( aTHX_  "Using engine %" UVxf "\n",
6732                         PTR2UV(eng));
6733     });
6734     return CALLREGCOMP_ENG(eng, pattern, flags);
6735 }
6736 #endif
6737
6738 /* public(ish) entry point for the perl core's own regex compiling code.
6739  * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6740  * pattern rather than a list of OPs, and uses the internal engine rather
6741  * than the current one */
6742
6743 REGEXP *
6744 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6745 {
6746     SV *pat = pattern; /* defeat constness! */
6747
6748     PERL_ARGS_ASSERT_RE_COMPILE;
6749
6750     return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6751 #ifdef PERL_IN_XSUB_RE
6752                                 &my_reg_engine,
6753 #else
6754                                 &PL_core_reg_engine,
6755 #endif
6756                                 NULL, NULL, rx_flags, 0);
6757 }
6758
6759 static void
6760 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6761 {
6762     int n;
6763
6764     if (--cbs->refcnt > 0)
6765         return;
6766     for (n = 0; n < cbs->count; n++) {
6767         REGEXP *rx = cbs->cb[n].src_regex;
6768         if (rx) {
6769             cbs->cb[n].src_regex = NULL;
6770             SvREFCNT_dec_NN(rx);
6771         }
6772     }
6773     Safefree(cbs->cb);
6774     Safefree(cbs);
6775 }
6776
6777
6778 static struct reg_code_blocks *
6779 S_alloc_code_blocks(pTHX_  int ncode)
6780 {
6781      struct reg_code_blocks *cbs;
6782     Newx(cbs, 1, struct reg_code_blocks);
6783     cbs->count = ncode;
6784     cbs->refcnt = 1;
6785     SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6786     if (ncode)
6787         Newx(cbs->cb, ncode, struct reg_code_block);
6788     else
6789         cbs->cb = NULL;
6790     return cbs;
6791 }
6792
6793
6794 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6795  * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6796  * point to the realloced string and length.
6797  *
6798  * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6799  * stuff added */
6800
6801 static void
6802 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6803                     char **pat_p, STRLEN *plen_p, int num_code_blocks)
6804 {
6805     U8 *const src = (U8*)*pat_p;
6806     U8 *dst, *d;
6807     int n=0;
6808     STRLEN s = 0;
6809     bool do_end = 0;
6810     DECLARE_AND_GET_RE_DEBUG_FLAGS;
6811
6812     DEBUG_PARSE_r(Perl_re_printf( aTHX_
6813         "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6814
6815     /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6816     Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6817     d = dst;
6818
6819     while (s < *plen_p) {
6820         append_utf8_from_native_byte(src[s], &d);
6821
6822         if (n < num_code_blocks) {
6823             assert(pRExC_state->code_blocks);
6824             if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6825                 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6826                 assert(*(d - 1) == '(');
6827                 do_end = 1;
6828             }
6829             else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6830                 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6831                 assert(*(d - 1) == ')');
6832                 do_end = 0;
6833                 n++;
6834             }
6835         }
6836         s++;
6837     }
6838     *d = '\0';
6839     *plen_p = d - dst;
6840     *pat_p = (char*) dst;
6841     SAVEFREEPV(*pat_p);
6842     RExC_orig_utf8 = RExC_utf8 = 1;
6843 }
6844
6845
6846
6847 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6848  * while recording any code block indices, and handling overloading,
6849  * nested qr// objects etc.  If pat is null, it will allocate a new
6850  * string, or just return the first arg, if there's only one.
6851  *
6852  * Returns the malloced/updated pat.
6853  * patternp and pat_count is the array of SVs to be concatted;
6854  * oplist is the optional list of ops that generated the SVs;
6855  * recompile_p is a pointer to a boolean that will be set if
6856  *   the regex will need to be recompiled.
6857  * delim, if non-null is an SV that will be inserted between each element
6858  */
6859
6860 static SV*
6861 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6862                 SV *pat, SV ** const patternp, int pat_count,
6863                 OP *oplist, bool *recompile_p, SV *delim)
6864 {
6865     SV **svp;
6866     int n = 0;
6867     bool use_delim = FALSE;
6868     bool alloced = FALSE;
6869
6870     /* if we know we have at least two args, create an empty string,
6871      * then concatenate args to that. For no args, return an empty string */
6872     if (!pat && pat_count != 1) {
6873         pat = newSVpvs("");
6874         SAVEFREESV(pat);
6875         alloced = TRUE;
6876     }
6877
6878     for (svp = patternp; svp < patternp + pat_count; svp++) {
6879         SV *sv;
6880         SV *rx  = NULL;
6881         STRLEN orig_patlen = 0;
6882         bool code = 0;
6883         SV *msv = use_delim ? delim : *svp;
6884         if (!msv) msv = &PL_sv_undef;
6885
6886         /* if we've got a delimiter, we go round the loop twice for each
6887          * svp slot (except the last), using the delimiter the second
6888          * time round */
6889         if (use_delim) {
6890             svp--;
6891             use_delim = FALSE;
6892         }
6893         else if (delim)
6894             use_delim = TRUE;
6895
6896         if (SvTYPE(msv) == SVt_PVAV) {
6897             /* we've encountered an interpolated array within
6898              * the pattern, e.g. /...@a..../. Expand the list of elements,
6899              * then recursively append elements.
6900              * The code in this block is based on S_pushav() */
6901
6902             AV *const av = (AV*)msv;
6903             const SSize_t maxarg = AvFILL(av) + 1;
6904             SV **array;
6905
6906             if (oplist) {
6907                 assert(oplist->op_type == OP_PADAV
6908                     || oplist->op_type == OP_RV2AV);
6909                 oplist = OpSIBLING(oplist);
6910             }
6911
6912             if (SvRMAGICAL(av)) {
6913                 SSize_t i;
6914
6915                 Newx(array, maxarg, SV*);
6916                 SAVEFREEPV(array);
6917                 for (i=0; i < maxarg; i++) {
6918                     SV ** const svp = av_fetch(av, i, FALSE);
6919                     array[i] = svp ? *svp : &PL_sv_undef;
6920                 }
6921             }
6922             else
6923                 array = AvARRAY(av);
6924
6925             pat = S_concat_pat(aTHX_ pRExC_state, pat,
6926                                 array, maxarg, NULL, recompile_p,
6927                                 /* $" */
6928                                 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6929
6930             continue;
6931         }
6932
6933
6934         /* we make the assumption here that each op in the list of
6935          * op_siblings maps to one SV pushed onto the stack,
6936          * except for code blocks, with have both an OP_NULL and
6937          * an OP_CONST.
6938          * This allows us to match up the list of SVs against the
6939          * list of OPs to find the next code block.
6940          *
6941          * Note that       PUSHMARK PADSV PADSV ..
6942          * is optimised to
6943          *                 PADRANGE PADSV  PADSV  ..
6944          * so the alignment still works. */
6945
6946         if (oplist) {
6947             if (oplist->op_type == OP_NULL
6948                 && (oplist->op_flags & OPf_SPECIAL))
6949             {
6950                 assert(n < pRExC_state->code_blocks->count);
6951                 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6952                 pRExC_state->code_blocks->cb[n].block = oplist;
6953                 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6954                 n++;
6955                 code = 1;
6956                 oplist = OpSIBLING(oplist); /* skip CONST */
6957                 assert(oplist);
6958             }
6959             oplist = OpSIBLING(oplist);;
6960         }
6961
6962         /* apply magic and QR overloading to arg */
6963
6964         SvGETMAGIC(msv);
6965         if (SvROK(msv) && SvAMAGIC(msv)) {
6966             SV *sv = AMG_CALLunary(msv, regexp_amg);
6967             if (sv) {
6968                 if (SvROK(sv))
6969                     sv = SvRV(sv);
6970                 if (SvTYPE(sv) != SVt_REGEXP)
6971                     Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6972                 msv = sv;
6973             }
6974         }
6975
6976         /* try concatenation overload ... */
6977         if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6978                 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6979         {
6980             sv_setsv(pat, sv);
6981             /* overloading involved: all bets are off over literal
6982              * code. Pretend we haven't seen it */
6983             if (n)
6984                 pRExC_state->code_blocks->count -= n;
6985             n = 0;
6986         }
6987         else {
6988             /* ... or failing that, try "" overload */
6989             while (SvAMAGIC(msv)
6990                     && (sv = AMG_CALLunary(msv, string_amg))
6991                     && sv != msv
6992                     &&  !(   SvROK(msv)
6993                           && SvROK(sv)
6994                           && SvRV(msv) == SvRV(sv))
6995             ) {
6996                 msv = sv;
6997                 SvGETMAGIC(msv);
6998             }
6999             if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
7000                 msv = SvRV(msv);
7001
7002             if (pat) {
7003                 /* this is a partially unrolled
7004                  *     sv_catsv_nomg(pat, msv);
7005                  * that allows us to adjust code block indices if
7006                  * needed */
7007                 STRLEN dlen;
7008                 char *dst = SvPV_force_nomg(pat, dlen);
7009                 orig_patlen = dlen;
7010                 if (SvUTF8(msv) && !SvUTF8(pat)) {
7011                     S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
7012                     sv_setpvn(pat, dst, dlen);
7013                     SvUTF8_on(pat);
7014                 }
7015                 sv_catsv_nomg(pat, msv);
7016                 rx = msv;
7017             }
7018             else {
7019                 /* We have only one SV to process, but we need to verify
7020                  * it is properly null terminated or we will fail asserts
7021                  * later. In theory we probably shouldn't get such SV's,
7022                  * but if we do we should handle it gracefully. */
7023                 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
7024                     /* not a string, or a string with a trailing null */
7025                     pat = msv;
7026                 } else {
7027                     /* a string with no trailing null, we need to copy it
7028                      * so it has a trailing null */
7029                     pat = sv_2mortal(newSVsv(msv));
7030                 }
7031             }
7032
7033             if (code)
7034                 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
7035         }
7036
7037         /* extract any code blocks within any embedded qr//'s */
7038         if (rx && SvTYPE(rx) == SVt_REGEXP
7039             && RX_ENGINE((REGEXP*)rx)->op_comp)
7040         {
7041
7042             RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
7043             if (ri->code_blocks && ri->code_blocks->count) {
7044                 int i;
7045                 /* the presence of an embedded qr// with code means
7046                  * we should always recompile: the text of the
7047                  * qr// may not have changed, but it may be a
7048                  * different closure than last time */
7049                 *recompile_p = 1;
7050                 if (pRExC_state->code_blocks) {
7051                     int new_count = pRExC_state->code_blocks->count
7052                             + ri->code_blocks->count;
7053                     Renew(pRExC_state->code_blocks->cb,
7054                             new_count, struct reg_code_block);
7055                     pRExC_state->code_blocks->count = new_count;
7056                 }
7057                 else
7058                     pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
7059                                                     ri->code_blocks->count);
7060
7061                 for (i=0; i < ri->code_blocks->count; i++) {
7062                     struct reg_code_block *src, *dst;
7063                     STRLEN offset =  orig_patlen
7064                         + ReANY((REGEXP *)rx)->pre_prefix;
7065                     assert(n < pRExC_state->code_blocks->count);
7066                     src = &ri->code_blocks->cb[i];
7067                     dst = &pRExC_state->code_blocks->cb[n];
7068                     dst->start      = src->start + offset;
7069                     dst->end        = src->end   + offset;
7070                     dst->block      = src->block;
7071                     dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
7072                                             src->src_regex
7073                                                 ? src->src_regex
7074                                                 : (REGEXP*)rx);
7075                     n++;
7076                 }
7077             }
7078         }
7079     }
7080     /* avoid calling magic multiple times on a single element e.g. =~ $qr */
7081     if (alloced)
7082         SvSETMAGIC(pat);
7083
7084     return pat;
7085 }
7086
7087
7088
7089 /* see if there are any run-time code blocks in the pattern.
7090  * False positives are allowed */
7091
7092 static bool
7093 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7094                     char *pat, STRLEN plen)
7095 {
7096     int n = 0;
7097     STRLEN s;
7098
7099     PERL_UNUSED_CONTEXT;
7100
7101     for (s = 0; s < plen; s++) {
7102         if (   pRExC_state->code_blocks
7103             && n < pRExC_state->code_blocks->count
7104             && s == pRExC_state->code_blocks->cb[n].start)
7105         {
7106             s = pRExC_state->code_blocks->cb[n].end;
7107             n++;
7108             continue;
7109         }
7110         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
7111          * positives here */
7112         if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
7113             (pat[s+2] == '{'
7114                 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
7115         )
7116             return 1;
7117     }
7118     return 0;
7119 }
7120
7121 /* Handle run-time code blocks. We will already have compiled any direct
7122  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
7123  * copy of it, but with any literal code blocks blanked out and
7124  * appropriate chars escaped; then feed it into
7125  *
7126  *    eval "qr'modified_pattern'"
7127  *
7128  * For example,
7129  *
7130  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
7131  *
7132  * becomes
7133  *
7134  *    qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
7135  *
7136  * After eval_sv()-ing that, grab any new code blocks from the returned qr
7137  * and merge them with any code blocks of the original regexp.
7138  *
7139  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
7140  * instead, just save the qr and return FALSE; this tells our caller that
7141  * the original pattern needs upgrading to utf8.
7142  */
7143
7144 static bool
7145 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7146     char *pat, STRLEN plen)
7147 {
7148     SV *qr;
7149
7150     DECLARE_AND_GET_RE_DEBUG_FLAGS;
7151
7152     if (pRExC_state->runtime_code_qr) {
7153         /* this is the second time we've been called; this should
7154          * only happen if the main pattern got upgraded to utf8
7155          * during compilation; re-use the qr we compiled first time
7156          * round (which should be utf8 too)
7157          */
7158         qr = pRExC_state->runtime_code_qr;
7159         pRExC_state->runtime_code_qr = NULL;
7160         assert(RExC_utf8 && SvUTF8(qr));
7161     }
7162     else {
7163         int n = 0;
7164         STRLEN s;
7165         char *p, *newpat;
7166         int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
7167         SV *sv, *qr_ref;
7168         dSP;
7169
7170         /* determine how many extra chars we need for ' and \ escaping */
7171         for (s = 0; s < plen; s++) {
7172             if (pat[s] == '\'' || pat[s] == '\\')
7173                 newlen++;
7174         }
7175
7176         Newx(newpat, newlen, char);
7177         p = newpat;
7178         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
7179
7180         for (s = 0; s < plen; s++) {
7181             if (   pRExC_state->code_blocks
7182                 && n < pRExC_state->code_blocks->count
7183                 && s == pRExC_state->code_blocks->cb[n].start)
7184             {
7185                 /* blank out literal code block so that they aren't
7186                  * recompiled: eg change from/to:
7187                  *     /(?{xyz})/
7188                  *     /(?=====)/
7189                  * and
7190                  *     /(??{xyz})/
7191                  *     /(?======)/
7192                  * and
7193                  *     /(?(?{xyz}))/
7194                  *     /(?(?=====))/
7195                 */
7196                 assert(pat[s]   == '(');
7197                 assert(pat[s+1] == '?');
7198                 *p++ = '(';
7199                 *p++ = '?';
7200                 s += 2;
7201                 while (s < pRExC_state->code_blocks->cb[n].end) {
7202                     *p++ = '=';
7203                     s++;
7204                 }
7205                 *p++ = ')';
7206                 n++;
7207                 continue;
7208             }
7209             if (pat[s] == '\'' || pat[s] == '\\')
7210                 *p++ = '\\';
7211             *p++ = pat[s];
7212         }
7213         *p++ = '\'';
7214         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
7215             *p++ = 'x';
7216             if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
7217                 *p++ = 'x';
7218             }
7219         }
7220         *p++ = '\0';
7221         DEBUG_COMPILE_r({
7222             Perl_re_printf( aTHX_
7223                 "%sre-parsing pattern for runtime code:%s %s\n",
7224                 PL_colors[4], PL_colors[5], newpat);
7225         });
7226
7227         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
7228         Safefree(newpat);
7229
7230         ENTER;
7231         SAVETMPS;
7232         save_re_context();
7233         PUSHSTACKi(PERLSI_REQUIRE);
7234         /* G_RE_REPARSING causes the toker to collapse \\ into \ when
7235          * parsing qr''; normally only q'' does this. It also alters
7236          * hints handling */
7237         eval_sv(sv, G_SCALAR|G_RE_REPARSING);
7238         SvREFCNT_dec_NN(sv);
7239         SPAGAIN;
7240         qr_ref = POPs;
7241         PUTBACK;
7242         {
7243             SV * const errsv = ERRSV;
7244             if (SvTRUE_NN(errsv))
7245                 /* use croak_sv ? */
7246                 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
7247         }
7248         assert(SvROK(qr_ref));
7249         qr = SvRV(qr_ref);
7250         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
7251         /* the leaving below frees the tmp qr_ref.
7252          * Give qr a life of its own */
7253         SvREFCNT_inc(qr);
7254         POPSTACK;
7255         FREETMPS;
7256         LEAVE;
7257
7258     }
7259
7260     if (!RExC_utf8 && SvUTF8(qr)) {
7261         /* first time through; the pattern got upgraded; save the
7262          * qr for the next time through */
7263         assert(!pRExC_state->runtime_code_qr);
7264         pRExC_state->runtime_code_qr = qr;
7265         return 0;
7266     }
7267
7268
7269     /* extract any code blocks within the returned qr//  */
7270
7271
7272     /* merge the main (r1) and run-time (r2) code blocks into one */
7273     {
7274         RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
7275         struct reg_code_block *new_block, *dst;
7276         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
7277         int i1 = 0, i2 = 0;
7278         int r1c, r2c;
7279
7280         if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
7281         {
7282             SvREFCNT_dec_NN(qr);
7283             return 1;
7284         }
7285
7286         if (!r1->code_blocks)
7287             r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
7288
7289         r1c = r1->code_blocks->count;
7290         r2c = r2->code_blocks->count;
7291
7292         Newx(new_block, r1c + r2c, struct reg_code_block);
7293
7294         dst = new_block;
7295
7296         while (i1 < r1c || i2 < r2c) {
7297             struct reg_code_block *src;
7298             bool is_qr = 0;
7299
7300             if (i1 == r1c) {
7301                 src = &r2->code_blocks->cb[i2++];
7302                 is_qr = 1;
7303             }
7304             else if (i2 == r2c)
7305                 src = &r1->code_blocks->cb[i1++];
7306             else if (  r1->code_blocks->cb[i1].start
7307                      < r2->code_blocks->cb[i2].start)
7308             {
7309                 src = &r1->code_blocks->cb[i1++];
7310                 assert(src->end < r2->code_blocks->cb[i2].start);
7311             }
7312             else {
7313                 assert(  r1->code_blocks->cb[i1].start
7314                        > r2->code_blocks->cb[i2].start);
7315                 src = &r2->code_blocks->cb[i2++];
7316                 is_qr = 1;
7317                 assert(src->end < r1->code_blocks->cb[i1].start);
7318             }
7319
7320             assert(pat[src->start] == '(');
7321             assert(pat[src->end]   == ')');
7322             dst->start      = src->start;
7323             dst->end        = src->end;
7324             dst->block      = src->block;
7325             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
7326                                     : src->src_regex;
7327             dst++;
7328         }
7329         r1->code_blocks->count += r2c;
7330         Safefree(r1->code_blocks->cb);
7331         r1->code_blocks->cb = new_block;
7332     }
7333
7334     SvREFCNT_dec_NN(qr);
7335     return 1;
7336 }
7337
7338
7339 STATIC bool
7340 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
7341                       struct reg_substr_datum  *rsd,
7342                       struct scan_data_substrs *sub,
7343                       STRLEN longest_length)
7344 {
7345     /* This is the common code for setting up the floating and fixed length
7346      * string data extracted from Perl_re_op_compile() below.  Returns a boolean
7347      * as to whether succeeded or not */
7348
7349     I32 t;
7350     SSize_t ml;
7351     bool eol  = cBOOL(sub->flags & SF_BEFORE_EOL);
7352     bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
7353
7354     if (! (longest_length
7355            || (eol /* Can't have SEOL and MULTI */
7356                && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
7357           )
7358             /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
7359         || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
7360     {
7361         return FALSE;
7362     }
7363
7364     /* copy the information about the longest from the reg_scan_data
7365         over to the program. */
7366     if (SvUTF8(sub->str)) {
7367         rsd->substr      = NULL;
7368         rsd->utf8_substr = sub->str;
7369     } else {
7370         rsd->substr      = sub->str;
7371         rsd->utf8_substr = NULL;
7372     }
7373     /* end_shift is how many chars that must be matched that
7374         follow this item. We calculate it ahead of time as once the
7375         lookbehind offset is added in we lose the ability to correctly
7376         calculate it.*/
7377     ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
7378     rsd->end_shift = ml - sub->min_offset
7379         - longest_length
7380             /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
7381              * intead? - DAPM
7382             + (SvTAIL(sub->str) != 0)
7383             */
7384         + sub->lookbehind;
7385
7386     t = (eol/* Can't have SEOL and MULTI */
7387          && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
7388     fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
7389
7390     return TRUE;
7391 }
7392
7393 STATIC void
7394 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
7395 {
7396     /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
7397      * properly wrapped with the right modifiers */
7398
7399     bool has_p     = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7400     bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
7401                                                 != REGEX_DEPENDS_CHARSET);
7402
7403     /* The caret is output if there are any defaults: if not all the STD
7404         * flags are set, or if no character set specifier is needed */
7405     bool has_default =
7406                 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7407                 || ! has_charset);
7408     bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7409                                                 == REG_RUN_ON_COMMENT_SEEN);
7410     U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
7411                         >> RXf_PMf_STD_PMMOD_SHIFT);
7412     const char *fptr = STD_PAT_MODS;        /*"msixxn"*/
7413     char *p;
7414     STRLEN pat_len = RExC_precomp_end - RExC_precomp;
7415
7416     /* We output all the necessary flags; we never output a minus, as all
7417         * those are defaults, so are
7418         * covered by the caret */
7419     const STRLEN wraplen = pat_len + has_p + has_runon
7420         + has_default       /* If needs a caret */
7421         + PL_bitcount[reganch] /* 1 char for each set standard flag */
7422
7423             /* If needs a character set specifier */
7424         + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7425         + (sizeof("(?:)") - 1);
7426
7427     PERL_ARGS_ASSERT_SET_REGEX_PV;
7428
7429     /* make sure PL_bitcount bounds not exceeded */
7430     STATIC_ASSERT_STMT(sizeof(STD_PAT_MODS) <= 8);
7431
7432     p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
7433     SvPOK_on(Rx);
7434     if (RExC_utf8)
7435         SvFLAGS(Rx) |= SVf_UTF8;
7436     *p++='('; *p++='?';
7437
7438     /* If a default, cover it using the caret */
7439     if (has_default) {
7440         *p++= DEFAULT_PAT_MOD;
7441     }
7442     if (has_charset) {
7443         STRLEN len;
7444         const char* name;
7445
7446         name = get_regex_charset_name(RExC_rx->extflags, &len);
7447         if (strEQ(name, DEPENDS_PAT_MODS)) {  /* /d under UTF-8 => /u */
7448             assert(RExC_utf8);
7449             name = UNICODE_PAT_MODS;
7450             len = sizeof(UNICODE_PAT_MODS) - 1;
7451         }
7452         Copy(name, p, len, char);
7453         p += len;
7454     }
7455     if (has_p)
7456         *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7457     {
7458         char ch;
7459         while((ch = *fptr++)) {
7460             if(reganch & 1)
7461                 *p++ = ch;
7462             reganch >>= 1;
7463         }
7464     }
7465
7466     *p++ = ':';
7467     Copy(RExC_precomp, p, pat_len, char);
7468     assert ((RX_WRAPPED(Rx) - p) < 16);
7469     RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7470     p += pat_len;
7471
7472     /* Adding a trailing \n causes this to compile properly:
7473             my $R = qr / A B C # D E/x; /($R)/
7474         Otherwise the parens are considered part of the comment */
7475     if (has_runon)
7476         *p++ = '\n';
7477     *p++ = ')';
7478     *p = 0;
7479     SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7480 }
7481
7482 /*
7483  * Perl_re_op_compile - the perl internal RE engine's function to compile a
7484  * regular expression into internal code.
7485  * The pattern may be passed either as:
7486  *    a list of SVs (patternp plus pat_count)
7487  *    a list of OPs (expr)
7488  * If both are passed, the SV list is used, but the OP list indicates
7489  * which SVs are actually pre-compiled code blocks
7490  *
7491  * The SVs in the list have magic and qr overloading applied to them (and
7492  * the list may be modified in-place with replacement SVs in the latter
7493  * case).
7494  *
7495  * If the pattern hasn't changed from old_re, then old_re will be
7496  * returned.
7497  *
7498  * eng is the current engine. If that engine has an op_comp method, then
7499  * handle directly (i.e. we assume that op_comp was us); otherwise, just
7500  * do the initial concatenation of arguments and pass on to the external
7501  * engine.
7502  *
7503  * If is_bare_re is not null, set it to a boolean indicating whether the
7504  * arg list reduced (after overloading) to a single bare regex which has
7505  * been returned (i.e. /$qr/).
7506  *
7507  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7508  *
7509  * pm_flags contains the PMf_* flags, typically based on those from the
7510  * pm_flags field of the related PMOP. Currently we're only interested in
7511  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL, PMf_WILDCARD.
7512  *
7513  * For many years this code had an initial sizing pass that calculated
7514  * (sometimes incorrectly, leading to security holes) the size needed for the
7515  * compiled pattern.  That was changed by commit
7516  * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7517  * node at a time, as parsing goes along.  Patches welcome to fix any obsolete
7518  * references to this sizing pass.
7519  *
7520  * Now, an initial crude guess as to the size needed is made, based on the
7521  * length of the pattern.  Patches welcome to improve that guess.  That amount
7522  * of space is malloc'd and then immediately freed, and then clawed back node
7523  * by node.  This design is to minimze, to the extent possible, memory churn
7524  * when doing the reallocs.
7525  *
7526  * A separate parentheses counting pass may be needed in some cases.
7527  * (Previously the sizing pass did this.)  Patches welcome to reduce the number
7528  * of these cases.
7529  *
7530  * The existence of a sizing pass necessitated design decisions that are no
7531  * longer needed.  There are potential areas of simplification.
7532  *
7533  * Beware that the optimization-preparation code in here knows about some
7534  * of the structure of the compiled regexp.  [I'll say.]
7535  */
7536
7537 REGEXP *
7538 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7539                     OP *expr, const regexp_engine* eng, REGEXP *old_re,
7540                      bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7541 {
7542     REGEXP *Rx;         /* Capital 'R' means points to a REGEXP */
7543     STRLEN plen;
7544     char *exp;
7545     regnode *scan;
7546     I32 flags;
7547     SSize_t minlen = 0;
7548     U32 rx_flags;
7549     SV *pat;
7550     SV** new_patternp = patternp;
7551
7552     /* these are all flags - maybe they should be turned
7553      * into a single int with different bit masks */
7554     I32 sawlookahead = 0;
7555     I32 sawplus = 0;
7556     I32 sawopen = 0;
7557     I32 sawminmod = 0;
7558
7559     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7560     bool recompile = 0;
7561     bool runtime_code = 0;
7562     scan_data_t data;
7563     RExC_state_t RExC_state;
7564     RExC_state_t * const pRExC_state = &RExC_state;
7565 #ifdef TRIE_STUDY_OPT
7566     int restudied = 0;
7567     RExC_state_t copyRExC_state;
7568 #endif
7569     DECLARE_AND_GET_RE_DEBUG_FLAGS;
7570
7571     PERL_ARGS_ASSERT_RE_OP_COMPILE;
7572
7573     DEBUG_r(if (!PL_colorset) reginitcolors());
7574
7575
7576     pRExC_state->warn_text = NULL;
7577     pRExC_state->unlexed_names = NULL;
7578     pRExC_state->code_blocks = NULL;
7579
7580     if (is_bare_re)
7581         *is_bare_re = FALSE;
7582
7583     if (expr && (expr->op_type == OP_LIST ||
7584                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7585         /* allocate code_blocks if needed */
7586         OP *o;
7587         int ncode = 0;
7588
7589         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7590             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7591                 ncode++; /* count of DO blocks */
7592
7593         if (ncode)
7594             pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7595     }
7596
7597     if (!pat_count) {
7598         /* compile-time pattern with just OP_CONSTs and DO blocks */
7599
7600         int n;
7601         OP *o;
7602
7603         /* find how many CONSTs there are */
7604         assert(expr);
7605         n = 0;
7606         if (expr->op_type == OP_CONST)
7607             n = 1;
7608         else
7609             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7610                 if (o->op_type == OP_CONST)
7611                     n++;
7612             }
7613
7614         /* fake up an SV array */
7615
7616         assert(!new_patternp);
7617         Newx(new_patternp, n, SV*);
7618         SAVEFREEPV(new_patternp);
7619         pat_count = n;
7620
7621         n = 0;
7622         if (expr->op_type == OP_CONST)
7623             new_patternp[n] = cSVOPx_sv(expr);
7624         else
7625             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7626                 if (o->op_type == OP_CONST)
7627                     new_patternp[n++] = cSVOPo_sv;
7628             }
7629
7630     }
7631
7632     DEBUG_PARSE_r(Perl_re_printf( aTHX_
7633         "Assembling pattern from %d elements%s\n", pat_count,
7634             orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7635
7636     /* set expr to the first arg op */
7637
7638     if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7639          && expr->op_type != OP_CONST)
7640     {
7641             expr = cLISTOPx(expr)->op_first;
7642             assert(   expr->op_type == OP_PUSHMARK
7643                    || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7644                    || expr->op_type == OP_PADRANGE);
7645             expr = OpSIBLING(expr);
7646     }
7647
7648     pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7649                         expr, &recompile, NULL);
7650
7651     /* handle bare (possibly after overloading) regex: foo =~ $re */
7652     {
7653         SV *re = pat;
7654         if (SvROK(re))
7655             re = SvRV(re);
7656         if (SvTYPE(re) == SVt_REGEXP) {
7657             if (is_bare_re)
7658                 *is_bare_re = TRUE;
7659             SvREFCNT_inc(re);
7660             DEBUG_PARSE_r(Perl_re_printf( aTHX_
7661                 "Precompiled pattern%s\n",
7662                     orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7663
7664             return (REGEXP*)re;
7665         }
7666     }
7667
7668     exp = SvPV_nomg(pat, plen);
7669
7670     if (!eng->op_comp) {
7671         if ((SvUTF8(pat) && IN_BYTES)
7672                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7673         {
7674             /* make a temporary copy; either to convert to bytes,
7675              * or to avoid repeating get-magic / overloaded stringify */
7676             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7677                                         (IN_BYTES ? 0 : SvUTF8(pat)));
7678         }
7679         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7680     }
7681
7682     /* ignore the utf8ness if the pattern is 0 length */
7683     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7684     RExC_uni_semantics = 0;
7685     RExC_contains_locale = 0;
7686     RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7687     RExC_in_script_run = 0;
7688     RExC_study_started = 0;
7689     pRExC_state->runtime_code_qr = NULL;
7690     RExC_frame_head= NULL;
7691     RExC_frame_last= NULL;
7692     RExC_frame_count= 0;
7693     RExC_latest_warn_offset = 0;
7694     RExC_use_BRANCHJ = 0;
7695     RExC_warned_WARN_EXPERIMENTAL__VLB = 0;
7696     RExC_warned_WARN_EXPERIMENTAL__REGEX_SETS = 0;
7697     RExC_total_parens = 0;
7698     RExC_open_parens = NULL;
7699     RExC_close_parens = NULL;
7700     RExC_paren_names = NULL;
7701     RExC_size = 0;
7702     RExC_seen_d_op = FALSE;
7703 #ifdef DEBUGGING
7704     RExC_paren_name_list = NULL;
7705 #endif
7706
7707     DEBUG_r({
7708         RExC_mysv1= sv_newmortal();
7709         RExC_mysv2= sv_newmortal();
7710     });
7711
7712     DEBUG_COMPILE_r({
7713             SV *dsv= sv_newmortal();
7714             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7715             Perl_re_printf( aTHX_  "%sCompiling REx%s %s\n",
7716                           PL_colors[4], PL_colors[5], s);
7717         });
7718
7719     /* we jump here if we have to recompile, e.g., from upgrading the pattern
7720      * to utf8 */
7721
7722     if ((pm_flags & PMf_USE_RE_EVAL)
7723                 /* this second condition covers the non-regex literal case,
7724                  * i.e.  $foo =~ '(?{})'. */
7725                 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7726     )
7727         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7728
7729   redo_parse:
7730     /* return old regex if pattern hasn't changed */
7731     /* XXX: note in the below we have to check the flags as well as the
7732      * pattern.
7733      *
7734      * Things get a touch tricky as we have to compare the utf8 flag
7735      * independently from the compile flags.  */
7736
7737     if (   old_re
7738         && !recompile
7739         && !!RX_UTF8(old_re) == !!RExC_utf8
7740         && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7741         && RX_PRECOMP(old_re)
7742         && RX_PRELEN(old_re) == plen
7743         && memEQ(RX_PRECOMP(old_re), exp, plen)
7744         && !runtime_code /* with runtime code, always recompile */ )
7745     {
7746         DEBUG_COMPILE_r({
7747             SV *dsv= sv_newmortal();
7748             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7749             Perl_re_printf( aTHX_  "%sSkipping recompilation of unchanged REx%s %s\n",
7750                           PL_colors[4], PL_colors[5], s);
7751         });
7752         return old_re;
7753     }
7754
7755     /* Allocate the pattern's SV */
7756     RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7757     RExC_rx = ReANY(Rx);
7758     if ( RExC_rx == NULL )
7759         FAIL("Regexp out of space");
7760
7761     rx_flags = orig_rx_flags;
7762
7763     if (   toUSE_UNI_CHARSET_NOT_DEPENDS
7764         && initial_charset == REGEX_DEPENDS_CHARSET)
7765     {
7766
7767         /* Set to use unicode semantics if the pattern is in utf8 and has the
7768          * 'depends' charset specified, as it means unicode when utf8  */
7769         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7770         RExC_uni_semantics = 1;
7771     }
7772
7773     RExC_pm_flags = pm_flags;
7774
7775     if (runtime_code) {
7776         assert(TAINTING_get || !TAINT_get);
7777         if (TAINT_get)
7778             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7779
7780         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7781             /* whoops, we have a non-utf8 pattern, whilst run-time code
7782              * got compiled as utf8. Try again with a utf8 pattern */
7783             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7784                 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7785             goto redo_parse;
7786         }
7787     }
7788     assert(!pRExC_state->runtime_code_qr);
7789
7790     RExC_sawback = 0;
7791
7792     RExC_seen = 0;
7793     RExC_maxlen = 0;
7794     RExC_in_lookaround = 0;
7795     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7796     RExC_recode_x_to_native = 0;
7797     RExC_in_multi_char_class = 0;
7798
7799     RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7800     RExC_precomp_end = RExC_end = exp + plen;
7801     RExC_nestroot = 0;
7802     RExC_whilem_seen = 0;
7803     RExC_end_op = NULL;
7804     RExC_recurse = NULL;
7805     RExC_study_chunk_recursed = NULL;
7806     RExC_study_chunk_recursed_bytes= 0;
7807     RExC_recurse_count = 0;
7808     RExC_sets_depth = 0;
7809     pRExC_state->code_index = 0;
7810
7811     /* Initialize the string in the compiled pattern.  This is so that there is
7812      * something to output if necessary */
7813     set_regex_pv(pRExC_state, Rx);
7814
7815     DEBUG_PARSE_r({
7816         Perl_re_printf( aTHX_
7817             "Starting parse and generation\n");
7818         RExC_lastnum=0;
7819         RExC_lastparse=NULL;
7820     });
7821
7822     /* Allocate space and zero-initialize. Note, the two step process
7823        of zeroing when in debug mode, thus anything assigned has to
7824        happen after that */
7825     if (!  RExC_size) {
7826
7827         /* On the first pass of the parse, we guess how big this will be.  Then
7828          * we grow in one operation to that amount and then give it back.  As
7829          * we go along, we re-allocate what we need.
7830          *
7831          * XXX Currently the guess is essentially that the pattern will be an
7832          * EXACT node with one byte input, one byte output.  This is crude, and
7833          * better heuristics are welcome.
7834          *
7835          * On any subsequent passes, we guess what we actually computed in the
7836          * latest earlier pass.  Such a pass probably didn't complete so is
7837          * missing stuff.  We could improve those guesses by knowing where the
7838          * parse stopped, and use the length so far plus apply the above
7839          * assumption to what's left. */
7840         RExC_size = STR_SZ(RExC_end - RExC_start);
7841     }
7842
7843     Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7844     if ( RExC_rxi == NULL )
7845         FAIL("Regexp out of space");
7846
7847     Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7848     RXi_SET( RExC_rx, RExC_rxi );
7849
7850     /* We start from 0 (over from 0 in the case this is a reparse.  The first
7851      * node parsed will give back any excess memory we have allocated so far).
7852      * */
7853     RExC_size = 0;
7854
7855     /* non-zero initialization begins here */
7856     RExC_rx->engine= eng;
7857     RExC_rx->extflags = rx_flags;
7858     RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7859
7860     if (pm_flags & PMf_IS_QR) {
7861         RExC_rxi->code_blocks = pRExC_state->code_blocks;
7862         if (RExC_rxi->code_blocks) {
7863             RExC_rxi->code_blocks->refcnt++;
7864         }
7865     }
7866
7867     RExC_rx->intflags = 0;
7868
7869     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
7870     RExC_parse = exp;
7871
7872     /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7873      * code makes sure the final byte is an uncounted NUL.  But should this
7874      * ever not be the case, lots of things could read beyond the end of the
7875      * buffer: loops like
7876      *      while(isFOO(*RExC_parse)) RExC_parse++;
7877      *      strchr(RExC_parse, "foo");
7878      * etc.  So it is worth noting. */
7879     assert(*RExC_end == '\0');
7880
7881     RExC_naughty = 0;
7882     RExC_npar = 1;
7883     RExC_parens_buf_size = 0;
7884     RExC_emit_start = RExC_rxi->program;
7885     pRExC_state->code_index = 0;
7886
7887     *((char*) RExC_emit_start) = (char) REG_MAGIC;
7888     RExC_emit = 1;
7889
7890     /* Do the parse */
7891     if (reg(pRExC_state, 0, &flags, 1)) {
7892
7893         /* Success!, But we may need to redo the parse knowing how many parens
7894          * there actually are */
7895         if (IN_PARENS_PASS) {
7896             flags |= RESTART_PARSE;
7897         }
7898
7899         /* We have that number in RExC_npar */
7900         RExC_total_parens = RExC_npar;
7901     }
7902     else if (! MUST_RESTART(flags)) {
7903         ReREFCNT_dec(Rx);
7904         Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7905     }
7906
7907     /* Here, we either have success, or we have to redo the parse for some reason */
7908     if (MUST_RESTART(flags)) {
7909
7910         /* It's possible to write a regexp in ascii that represents Unicode
7911         codepoints outside of the byte range, such as via \x{100}. If we
7912         detect such a sequence we have to convert the entire pattern to utf8
7913         and then recompile, as our sizing calculation will have been based
7914         on 1 byte == 1 character, but we will need to use utf8 to encode
7915         at least some part of the pattern, and therefore must convert the whole
7916         thing.
7917         -- dmq */
7918         if (flags & NEED_UTF8) {
7919
7920             /* We have stored the offset of the final warning output so far.
7921              * That must be adjusted.  Any variant characters between the start
7922              * of the pattern and this warning count for 2 bytes in the final,
7923              * so just add them again */
7924             if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7925                 RExC_latest_warn_offset +=
7926                             variant_under_utf8_count((U8 *) exp, (U8 *) exp
7927                                                 + RExC_latest_warn_offset);
7928             }
7929             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7930             pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7931             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7932         }
7933         else {
7934             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7935         }
7936
7937         if (ALL_PARENS_COUNTED) {
7938             /* Make enough room for all the known parens, and zero it */
7939             Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7940             Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7941             RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
7942
7943             Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7944             Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7945         }
7946         else { /* Parse did not complete.  Reinitialize the parentheses
7947                   structures */
7948             RExC_total_parens = 0;
7949             if (RExC_open_parens) {
7950                 Safefree(RExC_open_parens);
7951                 RExC_open_parens = NULL;
7952             }
7953             if (RExC_close_parens) {
7954                 Safefree(RExC_close_parens);
7955                 RExC_close_parens = NULL;
7956             }
7957         }
7958
7959         /* Clean up what we did in this parse */
7960         SvREFCNT_dec_NN(RExC_rx_sv);
7961
7962         goto redo_parse;
7963     }
7964
7965     /* Here, we have successfully parsed and generated the pattern's program
7966      * for the regex engine.  We are ready to finish things up and look for
7967      * optimizations. */
7968
7969     /* Update the string to compile, with correct modifiers, etc */
7970     set_regex_pv(pRExC_state, Rx);
7971
7972     RExC_rx->nparens = RExC_total_parens - 1;
7973
7974     /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7975     if (RExC_whilem_seen > 15)
7976         RExC_whilem_seen = 15;
7977
7978     DEBUG_PARSE_r({
7979         Perl_re_printf( aTHX_
7980             "Required size %" IVdf " nodes\n", (IV)RExC_size);
7981         RExC_lastnum=0;
7982         RExC_lastparse=NULL;
7983     });
7984
7985 #ifdef RE_TRACK_PATTERN_OFFSETS
7986     DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7987                           "%s %" UVuf " bytes for offset annotations.\n",
7988                           RExC_offsets ? "Got" : "Couldn't get",
7989                           (UV)((RExC_offsets[0] * 2 + 1))));
7990     DEBUG_OFFSETS_r(if (RExC_offsets) {
7991         const STRLEN len = RExC_offsets[0];
7992         STRLEN i;
7993         DECLARE_AND_GET_RE_DEBUG_FLAGS;
7994         Perl_re_printf( aTHX_
7995                       "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7996         for (i = 1; i <= len; i++) {
7997             if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7998                 Perl_re_printf( aTHX_  "%" UVuf ":%" UVuf "[%" UVuf "] ",
7999                 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
8000         }
8001         Perl_re_printf( aTHX_  "\n");
8002     });
8003
8004 #else
8005     SetProgLen(RExC_rxi,RExC_size);
8006 #endif
8007
8008     DEBUG_DUMP_PRE_OPTIMIZE_r({
8009         SV * const sv = sv_newmortal();
8010         RXi_GET_DECL(RExC_rx, ri);
8011         DEBUG_RExC_seen();
8012         Perl_re_printf( aTHX_ "Program before optimization:\n");
8013
8014         (void)dumpuntil(RExC_rx, ri->program, ri->program + 1, NULL, NULL,
8015                         sv, 0, 0);
8016     });
8017
8018     DEBUG_OPTIMISE_r(
8019         Perl_re_printf( aTHX_  "Starting post parse optimization\n");
8020     );
8021
8022     /* XXXX To minimize changes to RE engine we always allocate
8023        3-units-long substrs field. */
8024     Newx(RExC_rx->substrs, 1, struct reg_substr_data);
8025     if (RExC_recurse_count) {
8026         Newx(RExC_recurse, RExC_recurse_count, regnode *);
8027         SAVEFREEPV(RExC_recurse);
8028     }
8029
8030     if (RExC_seen & REG_RECURSE_SEEN) {
8031         /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
8032          * So its 1 if there are no parens. */
8033         RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
8034                                          ((RExC_total_parens & 0x07) != 0);
8035         Newx(RExC_study_chunk_recursed,
8036              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
8037         SAVEFREEPV(RExC_study_chunk_recursed);
8038     }
8039
8040   reStudy:
8041     RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
8042     DEBUG_r(
8043         RExC_study_chunk_recursed_count= 0;
8044     );
8045     Zero(RExC_rx->substrs, 1, struct reg_substr_data);
8046     if (RExC_study_chunk_recursed) {
8047         Zero(RExC_study_chunk_recursed,
8048              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
8049     }
8050
8051
8052 #ifdef TRIE_STUDY_OPT
8053     if (!restudied) {
8054         StructCopy(&zero_scan_data, &data, scan_data_t);
8055         copyRExC_state = RExC_state;
8056     } else {
8057         U32 seen=RExC_seen;
8058         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
8059
8060         RExC_state = copyRExC_state;
8061         if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
8062             RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
8063         else
8064             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
8065         StructCopy(&zero_scan_data, &data, scan_data_t);
8066     }
8067 #else
8068     StructCopy(&zero_scan_data, &data, scan_data_t);
8069 #endif
8070
8071     /* Dig out information for optimizations. */
8072     RExC_rx->extflags = RExC_flags; /* was pm_op */
8073     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
8074
8075     if (UTF)
8076         SvUTF8_on(Rx);  /* Unicode in it? */
8077     RExC_rxi->regstclass = NULL;
8078     if (RExC_naughty >= TOO_NAUGHTY)    /* Probably an expensive pattern. */
8079         RExC_rx->intflags |= PREGf_NAUGHTY;
8080     scan = RExC_rxi->program + 1;               /* First BRANCH. */
8081
8082     /* testing for BRANCH here tells us whether there is "must appear"
8083        data in the pattern. If there is then we can use it for optimisations */
8084     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /*  Only one top-level choice.
8085                                                   */
8086         SSize_t fake;
8087         STRLEN longest_length[2];
8088         regnode_ssc ch_class; /* pointed to by data */
8089         int stclass_flag;
8090         SSize_t last_close = 0; /* pointed to by data */
8091         regnode *first= scan;
8092         regnode *first_next= regnext(first);
8093         int i;
8094
8095         /*
8096          * Skip introductions and multiplicators >= 1
8097          * so that we can extract the 'meat' of the pattern that must
8098          * match in the large if() sequence following.
8099          * NOTE that EXACT is NOT covered here, as it is normally
8100          * picked up by the optimiser separately.
8101          *
8102          * This is unfortunate as the optimiser isnt handling lookahead
8103          * properly currently.
8104          *
8105          */
8106         while ((OP(first) == OPEN && (sawopen = 1)) ||
8107                /* An OR of *one* alternative - should not happen now. */
8108             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
8109             /* for now we can't handle lookbehind IFMATCH*/
8110             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
8111             (OP(first) == PLUS) ||
8112             (OP(first) == MINMOD) ||
8113                /* An {n,m} with n>0 */
8114             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
8115             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
8116         {
8117                 /*
8118                  * the only op that could be a regnode is PLUS, all the rest
8119                  * will be regnode_1 or regnode_2.
8120                  *
8121                  * (yves doesn't think this is true)
8122                  */
8123                 if (OP(first) == PLUS)
8124                     sawplus = 1;
8125                 else {
8126                     if (OP(first) == MINMOD)
8127                         sawminmod = 1;
8128                     first += regarglen[OP(first)];
8129                 }
8130                 first = NEXTOPER(first);
8131                 first_next= regnext(first);
8132         }
8133
8134         /* Starting-point info. */
8135       again:
8136         DEBUG_PEEP("first:", first, 0, 0);
8137         /* Ignore EXACT as we deal with it later. */
8138         if (PL_regkind[OP(first)] == EXACT) {
8139             if (! isEXACTFish(OP(first))) {
8140                 NOOP;   /* Empty, get anchored substr later. */
8141             }
8142             else
8143                 RExC_rxi->regstclass = first;
8144         }
8145 #ifdef TRIE_STCLASS
8146         else if (PL_regkind[OP(first)] == TRIE &&
8147                 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
8148         {
8149             /* this can happen only on restudy */
8150             RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
8151         }
8152 #endif
8153         else if (REGNODE_SIMPLE(OP(first)))
8154             RExC_rxi->regstclass = first;
8155         else if (PL_regkind[OP(first)] == BOUND ||
8156                  PL_regkind[OP(first)] == NBOUND)
8157             RExC_rxi->regstclass = first;
8158         else if (PL_regkind[OP(first)] == BOL) {
8159             RExC_rx->intflags |= (OP(first) == MBOL
8160                            ? PREGf_ANCH_MBOL
8161                            : PREGf_ANCH_SBOL);
8162             first = NEXTOPER(first);
8163             goto again;
8164         }
8165         else if (OP(first) == GPOS) {
8166             RExC_rx->intflags |= PREGf_ANCH_GPOS;
8167             first = NEXTOPER(first);
8168             goto again;
8169         }
8170         else if ((!sawopen || !RExC_sawback) &&
8171             !sawlookahead &&
8172             (OP(first) == STAR &&
8173             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
8174             !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
8175         {
8176             /* turn .* into ^.* with an implied $*=1 */
8177             const int type =
8178                 (OP(NEXTOPER(first)) == REG_ANY)
8179                     ? PREGf_ANCH_MBOL
8180                     : PREGf_ANCH_SBOL;
8181             RExC_rx->intflags |= (type | PREGf_IMPLICIT);
8182             first = NEXTOPER(first);
8183             goto again;
8184         }
8185         if (sawplus && !sawminmod && !sawlookahead
8186             && (!sawopen || !RExC_sawback)
8187             && !pRExC_state->code_blocks) /* May examine pos and $& */
8188             /* x+ must match at the 1st pos of run of x's */
8189             RExC_rx->intflags |= PREGf_SKIP;
8190
8191         /* Scan is after the zeroth branch, first is atomic matcher. */
8192 #ifdef TRIE_STUDY_OPT
8193         DEBUG_PARSE_r(
8194             if (!restudied)
8195                 Perl_re_printf( aTHX_  "first at %" IVdf "\n",
8196                               (IV)(first - scan + 1))
8197         );
8198 #else
8199         DEBUG_PARSE_r(
8200             Perl_re_printf( aTHX_  "first at %" IVdf "\n",
8201                 (IV)(first - scan + 1))
8202         );
8203 #endif
8204
8205
8206         /*
8207         * If there's something expensive in the r.e., find the
8208         * longest literal string that must appear and make it the
8209         * regmust.  Resolve ties in favor of later strings, since
8210         * the regstart check works with the beginning of the r.e.
8211         * and avoiding duplication strengthens checking.  Not a
8212         * strong reason, but sufficient in the absence of others.
8213         * [Now we resolve ties in favor of the earlier string if
8214         * it happens that c_offset_min has been invalidated, since the
8215         * earlier string may buy us something the later one won't.]
8216         */
8217
8218         data.substrs[0].str = newSVpvs("");
8219         data.substrs[1].str = newSVpvs("");
8220         data.last_found = newSVpvs("");
8221         data.cur_is_floating = 0; /* initially any found substring is fixed */
8222         ENTER_with_name("study_chunk");
8223         SAVEFREESV(data.substrs[0].str);
8224         SAVEFREESV(data.substrs[1].str);
8225         SAVEFREESV(data.last_found);
8226         first = scan;
8227         if (!RExC_rxi->regstclass) {
8228             ssc_init(pRExC_state, &ch_class);
8229             data.start_class = &ch_class;
8230             stclass_flag = SCF_DO_STCLASS_AND;
8231         } else                          /* XXXX Check for BOUND? */
8232             stclass_flag = 0;
8233         data.last_closep = &last_close;
8234
8235         DEBUG_RExC_seen();
8236         /*
8237          * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
8238          * (NO top level branches)
8239          */
8240         minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
8241                              scan + RExC_size, /* Up to end */
8242             &data, -1, 0, NULL,
8243             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
8244                           | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
8245             0, TRUE);
8246
8247
8248         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
8249
8250
8251         if ( RExC_total_parens == 1 && !data.cur_is_floating
8252              && data.last_start_min == 0 && data.last_end > 0
8253              && !RExC_seen_zerolen
8254              && !(RExC_seen & REG_VERBARG_SEEN)
8255              && !(RExC_seen & REG_GPOS_SEEN)
8256         ){
8257             RExC_rx->extflags |= RXf_CHECK_ALL;
8258         }
8259         scan_commit(pRExC_state, &data,&minlen, 0);
8260
8261
8262         /* XXX this is done in reverse order because that's the way the
8263          * code was before it was parameterised. Don't know whether it
8264          * actually needs doing in reverse order. DAPM */
8265         for (i = 1; i >= 0; i--) {
8266             longest_length[i] = CHR_SVLEN(data.substrs[i].str);
8267
8268             if (   !(   i
8269                      && SvCUR(data.substrs[0].str)  /* ok to leave SvCUR */
8270                      &&    data.substrs[0].min_offset
8271                         == data.substrs[1].min_offset
8272                      &&    SvCUR(data.substrs[0].str)
8273                         == SvCUR(data.substrs[1].str)
8274                     )
8275                 && S_setup_longest (aTHX_ pRExC_state,
8276                                         &(RExC_rx->substrs->data[i]),
8277                                         &(data.substrs[i]),
8278                                         longest_length[i]))
8279             {
8280                 RExC_rx->substrs->data[i].min_offset =
8281                         data.substrs[i].min_offset - data.substrs[i].lookbehind;
8282
8283                 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
8284                 /* Don't offset infinity */
8285                 if (data.substrs[i].max_offset < OPTIMIZE_INFTY)
8286                     RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
8287                 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
8288             }
8289             else {
8290                 RExC_rx->substrs->data[i].substr      = NULL;
8291                 RExC_rx->substrs->data[i].utf8_substr = NULL;
8292                 longest_length[i] = 0;
8293             }
8294         }
8295
8296         LEAVE_with_name("study_chunk");
8297
8298         if (RExC_rxi->regstclass
8299             && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
8300             RExC_rxi->regstclass = NULL;
8301
8302         if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
8303               || RExC_rx->substrs->data[0].min_offset)
8304             && stclass_flag
8305             && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8306             && is_ssc_worth_it(pRExC_state, data.start_class))
8307         {
8308             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8309
8310             ssc_finalize(pRExC_state, data.start_class);
8311
8312             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8313             StructCopy(data.start_class,
8314                        (regnode_ssc*)RExC_rxi->data->data[n],
8315                        regnode_ssc);
8316             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8317             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
8318             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
8319                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8320                       Perl_re_printf( aTHX_
8321                                     "synthetic stclass \"%s\".\n",
8322                                     SvPVX_const(sv));});
8323             data.start_class = NULL;
8324         }
8325
8326         /* A temporary algorithm prefers floated substr to fixed one of
8327          * same length to dig more info. */
8328         i = (longest_length[0] <= longest_length[1]);
8329         RExC_rx->substrs->check_ix = i;
8330         RExC_rx->check_end_shift  = RExC_rx->substrs->data[i].end_shift;
8331         RExC_rx->check_substr     = RExC_rx->substrs->data[i].substr;
8332         RExC_rx->check_utf8       = RExC_rx->substrs->data[i].utf8_substr;
8333         RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
8334         RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
8335         if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
8336             RExC_rx->intflags |= PREGf_NOSCAN;
8337
8338         if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
8339             RExC_rx->extflags |= RXf_USE_INTUIT;
8340             if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
8341                 RExC_rx->extflags |= RXf_INTUIT_TAIL;
8342         }
8343
8344         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
8345         if ( (STRLEN)minlen < longest_length[1] )
8346             minlen= longest_length[1];
8347         if ( (STRLEN)minlen < longest_length[0] )
8348             minlen= longest_length[0];
8349         */
8350     }
8351     else {
8352         /* Several toplevels. Best we can is to set minlen. */
8353         SSize_t fake;
8354         regnode_ssc ch_class;
8355         SSize_t last_close = 0;
8356
8357         DEBUG_PARSE_r(Perl_re_printf( aTHX_  "\nMulti Top Level\n"));
8358
8359         scan = RExC_rxi->program + 1;
8360         ssc_init(pRExC_state, &ch_class);
8361         data.start_class = &ch_class;
8362         data.last_closep = &last_close;
8363
8364         DEBUG_RExC_seen();
8365         /*
8366          * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
8367          * (patterns WITH top level branches)
8368          */
8369         minlen = study_chunk(pRExC_state,
8370             &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
8371             SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
8372                                                       ? SCF_TRIE_DOING_RESTUDY
8373                                                       : 0),
8374             0, TRUE);
8375
8376         CHECK_RESTUDY_GOTO_butfirst(NOOP);
8377
8378         RExC_rx->check_substr = NULL;
8379         RExC_rx->check_utf8 = NULL;
8380         RExC_rx->substrs->data[0].substr      = NULL;
8381         RExC_rx->substrs->data[0].utf8_substr = NULL;
8382         RExC_rx->substrs->data[1].substr      = NULL;
8383         RExC_rx->substrs->data[1].utf8_substr = NULL;
8384
8385         if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8386             && is_ssc_worth_it(pRExC_state, data.start_class))
8387         {
8388             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8389
8390             ssc_finalize(pRExC_state, data.start_class);
8391
8392             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8393             StructCopy(data.start_class,
8394                        (regnode_ssc*)RExC_rxi->data->data[n],
8395                        regnode_ssc);
8396             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8397             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
8398             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
8399                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8400                       Perl_re_printf( aTHX_
8401                                     "synthetic stclass \"%s\".\n",
8402                                     SvPVX_const(sv));});
8403             data.start_class = NULL;
8404         }
8405     }
8406
8407     if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
8408         RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
8409         RExC_rx->maxlen = REG_INFTY;
8410     }
8411     else {
8412         RExC_rx->maxlen = RExC_maxlen;
8413     }
8414
8415     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
8416        the "real" pattern. */
8417     DEBUG_OPTIMISE_r({
8418         Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
8419                       (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
8420     });
8421     RExC_rx->minlenret = minlen;
8422     if (RExC_rx->minlen < minlen)
8423         RExC_rx->minlen = minlen;
8424
8425     if (RExC_seen & REG_RECURSE_SEEN ) {
8426         RExC_rx->intflags |= PREGf_RECURSE_SEEN;
8427         Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
8428     }
8429     if (RExC_seen & REG_GPOS_SEEN)
8430         RExC_rx->intflags |= PREGf_GPOS_SEEN;
8431     if (RExC_seen & REG_LOOKBEHIND_SEEN)
8432         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
8433                                                 lookbehind */
8434     if (pRExC_state->code_blocks)
8435         RExC_rx->extflags |= RXf_EVAL_SEEN;
8436     if (RExC_seen & REG_VERBARG_SEEN)
8437     {
8438         RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8439         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8440     }
8441     if (RExC_seen & REG_CUTGROUP_SEEN)
8442         RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8443     if (pm_flags & PMf_USE_RE_EVAL)
8444         RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8445     if (RExC_paren_names)
8446         RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8447     else
8448         RXp_PAREN_NAMES(RExC_rx) = NULL;
8449
8450     /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8451      * so it can be used in pp.c */
8452     if (RExC_rx->intflags & PREGf_ANCH)
8453         RExC_rx->extflags |= RXf_IS_ANCHORED;
8454
8455
8456     {
8457         /* this is used to identify "special" patterns that might result
8458          * in Perl NOT calling the regex engine and instead doing the match "itself",
8459          * particularly special cases in split//. By having the regex compiler
8460          * do this pattern matching at a regop level (instead of by inspecting the pattern)
8461          * we avoid weird issues with equivalent patterns resulting in different behavior,
8462          * AND we allow non Perl engines to get the same optimizations by the setting the
8463          * flags appropriately - Yves */
8464         regnode *first = RExC_rxi->program + 1;
8465         U8 fop = OP(first);
8466         regnode *next = NEXTOPER(first);
8467         /* It's safe to read through *next only if OP(first) is a regop of
8468          * the right type (not EXACT, for example).
8469          */
8470         U8 nop = (fop == NOTHING || fop == MBOL || fop == SBOL || fop == PLUS)
8471                 ? OP(next) : 0;
8472
8473         if (PL_regkind[fop] == NOTHING && nop == END)
8474             RExC_rx->extflags |= RXf_NULL;
8475         else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8476             /* when fop is SBOL first->flags will be true only when it was
8477              * produced by parsing /\A/, and not when parsing /^/. This is
8478              * very important for the split code as there we want to
8479              * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8480              * See rt #122761 for more details. -- Yves */
8481             RExC_rx->extflags |= RXf_START_ONLY;
8482         else if (fop == PLUS
8483                  && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8484                  && OP(regnext(first)) == END)
8485             RExC_rx->extflags |= RXf_WHITE;
8486         else if ( RExC_rx->extflags & RXf_SPLIT
8487                   && (PL_regkind[fop] == EXACT && ! isEXACTFish(fop))
8488                   && STR_LEN(first) == 1
8489                   && *(STRING(first)) == ' '
8490                   && OP(regnext(first)) == END )
8491             RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8492
8493     }
8494
8495     if (RExC_contains_locale) {
8496         RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8497     }
8498
8499 #ifdef DEBUGGING
8500     if (RExC_paren_names) {
8501         RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8502         RExC_rxi->data->data[RExC_rxi->name_list_idx]
8503                                    = (void*)SvREFCNT_inc(RExC_paren_name_list);
8504     } else
8505 #endif
8506     RExC_rxi->name_list_idx = 0;
8507
8508     while ( RExC_recurse_count > 0 ) {
8509         const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8510         /*
8511          * This data structure is set up in study_chunk() and is used
8512          * to calculate the distance between a GOSUB regopcode and
8513          * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8514          * it refers to.
8515          *
8516          * If for some reason someone writes code that optimises
8517          * away a GOSUB opcode then the assert should be changed to
8518          * an if(scan) to guard the ARG2L_SET() - Yves
8519          *
8520          */
8521         assert(scan && OP(scan) == GOSUB);
8522         ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8523     }
8524
8525     Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8526     /* assume we don't need to swap parens around before we match */
8527     DEBUG_TEST_r({
8528         Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8529             (unsigned long)RExC_study_chunk_recursed_count);
8530     });
8531     DEBUG_DUMP_r({
8532         DEBUG_RExC_seen();
8533         Perl_re_printf( aTHX_ "Final program:\n");
8534         regdump(RExC_rx);
8535     });
8536
8537     if (RExC_open_parens) {
8538         Safefree(RExC_open_parens);
8539         RExC_open_parens = NULL;
8540     }
8541     if (RExC_close_parens) {
8542         Safefree(RExC_close_parens);
8543         RExC_close_parens = NULL;
8544     }
8545
8546 #ifdef USE_ITHREADS
8547     /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8548      * by setting the regexp SV to readonly-only instead. If the
8549      * pattern's been recompiled, the USEDness should remain. */
8550     if (old_re && SvREADONLY(old_re))
8551         SvREADONLY_on(Rx);
8552 #endif
8553     return Rx;
8554 }
8555
8556
8557 SV*
8558 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8559                     const U32 flags)
8560 {
8561     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8562
8563     PERL_UNUSED_ARG(value);
8564
8565     if (flags & RXapif_FETCH) {
8566         return reg_named_buff_fetch(rx, key, flags);
8567     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8568         Perl_croak_no_modify();
8569         return NULL;
8570     } else if (flags & RXapif_EXISTS) {
8571         return reg_named_buff_exists(rx, key, flags)
8572             ? &PL_sv_yes
8573             : &PL_sv_no;
8574     } else if (flags & RXapif_REGNAMES) {
8575         return reg_named_buff_all(rx, flags);
8576     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8577         return reg_named_buff_scalar(rx, flags);
8578     } else {
8579         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8580         return NULL;
8581     }
8582 }
8583
8584 SV*
8585 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8586                          const U32 flags)
8587 {
8588     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8589     PERL_UNUSED_ARG(lastkey);
8590
8591     if (flags & RXapif_FIRSTKEY)
8592         return reg_named_buff_firstkey(rx, flags);
8593     else if (flags & RXapif_NEXTKEY)
8594         return reg_named_buff_nextkey(rx, flags);
8595     else {
8596         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8597                                             (int)flags);
8598         return NULL;
8599     }
8600 }
8601
8602 SV*
8603 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8604                           const U32 flags)
8605 {
8606     SV *ret;
8607     struct regexp *const rx = ReANY(r);
8608
8609     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8610
8611     if (rx && RXp_PAREN_NAMES(rx)) {
8612         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8613         if (he_str) {
8614             IV i;
8615             SV* sv_dat=HeVAL(he_str);
8616             I32 *nums=(I32*)SvPVX(sv_dat);
8617             AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8618             for ( i=0; i<SvIVX(sv_dat); i++ ) {
8619                 if ((I32)(rx->nparens) >= nums[i]
8620                     && rx->offs[nums[i]].start != -1
8621                     && rx->offs[nums[i]].end != -1)
8622                 {
8623                     ret = newSVpvs("");
8624                     CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8625                     if (!retarray)
8626                         return ret;
8627                 } else {
8628                     if (retarray)
8629                         ret = newSVsv(&PL_sv_undef);
8630                 }
8631                 if (retarray)
8632                     av_push(retarray, ret);
8633             }
8634             if (retarray)
8635                 return newRV_noinc(MUTABLE_SV(retarray));
8636         }
8637     }
8638     return NULL;
8639 }
8640
8641 bool
8642 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8643                            const U32 flags)
8644 {
8645     struct regexp *const rx = ReANY(r);
8646
8647     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8648
8649     if (rx && RXp_PAREN_NAMES(rx)) {
8650         if (flags & RXapif_ALL) {
8651             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8652         } else {
8653             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8654             if (sv) {
8655                 SvREFCNT_dec_NN(sv);
8656                 return TRUE;
8657             } else {
8658                 return FALSE;
8659             }
8660         }
8661     } else {
8662         return FALSE;
8663     }
8664 }
8665
8666 SV*
8667 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8668 {
8669     struct regexp *const rx = ReANY(r);
8670
8671     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8672
8673     if ( rx && RXp_PAREN_NAMES(rx) ) {
8674         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8675
8676         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8677     } else {
8678         return FALSE;
8679     }
8680 }
8681
8682 SV*
8683 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8684 {
8685     struct regexp *const rx = ReANY(r);
8686     DECLARE_AND_GET_RE_DEBUG_FLAGS;
8687
8688     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8689
8690     if (rx && RXp_PAREN_NAMES(rx)) {
8691         HV *hv = RXp_PAREN_NAMES(rx);
8692         HE *temphe;
8693         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8694             IV i;
8695             IV parno = 0;
8696             SV* sv_dat = HeVAL(temphe);
8697             I32 *nums = (I32*)SvPVX(sv_dat);
8698             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8699                 if ((I32)(rx->lastparen) >= nums[i] &&
8700                     rx->offs[nums[i]].start != -1 &&
8701                     rx->offs[nums[i]].end != -1)
8702                 {
8703                     parno = nums[i];
8704                     break;
8705                 }
8706             }
8707             if (parno || flags & RXapif_ALL) {
8708                 return newSVhek(HeKEY_hek(temphe));
8709             }
8710         }
8711     }
8712     return NULL;
8713 }
8714
8715 SV*
8716 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8717 {
8718     SV *ret;
8719     AV *av;
8720     SSize_t length;
8721     struct regexp *const rx = ReANY(r);
8722
8723     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8724
8725     if (rx && RXp_PAREN_NAMES(rx)) {
8726         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8727             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8728         } else if (flags & RXapif_ONE) {
8729             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8730             av = MUTABLE_AV(SvRV(ret));
8731             length = av_count(av);
8732             SvREFCNT_dec_NN(ret);
8733             return newSViv(length);
8734         } else {
8735             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8736                                                 (int)flags);
8737             return NULL;
8738         }
8739     }
8740     return &PL_sv_undef;
8741 }
8742
8743 SV*
8744 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8745 {
8746     struct regexp *const rx = ReANY(r);
8747     AV *av = newAV();
8748
8749     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8750
8751     if (rx && RXp_PAREN_NAMES(rx)) {
8752         HV *hv= RXp_PAREN_NAMES(rx);
8753         HE *temphe;
8754         (void)hv_iterinit(hv);
8755         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8756             IV i;
8757             IV parno = 0;
8758             SV* sv_dat = HeVAL(temphe);
8759             I32 *nums = (I32*)SvPVX(sv_dat);
8760             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8761                 if ((I32)(rx->lastparen) >= nums[i] &&
8762                     rx->offs[nums[i]].start != -1 &&
8763                     rx->offs[nums[i]].end != -1)
8764                 {
8765                     parno = nums[i];
8766                     break;
8767                 }
8768             }
8769             if (parno || flags & RXapif_ALL) {
8770                 av_push(av, newSVhek(HeKEY_hek(temphe)));
8771             }
8772         }
8773     }
8774
8775     return newRV_noinc(MUTABLE_SV(av));
8776 }
8777
8778 void
8779 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8780                              SV * const sv)
8781 {
8782     struct regexp *const rx = ReANY(r);
8783     char *s = NULL;
8784     SSize_t i = 0;
8785     SSize_t s1, t1;
8786     I32 n = paren;
8787
8788     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8789
8790     if (      n == RX_BUFF_IDX_CARET_PREMATCH
8791            || n == RX_BUFF_IDX_CARET_FULLMATCH
8792            || n == RX_BUFF_IDX_CARET_POSTMATCH
8793        )
8794     {
8795         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8796         if (!keepcopy) {
8797             /* on something like
8798              *    $r = qr/.../;
8799              *    /$qr/p;
8800              * the KEEPCOPY is set on the PMOP rather than the regex */
8801             if (PL_curpm && r == PM_GETRE(PL_curpm))
8802                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8803         }
8804         if (!keepcopy)
8805             goto ret_undef;
8806     }
8807
8808     if (!rx->subbeg)
8809         goto ret_undef;
8810
8811     if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8812         /* no need to distinguish between them any more */
8813         n = RX_BUFF_IDX_FULLMATCH;
8814
8815     if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8816         && rx->offs[0].start != -1)
8817     {
8818         /* $`, ${^PREMATCH} */
8819         i = rx->offs[0].start;
8820         s = rx->subbeg;
8821     }
8822     else
8823     if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8824         && rx->offs[0].end != -1)
8825     {
8826         /* $', ${^POSTMATCH} */
8827         s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8828         i = rx->sublen + rx->suboffset - rx->offs[0].end;
8829     }
8830     else
8831     if (inRANGE(n, 0, (I32)rx->nparens) &&
8832         (s1 = rx->offs[n].start) != -1  &&
8833         (t1 = rx->offs[n].end) != -1)
8834     {
8835         /* $&, ${^MATCH},  $1 ... */
8836         i = t1 - s1;
8837         s = rx->subbeg + s1 - rx->suboffset;
8838     } else {
8839         goto ret_undef;
8840     }
8841
8842     assert(s >= rx->subbeg);
8843     assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8844     if (i >= 0) {
8845 #ifdef NO_TAINT_SUPPORT
8846         sv_setpvn(sv, s, i);
8847 #else
8848         const int oldtainted = TAINT_get;
8849         TAINT_NOT;
8850         sv_setpvn(sv, s, i);
8851         TAINT_set(oldtainted);
8852 #endif
8853         if (RXp_MATCH_UTF8(rx))
8854             SvUTF8_on(sv);
8855         else
8856             SvUTF8_off(sv);
8857         if (TAINTING_get) {
8858             if (RXp_MATCH_TAINTED(rx)) {
8859                 if (SvTYPE(sv) >= SVt_PVMG) {
8860                     MAGIC* const mg = SvMAGIC(sv);
8861                     MAGIC* mgt;
8862                     TAINT;
8863                     SvMAGIC_set(sv, mg->mg_moremagic);
8864                     SvTAINT(sv);
8865                     if ((mgt = SvMAGIC(sv))) {
8866                         mg->mg_moremagic = mgt;
8867                         SvMAGIC_set(sv, mg);
8868                     }
8869                 } else {
8870                     TAINT;
8871                     SvTAINT(sv);
8872                 }
8873             } else
8874                 SvTAINTED_off(sv);
8875         }
8876     } else {
8877       ret_undef:
8878         sv_set_undef(sv);
8879         return;
8880     }
8881 }
8882
8883 void
8884 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8885                                                          SV const * const value)
8886 {
8887     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8888
8889     PERL_UNUSED_ARG(rx);
8890     PERL_UNUSED_ARG(paren);
8891     PERL_UNUSED_ARG(value);
8892
8893     if (!PL_localizing)
8894         Perl_croak_no_modify();
8895 }
8896
8897 I32
8898 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8899                               const I32 paren)
8900 {
8901     struct regexp *const rx = ReANY(r);
8902     I32 i;
8903     I32 s1, t1;
8904
8905     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8906
8907     if (   paren == RX_BUFF_IDX_CARET_PREMATCH
8908         || paren == RX_BUFF_IDX_CARET_FULLMATCH
8909         || paren == RX_BUFF_IDX_CARET_POSTMATCH
8910     )
8911     {
8912         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8913         if (!keepcopy) {
8914             /* on something like
8915              *    $r = qr/.../;
8916              *    /$qr/p;
8917              * the KEEPCOPY is set on the PMOP rather than the regex */
8918             if (PL_curpm && r == PM_GETRE(PL_curpm))
8919                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8920         }
8921         if (!keepcopy)
8922             goto warn_undef;
8923     }
8924
8925     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8926     switch (paren) {
8927       case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8928       case RX_BUFF_IDX_PREMATCH:       /* $` */
8929         if (rx->offs[0].start != -1) {
8930                         i = rx->offs[0].start;
8931                         if (i > 0) {
8932                                 s1 = 0;
8933                                 t1 = i;
8934                                 goto getlen;
8935                         }
8936             }
8937         return 0;
8938
8939       case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8940       case RX_BUFF_IDX_POSTMATCH:       /* $' */
8941             if (rx->offs[0].end != -1) {
8942                         i = rx->sublen - rx->offs[0].end;
8943                         if (i > 0) {
8944                                 s1 = rx->offs[0].end;
8945                                 t1 = rx->sublen;
8946                                 goto getlen;
8947                         }
8948             }
8949         return 0;
8950
8951       default: /* $& / ${^MATCH}, $1, $2, ... */
8952             if (paren <= (I32)rx->nparens &&
8953             (s1 = rx->offs[paren].start) != -1 &&
8954             (t1 = rx->offs[paren].end) != -1)
8955             {
8956             i = t1 - s1;
8957             goto getlen;
8958         } else {
8959           warn_undef:
8960             if (ckWARN(WARN_UNINITIALIZED))
8961                 report_uninit((const SV *)sv);
8962             return 0;
8963         }
8964     }
8965   getlen:
8966     if (i > 0 && RXp_MATCH_UTF8(rx)) {
8967         const char * const s = rx->subbeg - rx->suboffset + s1;
8968         const U8 *ep;
8969         STRLEN el;
8970
8971         i = t1 - s1;
8972         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8973             i = el;
8974     }
8975     return i;
8976 }
8977
8978 SV*
8979 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8980 {
8981     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8982         PERL_UNUSED_ARG(rx);
8983         if (0)
8984             return NULL;
8985         else
8986             return newSVpvs("Regexp");
8987 }
8988
8989 /* Scans the name of a named buffer from the pattern.
8990  * If flags is REG_RSN_RETURN_NULL returns null.
8991  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8992  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8993  * to the parsed name as looked up in the RExC_paren_names hash.
8994  * If there is an error throws a vFAIL().. type exception.
8995  */
8996
8997 #define REG_RSN_RETURN_NULL    0
8998 #define REG_RSN_RETURN_NAME    1
8999 #define REG_RSN_RETURN_DATA    2
9000
9001 STATIC SV*
9002 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
9003 {
9004     char *name_start = RExC_parse;
9005     SV* sv_name;
9006
9007     PERL_ARGS_ASSERT_REG_SCAN_NAME;
9008
9009     assert (RExC_parse <= RExC_end);
9010     if (RExC_parse == RExC_end) NOOP;
9011     else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
9012          /* Note that the code here assumes well-formed UTF-8.  Skip IDFIRST by
9013           * using do...while */
9014         if (UTF)
9015             do {
9016                 RExC_parse += UTF8SKIP(RExC_parse);
9017             } while (   RExC_parse < RExC_end
9018                      && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
9019         else
9020             do {
9021                 RExC_parse++;
9022             } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
9023     } else {
9024         RExC_parse++; /* so the <- from the vFAIL is after the offending
9025                          character */
9026         vFAIL("Group name must start with a non-digit word character");
9027     }
9028     sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
9029                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
9030     if ( flags == REG_RSN_RETURN_NAME)
9031         return sv_name;
9032     else if (flags==REG_RSN_RETURN_DATA) {
9033         HE *he_str = NULL;
9034         SV *sv_dat = NULL;
9035         if ( ! sv_name )      /* should not happen*/
9036             Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
9037         if (RExC_paren_names)
9038             he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
9039         if ( he_str )
9040             sv_dat = HeVAL(he_str);
9041         if ( ! sv_dat ) {   /* Didn't find group */
9042
9043             /* It might be a forward reference; we can't fail until we
9044                 * know, by completing the parse to get all the groups, and
9045                 * then reparsing */
9046             if (ALL_PARENS_COUNTED)  {
9047                 vFAIL("Reference to nonexistent named group");
9048             }
9049             else {
9050                 REQUIRE_PARENS_PASS;
9051             }
9052         }
9053         return sv_dat;
9054     }
9055
9056     Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
9057                      (unsigned long) flags);
9058 }
9059
9060 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
9061     if (RExC_lastparse!=RExC_parse) {                           \
9062         Perl_re_printf( aTHX_  "%s",                            \
9063             Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse,        \
9064                 RExC_end - RExC_parse, 16,                      \
9065                 "", "",                                         \
9066                 PERL_PV_ESCAPE_UNI_DETECT |                     \
9067                 PERL_PV_PRETTY_ELLIPSES   |                     \
9068                 PERL_PV_PRETTY_LTGT       |                     \
9069                 PERL_PV_ESCAPE_RE         |                     \
9070                 PERL_PV_PRETTY_EXACTSIZE                        \
9071             )                                                   \
9072         );                                                      \
9073     } else                                                      \
9074         Perl_re_printf( aTHX_ "%16s","");                       \
9075                                                                 \
9076     if (RExC_lastnum!=RExC_emit)                                \
9077        Perl_re_printf( aTHX_ "|%4zu", RExC_emit);                \
9078     else                                                        \
9079        Perl_re_printf( aTHX_ "|%4s","");                        \
9080     Perl_re_printf( aTHX_ "|%*s%-4s",                           \
9081         (int)((depth*2)), "",                                   \
9082         (funcname)                                              \
9083     );                                                          \
9084     RExC_lastnum=RExC_emit;                                     \
9085     RExC_lastparse=RExC_parse;                                  \
9086 })
9087
9088
9089
9090 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
9091     DEBUG_PARSE_MSG((funcname));                            \
9092     Perl_re_printf( aTHX_ "%4s","\n");                                  \
9093 })
9094 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({\
9095     DEBUG_PARSE_MSG((funcname));                            \
9096     Perl_re_printf( aTHX_ fmt "\n",args);                               \
9097 })
9098
9099 /* This section of code defines the inversion list object and its methods.  The
9100  * interfaces are highly subject to change, so as much as possible is static to
9101  * this file.  An inversion list is here implemented as a malloc'd C UV array
9102  * as an SVt_INVLIST scalar.
9103  *
9104  * An inversion list for Unicode is an array of code points, sorted by ordinal
9105  * number.  Each element gives the code point that begins a range that extends
9106  * up-to but not including the code point given by the next element.  The final
9107  * element gives the first code point of a range that extends to the platform's
9108  * infinity.  The even-numbered elements (invlist[0], invlist[2], invlist[4],
9109  * ...) give ranges whose code points are all in the inversion list.  We say
9110  * that those ranges are in the set.  The odd-numbered elements give ranges
9111  * whose code points are not in the inversion list, and hence not in the set.
9112  * Thus, element [0] is the first code point in the list.  Element [1]
9113  * is the first code point beyond that not in the list; and element [2] is the
9114  * first code point beyond that that is in the list.  In other words, the first
9115  * range is invlist[0]..(invlist[1]-1), and all code points in that range are
9116  * in the inversion list.  The second range is invlist[1]..(invlist[2]-1), and
9117  * all code points in that range are not in the inversion list.  The third
9118  * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
9119  * list, and so forth.  Thus every element whose index is divisible by two
9120  * gives the beginning of a range that is in the list, and every element whose
9121  * index is not divisible by two gives the beginning of a range not in the
9122  * list.  If the final element's index is divisible by two, the inversion list
9123  * extends to the platform's infinity; otherwise the highest code point in the
9124  * inversion list is the contents of that element minus 1.
9125  *
9126  * A range that contains just a single code point N will look like
9127  *  invlist[i]   == N
9128  *  invlist[i+1] == N+1
9129  *
9130  * If N is UV_MAX (the highest representable code point on the machine), N+1 is
9131  * impossible to represent, so element [i+1] is omitted.  The single element
9132  * inversion list
9133  *  invlist[0] == UV_MAX
9134  * contains just UV_MAX, but is interpreted as matching to infinity.
9135  *
9136  * Taking the complement (inverting) an inversion list is quite simple, if the
9137  * first element is 0, remove it; otherwise add a 0 element at the beginning.
9138  * This implementation reserves an element at the beginning of each inversion
9139  * list to always contain 0; there is an additional flag in the header which
9140  * indicates if the list begins at the 0, or is offset to begin at the next
9141  * element.  This means that the inversion list can be inverted without any
9142  * copying; just flip the flag.
9143  *
9144  * More about inversion lists can be found in "Unicode Demystified"
9145  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
9146  *
9147  * The inversion list data structure is currently implemented as an SV pointing
9148  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
9149  * array of UV whose memory management is automatically handled by the existing
9150  * facilities for SV's.
9151  *
9152  * Some of the methods should always be private to the implementation, and some
9153  * should eventually be made public */
9154
9155 /* The header definitions are in F<invlist_inline.h> */
9156
9157 #ifndef PERL_IN_XSUB_RE
9158
9159 PERL_STATIC_INLINE UV*
9160 S__invlist_array_init(SV* const invlist, const bool will_have_0)
9161 {
9162     /* Returns a pointer to the first element in the inversion list's array.
9163      * This is called upon initialization of an inversion list.  Where the
9164      * array begins depends on whether the list has the code point U+0000 in it
9165      * or not.  The other parameter tells it whether the code that follows this
9166      * call is about to put a 0 in the inversion list or not.  The first
9167      * element is either the element reserved for 0, if TRUE, or the element
9168      * after it, if FALSE */
9169
9170     bool* offset = get_invlist_offset_addr(invlist);
9171     UV* zero_addr = (UV *) SvPVX(invlist);
9172
9173     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
9174
9175     /* Must be empty */
9176     assert(! _invlist_len(invlist));
9177
9178     *zero_addr = 0;
9179
9180     /* 1^1 = 0; 1^0 = 1 */
9181     *offset = 1 ^ will_have_0;
9182     return zero_addr + *offset;
9183 }
9184
9185 STATIC void
9186 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
9187 {
9188     /* Replaces the inversion list in 'dest' with the one from 'src'.  It
9189      * steals the list from 'src', so 'src' is made to have a NULL list.  This
9190      * is similar to what SvSetMagicSV() would do, if it were implemented on
9191      * inversion lists, though this routine avoids a copy */
9192
9193     const UV src_len          = _invlist_len(src);
9194     const bool src_offset     = *get_invlist_offset_addr(src);
9195     const STRLEN src_byte_len = SvLEN(src);
9196     char * array              = SvPVX(src);
9197
9198     const int oldtainted = TAINT_get;
9199
9200     PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
9201
9202     assert(is_invlist(src));
9203     assert(is_invlist(dest));
9204     assert(! invlist_is_iterating(src));
9205     assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
9206
9207     /* Make sure it ends in the right place with a NUL, as our inversion list
9208      * manipulations aren't careful to keep this true, but sv_usepvn_flags()
9209      * asserts it */
9210     array[src_byte_len - 1] = '\0';
9211
9212     TAINT_NOT;      /* Otherwise it breaks */
9213     sv_usepvn_flags(dest,
9214                     (char *) array,
9215                     src_byte_len - 1,
9216
9217                     /* This flag is documented to cause a copy to be avoided */
9218                     SV_HAS_TRAILING_NUL);
9219     TAINT_set(oldtainted);
9220     SvPV_set(src, 0);
9221     SvLEN_set(src, 0);
9222     SvCUR_set(src, 0);
9223
9224     /* Finish up copying over the other fields in an inversion list */
9225     *get_invlist_offset_addr(dest) = src_offset;
9226     invlist_set_len(dest, src_len, src_offset);
9227     *get_invlist_previous_index_addr(dest) = 0;
9228     invlist_iterfinish(dest);
9229 }
9230
9231 PERL_STATIC_INLINE IV*
9232 S_get_invlist_previous_index_addr(SV* invlist)
9233 {
9234     /* Return the address of the IV that is reserved to hold the cached index
9235      * */
9236     PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
9237
9238     assert(is_invlist(invlist));
9239
9240     return &(((XINVLIST*) SvANY(invlist))->prev_index);
9241 }
9242
9243 PERL_STATIC_INLINE IV
9244 S_invlist_previous_index(SV* const invlist)
9245 {
9246     /* Returns cached index of previous search */
9247
9248     PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
9249
9250     return *get_invlist_previous_index_addr(invlist);
9251 }
9252
9253 PERL_STATIC_INLINE void
9254 S_invlist_set_previous_index(SV* const invlist, const IV index)
9255 {
9256     /* Caches <index> for later retrieval */
9257
9258     PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
9259
9260     assert(index == 0 || index < (int) _invlist_len(invlist));
9261
9262     *get_invlist_previous_index_addr(invlist) = index;
9263 }
9264
9265 PERL_STATIC_INLINE void
9266 S_invlist_trim(SV* invlist)
9267 {
9268     /* Free the not currently-being-used space in an inversion list */
9269
9270     /* But don't free up the space needed for the 0 UV that is always at the
9271      * beginning of the list, nor the trailing NUL */
9272     const UV min_size = TO_INTERNAL_SIZE(1) + 1;
9273
9274     PERL_ARGS_ASSERT_INVLIST_TRIM;
9275
9276     assert(is_invlist(invlist));
9277
9278     SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
9279 }
9280
9281 PERL_STATIC_INLINE void
9282 S_invlist_clear(pTHX_ SV* invlist)    /* Empty the inversion list */
9283 {
9284     PERL_ARGS_ASSERT_INVLIST_CLEAR;
9285
9286     assert(is_invlist(invlist));
9287
9288     invlist_set_len(invlist, 0, 0);
9289     invlist_trim(invlist);
9290 }
9291
9292 #endif /* ifndef PERL_IN_XSUB_RE */
9293
9294 PERL_STATIC_INLINE bool
9295 S_invlist_is_iterating(SV* const invlist)
9296 {
9297     PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
9298
9299     return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
9300 }
9301
9302 #ifndef PERL_IN_XSUB_RE
9303
9304 PERL_STATIC_INLINE UV
9305 S_invlist_max(SV* const invlist)
9306 {
9307     /* Returns the maximum number of elements storable in the inversion list's
9308      * array, without having to realloc() */
9309
9310     PERL_ARGS_ASSERT_INVLIST_MAX;
9311
9312     assert(is_invlist(invlist));
9313
9314     /* Assumes worst case, in which the 0 element is not counted in the
9315      * inversion list, so subtracts 1 for that */
9316     return SvLEN(invlist) == 0  /* This happens under _new_invlist_C_array */
9317            ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
9318            : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
9319 }
9320
9321 STATIC void
9322 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
9323 {
9324     PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
9325
9326     /* First 1 is in case the zero element isn't in the list; second 1 is for
9327      * trailing NUL */
9328     SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
9329     invlist_set_len(invlist, 0, 0);
9330
9331     /* Force iterinit() to be used to get iteration to work */
9332     invlist_iterfinish(invlist);
9333
9334     *get_invlist_previous_index_addr(invlist) = 0;
9335     SvPOK_on(invlist);  /* This allows B to extract the PV */
9336 }
9337
9338 SV*
9339 Perl__new_invlist(pTHX_ IV initial_size)
9340 {
9341
9342     /* Return a pointer to a newly constructed inversion list, with enough
9343      * space to store 'initial_size' elements.  If that number is negative, a
9344      * system default is used instead */
9345
9346     SV* new_list;
9347
9348     if (initial_size < 0) {
9349         initial_size = 10;
9350     }
9351
9352     new_list = newSV_type(SVt_INVLIST);
9353     initialize_invlist_guts(new_list, initial_size);
9354
9355     return new_list;
9356 }
9357
9358 SV*
9359 Perl__new_invlist_C_array(pTHX_ const UV* const list)
9360 {
9361     /* Return a pointer to a newly constructed inversion list, initialized to
9362      * point to <list>, which has to be in the exact correct inversion list
9363      * form, including internal fields.  Thus this is a dangerous routine that
9364      * should not be used in the wrong hands.  The passed in 'list' contains
9365      * several header fields at the beginning that are not part of the
9366      * inversion list body proper */
9367
9368     const STRLEN length = (STRLEN) list[0];
9369     const UV version_id =          list[1];
9370     const bool offset   =    cBOOL(list[2]);
9371 #define HEADER_LENGTH 3
9372     /* If any of the above changes in any way, you must change HEADER_LENGTH
9373      * (if appropriate) and regenerate INVLIST_VERSION_ID by running
9374      *      perl -E 'say int(rand 2**31-1)'
9375      */
9376 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
9377                                         data structure type, so that one being
9378                                         passed in can be validated to be an
9379                                         inversion list of the correct vintage.
9380                                        */
9381
9382     SV* invlist = newSV_type(SVt_INVLIST);
9383
9384     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
9385
9386     if (version_id != INVLIST_VERSION_ID) {
9387         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
9388     }
9389
9390     /* The generated array passed in includes header elements that aren't part
9391      * of the list proper, so start it just after them */
9392     SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
9393
9394     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
9395                                shouldn't touch it */
9396
9397     *(get_invlist_offset_addr(invlist)) = offset;
9398
9399     /* The 'length' passed to us is the physical number of elements in the
9400      * inversion list.  But if there is an offset the logical number is one
9401      * less than that */
9402     invlist_set_len(invlist, length  - offset, offset);
9403
9404     invlist_set_previous_index(invlist, 0);
9405
9406     /* Initialize the iteration pointer. */
9407     invlist_iterfinish(invlist);
9408
9409     SvREADONLY_on(invlist);
9410     SvPOK_on(invlist);
9411
9412     return invlist;
9413 }
9414
9415 STATIC void
9416 S__append_range_to_invlist(pTHX_ SV* const invlist,
9417                                  const UV start, const UV end)
9418 {
9419    /* Subject to change or removal.  Append the range from 'start' to 'end' at
9420     * the end of the inversion list.  The range must be above any existing
9421     * ones. */
9422
9423     UV* array;
9424     UV max = invlist_max(invlist);
9425     UV len = _invlist_len(invlist);
9426     bool offset;
9427
9428     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9429
9430     if (len == 0) { /* Empty lists must be initialized */
9431         offset = start != 0;
9432         array = _invlist_array_init(invlist, ! offset);
9433     }
9434     else {
9435         /* Here, the existing list is non-empty. The current max entry in the
9436          * list is generally the first value not in the set, except when the
9437          * set extends to the end of permissible values, in which case it is
9438          * the first entry in that final set, and so this call is an attempt to
9439          * append out-of-order */
9440
9441         UV final_element = len - 1;
9442         array = invlist_array(invlist);
9443         if (   array[final_element] > start
9444             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9445         {
9446             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",
9447                      array[final_element], start,
9448                      ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9449         }
9450
9451         /* Here, it is a legal append.  If the new range begins 1 above the end
9452          * of the range below it, it is extending the range below it, so the
9453          * new first value not in the set is one greater than the newly
9454          * extended range.  */
9455         offset = *get_invlist_offset_addr(invlist);
9456         if (array[final_element] == start) {
9457             if (end != UV_MAX) {
9458                 array[final_element] = end + 1;
9459             }
9460             else {
9461                 /* But if the end is the maximum representable on the machine,
9462                  * assume that infinity was actually what was meant.  Just let
9463                  * the range that this would extend to have no end */
9464                 invlist_set_len(invlist, len - 1, offset);
9465             }
9466             return;
9467         }
9468     }
9469
9470     /* Here the new range doesn't extend any existing set.  Add it */
9471
9472     len += 2;   /* Includes an element each for the start and end of range */
9473
9474     /* If wll overflow the existing space, extend, which may cause the array to
9475      * be moved */
9476     if (max < len) {
9477         invlist_extend(invlist, len);
9478
9479         /* Have to set len here to avoid assert failure in invlist_array() */
9480         invlist_set_len(invlist, len, offset);
9481
9482         array = invlist_array(invlist);
9483     }
9484     else {
9485         invlist_set_len(invlist, len, offset);
9486     }
9487
9488     /* The next item on the list starts the range, the one after that is
9489      * one past the new range.  */
9490     array[len - 2] = start;
9491     if (end != UV_MAX) {
9492         array[len - 1] = end + 1;
9493     }
9494     else {
9495         /* But if the end is the maximum representable on the machine, just let
9496          * the range have no end */
9497         invlist_set_len(invlist, len - 1, offset);
9498     }
9499 }
9500
9501 SSize_t
9502 Perl__invlist_search(SV* const invlist, const UV cp)
9503 {
9504     /* Searches the inversion list for the entry that contains the input code
9505      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
9506      * return value is the index into the list's array of the range that
9507      * contains <cp>, that is, 'i' such that
9508      *  array[i] <= cp < array[i+1]
9509      */
9510
9511     IV low = 0;
9512     IV mid;
9513     IV high = _invlist_len(invlist);
9514     const IV highest_element = high - 1;
9515     const UV* array;
9516
9517     PERL_ARGS_ASSERT__INVLIST_SEARCH;
9518
9519     /* If list is empty, return failure. */
9520     if (UNLIKELY(high == 0)) {
9521         return -1;
9522     }
9523
9524     /* (We can't get the array unless we know the list is non-empty) */
9525     array = invlist_array(invlist);
9526
9527     mid = invlist_previous_index(invlist);
9528     assert(mid >=0);
9529     if (UNLIKELY(mid > highest_element)) {
9530         mid = highest_element;
9531     }
9532
9533     /* <mid> contains the cache of the result of the previous call to this
9534      * function (0 the first time).  See if this call is for the same result,
9535      * or if it is for mid-1.  This is under the theory that calls to this
9536      * function will often be for related code points that are near each other.
9537      * And benchmarks show that caching gives better results.  We also test
9538      * here if the code point is within the bounds of the list.  These tests
9539      * replace others that would have had to be made anyway to make sure that
9540      * the array bounds were not exceeded, and these give us extra information
9541      * at the same time */
9542     if (cp >= array[mid]) {
9543         if (cp >= array[highest_element]) {
9544             return highest_element;
9545         }
9546
9547         /* Here, array[mid] <= cp < array[highest_element].  This means that
9548          * the final element is not the answer, so can exclude it; it also
9549          * means that <mid> is not the final element, so can refer to 'mid + 1'
9550          * safely */
9551         if (cp < array[mid + 1]) {
9552             return mid;
9553         }
9554         high--;
9555         low = mid + 1;
9556     }
9557     else { /* cp < aray[mid] */
9558         if (cp < array[0]) { /* Fail if outside the array */
9559             return -1;
9560         }
9561         high = mid;
9562         if (cp >= array[mid - 1]) {
9563             goto found_entry;
9564         }
9565     }
9566
9567     /* Binary search.  What we are looking for is <i> such that
9568      *  array[i] <= cp < array[i+1]
9569      * The loop below converges on the i+1.  Note that there may not be an
9570      * (i+1)th element in the array, and things work nonetheless */
9571     while (low < high) {
9572         mid = (low + high) / 2;
9573         assert(mid <= highest_element);
9574         if (array[mid] <= cp) { /* cp >= array[mid] */
9575             low = mid + 1;
9576
9577             /* We could do this extra test to exit the loop early.
9578             if (cp < array[low]) {
9579                 return mid;
9580             }
9581             */
9582         }
9583         else { /* cp < array[mid] */
9584             high = mid;
9585         }
9586     }
9587
9588   found_entry:
9589     high--;
9590     invlist_set_previous_index(invlist, high);
9591     return high;
9592 }
9593
9594 void
9595 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9596                                          const bool complement_b, SV** output)
9597 {
9598     /* Take the union of two inversion lists and point '*output' to it.  On
9599      * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9600      * even 'a' or 'b').  If to an inversion list, the contents of the original
9601      * list will be replaced by the union.  The first list, 'a', may be
9602      * NULL, in which case a copy of the second list is placed in '*output'.
9603      * If 'complement_b' is TRUE, the union is taken of the complement
9604      * (inversion) of 'b' instead of b itself.
9605      *
9606      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9607      * Richard Gillam, published by Addison-Wesley, and explained at some
9608      * length there.  The preface says to incorporate its examples into your
9609      * code at your own risk.
9610      *
9611      * The algorithm is like a merge sort. */
9612
9613     const UV* array_a;    /* a's array */
9614     const UV* array_b;
9615     UV len_a;       /* length of a's array */
9616     UV len_b;
9617
9618     SV* u;                      /* the resulting union */
9619     UV* array_u;
9620     UV len_u = 0;
9621
9622     UV i_a = 0;             /* current index into a's array */
9623     UV i_b = 0;
9624     UV i_u = 0;
9625
9626     /* running count, as explained in the algorithm source book; items are
9627      * stopped accumulating and are output when the count changes to/from 0.
9628      * The count is incremented when we start a range that's in an input's set,
9629      * and decremented when we start a range that's not in a set.  So this
9630      * variable can be 0, 1, or 2.  When it is 0 neither input is in their set,
9631      * and hence nothing goes into the union; 1, just one of the inputs is in
9632      * its set (and its current range gets added to the union); and 2 when both
9633      * inputs are in their sets.  */
9634     UV count = 0;
9635
9636     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9637     assert(a != b);
9638     assert(*output == NULL || is_invlist(*output));
9639
9640     len_b = _invlist_len(b);
9641     if (len_b == 0) {
9642
9643         /* Here, 'b' is empty, hence it's complement is all possible code
9644          * points.  So if the union includes the complement of 'b', it includes
9645          * everything, and we need not even look at 'a'.  It's easiest to
9646          * create a new inversion list that matches everything.  */
9647         if (complement_b) {
9648             SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9649
9650             if (*output == NULL) { /* If the output didn't exist, just point it
9651                                       at the new list */
9652                 *output = everything;
9653             }
9654             else { /* Otherwise, replace its contents with the new list */
9655                 invlist_replace_list_destroys_src(*output, everything);
9656                 SvREFCNT_dec_NN(everything);
9657             }
9658
9659             return;
9660         }
9661
9662         /* Here, we don't want the complement of 'b', and since 'b' is empty,
9663          * the union will come entirely from 'a'.  If 'a' is NULL or empty, the
9664          * output will be empty */
9665
9666         if (a == NULL || _invlist_len(a) == 0) {
9667             if (*output == NULL) {
9668                 *output = _new_invlist(0);
9669             }
9670             else {
9671                 invlist_clear(*output);
9672             }
9673             return;
9674         }
9675
9676         /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9677          * union.  We can just return a copy of 'a' if '*output' doesn't point
9678          * to an existing list */
9679         if (*output == NULL) {
9680             *output = invlist_clone(a, NULL);
9681             return;
9682         }
9683
9684         /* If the output is to overwrite 'a', we have a no-op, as it's
9685          * already in 'a' */
9686         if (*output == a) {
9687             return;
9688         }
9689
9690         /* Here, '*output' is to be overwritten by 'a' */
9691         u = invlist_clone(a, NULL);
9692         invlist_replace_list_destroys_src(*output, u);
9693         SvREFCNT_dec_NN(u);
9694
9695         return;
9696     }
9697
9698     /* Here 'b' is not empty.  See about 'a' */
9699
9700     if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9701
9702         /* Here, 'a' is empty (and b is not).  That means the union will come
9703          * entirely from 'b'.  If '*output' is NULL, we can directly return a
9704          * clone of 'b'.  Otherwise, we replace the contents of '*output' with
9705          * the clone */
9706
9707         SV ** dest = (*output == NULL) ? output : &u;
9708         *dest = invlist_clone(b, NULL);
9709         if (complement_b) {
9710             _invlist_invert(*dest);
9711         }
9712
9713         if (dest == &u) {
9714             invlist_replace_list_destroys_src(*output, u);
9715             SvREFCNT_dec_NN(u);
9716         }
9717
9718         return;
9719     }
9720
9721     /* Here both lists exist and are non-empty */
9722     array_a = invlist_array(a);
9723     array_b = invlist_array(b);
9724
9725     /* If are to take the union of 'a' with the complement of b, set it
9726      * up so are looking at b's complement. */
9727     if (complement_b) {
9728
9729         /* To complement, we invert: if the first element is 0, remove it.  To
9730          * do this, we just pretend the array starts one later */
9731         if (array_b[0] == 0) {
9732             array_b++;
9733             len_b--;
9734         }
9735         else {
9736
9737             /* But if the first element is not zero, we pretend the list starts
9738              * at the 0 that is always stored immediately before the array. */
9739             array_b--;
9740             len_b++;
9741         }
9742     }
9743
9744     /* Size the union for the worst case: that the sets are completely
9745      * disjoint */
9746     u = _new_invlist(len_a + len_b);
9747
9748     /* Will contain U+0000 if either component does */
9749     array_u = _invlist_array_init(u, (    len_a > 0 && array_a[0] == 0)
9750                                       || (len_b > 0 && array_b[0] == 0));
9751
9752     /* Go through each input list item by item, stopping when have exhausted
9753      * one of them */
9754     while (i_a < len_a && i_b < len_b) {
9755         UV cp;      /* The element to potentially add to the union's array */
9756         bool cp_in_set;   /* is it in the input list's set or not */
9757
9758         /* We need to take one or the other of the two inputs for the union.
9759          * Since we are merging two sorted lists, we take the smaller of the
9760          * next items.  In case of a tie, we take first the one that is in its
9761          * set.  If we first took the one not in its set, it would decrement
9762          * the count, possibly to 0 which would cause it to be output as ending
9763          * the range, and the next time through we would take the same number,
9764          * and output it again as beginning the next range.  By doing it the
9765          * opposite way, there is no possibility that the count will be
9766          * momentarily decremented to 0, and thus the two adjoining ranges will
9767          * be seamlessly merged.  (In a tie and both are in the set or both not
9768          * in the set, it doesn't matter which we take first.) */
9769         if (       array_a[i_a] < array_b[i_b]
9770             || (   array_a[i_a] == array_b[i_b]
9771                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9772         {
9773             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9774             cp = array_a[i_a++];
9775         }
9776         else {
9777             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9778             cp = array_b[i_b++];
9779         }
9780
9781         /* Here, have chosen which of the two inputs to look at.  Only output
9782          * if the running count changes to/from 0, which marks the
9783          * beginning/end of a range that's in the set */
9784         if (cp_in_set) {
9785             if (count == 0) {
9786                 array_u[i_u++] = cp;
9787             }
9788             count++;
9789         }
9790         else {
9791             count--;
9792             if (count == 0) {
9793                 array_u[i_u++] = cp;
9794             }
9795         }
9796     }
9797
9798
9799     /* The loop above increments the index into exactly one of the input lists
9800      * each iteration, and ends when either index gets to its list end.  That
9801      * means the other index is lower than its end, and so something is
9802      * remaining in that one.  We decrement 'count', as explained below, if
9803      * that list is in its set.  (i_a and i_b each currently index the element
9804      * beyond the one we care about.) */
9805     if (   (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9806         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9807     {
9808         count--;
9809     }
9810
9811     /* Above we decremented 'count' if the list that had unexamined elements in
9812      * it was in its set.  This has made it so that 'count' being non-zero
9813      * means there isn't anything left to output; and 'count' equal to 0 means
9814      * that what is left to output is precisely that which is left in the
9815      * non-exhausted input list.
9816      *
9817      * To see why, note first that the exhausted input obviously has nothing
9818      * left to add to the union.  If it was in its set at its end, that means
9819      * the set extends from here to the platform's infinity, and hence so does
9820      * the union and the non-exhausted set is irrelevant.  The exhausted set
9821      * also contributed 1 to 'count'.  If 'count' was 2, it got decremented to
9822      * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9823      * 'count' remains at 1.  This is consistent with the decremented 'count'
9824      * != 0 meaning there's nothing left to add to the union.
9825      *
9826      * But if the exhausted input wasn't in its set, it contributed 0 to
9827      * 'count', and the rest of the union will be whatever the other input is.
9828      * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9829      * otherwise it gets decremented to 0.  This is consistent with 'count'
9830      * == 0 meaning the remainder of the union is whatever is left in the
9831      * non-exhausted list. */
9832     if (count != 0) {
9833         len_u = i_u;
9834     }
9835     else {
9836         IV copy_count = len_a - i_a;
9837         if (copy_count > 0) {   /* The non-exhausted input is 'a' */
9838             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9839         }
9840         else { /* The non-exhausted input is b */
9841             copy_count = len_b - i_b;
9842             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9843         }
9844         len_u = i_u + copy_count;
9845     }
9846
9847     /* Set the result to the final length, which can change the pointer to
9848      * array_u, so re-find it.  (Note that it is unlikely that this will
9849      * change, as we are shrinking the space, not enlarging it) */
9850     if (len_u != _invlist_len(u)) {
9851         invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9852         invlist_trim(u);
9853         array_u = invlist_array(u);
9854     }
9855
9856     if (*output == NULL) {  /* Simply return the new inversion list */
9857         *output = u;
9858     }
9859     else {
9860         /* Otherwise, overwrite the inversion list that was in '*output'.  We
9861          * could instead free '*output', and then set it to 'u', but experience
9862          * has shown [perl #127392] that if the input is a mortal, we can get a
9863          * huge build-up of these during regex compilation before they get
9864          * freed. */
9865         invlist_replace_list_destroys_src(*output, u);
9866         SvREFCNT_dec_NN(u);
9867     }
9868
9869     return;
9870 }
9871
9872 void
9873 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9874                                                const bool complement_b, SV** i)
9875 {
9876     /* Take the intersection of two inversion lists and point '*i' to it.  On
9877      * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9878      * even 'a' or 'b').  If to an inversion list, the contents of the original
9879      * list will be replaced by the intersection.  The first list, 'a', may be
9880      * NULL, in which case '*i' will be an empty list.  If 'complement_b' is
9881      * TRUE, the result will be the intersection of 'a' and the complement (or
9882      * inversion) of 'b' instead of 'b' directly.
9883      *
9884      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9885      * Richard Gillam, published by Addison-Wesley, and explained at some
9886      * length there.  The preface says to incorporate its examples into your
9887      * code at your own risk.  In fact, it had bugs
9888      *
9889      * The algorithm is like a merge sort, and is essentially the same as the
9890      * union above
9891      */
9892
9893     const UV* array_a;          /* a's array */
9894     const UV* array_b;
9895     UV len_a;   /* length of a's array */
9896     UV len_b;
9897
9898     SV* r;                   /* the resulting intersection */
9899     UV* array_r;
9900     UV len_r = 0;
9901
9902     UV i_a = 0;             /* current index into a's array */
9903     UV i_b = 0;
9904     UV i_r = 0;
9905
9906     /* running count of how many of the two inputs are postitioned at ranges
9907      * that are in their sets.  As explained in the algorithm source book,
9908      * items are stopped accumulating and are output when the count changes
9909      * to/from 2.  The count is incremented when we start a range that's in an
9910      * input's set, and decremented when we start a range that's not in a set.
9911      * Only when it is 2 are we in the intersection. */
9912     UV count = 0;
9913
9914     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9915     assert(a != b);
9916     assert(*i == NULL || is_invlist(*i));
9917
9918     /* Special case if either one is empty */
9919     len_a = (a == NULL) ? 0 : _invlist_len(a);
9920     if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9921         if (len_a != 0 && complement_b) {
9922
9923             /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9924              * must be empty.  Here, also we are using 'b's complement, which
9925              * hence must be every possible code point.  Thus the intersection
9926              * is simply 'a'. */
9927
9928             if (*i == a) {  /* No-op */
9929                 return;
9930             }
9931
9932             if (*i == NULL) {
9933                 *i = invlist_clone(a, NULL);
9934                 return;
9935             }
9936
9937             r = invlist_clone(a, NULL);
9938             invlist_replace_list_destroys_src(*i, r);
9939             SvREFCNT_dec_NN(r);
9940             return;
9941         }
9942
9943         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
9944          * intersection must be empty */
9945         if (*i == NULL) {
9946             *i = _new_invlist(0);
9947             return;
9948         }
9949
9950         invlist_clear(*i);
9951         return;
9952     }
9953
9954     /* Here both lists exist and are non-empty */
9955     array_a = invlist_array(a);
9956     array_b = invlist_array(b);
9957
9958     /* If are to take the intersection of 'a' with the complement of b, set it
9959      * up so are looking at b's complement. */
9960     if (complement_b) {
9961
9962         /* To complement, we invert: if the first element is 0, remove it.  To
9963          * do this, we just pretend the array starts one later */
9964         if (array_b[0] == 0) {
9965             array_b++;
9966             len_b--;
9967         }
9968         else {
9969
9970             /* But if the first element is not zero, we pretend the list starts
9971              * at the 0 that is always stored immediately before the array. */
9972             array_b--;
9973             len_b++;
9974         }
9975     }
9976
9977     /* Size the intersection for the worst case: that the intersection ends up
9978      * fragmenting everything to be completely disjoint */
9979     r= _new_invlist(len_a + len_b);
9980
9981     /* Will contain U+0000 iff both components do */
9982     array_r = _invlist_array_init(r,    len_a > 0 && array_a[0] == 0
9983                                      && len_b > 0 && array_b[0] == 0);
9984
9985     /* Go through each list item by item, stopping when have exhausted one of
9986      * them */
9987     while (i_a < len_a && i_b < len_b) {
9988         UV cp;      /* The element to potentially add to the intersection's
9989                        array */
9990         bool cp_in_set; /* Is it in the input list's set or not */
9991
9992         /* We need to take one or the other of the two inputs for the
9993          * intersection.  Since we are merging two sorted lists, we take the
9994          * smaller of the next items.  In case of a tie, we take first the one
9995          * that is not in its set (a difference from the union algorithm).  If
9996          * we first took the one in its set, it would increment the count,
9997          * possibly to 2 which would cause it to be output as starting a range
9998          * in the intersection, and the next time through we would take that
9999          * same number, and output it again as ending the set.  By doing the
10000          * opposite of this, there is no possibility that the count will be
10001          * momentarily incremented to 2.  (In a tie and both are in the set or
10002          * both not in the set, it doesn't matter which we take first.) */
10003         if (       array_a[i_a] < array_b[i_b]
10004             || (   array_a[i_a] == array_b[i_b]
10005                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
10006         {
10007             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
10008             cp = array_a[i_a++];
10009         }
10010         else {
10011             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
10012             cp= array_b[i_b++];
10013         }
10014
10015         /* Here, have chosen which of the two inputs to look at.  Only output
10016          * if the running count changes to/from 2, which marks the
10017          * beginning/end of a range that's in the intersection */
10018         if (cp_in_set) {
10019             count++;
10020             if (count == 2) {
10021                 array_r[i_r++] = cp;
10022             }
10023         }
10024         else {
10025             if (count == 2) {
10026                 array_r[i_r++] = cp;
10027             }
10028             count--;
10029         }
10030
10031     }
10032
10033     /* The loop above increments the index into exactly one of the input lists
10034      * each iteration, and ends when either index gets to its list end.  That
10035      * means the other index is lower than its end, and so something is
10036      * remaining in that one.  We increment 'count', as explained below, if the
10037      * exhausted list was in its set.  (i_a and i_b each currently index the
10038      * element beyond the one we care about.) */
10039     if (   (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
10040         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
10041     {
10042         count++;
10043     }
10044
10045     /* Above we incremented 'count' if the exhausted list was in its set.  This
10046      * has made it so that 'count' being below 2 means there is nothing left to
10047      * output; otheriwse what's left to add to the intersection is precisely
10048      * that which is left in the non-exhausted input list.
10049      *
10050      * To see why, note first that the exhausted input obviously has nothing
10051      * left to affect the intersection.  If it was in its set at its end, that
10052      * means the set extends from here to the platform's infinity, and hence
10053      * anything in the non-exhausted's list will be in the intersection, and
10054      * anything not in it won't be.  Hence, the rest of the intersection is
10055      * precisely what's in the non-exhausted list  The exhausted set also
10056      * contributed 1 to 'count', meaning 'count' was at least 1.  Incrementing
10057      * it means 'count' is now at least 2.  This is consistent with the
10058      * incremented 'count' being >= 2 means to add the non-exhausted list to
10059      * the intersection.
10060      *
10061      * But if the exhausted input wasn't in its set, it contributed 0 to
10062      * 'count', and the intersection can't include anything further; the
10063      * non-exhausted set is irrelevant.  'count' was at most 1, and doesn't get
10064      * incremented.  This is consistent with 'count' being < 2 meaning nothing
10065      * further to add to the intersection. */
10066     if (count < 2) { /* Nothing left to put in the intersection. */
10067         len_r = i_r;
10068     }
10069     else { /* copy the non-exhausted list, unchanged. */
10070         IV copy_count = len_a - i_a;
10071         if (copy_count > 0) {   /* a is the one with stuff left */
10072             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
10073         }
10074         else {  /* b is the one with stuff left */
10075             copy_count = len_b - i_b;
10076             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
10077         }
10078         len_r = i_r + copy_count;
10079     }
10080
10081     /* Set the result to the final length, which can change the pointer to
10082      * array_r, so re-find it.  (Note that it is unlikely that this will
10083      * change, as we are shrinking the space, not enlarging it) */
10084     if (len_r != _invlist_len(r)) {
10085         invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
10086         invlist_trim(r);
10087         array_r = invlist_array(r);
10088     }
10089
10090     if (*i == NULL) { /* Simply return the calculated intersection */
10091         *i = r;
10092     }
10093     else { /* Otherwise, replace the existing inversion list in '*i'.  We could
10094               instead free '*i', and then set it to 'r', but experience has
10095               shown [perl #127392] that if the input is a mortal, we can get a
10096               huge build-up of these during regex compilation before they get
10097               freed. */
10098         if (len_r) {
10099             invlist_replace_list_destroys_src(*i, r);
10100         }
10101         else {
10102             invlist_clear(*i);
10103         }
10104         SvREFCNT_dec_NN(r);
10105     }
10106
10107     return;
10108 }
10109
10110 SV*
10111 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
10112 {
10113     /* Add the range from 'start' to 'end' inclusive to the inversion list's
10114      * set.  A pointer to the inversion list is returned.  This may actually be
10115      * a new list, in which case the passed in one has been destroyed.  The
10116      * passed-in inversion list can be NULL, in which case a new one is created
10117      * with just the one range in it.  The new list is not necessarily
10118      * NUL-terminated.  Space is not freed if the inversion list shrinks as a
10119      * result of this function.  The gain would not be large, and in many
10120      * cases, this is called multiple times on a single inversion list, so
10121      * anything freed may almost immediately be needed again.
10122      *
10123      * This used to mostly call the 'union' routine, but that is much more
10124      * heavyweight than really needed for a single range addition */
10125
10126     UV* array;              /* The array implementing the inversion list */
10127     UV len;                 /* How many elements in 'array' */
10128     SSize_t i_s;            /* index into the invlist array where 'start'
10129                                should go */
10130     SSize_t i_e = 0;        /* And the index where 'end' should go */
10131     UV cur_highest;         /* The highest code point in the inversion list
10132                                upon entry to this function */
10133
10134     /* This range becomes the whole inversion list if none already existed */
10135     if (invlist == NULL) {
10136         invlist = _new_invlist(2);
10137         _append_range_to_invlist(invlist, start, end);
10138         return invlist;
10139     }
10140
10141     /* Likewise, if the inversion list is currently empty */
10142     len = _invlist_len(invlist);
10143     if (len == 0) {
10144         _append_range_to_invlist(invlist, start, end);
10145         return invlist;
10146     }
10147
10148     /* Starting here, we have to know the internals of the list */
10149     array = invlist_array(invlist);
10150
10151     /* If the new range ends higher than the current highest ... */
10152     cur_highest = invlist_highest(invlist);
10153     if (end > cur_highest) {
10154
10155         /* If the whole range is higher, we can just append it */
10156         if (start > cur_highest) {
10157             _append_range_to_invlist(invlist, start, end);
10158             return invlist;
10159         }
10160
10161         /* Otherwise, add the portion that is higher ... */
10162         _append_range_to_invlist(invlist, cur_highest + 1, end);
10163
10164         /* ... and continue on below to handle the rest.  As a result of the
10165          * above append, we know that the index of the end of the range is the
10166          * final even numbered one of the array.  Recall that the final element
10167          * always starts a range that extends to infinity.  If that range is in
10168          * the set (meaning the set goes from here to infinity), it will be an
10169          * even index, but if it isn't in the set, it's odd, and the final
10170          * range in the set is one less, which is even. */
10171         if (end == UV_MAX) {
10172             i_e = len;
10173         }
10174         else {
10175             i_e = len - 2;
10176         }
10177     }
10178
10179     /* We have dealt with appending, now see about prepending.  If the new
10180      * range starts lower than the current lowest ... */
10181     if (start < array[0]) {
10182
10183         /* Adding something which has 0 in it is somewhat tricky, and uncommon.
10184          * Let the union code handle it, rather than having to know the
10185          * trickiness in two code places.  */
10186         if (UNLIKELY(start == 0)) {
10187             SV* range_invlist;
10188
10189             range_invlist = _new_invlist(2);
10190             _append_range_to_invlist(range_invlist, start, end);
10191
10192             _invlist_union(invlist, range_invlist, &invlist);
10193
10194             SvREFCNT_dec_NN(range_invlist);
10195
10196             return invlist;
10197         }
10198
10199         /* If the whole new range comes before the first entry, and doesn't
10200          * extend it, we have to insert it as an additional range */
10201         if (end < array[0] - 1) {
10202             i_s = i_e = -1;
10203             goto splice_in_new_range;
10204         }
10205
10206         /* Here the new range adjoins the existing first range, extending it
10207          * downwards. */
10208         array[0] = start;
10209
10210         /* And continue on below to handle the rest.  We know that the index of
10211          * the beginning of the range is the first one of the array */
10212         i_s = 0;
10213     }
10214     else { /* Not prepending any part of the new range to the existing list.
10215             * Find where in the list it should go.  This finds i_s, such that:
10216             *     invlist[i_s] <= start < array[i_s+1]
10217             */
10218         i_s = _invlist_search(invlist, start);
10219     }
10220
10221     /* At this point, any extending before the beginning of the inversion list
10222      * and/or after the end has been done.  This has made it so that, in the
10223      * code below, each endpoint of the new range is either in a range that is
10224      * in the set, or is in a gap between two ranges that are.  This means we
10225      * don't have to worry about exceeding the array bounds.
10226      *
10227      * Find where in the list the new range ends (but we can skip this if we
10228      * have already determined what it is, or if it will be the same as i_s,
10229      * which we already have computed) */
10230     if (i_e == 0) {
10231         i_e = (start == end)
10232               ? i_s
10233               : _invlist_search(invlist, end);
10234     }
10235
10236     /* Here generally invlist[i_e] <= end < array[i_e+1].  But if invlist[i_e]
10237      * is a range that goes to infinity there is no element at invlist[i_e+1],
10238      * so only the first relation holds. */
10239
10240     if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10241
10242         /* Here, the ranges on either side of the beginning of the new range
10243          * are in the set, and this range starts in the gap between them.
10244          *
10245          * The new range extends the range above it downwards if the new range
10246          * ends at or above that range's start */
10247         const bool extends_the_range_above = (   end == UV_MAX
10248                                               || end + 1 >= array[i_s+1]);
10249
10250         /* The new range extends the range below it upwards if it begins just
10251          * after where that range ends */
10252         if (start == array[i_s]) {
10253
10254             /* If the new range fills the entire gap between the other ranges,
10255              * they will get merged together.  Other ranges may also get
10256              * merged, depending on how many of them the new range spans.  In
10257              * the general case, we do the merge later, just once, after we
10258              * figure out how many to merge.  But in the case where the new
10259              * range exactly spans just this one gap (possibly extending into
10260              * the one above), we do the merge here, and an early exit.  This
10261              * is done here to avoid having to special case later. */
10262             if (i_e - i_s <= 1) {
10263
10264                 /* If i_e - i_s == 1, it means that the new range terminates
10265                  * within the range above, and hence 'extends_the_range_above'
10266                  * must be true.  (If the range above it extends to infinity,
10267                  * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
10268                  * will be 0, so no harm done.) */
10269                 if (extends_the_range_above) {
10270                     Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
10271                     invlist_set_len(invlist,
10272                                     len - 2,
10273                                     *(get_invlist_offset_addr(invlist)));
10274                     return invlist;
10275                 }
10276
10277                 /* Here, i_e must == i_s.  We keep them in sync, as they apply
10278                  * to the same range, and below we are about to decrement i_s
10279                  * */
10280                 i_e--;
10281             }
10282
10283             /* Here, the new range is adjacent to the one below.  (It may also
10284              * span beyond the range above, but that will get resolved later.)
10285              * Extend the range below to include this one. */
10286             array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
10287             i_s--;
10288             start = array[i_s];
10289         }
10290         else if (extends_the_range_above) {
10291
10292             /* Here the new range only extends the range above it, but not the
10293              * one below.  It merges with the one above.  Again, we keep i_e
10294              * and i_s in sync if they point to the same range */
10295             if (i_e == i_s) {
10296                 i_e++;
10297             }
10298             i_s++;
10299             array[i_s] = start;
10300         }
10301     }
10302
10303     /* Here, we've dealt with the new range start extending any adjoining
10304      * existing ranges.
10305      *
10306      * If the new range extends to infinity, it is now the final one,
10307      * regardless of what was there before */
10308     if (UNLIKELY(end == UV_MAX)) {
10309         invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10310         return invlist;
10311     }
10312
10313     /* If i_e started as == i_s, it has also been dealt with,
10314      * and been updated to the new i_s, which will fail the following if */
10315     if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10316
10317         /* Here, the ranges on either side of the end of the new range are in
10318          * the set, and this range ends in the gap between them.
10319          *
10320          * If this range is adjacent to (hence extends) the range above it, it
10321          * becomes part of that range; likewise if it extends the range below,
10322          * it becomes part of that range */
10323         if (end + 1 == array[i_e+1]) {
10324             i_e++;
10325             array[i_e] = start;
10326         }
10327         else if (start <= array[i_e]) {
10328             array[i_e] = end + 1;
10329             i_e--;
10330         }
10331     }
10332
10333     if (i_s == i_e) {
10334
10335         /* If the range fits entirely in an existing range (as possibly already
10336          * extended above), it doesn't add anything new */
10337         if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10338             return invlist;
10339         }
10340
10341         /* Here, no part of the range is in the list.  Must add it.  It will
10342          * occupy 2 more slots */
10343       splice_in_new_range:
10344
10345         invlist_extend(invlist, len + 2);
10346         array = invlist_array(invlist);
10347         /* Move the rest of the array down two slots. Don't include any
10348          * trailing NUL */
10349         Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10350
10351         /* Do the actual splice */
10352         array[i_e+1] = start;
10353         array[i_e+2] = end + 1;
10354         invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10355         return invlist;
10356     }
10357
10358     /* Here the new range crossed the boundaries of a pre-existing range.  The
10359      * code above has adjusted things so that both ends are in ranges that are
10360      * in the set.  This means everything in between must also be in the set.
10361      * Just squash things together */
10362     Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10363     invlist_set_len(invlist,
10364                     len - i_e + i_s,
10365                     *(get_invlist_offset_addr(invlist)));
10366
10367     return invlist;
10368 }
10369
10370 SV*
10371 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10372                                  UV** other_elements_ptr)
10373 {
10374     /* Create and return an inversion list whose contents are to be populated
10375      * by the caller.  The caller gives the number of elements (in 'size') and
10376      * the very first element ('element0').  This function will set
10377      * '*other_elements_ptr' to an array of UVs, where the remaining elements
10378      * are to be placed.
10379      *
10380      * Obviously there is some trust involved that the caller will properly
10381      * fill in the other elements of the array.
10382      *
10383      * (The first element needs to be passed in, as the underlying code does
10384      * things differently depending on whether it is zero or non-zero) */
10385
10386     SV* invlist = _new_invlist(size);
10387     bool offset;
10388
10389     PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10390
10391     invlist = add_cp_to_invlist(invlist, element0);
10392     offset = *get_invlist_offset_addr(invlist);
10393
10394     invlist_set_len(invlist, size, offset);
10395     *other_elements_ptr = invlist_array(invlist) + 1;
10396     return invlist;
10397 }
10398
10399 #endif
10400
10401 #ifndef PERL_IN_XSUB_RE
10402 void
10403 Perl__invlist_invert(pTHX_ SV* const invlist)
10404 {
10405     /* Complement the input inversion list.  This adds a 0 if the list didn't
10406      * have a zero; removes it otherwise.  As described above, the data
10407      * structure is set up so that this is very efficient */
10408
10409     PERL_ARGS_ASSERT__INVLIST_INVERT;
10410
10411     assert(! invlist_is_iterating(invlist));
10412
10413     /* The inverse of matching nothing is matching everything */
10414     if (_invlist_len(invlist) == 0) {
10415         _append_range_to_invlist(invlist, 0, UV_MAX);
10416         return;
10417     }
10418
10419     *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10420 }
10421
10422 SV*
10423 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10424 {
10425     /* Return a new inversion list that is a copy of the input one, which is
10426      * unchanged.  The new list will not be mortal even if the old one was. */
10427
10428     const STRLEN nominal_length = _invlist_len(invlist);
10429     const STRLEN physical_length = SvCUR(invlist);
10430     const bool offset = *(get_invlist_offset_addr(invlist));
10431
10432     PERL_ARGS_ASSERT_INVLIST_CLONE;
10433
10434     if (new_invlist == NULL) {
10435         new_invlist = _new_invlist(nominal_length);
10436     }
10437     else {
10438         sv_upgrade(new_invlist, SVt_INVLIST);
10439         initialize_invlist_guts(new_invlist, nominal_length);
10440     }
10441
10442     *(get_invlist_offset_addr(new_invlist)) = offset;
10443     invlist_set_len(new_invlist, nominal_length, offset);
10444     Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10445
10446     return new_invlist;
10447 }
10448
10449 #endif
10450
10451 PERL_STATIC_INLINE UV
10452 S_invlist_lowest(SV* const invlist)
10453 {
10454     /* Returns the lowest code point that matches an inversion list.  This API
10455      * has an ambiguity, as it returns 0 under either the lowest is actually
10456      * 0, or if the list is empty.  If this distinction matters to you, check
10457      * for emptiness before calling this function */
10458
10459     UV len = _invlist_len(invlist);
10460     UV *array;
10461
10462     PERL_ARGS_ASSERT_INVLIST_LOWEST;
10463
10464     if (len == 0) {
10465         return 0;
10466     }
10467
10468     array = invlist_array(invlist);
10469
10470     return array[0];
10471 }
10472
10473 STATIC SV *
10474 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10475 {
10476     /* Get the contents of an inversion list into a string SV so that they can
10477      * be printed out.  If 'traditional_style' is TRUE, it uses the format
10478      * traditionally done for debug tracing; otherwise it uses a format
10479      * suitable for just copying to the output, with blanks between ranges and
10480      * a dash between range components */
10481
10482     UV start, end;
10483     SV* output;
10484     const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10485     const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10486
10487     if (traditional_style) {
10488         output = newSVpvs("\n");
10489     }
10490     else {
10491         output = newSVpvs("");
10492     }
10493
10494     PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10495
10496     assert(! invlist_is_iterating(invlist));
10497
10498     invlist_iterinit(invlist);
10499     while (invlist_iternext(invlist, &start, &end)) {
10500         if (end == UV_MAX) {
10501             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
10502                                           start, intra_range_delimiter,
10503                                                  inter_range_delimiter);
10504         }
10505         else if (end != start) {
10506             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10507                                           start,
10508                                                    intra_range_delimiter,
10509                                                   end, inter_range_delimiter);
10510         }
10511         else {
10512             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10513                                           start, inter_range_delimiter);
10514         }
10515     }
10516
10517     if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10518         SvCUR_set(output, SvCUR(output) - 1);
10519     }
10520
10521     return output;
10522 }
10523
10524 #ifndef PERL_IN_XSUB_RE
10525 void
10526 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10527                          const char * const indent, SV* const invlist)
10528 {
10529     /* Designed to be called only by do_sv_dump().  Dumps out the ranges of the
10530      * inversion list 'invlist' to 'file' at 'level'  Each line is prefixed by
10531      * the string 'indent'.  The output looks like this:
10532          [0] 0x000A .. 0x000D
10533          [2] 0x0085
10534          [4] 0x2028 .. 0x2029
10535          [6] 0x3104 .. INFTY
10536      * This means that the first range of code points matched by the list are
10537      * 0xA through 0xD; the second range contains only the single code point
10538      * 0x85, etc.  An inversion list is an array of UVs.  Two array elements
10539      * are used to define each range (except if the final range extends to
10540      * infinity, only a single element is needed).  The array index of the
10541      * first element for the corresponding range is given in brackets. */
10542
10543     UV start, end;
10544     STRLEN count = 0;
10545
10546     PERL_ARGS_ASSERT__INVLIST_DUMP;
10547
10548     if (invlist_is_iterating(invlist)) {
10549         Perl_dump_indent(aTHX_ level, file,
10550              "%sCan't dump inversion list because is in middle of iterating\n",
10551              indent);
10552         return;
10553     }
10554
10555     invlist_iterinit(invlist);
10556     while (invlist_iternext(invlist, &start, &end)) {
10557         if (end == UV_MAX) {
10558             Perl_dump_indent(aTHX_ level, file,
10559                                        "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
10560                                    indent, (UV)count, start);
10561         }
10562         else if (end != start) {
10563             Perl_dump_indent(aTHX_ level, file,
10564                                     "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10565                                 indent, (UV)count, start,         end);
10566         }
10567         else {
10568             Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10569                                             indent, (UV)count, start);
10570         }
10571         count += 2;
10572     }
10573 }
10574
10575 #endif
10576
10577 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10578 bool
10579 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10580 {
10581     /* Return a boolean as to if the two passed in inversion lists are
10582      * identical.  The final argument, if TRUE, says to take the complement of
10583      * the second inversion list before doing the comparison */
10584
10585     const UV len_a = _invlist_len(a);
10586     UV len_b = _invlist_len(b);
10587
10588     const UV* array_a = NULL;
10589     const UV* array_b = NULL;
10590
10591     PERL_ARGS_ASSERT__INVLISTEQ;
10592
10593     /* This code avoids accessing the arrays unless it knows the length is
10594      * non-zero */
10595
10596     if (len_a == 0) {
10597         if (len_b == 0) {
10598             return ! complement_b;
10599         }
10600     }
10601     else {
10602         array_a = invlist_array(a);
10603     }
10604
10605     if (len_b != 0) {
10606         array_b = invlist_array(b);
10607     }
10608
10609     /* If are to compare 'a' with the complement of b, set it
10610      * up so are looking at b's complement. */
10611     if (complement_b) {
10612
10613         /* The complement of nothing is everything, so <a> would have to have
10614          * just one element, starting at zero (ending at infinity) */
10615         if (len_b == 0) {
10616             return (len_a == 1 && array_a[0] == 0);
10617         }
10618         if (array_b[0] == 0) {
10619
10620             /* Otherwise, to complement, we invert.  Here, the first element is
10621              * 0, just remove it.  To do this, we just pretend the array starts
10622              * one later */
10623
10624             array_b++;
10625             len_b--;
10626         }
10627         else {
10628
10629             /* But if the first element is not zero, we pretend the list starts
10630              * at the 0 that is always stored immediately before the array. */
10631             array_b--;
10632             len_b++;
10633         }
10634     }
10635
10636     return    len_a == len_b
10637            && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10638
10639 }
10640 #endif
10641
10642 /*
10643  * As best we can, determine the characters that can match the start of
10644  * the given EXACTF-ish node.  This is for use in creating ssc nodes, so there
10645  * can be false positive matches
10646  *
10647  * Returns the invlist as a new SV*; it is the caller's responsibility to
10648  * call SvREFCNT_dec() when done with it.
10649  */
10650 STATIC SV*
10651 S_make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10652 {
10653     const U8 * s = (U8*)STRING(node);
10654     SSize_t bytelen = STR_LEN(node);
10655     UV uc;
10656     /* Start out big enough for 2 separate code points */
10657     SV* invlist = _new_invlist(4);
10658
10659     PERL_ARGS_ASSERT_MAKE_EXACTF_INVLIST;
10660
10661     if (! UTF) {
10662         uc = *s;
10663
10664         /* We punt and assume can match anything if the node begins
10665          * with a multi-character fold.  Things are complicated.  For
10666          * example, /ffi/i could match any of:
10667          *  "\N{LATIN SMALL LIGATURE FFI}"
10668          *  "\N{LATIN SMALL LIGATURE FF}I"
10669          *  "F\N{LATIN SMALL LIGATURE FI}"
10670          *  plus several other things; and making sure we have all the
10671          *  possibilities is hard. */
10672         if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10673             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10674         }
10675         else {
10676             /* Any Latin1 range character can potentially match any
10677              * other depending on the locale, and in Turkic locales, U+130 and
10678              * U+131 */
10679             if (OP(node) == EXACTFL) {
10680                 _invlist_union(invlist, PL_Latin1, &invlist);
10681                 invlist = add_cp_to_invlist(invlist,
10682                                                 LATIN_SMALL_LETTER_DOTLESS_I);
10683                 invlist = add_cp_to_invlist(invlist,
10684                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10685             }
10686             else {
10687                 /* But otherwise, it matches at least itself.  We can
10688                  * quickly tell if it has a distinct fold, and if so,
10689                  * it matches that as well */
10690                 invlist = add_cp_to_invlist(invlist, uc);
10691                 if (IS_IN_SOME_FOLD_L1(uc))
10692                     invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10693             }
10694
10695             /* Some characters match above-Latin1 ones under /i.  This
10696              * is true of EXACTFL ones when the locale is UTF-8 */
10697             if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10698                 && (! isASCII(uc) || ! inRANGE(OP(node), EXACTFAA,
10699                                                          EXACTFAA_NO_TRIE)))
10700             {
10701                 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10702             }
10703         }
10704     }
10705     else {  /* Pattern is UTF-8 */
10706         U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10707         const U8* e = s + bytelen;
10708         IV fc;
10709
10710         fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10711
10712         /* The only code points that aren't folded in a UTF EXACTFish
10713          * node are the problematic ones in EXACTFL nodes */
10714         if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10715             /* We need to check for the possibility that this EXACTFL
10716              * node begins with a multi-char fold.  Therefore we fold
10717              * the first few characters of it so that we can make that
10718              * check */
10719             U8 *d = folded;
10720             int i;
10721
10722             fc = -1;
10723             for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10724                 if (isASCII(*s)) {
10725                     *(d++) = (U8) toFOLD(*s);
10726                     if (fc < 0) {       /* Save the first fold */
10727                         fc = *(d-1);
10728                     }
10729                     s++;
10730                 }
10731                 else {
10732                     STRLEN len;
10733                     UV fold = toFOLD_utf8_safe(s, e, d, &len);
10734                     if (fc < 0) {       /* Save the first fold */
10735                         fc = fold;
10736                     }
10737                     d += len;
10738                     s += UTF8SKIP(s);
10739                 }
10740             }
10741
10742             /* And set up so the code below that looks in this folded
10743              * buffer instead of the node's string */
10744             e = d;
10745             s = folded;
10746         }
10747
10748         /* When we reach here 's' points to the fold of the first
10749          * character(s) of the node; and 'e' points to far enough along
10750          * the folded string to be just past any possible multi-char
10751          * fold.
10752          *
10753          * Like the non-UTF case above, we punt if the node begins with a
10754          * multi-char fold  */
10755
10756         if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10757             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10758         }
10759         else {  /* Single char fold */
10760             unsigned int k;
10761             U32 first_fold;
10762             const U32 * remaining_folds;
10763             Size_t folds_count;
10764
10765             /* It matches itself */
10766             invlist = add_cp_to_invlist(invlist, fc);
10767
10768             /* ... plus all the things that fold to it, which are found in
10769              * PL_utf8_foldclosures */
10770             folds_count = _inverse_folds(fc, &first_fold,
10771                                                 &remaining_folds);
10772             for (k = 0; k < folds_count; k++) {
10773                 UV c = (k == 0) ? first_fold : remaining_folds[k-1];
10774
10775                 /* /aa doesn't allow folds between ASCII and non- */
10776                 if (   inRANGE(OP(node), EXACTFAA, EXACTFAA_NO_TRIE)
10777                     && isASCII(c) != isASCII(fc))
10778                 {
10779                     continue;
10780                 }
10781
10782                 invlist = add_cp_to_invlist(invlist, c);
10783             }
10784
10785             if (OP(node) == EXACTFL) {
10786
10787                 /* If either [iI] are present in an EXACTFL node the above code
10788                  * should have added its normal case pair, but under a Turkish
10789                  * locale they could match instead the case pairs from it.  Add
10790                  * those as potential matches as well */
10791                 if (isALPHA_FOLD_EQ(fc, 'I')) {
10792                     invlist = add_cp_to_invlist(invlist,
10793                                                 LATIN_SMALL_LETTER_DOTLESS_I);
10794                     invlist = add_cp_to_invlist(invlist,
10795                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10796                 }
10797                 else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
10798                     invlist = add_cp_to_invlist(invlist, 'I');
10799                 }
10800                 else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10801                     invlist = add_cp_to_invlist(invlist, 'i');
10802                 }
10803             }
10804         }
10805     }
10806
10807     return invlist;
10808 }
10809
10810 #undef HEADER_LENGTH
10811 #undef TO_INTERNAL_SIZE
10812 #undef FROM_INTERNAL_SIZE
10813 #undef INVLIST_VERSION_ID
10814
10815 /* End of inversion list object */
10816
10817 STATIC void
10818 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10819 {
10820     /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10821      * constructs, and updates RExC_flags with them.  On input, RExC_parse
10822      * should point to the first flag; it is updated on output to point to the
10823      * final ')' or ':'.  There needs to be at least one flag, or this will
10824      * abort */
10825
10826     /* for (?g), (?gc), and (?o) warnings; warning
10827        about (?c) will warn about (?g) -- japhy    */
10828
10829 #define WASTED_O  0x01
10830 #define WASTED_G  0x02
10831 #define WASTED_C  0x04
10832 #define WASTED_GC (WASTED_G|WASTED_C)
10833     I32 wastedflags = 0x00;
10834     U32 posflags = 0, negflags = 0;
10835     U32 *flagsp = &posflags;
10836     char has_charset_modifier = '\0';
10837     regex_charset cs;
10838     bool has_use_defaults = FALSE;
10839     const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10840     int x_mod_count = 0;
10841
10842     PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10843
10844     /* '^' as an initial flag sets certain defaults */
10845     if (UCHARAT(RExC_parse) == '^') {
10846         RExC_parse++;
10847         has_use_defaults = TRUE;
10848         STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10849         cs = (toUSE_UNI_CHARSET_NOT_DEPENDS)
10850              ? REGEX_UNICODE_CHARSET
10851              : REGEX_DEPENDS_CHARSET;
10852         set_regex_charset(&RExC_flags, cs);
10853     }
10854     else {
10855         cs = get_regex_charset(RExC_flags);
10856         if (   cs == REGEX_DEPENDS_CHARSET
10857             && (toUSE_UNI_CHARSET_NOT_DEPENDS))
10858         {
10859             cs = REGEX_UNICODE_CHARSET;
10860         }
10861     }
10862
10863     while (RExC_parse < RExC_end) {
10864         /* && memCHRs("iogcmsx", *RExC_parse) */
10865         /* (?g), (?gc) and (?o) are useless here
10866            and must be globally applied -- japhy */
10867         if ((RExC_pm_flags & PMf_WILDCARD)) {
10868             if (flagsp == & negflags) {
10869                 if (*RExC_parse == 'm') {
10870                     RExC_parse++;
10871                     /* diag_listed_as: Use of %s is not allowed in Unicode
10872                        property wildcard subpatterns in regex; marked by <--
10873                        HERE in m/%s/ */
10874                     vFAIL("Use of modifier '-m' is not allowed in Unicode"
10875                           " property wildcard subpatterns");
10876                 }
10877             }
10878             else {
10879                 if (*RExC_parse == 's') {
10880                     goto modifier_illegal_in_wildcard;
10881                 }
10882             }
10883         }
10884
10885         switch (*RExC_parse) {
10886
10887             /* Code for the imsxn flags */
10888             CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10889
10890             case LOCALE_PAT_MOD:
10891                 if (has_charset_modifier) {
10892                     goto excess_modifier;
10893                 }
10894                 else if (flagsp == &negflags) {
10895                     goto neg_modifier;
10896                 }
10897                 cs = REGEX_LOCALE_CHARSET;
10898                 has_charset_modifier = LOCALE_PAT_MOD;
10899                 break;
10900             case UNICODE_PAT_MOD:
10901                 if (has_charset_modifier) {
10902                     goto excess_modifier;
10903                 }
10904                 else if (flagsp == &negflags) {
10905                     goto neg_modifier;
10906                 }
10907                 cs = REGEX_UNICODE_CHARSET;
10908                 has_charset_modifier = UNICODE_PAT_MOD;
10909                 break;
10910             case ASCII_RESTRICT_PAT_MOD:
10911                 if (flagsp == &negflags) {
10912                     goto neg_modifier;
10913                 }
10914                 if (has_charset_modifier) {
10915                     if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10916                         goto excess_modifier;
10917                     }
10918                     /* Doubled modifier implies more restricted */
10919                     cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10920                 }
10921                 else {
10922                     cs = REGEX_ASCII_RESTRICTED_CHARSET;
10923                 }
10924                 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10925                 break;
10926             case DEPENDS_PAT_MOD:
10927                 if (has_use_defaults) {
10928                     goto fail_modifiers;
10929                 }
10930                 else if (flagsp == &negflags) {
10931                     goto neg_modifier;
10932                 }
10933                 else if (has_charset_modifier) {
10934                     goto excess_modifier;
10935                 }
10936
10937                 /* The dual charset means unicode semantics if the
10938                  * pattern (or target, not known until runtime) are
10939                  * utf8, or something in the pattern indicates unicode
10940                  * semantics */
10941                 cs = (toUSE_UNI_CHARSET_NOT_DEPENDS)
10942                      ? REGEX_UNICODE_CHARSET
10943                      : REGEX_DEPENDS_CHARSET;
10944                 has_charset_modifier = DEPENDS_PAT_MOD;
10945                 break;
10946               excess_modifier:
10947                 RExC_parse++;
10948                 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10949                     vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10950                 }
10951                 else if (has_charset_modifier == *(RExC_parse - 1)) {
10952                     vFAIL2("Regexp modifier \"%c\" may not appear twice",
10953                                         *(RExC_parse - 1));
10954                 }
10955                 else {
10956                     vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10957                 }
10958                 NOT_REACHED; /*NOTREACHED*/
10959               neg_modifier:
10960                 RExC_parse++;
10961                 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10962                                     *(RExC_parse - 1));
10963                 NOT_REACHED; /*NOTREACHED*/
10964             case GLOBAL_PAT_MOD: /* 'g' */
10965                 if (RExC_pm_flags & PMf_WILDCARD) {
10966                     goto modifier_illegal_in_wildcard;
10967                 }
10968                 /*FALLTHROUGH*/
10969             case ONCE_PAT_MOD: /* 'o' */
10970                 if (ckWARN(WARN_REGEXP)) {
10971                     const I32 wflagbit = *RExC_parse == 'o'
10972                                          ? WASTED_O
10973                                          : WASTED_G;
10974                     if (! (wastedflags & wflagbit) ) {
10975                         wastedflags |= wflagbit;
10976                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10977                         vWARN5(
10978                             RExC_parse + 1,
10979                             "Useless (%s%c) - %suse /%c modifier",
10980                             flagsp == &negflags ? "?-" : "?",
10981                             *RExC_parse,
10982                             flagsp == &negflags ? "don't " : "",
10983                             *RExC_parse
10984                         );
10985                     }
10986                 }
10987                 break;
10988
10989             case CONTINUE_PAT_MOD: /* 'c' */
10990                 if (RExC_pm_flags & PMf_WILDCARD) {
10991                     goto modifier_illegal_in_wildcard;
10992                 }
10993                 if (ckWARN(WARN_REGEXP)) {
10994                     if (! (wastedflags & WASTED_C) ) {
10995                         wastedflags |= WASTED_GC;
10996                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10997                         vWARN3(
10998                             RExC_parse + 1,
10999                             "Useless (%sc) - %suse /gc modifier",
11000                             flagsp == &negflags ? "?-" : "?",
11001                             flagsp == &negflags ? "don't " : ""
11002                         );
11003                     }
11004                 }
11005                 break;
11006             case KEEPCOPY_PAT_MOD: /* 'p' */
11007                 if (RExC_pm_flags & PMf_WILDCARD) {
11008                     goto modifier_illegal_in_wildcard;
11009                 }
11010                 if (flagsp == &negflags) {
11011                     ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
11012                 } else {
11013                     *flagsp |= RXf_PMf_KEEPCOPY;
11014                 }
11015                 break;
11016             case '-':
11017                 /* A flag is a default iff it is following a minus, so
11018                  * if there is a minus, it means will be trying to
11019                  * re-specify a default which is an error */
11020                 if (has_use_defaults || flagsp == &negflags) {
11021                     goto fail_modifiers;
11022                 }
11023                 flagsp = &negflags;
11024                 wastedflags = 0;  /* reset so (?g-c) warns twice */
11025                 x_mod_count = 0;
11026                 break;
11027             case ':':
11028             case ')':
11029
11030                 if (  (RExC_pm_flags & PMf_WILDCARD)
11031                     && cs != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
11032                 {
11033                     RExC_parse++;
11034                     /* diag_listed_as: Use of %s is not allowed in Unicode
11035                        property wildcard subpatterns in regex; marked by <--
11036                        HERE in m/%s/ */
11037                     vFAIL2("Use of modifier '%c' is not allowed in Unicode"
11038                            " property wildcard subpatterns",
11039                            has_charset_modifier);
11040                 }
11041
11042                 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
11043                     negflags |= RXf_PMf_EXTENDED_MORE;
11044                 }
11045                 RExC_flags |= posflags;
11046
11047                 if (negflags & RXf_PMf_EXTENDED) {
11048                     negflags |= RXf_PMf_EXTENDED_MORE;
11049                 }
11050                 RExC_flags &= ~negflags;
11051                 set_regex_charset(&RExC_flags, cs);
11052
11053                 return;
11054             default:
11055               fail_modifiers:
11056                 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11057                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11058                 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
11059                       UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11060                 NOT_REACHED; /*NOTREACHED*/
11061         }
11062
11063         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11064     }
11065
11066     vFAIL("Sequence (?... not terminated");
11067
11068   modifier_illegal_in_wildcard:
11069     RExC_parse++;
11070     /* diag_listed_as: Use of %s is not allowed in Unicode property wildcard
11071        subpatterns in regex; marked by <-- HERE in m/%s/ */
11072     vFAIL2("Use of modifier '%c' is not allowed in Unicode property wildcard"
11073            " subpatterns", *(RExC_parse - 1));
11074 }
11075
11076 /*
11077  - reg - regular expression, i.e. main body or parenthesized thing
11078  *
11079  * Caller must absorb opening parenthesis.
11080  *
11081  * Combining parenthesis handling with the base level of regular expression
11082  * is a trifle forced, but the need to tie the tails of the branches to what
11083  * follows makes it hard to avoid.
11084  */
11085 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
11086 #ifdef DEBUGGING
11087 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
11088 #else
11089 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
11090 #endif
11091
11092 STATIC regnode_offset
11093 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
11094                              I32 *flagp,
11095                              char * parse_start,
11096                              char ch
11097                       )
11098 {
11099     regnode_offset ret;
11100     char* name_start = RExC_parse;
11101     U32 num = 0;
11102     SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11103     DECLARE_AND_GET_RE_DEBUG_FLAGS;
11104
11105     PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
11106
11107     if (RExC_parse != name_start && ch == '}') {
11108         while (isBLANK(*RExC_parse)) {
11109             RExC_parse++;
11110         }
11111     }
11112     if (RExC_parse == name_start || *RExC_parse != ch) {
11113         /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
11114         vFAIL2("Sequence %.3s... not terminated", parse_start);
11115     }
11116
11117     if (sv_dat) {
11118         num = add_data( pRExC_state, STR_WITH_LEN("S"));
11119         RExC_rxi->data->data[num]=(void*)sv_dat;
11120         SvREFCNT_inc_simple_void_NN(sv_dat);
11121     }
11122     RExC_sawback = 1;
11123     ret = reganode(pRExC_state,
11124                    ((! FOLD)
11125                      ? REFN
11126                      : (ASCII_FOLD_RESTRICTED)
11127                        ? REFFAN
11128                        : (AT_LEAST_UNI_SEMANTICS)
11129                          ? REFFUN
11130                          : (LOC)
11131                            ? REFFLN
11132                            : REFFN),
11133                     num);
11134     *flagp |= HASWIDTH;
11135
11136     Set_Node_Offset(REGNODE_p(ret), parse_start+1);
11137     Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
11138
11139     nextchar(pRExC_state);
11140     return ret;
11141 }
11142
11143 /* On success, returns the offset at which any next node should be placed into
11144  * the regex engine program being compiled.
11145  *
11146  * Returns 0 otherwise, with *flagp set to indicate why:
11147  *  TRYAGAIN        at the end of (?) that only sets flags.
11148  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
11149  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
11150  *  Otherwise would only return 0 if regbranch() returns 0, which cannot
11151  *  happen.  */
11152 STATIC regnode_offset
11153 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
11154     /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
11155      * 2 is like 1, but indicates that nextchar() has been called to advance
11156      * RExC_parse beyond the '('.  Things like '(?' are indivisible tokens, and
11157      * this flag alerts us to the need to check for that */
11158 {
11159     regnode_offset ret = 0;    /* Will be the head of the group. */
11160     regnode_offset br;
11161     regnode_offset lastbr;
11162     regnode_offset ender = 0;
11163     I32 parno = 0;
11164     I32 flags;
11165     U32 oregflags = RExC_flags;
11166     bool have_branch = 0;
11167     bool is_open = 0;
11168     I32 freeze_paren = 0;
11169     I32 after_freeze = 0;
11170     I32 num; /* numeric backreferences */
11171     SV * max_open;  /* Max number of unclosed parens */
11172     I32 was_in_lookaround = RExC_in_lookaround;
11173
11174     char * parse_start = RExC_parse; /* MJD */
11175     char * const oregcomp_parse = RExC_parse;
11176
11177     DECLARE_AND_GET_RE_DEBUG_FLAGS;
11178
11179     PERL_ARGS_ASSERT_REG;
11180     DEBUG_PARSE("reg ");
11181
11182     max_open = get_sv(RE_COMPILE_RECURSION_LIMIT, GV_ADD);
11183     assert(max_open);
11184     if (!SvIOK(max_open)) {
11185         sv_setiv(max_open, RE_COMPILE_RECURSION_INIT);
11186     }
11187     if (depth > 4 * (UV) SvIV(max_open)) { /* We increase depth by 4 for each
11188                                               open paren */
11189         vFAIL("Too many nested open parens");
11190     }
11191
11192     *flagp = 0;                         /* Initialize. */
11193
11194     /* Having this true makes it feasible to have a lot fewer tests for the
11195      * parse pointer being in scope.  For example, we can write
11196      *      while(isFOO(*RExC_parse)) RExC_parse++;
11197      * instead of
11198      *      while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
11199      */
11200     assert(*RExC_end == '\0');
11201
11202     /* Make an OPEN node, if parenthesized. */
11203     if (paren) {
11204
11205         /* Under /x, space and comments can be gobbled up between the '(' and
11206          * here (if paren ==2).  The forms '(*VERB' and '(?...' disallow such
11207          * intervening space, as the sequence is a token, and a token should be
11208          * indivisible */
11209         bool has_intervening_patws = (paren == 2)
11210                                   && *(RExC_parse - 1) != '(';
11211
11212         if (RExC_parse >= RExC_end) {
11213             vFAIL("Unmatched (");
11214         }
11215
11216         if (paren == 'r') {     /* Atomic script run */
11217             paren = '>';
11218             goto parse_rest;
11219         }
11220         else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
11221             char *start_verb = RExC_parse + 1;
11222             STRLEN verb_len;
11223             char *start_arg = NULL;
11224             unsigned char op = 0;
11225             int arg_required = 0;
11226             int internal_argval = -1; /* if >-1 we are not allowed an argument*/
11227             bool has_upper = FALSE;
11228
11229             if (has_intervening_patws) {
11230                 RExC_parse++;   /* past the '*' */
11231
11232                 /* For strict backwards compatibility, don't change the message
11233                  * now that we also have lowercase operands */
11234                 if (isUPPER(*RExC_parse)) {
11235                     vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
11236                 }
11237                 else {
11238                     vFAIL("In '(*...)', the '(' and '*' must be adjacent");
11239                 }
11240             }
11241             while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
11242                 if ( *RExC_parse == ':' ) {
11243                     start_arg = RExC_parse + 1;
11244                     break;
11245                 }
11246                 else if (! UTF) {
11247                     if (isUPPER(*RExC_parse)) {
11248                         has_upper = TRUE;
11249                     }
11250                     RExC_parse++;
11251                 }
11252                 else {
11253                     RExC_parse += UTF8SKIP(RExC_parse);
11254                 }
11255             }
11256             verb_len = RExC_parse - start_verb;
11257             if ( start_arg ) {
11258                 if (RExC_parse >= RExC_end) {
11259                     goto unterminated_verb_pattern;
11260                 }
11261
11262                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11263                 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
11264                     RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11265                 }
11266                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11267                   unterminated_verb_pattern:
11268                     if (has_upper) {
11269                         vFAIL("Unterminated verb pattern argument");
11270                     }
11271                     else {
11272                         vFAIL("Unterminated '(*...' argument");
11273                     }
11274                 }
11275             } else {
11276                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11277                     if (has_upper) {
11278                         vFAIL("Unterminated verb pattern");
11279                     }
11280                     else {
11281                         vFAIL("Unterminated '(*...' construct");
11282                     }
11283                 }
11284             }
11285
11286             /* Here, we know that RExC_parse < RExC_end */
11287
11288             switch ( *start_verb ) {
11289             case 'A':  /* (*ACCEPT) */
11290                 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
11291                     op = ACCEPT;
11292                     internal_argval = RExC_nestroot;
11293                 }
11294                 break;
11295             case 'C':  /* (*COMMIT) */
11296                 if ( memEQs(start_verb, verb_len,"COMMIT") )
11297                     op = COMMIT;
11298                 break;
11299             case 'F':  /* (*FAIL) */
11300                 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
11301                     op = OPFAIL;
11302                 }
11303                 break;
11304             case ':':  /* (*:NAME) */
11305             case 'M':  /* (*MARK:NAME) */
11306                 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
11307                     op = MARKPOINT;
11308                     arg_required = 1;
11309                 }
11310                 break;
11311             case 'P':  /* (*PRUNE) */
11312                 if ( memEQs(start_verb, verb_len,"PRUNE") )
11313                     op = PRUNE;
11314                 break;
11315             case 'S':   /* (*SKIP) */
11316                 if ( memEQs(start_verb, verb_len,"SKIP") )
11317                     op = SKIP;
11318                 break;
11319             case 'T':  /* (*THEN) */
11320                 /* [19:06] <TimToady> :: is then */
11321                 if ( memEQs(start_verb, verb_len,"THEN") ) {
11322                     op = CUTGROUP;
11323                     RExC_seen |= REG_CUTGROUP_SEEN;
11324                 }
11325                 break;
11326             case 'a':
11327                 if (   memEQs(start_verb, verb_len, "asr")
11328                     || memEQs(start_verb, verb_len, "atomic_script_run"))
11329                 {
11330                     paren = 'r';        /* Mnemonic: recursed run */
11331                     goto script_run;
11332                 }
11333                 else if (memEQs(start_verb, verb_len, "atomic")) {
11334                     paren = 't';    /* AtOMIC */
11335                     goto alpha_assertions;
11336                 }
11337                 break;
11338             case 'p':
11339                 if (   memEQs(start_verb, verb_len, "plb")
11340                     || memEQs(start_verb, verb_len, "positive_lookbehind"))
11341                 {
11342                     paren = 'b';
11343                     goto lookbehind_alpha_assertions;
11344                 }
11345                 else if (   memEQs(start_verb, verb_len, "pla")
11346                          || memEQs(start_verb, verb_len, "positive_lookahead"))
11347                 {
11348                     paren = 'a';
11349                     goto alpha_assertions;
11350                 }
11351                 break;
11352             case 'n':
11353                 if (   memEQs(start_verb, verb_len, "nlb")
11354                     || memEQs(start_verb, verb_len, "negative_lookbehind"))
11355                 {
11356                     paren = 'B';
11357                     goto lookbehind_alpha_assertions;
11358                 }
11359                 else if (   memEQs(start_verb, verb_len, "nla")
11360                          || memEQs(start_verb, verb_len, "negative_lookahead"))
11361                 {
11362                     paren = 'A';
11363                     goto alpha_assertions;
11364                 }
11365                 break;
11366             case 's':
11367                 if (   memEQs(start_verb, verb_len, "sr")
11368                     || memEQs(start_verb, verb_len, "script_run"))
11369                 {
11370                     regnode_offset atomic;
11371
11372                     paren = 's';
11373
11374                    script_run:
11375
11376                     /* This indicates Unicode rules. */
11377                     REQUIRE_UNI_RULES(flagp, 0);
11378
11379                     if (! start_arg) {
11380                         goto no_colon;
11381                     }
11382
11383                     RExC_parse = start_arg;
11384
11385                     if (RExC_in_script_run) {
11386
11387                         /*  Nested script runs are treated as no-ops, because
11388                          *  if the nested one fails, the outer one must as
11389                          *  well.  It could fail sooner, and avoid (??{} with
11390                          *  side effects, but that is explicitly documented as
11391                          *  undefined behavior. */
11392
11393                         ret = 0;
11394
11395                         if (paren == 's') {
11396                             paren = ':';
11397                             goto parse_rest;
11398                         }
11399
11400                         /* But, the atomic part of a nested atomic script run
11401                          * isn't a no-op, but can be treated just like a '(?>'
11402                          * */
11403                         paren = '>';
11404                         goto parse_rest;
11405                     }
11406
11407                     if (paren == 's') {
11408                         /* Here, we're starting a new regular script run */
11409                         ret = reg_node(pRExC_state, SROPEN);
11410                         RExC_in_script_run = 1;
11411                         is_open = 1;
11412                         goto parse_rest;
11413                     }
11414
11415                     /* Here, we are starting an atomic script run.  This is
11416                      * handled by recursing to deal with the atomic portion
11417                      * separately, enclosed in SROPEN ... SRCLOSE nodes */
11418
11419                     ret = reg_node(pRExC_state, SROPEN);
11420
11421                     RExC_in_script_run = 1;
11422
11423                     atomic = reg(pRExC_state, 'r', &flags, depth);
11424                     if (flags & (RESTART_PARSE|NEED_UTF8)) {
11425                         *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11426                         return 0;
11427                     }
11428
11429                     if (! REGTAIL(pRExC_state, ret, atomic)) {
11430                         REQUIRE_BRANCHJ(flagp, 0);
11431                     }
11432
11433                     if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state,
11434                                                                 SRCLOSE)))
11435                     {
11436                         REQUIRE_BRANCHJ(flagp, 0);
11437                     }
11438
11439                     RExC_in_script_run = 0;
11440                     return ret;
11441                 }
11442
11443                 break;
11444
11445             lookbehind_alpha_assertions:
11446                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11447                 /*FALLTHROUGH*/
11448
11449             alpha_assertions:
11450
11451                 RExC_in_lookaround++;
11452                 RExC_seen_zerolen++;
11453
11454                 if (! start_arg) {
11455                     goto no_colon;
11456                 }
11457
11458                 /* An empty negative lookahead assertion simply is failure */
11459                 if (paren == 'A' && RExC_parse == start_arg) {
11460                     ret=reganode(pRExC_state, OPFAIL, 0);
11461                     nextchar(pRExC_state);
11462                     return ret;
11463                 }
11464
11465                 RExC_parse = start_arg;
11466                 goto parse_rest;
11467
11468               no_colon:
11469                 vFAIL2utf8f(
11470                 "'(*%" UTF8f "' requires a terminating ':'",
11471                 UTF8fARG(UTF, verb_len, start_verb));
11472                 NOT_REACHED; /*NOTREACHED*/
11473
11474             } /* End of switch */
11475             if ( ! op ) {
11476                 RExC_parse += UTF
11477                               ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11478                               : 1;
11479                 if (has_upper || verb_len == 0) {
11480                     vFAIL2utf8f(
11481                     "Unknown verb pattern '%" UTF8f "'",
11482                     UTF8fARG(UTF, verb_len, start_verb));
11483                 }
11484                 else {
11485                     vFAIL2utf8f(
11486                     "Unknown '(*...)' construct '%" UTF8f "'",
11487                     UTF8fARG(UTF, verb_len, start_verb));
11488                 }
11489             }
11490             if ( RExC_parse == start_arg ) {
11491                 start_arg = NULL;
11492             }
11493             if ( arg_required && !start_arg ) {
11494                 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11495                     (int) verb_len, start_verb);
11496             }
11497             if (internal_argval == -1) {
11498                 ret = reganode(pRExC_state, op, 0);
11499             } else {
11500                 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11501             }
11502             RExC_seen |= REG_VERBARG_SEEN;
11503             if (start_arg) {
11504                 SV *sv = newSVpvn( start_arg,
11505                                     RExC_parse - start_arg);
11506                 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11507                                         STR_WITH_LEN("S"));
11508                 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11509                 FLAGS(REGNODE_p(ret)) = 1;
11510             } else {
11511                 FLAGS(REGNODE_p(ret)) = 0;
11512             }
11513             if ( internal_argval != -1 )
11514                 ARG2L_SET(REGNODE_p(ret), internal_argval);
11515             nextchar(pRExC_state);
11516             return ret;
11517         }
11518         else if (*RExC_parse == '?') { /* (?...) */
11519             bool is_logical = 0;
11520             const char * const seqstart = RExC_parse;
11521             const char * endptr;
11522             const char non_existent_group_msg[]
11523                                             = "Reference to nonexistent group";
11524             const char impossible_group[] = "Invalid reference to group";
11525
11526             if (has_intervening_patws) {
11527                 RExC_parse++;
11528                 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11529             }
11530
11531             RExC_parse++;           /* past the '?' */
11532             paren = *RExC_parse;    /* might be a trailing NUL, if not
11533                                        well-formed */
11534             RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11535             if (RExC_parse > RExC_end) {
11536                 paren = '\0';
11537             }
11538             ret = 0;                    /* For look-ahead/behind. */
11539             switch (paren) {
11540
11541             case 'P':   /* (?P...) variants for those used to PCRE/Python */
11542                 paren = *RExC_parse;
11543                 if ( paren == '<') {    /* (?P<...>) named capture */
11544                     RExC_parse++;
11545                     if (RExC_parse >= RExC_end) {
11546                         vFAIL("Sequence (?P<... not terminated");
11547                     }
11548                     goto named_capture;
11549                 }
11550                 else if (paren == '>') {   /* (?P>name) named recursion */
11551                     RExC_parse++;
11552                     if (RExC_parse >= RExC_end) {
11553                         vFAIL("Sequence (?P>... not terminated");
11554                     }
11555                     goto named_recursion;
11556                 }
11557                 else if (paren == '=') {   /* (?P=...)  named backref */
11558                     RExC_parse++;
11559                     return handle_named_backref(pRExC_state, flagp,
11560                                                 parse_start, ')');
11561                 }
11562                 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11563                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11564                 vFAIL3("Sequence (%.*s...) not recognized",
11565                                 (int) (RExC_parse - seqstart), seqstart);
11566                 NOT_REACHED; /*NOTREACHED*/
11567             case '<':           /* (?<...) */
11568                 /* If you want to support (?<*...), first reconcile with GH #17363 */
11569                 if (*RExC_parse == '!')
11570                     paren = ',';
11571                 else if (*RExC_parse != '=')
11572               named_capture:
11573                 {               /* (?<...>) */
11574                     char *name_start;
11575                     SV *svname;
11576                     paren= '>';
11577                 /* FALLTHROUGH */
11578             case '\'':          /* (?'...') */
11579                     name_start = RExC_parse;
11580                     svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11581                     if (   RExC_parse == name_start
11582                         || RExC_parse >= RExC_end
11583                         || *RExC_parse != paren)
11584                     {
11585                         vFAIL2("Sequence (?%c... not terminated",
11586                             paren=='>' ? '<' : (char) paren);
11587                     }
11588                     {
11589                         HE *he_str;
11590                         SV *sv_dat = NULL;
11591                         if (!svname) /* shouldn't happen */
11592                             Perl_croak(aTHX_
11593                                 "panic: reg_scan_name returned NULL");
11594                         if (!RExC_paren_names) {
11595                             RExC_paren_names= newHV();
11596                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
11597 #ifdef DEBUGGING
11598                             RExC_paren_name_list= newAV();
11599                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11600 #endif
11601                         }
11602                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11603                         if ( he_str )
11604                             sv_dat = HeVAL(he_str);
11605                         if ( ! sv_dat ) {
11606                             /* croak baby croak */
11607                             Perl_croak(aTHX_
11608                                 "panic: paren_name hash element allocation failed");
11609                         } else if ( SvPOK(sv_dat) ) {
11610                             /* (?|...) can mean we have dupes so scan to check
11611                                its already been stored. Maybe a flag indicating
11612                                we are inside such a construct would be useful,
11613                                but the arrays are likely to be quite small, so
11614                                for now we punt -- dmq */
11615                             IV count = SvIV(sv_dat);
11616                             I32 *pv = (I32*)SvPVX(sv_dat);
11617                             IV i;
11618                             for ( i = 0 ; i < count ; i++ ) {
11619                                 if ( pv[i] == RExC_npar ) {
11620                                     count = 0;
11621                                     break;
11622                                 }
11623                             }
11624                             if ( count ) {
11625                                 pv = (I32*)SvGROW(sv_dat,
11626                                                 SvCUR(sv_dat) + sizeof(I32)+1);
11627                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11628                                 pv[count] = RExC_npar;
11629                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11630                             }
11631                         } else {
11632                             (void)SvUPGRADE(sv_dat, SVt_PVNV);
11633                             sv_setpvn(sv_dat, (char *)&(RExC_npar),
11634                                                                 sizeof(I32));
11635                             SvIOK_on(sv_dat);
11636                             SvIV_set(sv_dat, 1);
11637                         }
11638 #ifdef DEBUGGING
11639                         /* Yes this does cause a memory leak in debugging Perls
11640                          * */
11641                         if (!av_store(RExC_paren_name_list,
11642                                       RExC_npar, SvREFCNT_inc_NN(svname)))
11643                             SvREFCNT_dec_NN(svname);
11644 #endif
11645
11646                         /*sv_dump(sv_dat);*/
11647                     }
11648                     nextchar(pRExC_state);
11649                     paren = 1;
11650                     goto capturing_parens;
11651                 }
11652
11653                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11654                 RExC_in_lookaround++;
11655                 RExC_parse++;
11656                 if (RExC_parse >= RExC_end) {
11657                     vFAIL("Sequence (?... not terminated");
11658                 }
11659                 RExC_seen_zerolen++;
11660                 break;
11661             case '=':           /* (?=...) */
11662                 RExC_seen_zerolen++;
11663                 RExC_in_lookaround++;
11664                 break;
11665             case '!':           /* (?!...) */
11666                 RExC_seen_zerolen++;
11667                 /* check if we're really just a "FAIL" assertion */
11668                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11669                                         FALSE /* Don't force to /x */ );
11670                 if (*RExC_parse == ')') {
11671                     ret=reganode(pRExC_state, OPFAIL, 0);
11672                     nextchar(pRExC_state);
11673                     return ret;
11674                 }
11675                 RExC_in_lookaround++;
11676                 break;
11677             case '|':           /* (?|...) */
11678                 /* branch reset, behave like a (?:...) except that
11679                    buffers in alternations share the same numbers */
11680                 paren = ':';
11681                 after_freeze = freeze_paren = RExC_npar;
11682
11683                 /* XXX This construct currently requires an extra pass.
11684                  * Investigation would be required to see if that could be
11685                  * changed */
11686                 REQUIRE_PARENS_PASS;
11687                 break;
11688             case ':':           /* (?:...) */
11689             case '>':           /* (?>...) */
11690                 break;
11691             case '$':           /* (?$...) */
11692             case '@':           /* (?@...) */
11693                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11694                 break;
11695             case '0' :           /* (?0) */
11696             case 'R' :           /* (?R) */
11697                 if (RExC_parse == RExC_end || *RExC_parse != ')')
11698                     FAIL("Sequence (?R) not terminated");
11699                 num = 0;
11700                 RExC_seen |= REG_RECURSE_SEEN;
11701
11702                 /* XXX These constructs currently require an extra pass.
11703                  * It probably could be changed */
11704                 REQUIRE_PARENS_PASS;
11705
11706                 *flagp |= POSTPONED;
11707                 goto gen_recurse_regop;
11708                 /*notreached*/
11709             /* named and numeric backreferences */
11710             case '&':            /* (?&NAME) */
11711                 parse_start = RExC_parse - 1;
11712               named_recursion:
11713                 {
11714                     SV *sv_dat = reg_scan_name(pRExC_state,
11715                                                REG_RSN_RETURN_DATA);
11716                    num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11717                 }
11718                 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11719                     vFAIL("Sequence (?&... not terminated");
11720                 goto gen_recurse_regop;
11721                 /* NOTREACHED */
11722             case '+':
11723                 if (! inRANGE(RExC_parse[0], '1', '9')) {
11724                     RExC_parse++;
11725                     vFAIL("Illegal pattern");
11726                 }
11727                 goto parse_recursion;
11728                 /* NOTREACHED*/
11729             case '-': /* (?-1) */
11730                 if (! inRANGE(RExC_parse[0], '1', '9')) {
11731                     RExC_parse--; /* rewind to let it be handled later */
11732                     goto parse_flags;
11733                 }
11734                 /* FALLTHROUGH */
11735             case '1': case '2': case '3': case '4': /* (?1) */
11736             case '5': case '6': case '7': case '8': case '9':
11737                 RExC_parse = (char *) seqstart + 1;  /* Point to the digit */
11738               parse_recursion:
11739                 {
11740                     bool is_neg = FALSE;
11741                     UV unum;
11742                     parse_start = RExC_parse - 1; /* MJD */
11743                     if (*RExC_parse == '-') {
11744                         RExC_parse++;
11745                         is_neg = TRUE;
11746                     }
11747                     endptr = RExC_end;
11748                     if (grok_atoUV(RExC_parse, &unum, &endptr)
11749                         && unum <= I32_MAX
11750                     ) {
11751                         num = (I32)unum;
11752                         RExC_parse = (char*)endptr;
11753                     }
11754                     else {  /* Overflow, or something like that.  Position
11755                                beyond all digits for the message */
11756                         while (RExC_parse < RExC_end && isDIGIT(*RExC_parse))  {
11757                             RExC_parse++;
11758                         }
11759                         vFAIL(impossible_group);
11760                     }
11761                     if (is_neg) {
11762                         /* -num is always representable on 1 and 2's complement
11763                          * machines */
11764                         num = -num;
11765                     }
11766                 }
11767                 if (*RExC_parse!=')')
11768                     vFAIL("Expecting close bracket");
11769
11770               gen_recurse_regop:
11771                 if (paren == '-' || paren == '+') {
11772
11773                     /* Don't overflow */
11774                     if (UNLIKELY(I32_MAX - RExC_npar < num)) {
11775                         RExC_parse++;
11776                         vFAIL(impossible_group);
11777                     }
11778
11779                     /*
11780                     Diagram of capture buffer numbering.
11781                     Top line is the normal capture buffer numbers
11782                     Bottom line is the negative indexing as from
11783                     the X (the (?-2))
11784
11785                         1 2    3 4 5 X   Y      6 7
11786                        /(a(x)y)(a(b(c(?+2)d)e)f)(g(h))/
11787                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11788                     -   5 4    3 2 1 X   Y      x x
11789
11790                     Resolve to absolute group.  Recall that RExC_npar is +1 of
11791                     the actual parenthesis group number.  For lookahead, we
11792                     have to compensate for that.  Using the above example, when
11793                     we get to Y in the parse, num is 2 and RExC_npar is 6.  We
11794                     want 7 for +2, and 4 for -2.
11795                     */
11796                     if ( paren == '+' ) {
11797                         num--;
11798                     }
11799
11800                     num += RExC_npar;
11801
11802                     if (paren == '-' && num < 1) {
11803                         RExC_parse++;
11804                         vFAIL(non_existent_group_msg);
11805                     }
11806                 }
11807
11808                 if (num >= RExC_npar) {
11809
11810                     /* It might be a forward reference; we can't fail until we
11811                      * know, by completing the parse to get all the groups, and
11812                      * then reparsing */
11813                     if (ALL_PARENS_COUNTED)  {
11814                         if (num >= RExC_total_parens) {
11815                             RExC_parse++;
11816                             vFAIL(non_existent_group_msg);
11817                         }
11818                     }
11819                     else {
11820                         REQUIRE_PARENS_PASS;
11821                     }
11822                 }
11823
11824                 /* We keep track how many GOSUB items we have produced.
11825                    To start off the ARG2L() of the GOSUB holds its "id",
11826                    which is used later in conjunction with RExC_recurse
11827                    to calculate the offset we need to jump for the GOSUB,
11828                    which it will store in the final representation.
11829                    We have to defer the actual calculation until much later
11830                    as the regop may move.
11831                  */
11832                 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11833                 RExC_recurse_count++;
11834                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11835                     "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11836                             22, "|    |", (int)(depth * 2 + 1), "",
11837                             (UV)ARG(REGNODE_p(ret)),
11838                             (IV)ARG2L(REGNODE_p(ret))));
11839                 RExC_seen |= REG_RECURSE_SEEN;
11840
11841                 Set_Node_Length(REGNODE_p(ret),
11842                                 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11843                 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11844
11845                 *flagp |= POSTPONED;
11846                 assert(*RExC_parse == ')');
11847                 nextchar(pRExC_state);
11848                 return ret;
11849
11850             /* NOTREACHED */
11851
11852             case '?':           /* (??...) */
11853                 is_logical = 1;
11854                 if (*RExC_parse != '{') {
11855                     RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11856                     /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11857                     vFAIL2utf8f(
11858                         "Sequence (%" UTF8f "...) not recognized",
11859                         UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11860                     NOT_REACHED; /*NOTREACHED*/
11861                 }
11862                 *flagp |= POSTPONED;
11863                 paren = '{';
11864                 RExC_parse++;
11865                 /* FALLTHROUGH */
11866             case '{':           /* (?{...}) */
11867             {
11868                 U32 n = 0;
11869                 struct reg_code_block *cb;
11870                 OP * o;
11871
11872                 RExC_seen_zerolen++;
11873
11874                 if (   !pRExC_state->code_blocks
11875                     || pRExC_state->code_index
11876                                         >= pRExC_state->code_blocks->count
11877                     || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11878                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11879                             - RExC_start)
11880                 ) {
11881                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
11882                         FAIL("panic: Sequence (?{...}): no code block found\n");
11883                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
11884                 }
11885                 /* this is a pre-compiled code block (?{...}) */
11886                 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11887                 RExC_parse = RExC_start + cb->end;
11888                 o = cb->block;
11889                 if (cb->src_regex) {
11890                     n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11891                     RExC_rxi->data->data[n] =
11892                         (void*)SvREFCNT_inc((SV*)cb->src_regex);
11893                     RExC_rxi->data->data[n+1] = (void*)o;
11894                 }
11895                 else {
11896                     n = add_data(pRExC_state,
11897                             (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11898                     RExC_rxi->data->data[n] = (void*)o;
11899                 }
11900                 pRExC_state->code_index++;
11901                 nextchar(pRExC_state);
11902
11903                 if (is_logical) {
11904                     regnode_offset eval;
11905                     ret = reg_node(pRExC_state, LOGICAL);
11906
11907                     eval = reg2Lanode(pRExC_state, EVAL,
11908                                        n,
11909
11910                                        /* for later propagation into (??{})
11911                                         * return value */
11912                                        RExC_flags & RXf_PMf_COMPILETIME
11913                                       );
11914                     FLAGS(REGNODE_p(ret)) = 2;
11915                     if (! REGTAIL(pRExC_state, ret, eval)) {
11916                         REQUIRE_BRANCHJ(flagp, 0);
11917                     }
11918                     /* deal with the length of this later - MJD */
11919                     return ret;
11920                 }
11921                 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11922                 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11923                 Set_Node_Offset(REGNODE_p(ret), parse_start);
11924                 return ret;
11925             }
11926             case '(':           /* (?(?{...})...) and (?(?=...)...) */
11927             {
11928                 int is_define= 0;
11929                 const int DEFINE_len = sizeof("DEFINE") - 1;
11930                 if (    RExC_parse < RExC_end - 1
11931                     && (   (       RExC_parse[0] == '?'        /* (?(?...)) */
11932                             && (   RExC_parse[1] == '='
11933                                 || RExC_parse[1] == '!'
11934                                 || RExC_parse[1] == '<'
11935                                 || RExC_parse[1] == '{'))
11936                         || (       RExC_parse[0] == '*'        /* (?(*...)) */
11937                             && (   memBEGINs(RExC_parse + 1,
11938                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11939                                          "pla:")
11940                                 || memBEGINs(RExC_parse + 1,
11941                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11942                                          "plb:")
11943                                 || memBEGINs(RExC_parse + 1,
11944                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11945                                          "nla:")
11946                                 || memBEGINs(RExC_parse + 1,
11947                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11948                                          "nlb:")
11949                                 || memBEGINs(RExC_parse + 1,
11950                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11951                                          "positive_lookahead:")
11952                                 || memBEGINs(RExC_parse + 1,
11953                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11954                                          "positive_lookbehind:")
11955                                 || memBEGINs(RExC_parse + 1,
11956                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11957                                          "negative_lookahead:")
11958                                 || memBEGINs(RExC_parse + 1,
11959                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11960                                          "negative_lookbehind:"))))
11961                 ) { /* Lookahead or eval. */
11962                     I32 flag;
11963                     regnode_offset tail;
11964
11965                     ret = reg_node(pRExC_state, LOGICAL);
11966                     FLAGS(REGNODE_p(ret)) = 1;
11967
11968                     tail = reg(pRExC_state, 1, &flag, depth+1);
11969                     RETURN_FAIL_ON_RESTART(flag, flagp);
11970                     if (! REGTAIL(pRExC_state, ret, tail)) {
11971                         REQUIRE_BRANCHJ(flagp, 0);
11972                     }
11973                     goto insert_if;
11974                 }
11975                 else if (   RExC_parse[0] == '<'     /* (?(<NAME>)...) */
11976                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11977                 {
11978                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
11979                     char *name_start= RExC_parse++;
11980                     U32 num = 0;
11981                     SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11982                     if (   RExC_parse == name_start
11983                         || RExC_parse >= RExC_end
11984                         || *RExC_parse != ch)
11985                     {
11986                         vFAIL2("Sequence (?(%c... not terminated",
11987                             (ch == '>' ? '<' : ch));
11988                     }
11989                     RExC_parse++;
11990                     if (sv_dat) {
11991                         num = add_data( pRExC_state, STR_WITH_LEN("S"));
11992                         RExC_rxi->data->data[num]=(void*)sv_dat;
11993                         SvREFCNT_inc_simple_void_NN(sv_dat);
11994                     }
11995                     ret = reganode(pRExC_state, GROUPPN, num);
11996                     goto insert_if_check_paren;
11997                 }
11998                 else if (memBEGINs(RExC_parse,
11999                                    (STRLEN) (RExC_end - RExC_parse),
12000                                    "DEFINE"))
12001                 {
12002                     ret = reganode(pRExC_state, DEFINEP, 0);
12003                     RExC_parse += DEFINE_len;
12004                     is_define = 1;
12005                     goto insert_if_check_paren;
12006                 }
12007                 else if (RExC_parse[0] == 'R') {
12008                     RExC_parse++;
12009                     /* parno == 0 => /(?(R)YES|NO)/  "in any form of recursion OR eval"
12010                      * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
12011                      * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
12012                      */
12013                     parno = 0;
12014                     if (RExC_parse[0] == '0') {
12015                         parno = 1;
12016                         RExC_parse++;
12017                     }
12018                     else if (inRANGE(RExC_parse[0], '1', '9')) {
12019                         UV uv;
12020                         endptr = RExC_end;
12021                         if (grok_atoUV(RExC_parse, &uv, &endptr)
12022                             && uv <= I32_MAX
12023                         ) {
12024                             parno = (I32)uv + 1;
12025                             RExC_parse = (char*)endptr;
12026                         }
12027                         /* else "Switch condition not recognized" below */
12028                     } else if (RExC_parse[0] == '&') {
12029                         SV *sv_dat;
12030                         RExC_parse++;
12031                         sv_dat = reg_scan_name(pRExC_state,
12032                                                REG_RSN_RETURN_DATA);
12033                         if (sv_dat)
12034                             parno = 1 + *((I32 *)SvPVX(sv_dat));
12035                     }
12036                     ret = reganode(pRExC_state, INSUBP, parno);
12037                     goto insert_if_check_paren;
12038                 }
12039                 else if (inRANGE(RExC_parse[0], '1', '9')) {
12040                     /* (?(1)...) */
12041                     char c;
12042                     UV uv;
12043                     endptr = RExC_end;
12044                     if (grok_atoUV(RExC_parse, &uv, &endptr)
12045                         && uv <= I32_MAX
12046                     ) {
12047                         parno = (I32)uv;
12048                         RExC_parse = (char*)endptr;
12049                     }
12050                     else {
12051                         vFAIL("panic: grok_atoUV returned FALSE");
12052                     }
12053                     ret = reganode(pRExC_state, GROUPP, parno);
12054
12055                  insert_if_check_paren:
12056                     if (UCHARAT(RExC_parse) != ')') {
12057                         RExC_parse += UTF
12058                                       ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
12059                                       : 1;
12060                         vFAIL("Switch condition not recognized");
12061                     }
12062                     nextchar(pRExC_state);
12063                   insert_if:
12064                     if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state,
12065                                                              IFTHEN, 0)))
12066                     {
12067                         REQUIRE_BRANCHJ(flagp, 0);
12068                     }
12069                     br = regbranch(pRExC_state, &flags, 1, depth+1);
12070                     if (br == 0) {
12071                         RETURN_FAIL_ON_RESTART(flags,flagp);
12072                         FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
12073                               (UV) flags);
12074                     } else
12075                     if (! REGTAIL(pRExC_state, br, reganode(pRExC_state,
12076                                                              LONGJMP, 0)))
12077                     {
12078                         REQUIRE_BRANCHJ(flagp, 0);
12079                     }
12080                     c = UCHARAT(RExC_parse);
12081                     nextchar(pRExC_state);
12082                     if (flags&HASWIDTH)
12083                         *flagp |= HASWIDTH;
12084                     if (c == '|') {
12085                         if (is_define)
12086                             vFAIL("(?(DEFINE)....) does not allow branches");
12087
12088                         /* Fake one for optimizer.  */
12089                         lastbr = reganode(pRExC_state, IFTHEN, 0);
12090
12091                         if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
12092                             RETURN_FAIL_ON_RESTART(flags, flagp);
12093                             FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
12094                                   (UV) flags);
12095                         }
12096                         if (! REGTAIL(pRExC_state, ret, lastbr)) {
12097                             REQUIRE_BRANCHJ(flagp, 0);
12098                         }
12099                         if (flags&HASWIDTH)
12100                             *flagp |= HASWIDTH;
12101                         c = UCHARAT(RExC_parse);
12102                         nextchar(pRExC_state);
12103                     }
12104                     else
12105                         lastbr = 0;
12106                     if (c != ')') {
12107                         if (RExC_parse >= RExC_end)
12108                             vFAIL("Switch (?(condition)... not terminated");
12109                         else
12110                             vFAIL("Switch (?(condition)... contains too many branches");
12111                     }
12112                     ender = reg_node(pRExC_state, TAIL);
12113                     if (! REGTAIL(pRExC_state, br, ender)) {
12114                         REQUIRE_BRANCHJ(flagp, 0);
12115                     }
12116                     if (lastbr) {
12117                         if (! REGTAIL(pRExC_state, lastbr, ender)) {
12118                             REQUIRE_BRANCHJ(flagp, 0);
12119                         }
12120                         if (! REGTAIL(pRExC_state,
12121                                       REGNODE_OFFSET(
12122                                                  NEXTOPER(
12123                                                  NEXTOPER(REGNODE_p(lastbr)))),
12124                                       ender))
12125                         {
12126                             REQUIRE_BRANCHJ(flagp, 0);
12127                         }
12128                     }
12129                     else
12130                         if (! REGTAIL(pRExC_state, ret, ender)) {
12131                             REQUIRE_BRANCHJ(flagp, 0);
12132                         }
12133 #if 0  /* Removing this doesn't cause failures in the test suite -- khw */
12134                     RExC_size++; /* XXX WHY do we need this?!!
12135                                     For large programs it seems to be required
12136                                     but I can't figure out why. -- dmq*/
12137 #endif
12138                     return ret;
12139                 }
12140                 RExC_parse += UTF
12141                               ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
12142                               : 1;
12143                 vFAIL("Unknown switch condition (?(...))");
12144             }
12145             case '[':           /* (?[ ... ]) */
12146                 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
12147                                          oregcomp_parse);
12148             case 0: /* A NUL */
12149                 RExC_parse--; /* for vFAIL to print correctly */
12150                 vFAIL("Sequence (? incomplete");
12151                 break;
12152
12153             case ')':
12154                 if (RExC_strict) {  /* [perl #132851] */
12155                     ckWARNreg(RExC_parse, "Empty (?) without any modifiers");
12156                 }
12157                 /* FALLTHROUGH */
12158             case '*': /* If you want to support (?*...), first reconcile with GH #17363 */
12159             /* FALLTHROUGH */
12160             default: /* e.g., (?i) */
12161                 RExC_parse = (char *) seqstart + 1;
12162               parse_flags:
12163                 parse_lparen_question_flags(pRExC_state);
12164                 if (UCHARAT(RExC_parse) != ':') {
12165                     if (RExC_parse < RExC_end)
12166                         nextchar(pRExC_state);
12167                     *flagp = TRYAGAIN;
12168                     return 0;
12169                 }
12170                 paren = ':';
12171                 nextchar(pRExC_state);
12172                 ret = 0;
12173                 goto parse_rest;
12174             } /* end switch */
12175         }
12176         else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) {   /* (...) */
12177           capturing_parens:
12178             parno = RExC_npar;
12179             RExC_npar++;
12180             if (! ALL_PARENS_COUNTED) {
12181                 /* If we are in our first pass through (and maybe only pass),
12182                  * we  need to allocate memory for the capturing parentheses
12183                  * data structures.
12184                  */
12185
12186                 if (!RExC_parens_buf_size) {
12187                     /* first guess at number of parens we might encounter */
12188                     RExC_parens_buf_size = 10;
12189
12190                     /* setup RExC_open_parens, which holds the address of each
12191                      * OPEN tag, and to make things simpler for the 0 index the
12192                      * start of the program - this is used later for offsets */
12193                     Newxz(RExC_open_parens, RExC_parens_buf_size,
12194                             regnode_offset);
12195                     RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
12196
12197                     /* setup RExC_close_parens, which holds the address of each
12198                      * CLOSE tag, and to make things simpler for the 0 index
12199                      * the end of the program - this is used later for offsets
12200                      * */
12201                     Newxz(RExC_close_parens, RExC_parens_buf_size,
12202                             regnode_offset);
12203                     /* we dont know where end op starts yet, so we dont need to
12204                      * set RExC_close_parens[0] like we do RExC_open_parens[0]
12205                      * above */
12206                 }
12207                 else if (RExC_npar > RExC_parens_buf_size) {
12208                     I32 old_size = RExC_parens_buf_size;
12209
12210                     RExC_parens_buf_size *= 2;
12211
12212                     Renew(RExC_open_parens, RExC_parens_buf_size,
12213                             regnode_offset);
12214                     Zero(RExC_open_parens + old_size,
12215                             RExC_parens_buf_size - old_size, regnode_offset);
12216
12217                     Renew(RExC_close_parens, RExC_parens_buf_size,
12218                             regnode_offset);
12219                     Zero(RExC_close_parens + old_size,
12220                             RExC_parens_buf_size - old_size, regnode_offset);
12221                 }
12222             }
12223
12224             ret = reganode(pRExC_state, OPEN, parno);
12225             if (!RExC_nestroot)
12226                 RExC_nestroot = parno;
12227             if (RExC_open_parens && !RExC_open_parens[parno])
12228             {
12229                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12230                     "%*s%*s Setting open paren #%" IVdf " to %zu\n",
12231                     22, "|    |", (int)(depth * 2 + 1), "",
12232                     (IV)parno, ret));
12233                 RExC_open_parens[parno]= ret;
12234             }
12235
12236             Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
12237             Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
12238             is_open = 1;
12239         } else {
12240             /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
12241             paren = ':';
12242             ret = 0;
12243         }
12244     }
12245     else                        /* ! paren */
12246         ret = 0;
12247
12248    parse_rest:
12249     /* Pick up the branches, linking them together. */
12250     parse_start = RExC_parse;   /* MJD */
12251     br = regbranch(pRExC_state, &flags, 1, depth+1);
12252
12253     /*     branch_len = (paren != 0); */
12254
12255     if (br == 0) {
12256         RETURN_FAIL_ON_RESTART(flags, flagp);
12257         FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12258     }
12259     if (*RExC_parse == '|') {
12260         if (RExC_use_BRANCHJ) {
12261             reginsert(pRExC_state, BRANCHJ, br, depth+1);
12262         }
12263         else {                  /* MJD */
12264             reginsert(pRExC_state, BRANCH, br, depth+1);
12265             Set_Node_Length(REGNODE_p(br), paren != 0);
12266             Set_Node_Offset_To_R(br, parse_start-RExC_start);
12267         }
12268         have_branch = 1;
12269     }
12270     else if (paren == ':') {
12271         *flagp |= flags&SIMPLE;
12272     }
12273     if (is_open) {                              /* Starts with OPEN. */
12274         if (! REGTAIL(pRExC_state, ret, br)) {  /* OPEN -> first. */
12275             REQUIRE_BRANCHJ(flagp, 0);
12276         }
12277     }
12278     else if (paren != '?')              /* Not Conditional */
12279         ret = br;
12280     *flagp |= flags & (HASWIDTH | POSTPONED);
12281     lastbr = br;
12282     while (*RExC_parse == '|') {
12283         if (RExC_use_BRANCHJ) {
12284             bool shut_gcc_up;
12285
12286             ender = reganode(pRExC_state, LONGJMP, 0);
12287
12288             /* Append to the previous. */
12289             shut_gcc_up = REGTAIL(pRExC_state,
12290                          REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
12291                          ender);
12292             PERL_UNUSED_VAR(shut_gcc_up);
12293         }
12294         nextchar(pRExC_state);
12295         if (freeze_paren) {
12296             if (RExC_npar > after_freeze)
12297                 after_freeze = RExC_npar;
12298             RExC_npar = freeze_paren;
12299         }
12300         br = regbranch(pRExC_state, &flags, 0, depth+1);
12301
12302         if (br == 0) {
12303             RETURN_FAIL_ON_RESTART(flags, flagp);
12304             FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12305         }
12306         if (!  REGTAIL(pRExC_state, lastbr, br)) {  /* BRANCH -> BRANCH. */
12307             REQUIRE_BRANCHJ(flagp, 0);
12308         }
12309         lastbr = br;
12310         *flagp |= flags & (HASWIDTH | POSTPONED);
12311     }
12312
12313     if (have_branch || paren != ':') {
12314         regnode * br;
12315
12316         /* Make a closing node, and hook it on the end. */
12317         switch (paren) {
12318         case ':':
12319             ender = reg_node(pRExC_state, TAIL);
12320             break;
12321         case 1: case 2:
12322             ender = reganode(pRExC_state, CLOSE, parno);
12323             if ( RExC_close_parens ) {
12324                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12325                         "%*s%*s Setting close paren #%" IVdf " to %zu\n",
12326                         22, "|    |", (int)(depth * 2 + 1), "",
12327                         (IV)parno, ender));
12328                 RExC_close_parens[parno]= ender;
12329                 if (RExC_nestroot == parno)
12330                     RExC_nestroot = 0;
12331             }
12332             Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
12333             Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
12334             break;
12335         case 's':
12336             ender = reg_node(pRExC_state, SRCLOSE);
12337             RExC_in_script_run = 0;
12338             break;
12339         case '<':
12340         case 'a':
12341         case 'A':
12342         case 'b':
12343         case 'B':
12344         case ',':
12345         case '=':
12346         case '!':
12347             *flagp &= ~HASWIDTH;
12348             /* FALLTHROUGH */
12349         case 't':   /* aTomic */
12350         case '>':
12351             ender = reg_node(pRExC_state, SUCCEED);
12352             break;
12353         case 0:
12354             ender = reg_node(pRExC_state, END);
12355             assert(!RExC_end_op); /* there can only be one! */
12356             RExC_end_op = REGNODE_p(ender);
12357             if (RExC_close_parens) {
12358                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12359                     "%*s%*s Setting close paren #0 (END) to %zu\n",
12360                     22, "|    |", (int)(depth * 2 + 1), "",
12361                     ender));
12362
12363                 RExC_close_parens[0]= ender;
12364             }
12365             break;
12366         }
12367         DEBUG_PARSE_r({
12368             DEBUG_PARSE_MSG("lsbr");
12369             regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
12370             regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
12371             Perl_re_printf( aTHX_  "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12372                           SvPV_nolen_const(RExC_mysv1),
12373                           (IV)lastbr,
12374                           SvPV_nolen_const(RExC_mysv2),
12375                           (IV)ender,
12376                           (IV)(ender - lastbr)
12377             );
12378         });
12379         if (! REGTAIL(pRExC_state, lastbr, ender)) {
12380             REQUIRE_BRANCHJ(flagp, 0);
12381         }
12382
12383         if (have_branch) {
12384             char is_nothing= 1;
12385             if (depth==1)
12386                 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
12387
12388             /* Hook the tails of the branches to the closing node. */
12389             for (br = REGNODE_p(ret); br; br = regnext(br)) {
12390                 const U8 op = PL_regkind[OP(br)];
12391                 if (op == BRANCH) {
12392                     if (! REGTAIL_STUDY(pRExC_state,
12393                                         REGNODE_OFFSET(NEXTOPER(br)),
12394                                         ender))
12395                     {
12396                         REQUIRE_BRANCHJ(flagp, 0);
12397                     }
12398                     if ( OP(NEXTOPER(br)) != NOTHING
12399                          || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12400                         is_nothing= 0;
12401                 }
12402                 else if (op == BRANCHJ) {
12403                     bool shut_gcc_up = REGTAIL_STUDY(pRExC_state,
12404                                         REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12405                                         ender);
12406                     PERL_UNUSED_VAR(shut_gcc_up);
12407                     /* for now we always disable this optimisation * /
12408                     if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12409                          || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12410                     */
12411                         is_nothing= 0;
12412                 }
12413             }
12414             if (is_nothing) {
12415                 regnode * ret_as_regnode = REGNODE_p(ret);
12416                 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12417                                ? regnext(ret_as_regnode)
12418                                : ret_as_regnode;
12419                 DEBUG_PARSE_r({
12420                     DEBUG_PARSE_MSG("NADA");
12421                     regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12422                                      NULL, pRExC_state);
12423                     regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12424                                      NULL, pRExC_state);
12425                     Perl_re_printf( aTHX_  "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12426                                   SvPV_nolen_const(RExC_mysv1),
12427                                   (IV)REG_NODE_NUM(ret_as_regnode),
12428                                   SvPV_nolen_const(RExC_mysv2),
12429                                   (IV)ender,
12430                                   (IV)(ender - ret)
12431                     );
12432                 });
12433                 OP(br)= NOTHING;
12434                 if (OP(REGNODE_p(ender)) == TAIL) {
12435                     NEXT_OFF(br)= 0;
12436                     RExC_emit= REGNODE_OFFSET(br) + 1;
12437                 } else {
12438                     regnode *opt;
12439                     for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12440                         OP(opt)= OPTIMIZED;
12441                     NEXT_OFF(br)= REGNODE_p(ender) - br;
12442                 }
12443             }
12444         }
12445     }
12446
12447     {
12448         const char *p;
12449          /* Even/odd or x=don't care: 010101x10x */
12450         static const char parens[] = "=!aA<,>Bbt";
12451          /* flag below is set to 0 up through 'A'; 1 for larger */
12452
12453         if (paren && (p = strchr(parens, paren))) {
12454             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12455             int flag = (p - parens) > 3;
12456
12457             if (paren == '>' || paren == 't') {
12458                 node = SUSPEND, flag = 0;
12459             }
12460
12461             reginsert(pRExC_state, node, ret, depth+1);
12462             Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12463             Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12464             FLAGS(REGNODE_p(ret)) = flag;
12465             if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL)))
12466             {
12467                 REQUIRE_BRANCHJ(flagp, 0);
12468             }
12469         }
12470     }
12471
12472     /* Check for proper termination. */
12473     if (paren) {
12474         /* restore original flags, but keep (?p) and, if we've encountered
12475          * something in the parse that changes /d rules into /u, keep the /u */
12476         RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12477         if (DEPENDS_SEMANTICS && toUSE_UNI_CHARSET_NOT_DEPENDS) {
12478             set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12479         }
12480         if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12481             RExC_parse = oregcomp_parse;
12482             vFAIL("Unmatched (");
12483         }
12484         nextchar(pRExC_state);
12485     }
12486     else if (!paren && RExC_parse < RExC_end) {
12487         if (*RExC_parse == ')') {
12488             RExC_parse++;
12489             vFAIL("Unmatched )");
12490         }
12491         else
12492             FAIL("Junk on end of regexp");      /* "Can't happen". */
12493         NOT_REACHED; /* NOTREACHED */
12494     }
12495
12496     if (after_freeze > RExC_npar)
12497         RExC_npar = after_freeze;
12498
12499     RExC_in_lookaround = was_in_lookaround;
12500
12501     return(ret);
12502 }
12503
12504 /*
12505  - regbranch - one alternative of an | operator
12506  *
12507  * Implements the concatenation operator.
12508  *
12509  * On success, returns the offset at which any next node should be placed into
12510  * the regex engine program being compiled.
12511  *
12512  * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12513  * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12514  * UTF-8
12515  */
12516 STATIC regnode_offset
12517 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12518 {
12519     regnode_offset ret;
12520     regnode_offset chain = 0;
12521     regnode_offset latest;
12522     I32 flags = 0, c = 0;
12523     DECLARE_AND_GET_RE_DEBUG_FLAGS;
12524
12525     PERL_ARGS_ASSERT_REGBRANCH;
12526
12527     DEBUG_PARSE("brnc");
12528
12529     if (first)
12530         ret = 0;
12531     else {
12532         if (RExC_use_BRANCHJ)
12533             ret = reganode(pRExC_state, BRANCHJ, 0);
12534         else {
12535             ret = reg_node(pRExC_state, BRANCH);
12536             Set_Node_Length(REGNODE_p(ret), 1);
12537         }
12538     }
12539
12540     *flagp = 0;                 /* Initialize. */
12541
12542     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12543                             FALSE /* Don't force to /x */ );
12544     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12545         flags &= ~TRYAGAIN;
12546         latest = regpiece(pRExC_state, &flags, depth+1);
12547         if (latest == 0) {
12548             if (flags & TRYAGAIN)
12549                 continue;
12550             RETURN_FAIL_ON_RESTART(flags, flagp);
12551             FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12552         }
12553         else if (ret == 0)
12554             ret = latest;
12555         *flagp |= flags&(HASWIDTH|POSTPONED);
12556         if (chain != 0) {
12557             /* FIXME adding one for every branch after the first is probably
12558              * excessive now we have TRIE support. (hv) */
12559             MARK_NAUGHTY(1);
12560             if (! REGTAIL(pRExC_state, chain, latest)) {
12561                 /* XXX We could just redo this branch, but figuring out what
12562                  * bookkeeping needs to be reset is a pain, and it's likely
12563                  * that other branches that goto END will also be too large */
12564                 REQUIRE_BRANCHJ(flagp, 0);
12565             }
12566         }
12567         chain = latest;
12568         c++;
12569     }
12570     if (chain == 0) {   /* Loop ran zero times. */
12571         chain = reg_node(pRExC_state, NOTHING);
12572         if (ret == 0)
12573             ret = chain;
12574     }
12575     if (c == 1) {
12576         *flagp |= flags&SIMPLE;
12577     }
12578
12579     return ret;
12580 }
12581
12582 #define RBRACE  0
12583 #define MIN_S   1
12584 #define MIN_E   2
12585 #define MAX_S   3
12586 #define MAX_E   4
12587
12588 #ifndef PERL_IN_XSUB_RE
12589 bool
12590 Perl_regcurly(const char *s, const char *e, const char * result[5])
12591 {
12592     /* This function matches a {m,n} quantifier.  When called with a NULL final
12593      * argument, it simply parses the input from 's' up through 'e-1', and
12594      * returns a boolean as to whether or not this input is syntactically a
12595      * {m,n} quantifier.
12596      *
12597      * When called with a non-NULL final parameter, and when the function
12598      * returns TRUE, it additionally stores information into the array
12599      * specified by that parameter about what it found in the parse.  The
12600      * parameter must be a pointer into a 5 element array of 'const char *'
12601      * elements.  The returned information is as follows:
12602      *   result[RBRACE]  points to the closing brace
12603      *   result[MIN_S]   points to the first byte of the lower bound
12604      *   result[MIN_E]   points to one beyond the final byte of the lower bound
12605      *   result[MAX_S]   points to the first byte of the upper bound
12606      *   result[MAX_E]   points to one beyond the final byte of the upper bound
12607      *
12608      * If the quantifier is of the form {m,} (meaning an infinite upper
12609      * bound), result[MAX_E] is set to result[MAX_S]; what they actually point
12610      * to is irrelevant, just that it's the same place
12611      *
12612      * If instead the quantifier is of the form {m} there is actually only
12613      * one bound, and both the upper and lower result[] elements are set to
12614      * point to it.
12615      *
12616      * This function checks only for syntactic validity; it leaves checking for
12617      * semantic validity and raising any diagnostics to the caller.  This
12618      * function is called in multiple places to check for syntax, but only from
12619      * one for semantics.  It makes it as simple as possible for the
12620      * syntax-only callers, while furnishing just enough information for the
12621      * semantic caller.
12622      */
12623
12624     const char * min_start = NULL;
12625     const char * max_start = NULL;
12626     const char * min_end = NULL;
12627     const char * max_end = NULL;
12628
12629     bool has_comma = FALSE;
12630
12631     PERL_ARGS_ASSERT_REGCURLY;
12632
12633     if (s >= e || *s++ != '{')
12634         return FALSE;
12635
12636     while (s < e && isBLANK(*s)) {
12637         s++;
12638     }
12639
12640     if isDIGIT(*s) {
12641         min_start = s;
12642         do {
12643             s++;
12644         } while (s < e && isDIGIT(*s));
12645         min_end = s;
12646     }
12647
12648     while (s < e && isBLANK(*s)) {
12649         s++;
12650     }
12651
12652     if (*s == ',') {
12653         has_comma = TRUE;
12654         s++;
12655
12656         while (s < e && isBLANK(*s)) {
12657             s++;
12658         }
12659
12660         if isDIGIT(*s) {
12661             max_start = s;
12662             do {
12663                 s++;
12664             } while (s < e && isDIGIT(*s));
12665             max_end = s;
12666         }
12667     }
12668
12669     while (s < e && isBLANK(*s)) {
12670         s++;
12671     }
12672                                /* Need at least one number */
12673     if (s >= e || *s != '}' || (! min_start && ! max_end)) {
12674         return FALSE;
12675     }
12676
12677     if (result) {
12678
12679         result[RBRACE] = s;
12680
12681         result[MIN_S] = min_start;
12682         result[MIN_E] = min_end;
12683         if (has_comma) {
12684             if (max_start) {
12685                 result[MAX_S] = max_start;
12686                 result[MAX_E] = max_end;
12687             }
12688             else {
12689                 /* Having no value after the comma is signalled by setting
12690                  * start and end to the same value.  What that value is isn't
12691                  * relevant; NULL is chosen simply because it will fail if the
12692                  * caller mistakenly uses it */
12693                 result[MAX_S] = result[MAX_E] = NULL;
12694             }
12695         }
12696         else {  /* No comma means lower and upper bounds are the same */
12697             result[MAX_S] = min_start;
12698             result[MAX_E] = min_end;
12699         }
12700     }
12701
12702     return TRUE;
12703 }
12704 #endif
12705
12706 U32
12707 S_get_quantifier_value(pTHX_ RExC_state_t *pRExC_state,
12708                        const char * start, const char * end)
12709 {
12710     /* This is a helper function for regpiece() to compute, given the
12711      * quantifier {m,n}, the value of either m or n, based on the starting
12712      * position 'start' in the string, through the byte 'end-1', returning it
12713      * if valid, and failing appropriately if not.  It knows the restrictions
12714      * imposed on quantifier values */
12715
12716     UV uv;
12717     STATIC_ASSERT_DECL(REG_INFTY <= U32_MAX);
12718
12719     PERL_ARGS_ASSERT_GET_QUANTIFIER_VALUE;
12720
12721     if (grok_atoUV(start, &uv, &end)) {
12722         if (uv < REG_INFTY) {   /* A valid, small-enough number */
12723             return (U32) uv;
12724         }
12725     }
12726     else if (*start == '0') { /* grok_atoUV() fails for only two reasons:
12727                                  leading zeros or overflow */
12728         RExC_parse = (char * ) end;
12729
12730         /* Perhaps too generic a msg for what is only failure from having
12731          * leading zeros, but this is how it's always behaved. */
12732         vFAIL("Invalid quantifier in {,}");
12733         NOT_REACHED; /*NOTREACHED*/
12734     }
12735
12736     /* Here, found a quantifier, but was too large; either it overflowed or was
12737      * too big a legal number */
12738     RExC_parse = (char * ) end;
12739     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12740
12741     NOT_REACHED; /*NOTREACHED*/
12742     return U32_MAX; /* Perhaps some compilers will be expecting a return */
12743 }
12744
12745 /*
12746  - regpiece - something followed by possible quantifier * + ? {n,m}
12747  *
12748  * Note that the branching code sequences used for ? and the general cases
12749  * of * and + are somewhat optimized:  they use the same NOTHING node as
12750  * both the endmarker for their branch list and the body of the last branch.
12751  * It might seem that this node could be dispensed with entirely, but the
12752  * endmarker role is not redundant.
12753  *
12754  * On success, returns the offset at which any next node should be placed into
12755  * the regex engine program being compiled.
12756  *
12757  * Returns 0 otherwise, with *flagp set to indicate why:
12758  *  TRYAGAIN        if regatom() returns 0 with TRYAGAIN.
12759  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
12760  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12761  */
12762 STATIC regnode_offset
12763 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12764 {
12765     regnode_offset ret;
12766     char op;
12767     I32 flags;
12768     const char * const origparse = RExC_parse;
12769     I32 min;
12770     I32 max = REG_INFTY;
12771 #ifdef RE_TRACK_PATTERN_OFFSETS
12772     char *parse_start;
12773 #endif
12774
12775     /* Save the original in case we change the emitted regop to a FAIL. */
12776     const regnode_offset orig_emit = RExC_emit;
12777
12778     DECLARE_AND_GET_RE_DEBUG_FLAGS;
12779
12780     PERL_ARGS_ASSERT_REGPIECE;
12781
12782     DEBUG_PARSE("piec");
12783
12784     ret = regatom(pRExC_state, &flags, depth+1);
12785     if (ret == 0) {
12786         RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12787         FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12788     }
12789
12790 #ifdef RE_TRACK_PATTERN_OFFSETS
12791     parse_start = RExC_parse;
12792 #endif
12793
12794     op = *RExC_parse;
12795     switch (op) {
12796         const char * regcurly_return[5];
12797
12798       case '*':
12799         nextchar(pRExC_state);
12800         min = 0;
12801         break;
12802
12803       case '+':
12804         nextchar(pRExC_state);
12805         min = 1;
12806         break;
12807
12808       case '?':
12809         nextchar(pRExC_state);
12810         min = 0; max = 1;
12811         break;
12812
12813       case '{':  /* A '{' may or may not indicate a quantifier; call regcurly()
12814                     to determine which */
12815         if (regcurly(RExC_parse, RExC_end, regcurly_return)) {
12816             const char * min_start = regcurly_return[MIN_S];
12817             const char * min_end   = regcurly_return[MIN_E];
12818             const char * max_start = regcurly_return[MAX_S];
12819             const char * max_end   = regcurly_return[MAX_E];
12820
12821             if (min_start) {
12822                 min = get_quantifier_value(pRExC_state, min_start, min_end);
12823             }
12824             else {
12825                 min = 0;
12826             }
12827
12828             if (max_start == max_end) {     /* Was of the form {m,} */
12829                 max = REG_INFTY;
12830             }
12831             else if (max_start == min_start) {  /* Was of the form {m} */
12832                 max = min;
12833             }
12834             else {  /* Was of the form {m,n} */
12835                 assert(max_end >= max_start);
12836
12837                 max = get_quantifier_value(pRExC_state, max_start, max_end);
12838             }
12839
12840             RExC_parse = (char *) regcurly_return[RBRACE];
12841             nextchar(pRExC_state);
12842
12843             if (max < min) {    /* If can't match, warn and optimize to fail
12844                                    unconditionally */
12845                 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12846                 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12847                 NEXT_OFF(REGNODE_p(orig_emit)) =
12848                                     regarglen[OPFAIL] + NODE_STEP_REGNODE;
12849                 return ret;
12850             }
12851             else if (min == max && *RExC_parse == '?') {
12852                 ckWARN2reg(RExC_parse + 1,
12853                            "Useless use of greediness modifier '%c'",
12854                            *RExC_parse);
12855             }
12856
12857             break;
12858         } /* End of is {m,n} */
12859
12860         /* Here was a '{', but what followed it didn't form a quantifier. */
12861         /* FALLTHROUGH */
12862
12863       default:
12864         *flagp = flags;
12865         return(ret);
12866         NOT_REACHED; /*NOTREACHED*/
12867     }
12868
12869     /* Here we have a quantifier, and have calculated 'min' and 'max'.
12870      *
12871      * Check and possibly adjust a zero width operand */
12872     if (! (flags & (HASWIDTH|POSTPONED))) {
12873         if (max > REG_INFTY/3) {
12874             if (origparse[0] == '\\' && origparse[1] == 'K') {
12875                 vFAIL2utf8f(
12876                            "%" UTF8f " is forbidden - matches null string"
12877                            " many times",
12878                            UTF8fARG(UTF, (RExC_parse >= origparse
12879                                          ? RExC_parse - origparse
12880                                          : 0),
12881                            origparse));
12882             } else {
12883                 ckWARN2reg(RExC_parse,
12884                            "%" UTF8f " matches null string many times",
12885                            UTF8fARG(UTF, (RExC_parse >= origparse
12886                                          ? RExC_parse - origparse
12887                                          : 0),
12888                            origparse));
12889             }
12890         }
12891
12892         /* There's no point in trying to match something 0 length more than
12893          * once except for extra side effects, which we don't have here since
12894          * not POSTPONED */
12895         if (max > 1) {
12896             max = 1;
12897             if (min > max) {
12898                 min = max;
12899             }
12900         }
12901     }
12902
12903     /* If this is a code block pass it up */
12904     *flagp |= (flags & POSTPONED);
12905
12906     if (max > 0) {
12907         *flagp |= (flags & HASWIDTH);
12908         if (max == REG_INFTY)
12909             RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12910     }
12911
12912     /* 'SIMPLE' operands don't require full generality */
12913     if ((flags&SIMPLE)) {
12914         if (max == REG_INFTY) {
12915             if (min == 0) {
12916                 if (UNLIKELY(RExC_pm_flags & PMf_WILDCARD)) {
12917                     goto min0_maxINF_wildcard_forbidden;
12918                 }
12919
12920                 reginsert(pRExC_state, STAR, ret, depth+1);
12921                 MARK_NAUGHTY(4);
12922                 goto done_main_op;
12923             }
12924             else if (min == 1) {
12925                 reginsert(pRExC_state, PLUS, ret, depth+1);
12926                 MARK_NAUGHTY(3);
12927                 goto done_main_op;
12928             }
12929         }
12930
12931         /* Here, SIMPLE, but not the '*' and '+' special cases */
12932
12933         MARK_NAUGHTY_EXP(2, 2);
12934         reginsert(pRExC_state, CURLY, ret, depth+1);
12935         Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12936         Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12937     }
12938     else {  /* not SIMPLE */
12939         const regnode_offset w = reg_node(pRExC_state, WHILEM);
12940
12941         FLAGS(REGNODE_p(w)) = 0;
12942         if (!  REGTAIL(pRExC_state, ret, w)) {
12943             REQUIRE_BRANCHJ(flagp, 0);
12944         }
12945         if (RExC_use_BRANCHJ) {
12946             reginsert(pRExC_state, LONGJMP, ret, depth+1);
12947             reginsert(pRExC_state, NOTHING, ret, depth+1);
12948             NEXT_OFF(REGNODE_p(ret)) = 3;        /* Go over LONGJMP. */
12949         }
12950         reginsert(pRExC_state, CURLYX, ret, depth+1);
12951                         /* MJD hk */
12952         Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12953         Set_Node_Length(REGNODE_p(ret),
12954                         op == '{' ? (RExC_parse - parse_start) : 1);
12955
12956         if (RExC_use_BRANCHJ)
12957             NEXT_OFF(REGNODE_p(ret)) = 3;   /* Go over NOTHING to
12958                                                LONGJMP. */
12959         if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state,
12960                                                   NOTHING)))
12961         {
12962             REQUIRE_BRANCHJ(flagp, 0);
12963         }
12964         RExC_whilem_seen++;
12965         MARK_NAUGHTY_EXP(1, 4);     /* compound interest */
12966     }
12967
12968     /* Finish up the CURLY/CURLYX case */
12969     FLAGS(REGNODE_p(ret)) = 0;
12970
12971     ARG1_SET(REGNODE_p(ret), (U16)min);
12972     ARG2_SET(REGNODE_p(ret), (U16)max);
12973
12974   done_main_op:
12975
12976     /* Process any greediness modifiers */
12977     if (*RExC_parse == '?') {
12978         nextchar(pRExC_state);
12979         reginsert(pRExC_state, MINMOD, ret, depth+1);
12980         if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) {
12981             REQUIRE_BRANCHJ(flagp, 0);
12982         }
12983     }
12984     else if (*RExC_parse == '+') {
12985         regnode_offset ender;
12986         nextchar(pRExC_state);
12987         ender = reg_node(pRExC_state, SUCCEED);
12988         if (! REGTAIL(pRExC_state, ret, ender)) {
12989             REQUIRE_BRANCHJ(flagp, 0);
12990         }
12991         reginsert(pRExC_state, SUSPEND, ret, depth+1);
12992         ender = reg_node(pRExC_state, TAIL);
12993         if (! REGTAIL(pRExC_state, ret, ender)) {
12994             REQUIRE_BRANCHJ(flagp, 0);
12995         }
12996     }
12997
12998     /* Forbid extra quantifiers */
12999     if (isQUANTIFIER(RExC_parse, RExC_end)) {
13000         RExC_parse++;
13001         vFAIL("Nested quantifiers");
13002     }
13003
13004     return(ret);
13005
13006   min0_maxINF_wildcard_forbidden:
13007
13008     /* Here we are in a wildcard match, and the minimum match length is 0, and
13009      * the max could be infinity.  This is currently forbidden.  The only
13010      * reason is to make it harder to write patterns that take a long long time
13011      * to halt, and because the use of this construct isn't necessary in
13012      * matching Unicode property values */
13013     RExC_parse++;
13014     /* diag_listed_as: Use of %s is not allowed in Unicode property wildcard
13015        subpatterns in regex; marked by <-- HERE in m/%s/
13016      */
13017     vFAIL("Use of quantifier '*' is not allowed in Unicode property wildcard"
13018           " subpatterns");
13019
13020     /* Note, don't need to worry about the input being '{0,}', as a '}' isn't
13021      * legal at all in wildcards, so can't get this far */
13022
13023     NOT_REACHED; /*NOTREACHED*/
13024 }
13025
13026 STATIC bool
13027 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
13028                 regnode_offset * node_p,
13029                 UV * code_point_p,
13030                 int * cp_count,
13031                 I32 * flagp,
13032                 const bool strict,
13033                 const U32 depth
13034     )
13035 {
13036  /* This routine teases apart the various meanings of \N and returns
13037   * accordingly.  The input parameters constrain which meaning(s) is/are valid
13038   * in the current context.
13039   *
13040   * Exactly one of <node_p> and <code_point_p> must be non-NULL.
13041   *
13042   * If <code_point_p> is not NULL, the context is expecting the result to be a
13043   * single code point.  If this \N instance turns out to a single code point,
13044   * the function returns TRUE and sets *code_point_p to that code point.
13045   *
13046   * If <node_p> is not NULL, the context is expecting the result to be one of
13047   * the things representable by a regnode.  If this \N instance turns out to be
13048   * one such, the function generates the regnode, returns TRUE and sets *node_p
13049   * to point to the offset of that regnode into the regex engine program being
13050   * compiled.
13051   *
13052   * If this instance of \N isn't legal in any context, this function will
13053   * generate a fatal error and not return.
13054   *
13055   * On input, RExC_parse should point to the first char following the \N at the
13056   * time of the call.  On successful return, RExC_parse will have been updated
13057   * to point to just after the sequence identified by this routine.  Also
13058   * *flagp has been updated as needed.
13059   *
13060   * When there is some problem with the current context and this \N instance,
13061   * the function returns FALSE, without advancing RExC_parse, nor setting
13062   * *node_p, nor *code_point_p, nor *flagp.
13063   *
13064   * If <cp_count> is not NULL, the caller wants to know the length (in code
13065   * points) that this \N sequence matches.  This is set, and the input is
13066   * parsed for errors, even if the function returns FALSE, as detailed below.
13067   *
13068   * There are 6 possibilities here, as detailed in the next 6 paragraphs.
13069   *
13070   * Probably the most common case is for the \N to specify a single code point.
13071   * *cp_count will be set to 1, and *code_point_p will be set to that code
13072   * point.
13073   *
13074   * Another possibility is for the input to be an empty \N{}.  This is no
13075   * longer accepted, and will generate a fatal error.
13076   *
13077   * Another possibility is for a custom charnames handler to be in effect which
13078   * translates the input name to an empty string.  *cp_count will be set to 0.
13079   * *node_p will be set to a generated NOTHING node.
13080   *
13081   * Still another possibility is for the \N to mean [^\n]. *cp_count will be
13082   * set to 0. *node_p will be set to a generated REG_ANY node.
13083   *
13084   * The fifth possibility is that \N resolves to a sequence of more than one
13085   * code points.  *cp_count will be set to the number of code points in the
13086   * sequence. *node_p will be set to a generated node returned by this
13087   * function calling S_reg().
13088   *
13089   * The sixth and final possibility is that it is premature to be calling this
13090   * function; the parse needs to be restarted.  This can happen when this
13091   * changes from /d to /u rules, or when the pattern needs to be upgraded to
13092   * UTF-8.  The latter occurs only when the fifth possibility would otherwise
13093   * be in effect, and is because one of those code points requires the pattern
13094   * to be recompiled as UTF-8.  The function returns FALSE, and sets the
13095   * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate.  When this
13096   * happens, the caller needs to desist from continuing parsing, and return
13097   * this information to its caller.  This is not set for when there is only one
13098   * code point, as this can be called as part of an ANYOF node, and they can
13099   * store above-Latin1 code points without the pattern having to be in UTF-8.
13100   *
13101   * For non-single-quoted regexes, the tokenizer has resolved character and
13102   * sequence names inside \N{...} into their Unicode values, normalizing the
13103   * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
13104   * hex-represented code points in the sequence.  This is done there because
13105   * the names can vary based on what charnames pragma is in scope at the time,
13106   * so we need a way to take a snapshot of what they resolve to at the time of
13107   * the original parse. [perl #56444].
13108   *
13109   * That parsing is skipped for single-quoted regexes, so here we may get
13110   * '\N{NAME}', which is parsed now.  If the single-quoted regex is something
13111   * like '\N{U+41}', that code point is Unicode, and has to be translated into
13112   * the native character set for non-ASCII platforms.  The other possibilities
13113   * are already native, so no translation is done. */
13114
13115     char * endbrace;    /* points to '}' following the name */
13116     char * e;           /* points to final non-blank before endbrace */
13117     char* p = RExC_parse; /* Temporary */
13118
13119     SV * substitute_parse = NULL;
13120     char *orig_end;
13121     char *save_start;
13122     I32 flags;
13123
13124     DECLARE_AND_GET_RE_DEBUG_FLAGS;
13125
13126     PERL_ARGS_ASSERT_GROK_BSLASH_N;
13127
13128     assert(cBOOL(node_p) ^ cBOOL(code_point_p));  /* Exactly one should be set */
13129     assert(! (node_p && cp_count));               /* At most 1 should be set */
13130
13131     if (cp_count) {     /* Initialize return for the most common case */
13132         *cp_count = 1;
13133     }
13134
13135     /* The [^\n] meaning of \N ignores spaces and comments under the /x
13136      * modifier.  The other meanings do not (except blanks adjacent to and
13137      * within the braces), so use a temporary until we find out which we are
13138      * being called with */
13139     skip_to_be_ignored_text(pRExC_state, &p,
13140                             FALSE /* Don't force to /x */ );
13141
13142     /* Disambiguate between \N meaning a named character versus \N meaning
13143      * [^\n].  The latter is assumed when the {...} following the \N is a legal
13144      * quantifier, or if there is no '{' at all */
13145     if (*p != '{' || regcurly(p, RExC_end, NULL)) {
13146         RExC_parse = p;
13147         if (cp_count) {
13148             *cp_count = -1;
13149         }
13150
13151         if (! node_p) {
13152             return FALSE;
13153         }
13154
13155         *node_p = reg_node(pRExC_state, REG_ANY);
13156         *flagp |= HASWIDTH|SIMPLE;
13157         MARK_NAUGHTY(1);
13158         Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
13159         return TRUE;
13160     }
13161
13162     /* The test above made sure that the next real character is a '{', but
13163      * under the /x modifier, it could be separated by space (or a comment and
13164      * \n) and this is not allowed (for consistency with \x{...} and the
13165      * tokenizer handling of \N{NAME}). */
13166     if (*RExC_parse != '{') {
13167         vFAIL("Missing braces on \\N{}");
13168     }
13169
13170     RExC_parse++;       /* Skip past the '{' */
13171
13172     endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13173     if (! endbrace) { /* no trailing brace */
13174         vFAIL2("Missing right brace on \\%c{}", 'N');
13175     }
13176
13177     /* Here, we have decided it should be a named character or sequence.  These
13178      * imply Unicode semantics */
13179     REQUIRE_UNI_RULES(flagp, FALSE);
13180
13181     /* \N{_} is what toke.c returns to us to indicate a name that evaluates to
13182      * nothing at all (not allowed under strict) */
13183     if (endbrace - RExC_parse == 1 && *RExC_parse == '_') {
13184         RExC_parse = endbrace;
13185         if (strict) {
13186             RExC_parse++;   /* Position after the "}" */
13187             vFAIL("Zero length \\N{}");
13188         }
13189
13190         if (cp_count) {
13191             *cp_count = 0;
13192         }
13193         nextchar(pRExC_state);
13194         if (! node_p) {
13195             return FALSE;
13196         }
13197
13198         *node_p = reg_node(pRExC_state, NOTHING);
13199         return TRUE;
13200     }
13201
13202     while (isBLANK(*RExC_parse)) {
13203         RExC_parse++;
13204     }
13205
13206     e = endbrace;
13207     while (RExC_parse < e && isBLANK(*(e-1))) {
13208         e--;
13209     }
13210
13211     if (e - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) {
13212
13213         /* Here, the name isn't of the form  U+....  This can happen if the
13214          * pattern is single-quoted, so didn't get evaluated in toke.c.  Now
13215          * is the time to find out what the name means */
13216
13217         const STRLEN name_len = e - RExC_parse;
13218         SV *  value_sv;     /* What does this name evaluate to */
13219         SV ** value_svp;
13220         const U8 * value;   /* string of name's value */
13221         STRLEN value_len;   /* and its length */
13222
13223         /*  RExC_unlexed_names is a hash of names that weren't evaluated by
13224          *  toke.c, and their values. Make sure is initialized */
13225         if (! RExC_unlexed_names) {
13226             RExC_unlexed_names = newHV();
13227         }
13228
13229         /* If we have already seen this name in this pattern, use that.  This
13230          * allows us to only call the charnames handler once per name per
13231          * pattern.  A broken or malicious handler could return something
13232          * different each time, which could cause the results to vary depending
13233          * on if something gets added or subtracted from the pattern that
13234          * causes the number of passes to change, for example */
13235         if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse,
13236                                                       name_len, 0)))
13237         {
13238             value_sv = *value_svp;
13239         }
13240         else { /* Otherwise we have to go out and get the name */
13241             const char * error_msg = NULL;
13242             value_sv = get_and_check_backslash_N_name(RExC_parse, e,
13243                                                       UTF,
13244                                                       &error_msg);
13245             if (error_msg) {
13246                 RExC_parse = endbrace;
13247                 vFAIL(error_msg);
13248             }
13249
13250             /* If no error message, should have gotten a valid return */
13251             assert (value_sv);
13252
13253             /* Save the name's meaning for later use */
13254             if (! hv_store(RExC_unlexed_names, RExC_parse, name_len,
13255                            value_sv, 0))
13256             {
13257                 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
13258             }
13259         }
13260
13261         /* Here, we have the value the name evaluates to in 'value_sv' */
13262         value = (U8 *) SvPV(value_sv, value_len);
13263
13264         /* See if the result is one code point vs 0 or multiple */
13265         if (inRANGE(value_len, 1, ((UV) SvUTF8(value_sv)
13266                                   ? UTF8SKIP(value)
13267                                   : 1)))
13268         {
13269             /* Here, exactly one code point.  If that isn't what is wanted,
13270              * fail */
13271             if (! code_point_p) {
13272                 RExC_parse = p;
13273                 return FALSE;
13274             }
13275
13276             /* Convert from string to numeric code point */
13277             *code_point_p = (SvUTF8(value_sv))
13278                             ? valid_utf8_to_uvchr(value, NULL)
13279                             : *value;
13280
13281             /* Have parsed this entire single code point \N{...}.  *cp_count
13282              * has already been set to 1, so don't do it again. */
13283             RExC_parse = endbrace;
13284             nextchar(pRExC_state);
13285             return TRUE;
13286         } /* End of is a single code point */
13287
13288         /* Count the code points, if caller desires.  The API says to do this
13289          * even if we will later return FALSE */
13290         if (cp_count) {
13291             *cp_count = 0;
13292
13293             *cp_count = (SvUTF8(value_sv))
13294                         ? utf8_length(value, value + value_len)
13295                         : value_len;
13296         }
13297
13298         /* Fail if caller doesn't want to handle a multi-code-point sequence.
13299          * But don't back the pointer up if the caller wants to know how many
13300          * code points there are (they need to handle it themselves in this
13301          * case).  */
13302         if (! node_p) {
13303             if (! cp_count) {
13304                 RExC_parse = p;
13305             }
13306             return FALSE;
13307         }
13308
13309         /* Convert this to a sub-pattern of the form "(?: ... )", and then call
13310          * reg recursively to parse it.  That way, it retains its atomicness,
13311          * while not having to worry about any special handling that some code
13312          * points may have. */
13313
13314         substitute_parse = newSVpvs("?:");
13315         sv_catsv(substitute_parse, value_sv);
13316         sv_catpv(substitute_parse, ")");
13317
13318         /* The value should already be native, so no need to convert on EBCDIC
13319          * platforms.*/
13320         assert(! RExC_recode_x_to_native);
13321
13322     }
13323     else {   /* \N{U+...} */
13324         Size_t count = 0;   /* code point count kept internally */
13325
13326         /* We can get to here when the input is \N{U+...} or when toke.c has
13327          * converted a name to the \N{U+...} form.  This include changing a
13328          * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
13329
13330         RExC_parse += 2;    /* Skip past the 'U+' */
13331
13332         /* Code points are separated by dots.  The '}' terminates the whole
13333          * thing. */
13334
13335         do {    /* Loop until the ending brace */
13336             I32 flags = PERL_SCAN_SILENT_OVERFLOW
13337                       | PERL_SCAN_SILENT_ILLDIGIT
13338                       | PERL_SCAN_NOTIFY_ILLDIGIT
13339                       | PERL_SCAN_ALLOW_MEDIAL_UNDERSCORES
13340                       | PERL_SCAN_DISALLOW_PREFIX;
13341             STRLEN len = e - RExC_parse;
13342             NV overflow_value;
13343             char * start_digit = RExC_parse;
13344             UV cp = grok_hex(RExC_parse, &len, &flags, &overflow_value);
13345
13346             if (len == 0) {
13347                 RExC_parse++;
13348               bad_NU:
13349                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
13350             }
13351
13352             RExC_parse += len;
13353
13354             if (cp > MAX_LEGAL_CP) {
13355                 vFAIL(form_cp_too_large_msg(16, start_digit, len, 0));
13356             }
13357
13358             if (RExC_parse >= e) { /* Got to the closing '}' */
13359                 if (count) {
13360                     goto do_concat;
13361                 }
13362
13363                 /* Here, is a single code point; fail if doesn't want that */
13364                 if (! code_point_p) {
13365                     RExC_parse = p;
13366                     return FALSE;
13367                 }
13368
13369                 /* A single code point is easy to handle; just return it */
13370                 *code_point_p = UNI_TO_NATIVE(cp);
13371                 RExC_parse = endbrace;
13372                 nextchar(pRExC_state);
13373                 return TRUE;
13374             }
13375
13376             /* Here, the parse stopped bfore the ending brace.  This is legal
13377              * only if that character is a dot separating code points, like a
13378              * multiple character sequence (of the form "\N{U+c1.c2. ... }".
13379              * So the next character must be a dot (and the one after that
13380              * can't be the ending brace, or we'd have something like
13381              * \N{U+100.} )
13382              * */
13383             if (*RExC_parse != '.' || RExC_parse + 1 >= e) {
13384                 RExC_parse += (RExC_orig_utf8)  /* point to after 1st invalid */
13385                               ? UTF8SKIP(RExC_parse)
13386                               : 1;
13387                 RExC_parse = MIN(e, RExC_parse);/* Guard against malformed utf8
13388                                                  */
13389                 goto bad_NU;
13390             }
13391
13392             /* Here, looks like its really a multiple character sequence.  Fail
13393              * if that's not what the caller wants.  But continue with counting
13394              * and error checking if they still want a count */
13395             if (! node_p && ! cp_count) {
13396                 return FALSE;
13397             }
13398
13399             /* What is done here is to convert this to a sub-pattern of the
13400              * form \x{char1}\x{char2}...  and then call reg recursively to
13401              * parse it (enclosing in "(?: ... )" ).  That way, it retains its
13402              * atomicness, while not having to worry about special handling
13403              * that some code points may have.  We don't create a subpattern,
13404              * but go through the motions of code point counting and error
13405              * checking, if the caller doesn't want a node returned. */
13406
13407             if (node_p && ! substitute_parse) {
13408                 substitute_parse = newSVpvs("?:");
13409             }
13410
13411           do_concat:
13412
13413             if (node_p) {
13414                 /* Convert to notation the rest of the code understands */
13415                 sv_catpvs(substitute_parse, "\\x{");
13416                 sv_catpvn(substitute_parse, start_digit,
13417                                             RExC_parse - start_digit);
13418                 sv_catpvs(substitute_parse, "}");
13419             }
13420
13421             /* Move to after the dot (or ending brace the final time through.)
13422              * */
13423             RExC_parse++;
13424             count++;
13425
13426         } while (RExC_parse < e);
13427
13428         if (! node_p) { /* Doesn't want the node */
13429             assert (cp_count);
13430
13431             *cp_count = count;
13432             return FALSE;
13433         }
13434
13435         sv_catpvs(substitute_parse, ")");
13436
13437         /* The values are Unicode, and therefore have to be converted to native
13438          * on a non-Unicode (meaning non-ASCII) platform. */
13439         SET_recode_x_to_native(1);
13440     }
13441
13442     /* Here, we have the string the name evaluates to, ready to be parsed,
13443      * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
13444      * constructs.  This can be called from within a substitute parse already.
13445      * The error reporting mechanism doesn't work for 2 levels of this, but the
13446      * code above has validated this new construct, so there should be no
13447      * errors generated by the below.  And this isn't an exact copy, so the
13448      * mechanism to seamlessly deal with this won't work, so turn off warnings
13449      * during it */
13450     save_start = RExC_start;
13451     orig_end = RExC_end;
13452
13453     RExC_parse = RExC_start = SvPVX(substitute_parse);
13454     RExC_end = RExC_parse + SvCUR(substitute_parse);
13455     TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
13456
13457     *node_p = reg(pRExC_state, 1, &flags, depth+1);
13458
13459     /* Restore the saved values */
13460     RESTORE_WARNINGS;
13461     RExC_start = save_start;
13462     RExC_parse = endbrace;
13463     RExC_end = orig_end;
13464     SET_recode_x_to_native(0);
13465
13466     SvREFCNT_dec_NN(substitute_parse);
13467
13468     if (! *node_p) {
13469         RETURN_FAIL_ON_RESTART(flags, flagp);
13470         FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
13471             (UV) flags);
13472     }
13473     *flagp |= flags&(HASWIDTH|SIMPLE|POSTPONED);
13474
13475     nextchar(pRExC_state);
13476
13477     return TRUE;
13478 }
13479
13480
13481 STATIC U8
13482 S_compute_EXACTish(RExC_state_t *pRExC_state)
13483 {
13484     U8 op;
13485
13486     PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
13487
13488     if (! FOLD) {
13489         return (LOC)
13490                 ? EXACTL
13491                 : EXACT;
13492     }
13493
13494     op = get_regex_charset(RExC_flags);
13495     if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
13496         op--; /* /a is same as /u, and map /aa's offset to what /a's would have
13497                  been, so there is no hole */
13498     }
13499
13500     return op + EXACTF;
13501 }
13502
13503 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
13504  * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
13505
13506 static I32
13507 S_backref_value(char *p, char *e)
13508 {
13509     const char* endptr = e;
13510     UV val;
13511     if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13512         return (I32)val;
13513     return I32_MAX;
13514 }
13515
13516
13517 /*
13518  - regatom - the lowest level
13519
13520    Try to identify anything special at the start of the current parse position.
13521    If there is, then handle it as required. This may involve generating a
13522    single regop, such as for an assertion; or it may involve recursing, such as
13523    to handle a () structure.
13524
13525    If the string doesn't start with something special then we gobble up
13526    as much literal text as we can.  If we encounter a quantifier, we have to
13527    back off the final literal character, as that quantifier applies to just it
13528    and not to the whole string of literals.
13529
13530    Once we have been able to handle whatever type of thing started the
13531    sequence, we return the offset into the regex engine program being compiled
13532    at which any  next regnode should be placed.
13533
13534    Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13535    Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13536    restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13537    Otherwise does not return 0.
13538
13539    Note: we have to be careful with escapes, as they can be both literal
13540    and special, and in the case of \10 and friends, context determines which.
13541
13542    A summary of the code structure is:
13543
13544    switch (first_byte) {
13545         cases for each special:
13546             handle this special;
13547             break;
13548         case '\\':
13549             switch (2nd byte) {
13550                 cases for each unambiguous special:
13551                     handle this special;
13552                     break;
13553                 cases for each ambigous special/literal:
13554                     disambiguate;
13555                     if (special)  handle here
13556                     else goto defchar;
13557                 default: // unambiguously literal:
13558                     goto defchar;
13559             }
13560         default:  // is a literal char
13561             // FALL THROUGH
13562         defchar:
13563             create EXACTish node for literal;
13564             while (more input and node isn't full) {
13565                 switch (input_byte) {
13566                    cases for each special;
13567                        make sure parse pointer is set so that the next call to
13568                            regatom will see this special first
13569                        goto loopdone; // EXACTish node terminated by prev. char
13570                    default:
13571                        append char to EXACTISH node;
13572                 }
13573                 get next input byte;
13574             }
13575         loopdone:
13576    }
13577    return the generated node;
13578
13579    Specifically there are two separate switches for handling
13580    escape sequences, with the one for handling literal escapes requiring
13581    a dummy entry for all of the special escapes that are actually handled
13582    by the other.
13583
13584 */
13585
13586 STATIC regnode_offset
13587 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13588 {
13589     regnode_offset ret = 0;
13590     I32 flags = 0;
13591     char *parse_start;
13592     U8 op;
13593     int invert = 0;
13594
13595     DECLARE_AND_GET_RE_DEBUG_FLAGS;
13596
13597     *flagp = 0;         /* Initialize. */
13598
13599     DEBUG_PARSE("atom");
13600
13601     PERL_ARGS_ASSERT_REGATOM;
13602
13603   tryagain:
13604     parse_start = RExC_parse;
13605     assert(RExC_parse < RExC_end);
13606     switch ((U8)*RExC_parse) {
13607     case '^':
13608         RExC_seen_zerolen++;
13609         nextchar(pRExC_state);
13610         if (RExC_flags & RXf_PMf_MULTILINE)
13611             ret = reg_node(pRExC_state, MBOL);
13612         else
13613             ret = reg_node(pRExC_state, SBOL);
13614         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13615         break;
13616     case '$':
13617         nextchar(pRExC_state);
13618         if (*RExC_parse)
13619             RExC_seen_zerolen++;
13620         if (RExC_flags & RXf_PMf_MULTILINE)
13621             ret = reg_node(pRExC_state, MEOL);
13622         else
13623             ret = reg_node(pRExC_state, SEOL);
13624         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13625         break;
13626     case '.':
13627         nextchar(pRExC_state);
13628         if (RExC_flags & RXf_PMf_SINGLELINE)
13629             ret = reg_node(pRExC_state, SANY);
13630         else
13631             ret = reg_node(pRExC_state, REG_ANY);
13632         *flagp |= HASWIDTH|SIMPLE;
13633         MARK_NAUGHTY(1);
13634         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13635         break;
13636     case '[':
13637     {
13638         char * const oregcomp_parse = ++RExC_parse;
13639         ret = regclass(pRExC_state, flagp, depth+1,
13640                        FALSE, /* means parse the whole char class */
13641                        TRUE, /* allow multi-char folds */
13642                        FALSE, /* don't silence non-portable warnings. */
13643                        (bool) RExC_strict,
13644                        TRUE, /* Allow an optimized regnode result */
13645                        NULL);
13646         if (ret == 0) {
13647             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13648             FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13649                   (UV) *flagp);
13650         }
13651         if (*RExC_parse != ']') {
13652             RExC_parse = oregcomp_parse;
13653             vFAIL("Unmatched [");
13654         }
13655         nextchar(pRExC_state);
13656         Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13657         break;
13658     }
13659     case '(':
13660         nextchar(pRExC_state);
13661         ret = reg(pRExC_state, 2, &flags, depth+1);
13662         if (ret == 0) {
13663                 if (flags & TRYAGAIN) {
13664                     if (RExC_parse >= RExC_end) {
13665                          /* Make parent create an empty node if needed. */
13666                         *flagp |= TRYAGAIN;
13667                         return(0);
13668                     }
13669                     goto tryagain;
13670                 }
13671                 RETURN_FAIL_ON_RESTART(flags, flagp);
13672                 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13673                                                                  (UV) flags);
13674         }
13675         *flagp |= flags&(HASWIDTH|SIMPLE|POSTPONED);
13676         break;
13677     case '|':
13678     case ')':
13679         if (flags & TRYAGAIN) {
13680             *flagp |= TRYAGAIN;
13681             return 0;
13682         }
13683         vFAIL("Internal urp");
13684                                 /* Supposed to be caught earlier. */
13685         break;
13686     case '?':
13687     case '+':
13688     case '*':
13689         RExC_parse++;
13690         vFAIL("Quantifier follows nothing");
13691         break;
13692     case '\\':
13693         /* Special Escapes
13694
13695            This switch handles escape sequences that resolve to some kind
13696            of special regop and not to literal text. Escape sequences that
13697            resolve to literal text are handled below in the switch marked
13698            "Literal Escapes".
13699
13700            Every entry in this switch *must* have a corresponding entry
13701            in the literal escape switch. However, the opposite is not
13702            required, as the default for this switch is to jump to the
13703            literal text handling code.
13704         */
13705         RExC_parse++;
13706         switch ((U8)*RExC_parse) {
13707         /* Special Escapes */
13708         case 'A':
13709             RExC_seen_zerolen++;
13710             /* Under wildcards, this is changed to match \n; should be
13711              * invisible to the user, as they have to compile under /m */
13712             if (RExC_pm_flags & PMf_WILDCARD) {
13713                 ret = reg_node(pRExC_state, MBOL);
13714             }
13715             else {
13716                 ret = reg_node(pRExC_state, SBOL);
13717                 /* SBOL is shared with /^/ so we set the flags so we can tell
13718                  * /\A/ from /^/ in split. */
13719                 FLAGS(REGNODE_p(ret)) = 1;
13720             }
13721             goto finish_meta_pat;
13722         case 'G':
13723             if (RExC_pm_flags & PMf_WILDCARD) {
13724                 RExC_parse++;
13725                 /* diag_listed_as: Use of %s is not allowed in Unicode property
13726                    wildcard subpatterns in regex; marked by <-- HERE in m/%s/
13727                  */
13728                 vFAIL("Use of '\\G' is not allowed in Unicode property"
13729                       " wildcard subpatterns");
13730             }
13731             ret = reg_node(pRExC_state, GPOS);
13732             RExC_seen |= REG_GPOS_SEEN;
13733             goto finish_meta_pat;
13734         case 'K':
13735             if (!RExC_in_lookaround) {
13736                 RExC_seen_zerolen++;
13737                 ret = reg_node(pRExC_state, KEEPS);
13738                 /* XXX:dmq : disabling in-place substitution seems to
13739                  * be necessary here to avoid cases of memory corruption, as
13740                  * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13741                  */
13742                 RExC_seen |= REG_LOOKBEHIND_SEEN;
13743                 goto finish_meta_pat;
13744             }
13745             else {
13746                 ++RExC_parse; /* advance past the 'K' */
13747                 vFAIL("\\K not permitted in lookahead/lookbehind");
13748             }
13749         case 'Z':
13750             if (RExC_pm_flags & PMf_WILDCARD) {
13751                 /* See comment under \A above */
13752                 ret = reg_node(pRExC_state, MEOL);
13753             }
13754             else {
13755                 ret = reg_node(pRExC_state, SEOL);
13756             }
13757             RExC_seen_zerolen++;                /* Do not optimize RE away */
13758             goto finish_meta_pat;
13759         case 'z':
13760             if (RExC_pm_flags & PMf_WILDCARD) {
13761                 /* See comment under \A above */
13762                 ret = reg_node(pRExC_state, MEOL);
13763             }
13764             else {
13765                 ret = reg_node(pRExC_state, EOS);
13766             }
13767             RExC_seen_zerolen++;                /* Do not optimize RE away */
13768             goto finish_meta_pat;
13769         case 'C':
13770             vFAIL("\\C no longer supported");
13771         case 'X':
13772             ret = reg_node(pRExC_state, CLUMP);
13773             *flagp |= HASWIDTH;
13774             goto finish_meta_pat;
13775
13776         case 'B':
13777             invert = 1;
13778             /* FALLTHROUGH */
13779         case 'b':
13780           {
13781             U8 flags = 0;
13782             regex_charset charset = get_regex_charset(RExC_flags);
13783
13784             RExC_seen_zerolen++;
13785             RExC_seen |= REG_LOOKBEHIND_SEEN;
13786             op = BOUND + charset;
13787
13788             if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13789                 flags = TRADITIONAL_BOUND;
13790                 if (op > BOUNDA) {  /* /aa is same as /a */
13791                     op = BOUNDA;
13792                 }
13793             }
13794             else {
13795                 STRLEN length;
13796                 char name = *RExC_parse;
13797                 char * endbrace =  (char *) memchr(RExC_parse, '}',
13798                                                    RExC_end - RExC_parse);
13799                 char * e = endbrace;
13800
13801                 RExC_parse += 2;
13802
13803                 if (! endbrace) {
13804                     vFAIL2("Missing right brace on \\%c{}", name);
13805                 }
13806
13807                 while (isBLANK(*RExC_parse)) {
13808                     RExC_parse++;
13809                 }
13810
13811                 while (RExC_parse < e && isBLANK(*(e - 1))) {
13812                     e--;
13813                 }
13814
13815                 if (e == RExC_parse) {
13816                     RExC_parse = endbrace + 1;  /* After the '}' */
13817                     vFAIL2("Empty \\%c{}", name);
13818                 }
13819
13820                 length = e - RExC_parse;
13821
13822                 switch (*RExC_parse) {
13823                     case 'g':
13824                         if (    length != 1
13825                             && (memNEs(RExC_parse + 1, length - 1, "cb")))
13826                         {
13827                             goto bad_bound_type;
13828                         }
13829                         flags = GCB_BOUND;
13830                         break;
13831                     case 'l':
13832                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13833                             goto bad_bound_type;
13834                         }
13835                         flags = LB_BOUND;
13836                         break;
13837                     case 's':
13838                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13839                             goto bad_bound_type;
13840                         }
13841                         flags = SB_BOUND;
13842                         break;
13843                     case 'w':
13844                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13845                             goto bad_bound_type;
13846                         }
13847                         flags = WB_BOUND;
13848                         break;
13849                     default:
13850                       bad_bound_type:
13851                         RExC_parse = e;
13852                         vFAIL2utf8f(
13853                             "'%" UTF8f "' is an unknown bound type",
13854                             UTF8fARG(UTF, length, e - length));
13855                         NOT_REACHED; /*NOTREACHED*/
13856                 }
13857                 RExC_parse = endbrace;
13858                 REQUIRE_UNI_RULES(flagp, 0);
13859
13860                 if (op == BOUND) {
13861                     op = BOUNDU;
13862                 }
13863                 else if (op >= BOUNDA) {  /* /aa is same as /a */
13864                     op = BOUNDU;
13865                     length += 4;
13866
13867                     /* Don't have to worry about UTF-8, in this message because
13868                      * to get here the contents of the \b must be ASCII */
13869                     ckWARN4reg(RExC_parse + 1,  /* Include the '}' in msg */
13870                               "Using /u for '%.*s' instead of /%s",
13871                               (unsigned) length,
13872                               endbrace - length + 1,
13873                               (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13874                               ? ASCII_RESTRICT_PAT_MODS
13875                               : ASCII_MORE_RESTRICT_PAT_MODS);
13876                 }
13877             }
13878
13879             if (op == BOUND) {
13880                 RExC_seen_d_op = TRUE;
13881             }
13882             else if (op == BOUNDL) {
13883                 RExC_contains_locale = 1;
13884             }
13885
13886             if (invert) {
13887                 op += NBOUND - BOUND;
13888             }
13889
13890             ret = reg_node(pRExC_state, op);
13891             FLAGS(REGNODE_p(ret)) = flags;
13892
13893             goto finish_meta_pat;
13894           }
13895
13896         case 'R':
13897             ret = reg_node(pRExC_state, LNBREAK);
13898             *flagp |= HASWIDTH|SIMPLE;
13899             goto finish_meta_pat;
13900
13901         case 'd':
13902         case 'D':
13903         case 'h':
13904         case 'H':
13905         case 'p':
13906         case 'P':
13907         case 's':
13908         case 'S':
13909         case 'v':
13910         case 'V':
13911         case 'w':
13912         case 'W':
13913             /* These all have the same meaning inside [brackets], and it knows
13914              * how to do the best optimizations for them.  So, pretend we found
13915              * these within brackets, and let it do the work */
13916             RExC_parse--;
13917
13918             ret = regclass(pRExC_state, flagp, depth+1,
13919                            TRUE, /* means just parse this element */
13920                            FALSE, /* don't allow multi-char folds */
13921                            FALSE, /* don't silence non-portable warnings.  It
13922                                      would be a bug if these returned
13923                                      non-portables */
13924                            (bool) RExC_strict,
13925                            TRUE, /* Allow an optimized regnode result */
13926                            NULL);
13927             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13928             /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13929              * multi-char folds are allowed.  */
13930             if (!ret)
13931                 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13932                       (UV) *flagp);
13933
13934             RExC_parse--;   /* regclass() leaves this one too far ahead */
13935
13936           finish_meta_pat:
13937                    /* The escapes above that don't take a parameter can't be
13938                     * followed by a '{'.  But 'pX', 'p{foo}' and
13939                     * correspondingly 'P' can be */
13940             if (   RExC_parse - parse_start == 1
13941                 && UCHARAT(RExC_parse + 1) == '{'
13942                 && UNLIKELY(! regcurly(RExC_parse + 1, RExC_end, NULL)))
13943             {
13944                 RExC_parse += 2;
13945                 vFAIL("Unescaped left brace in regex is illegal here");
13946             }
13947             Set_Node_Offset(REGNODE_p(ret), parse_start);
13948             Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1); /* MJD */
13949             nextchar(pRExC_state);
13950             break;
13951         case 'N':
13952             /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13953              * \N{...} evaluates to a sequence of more than one code points).
13954              * The function call below returns a regnode, which is our result.
13955              * The parameters cause it to fail if the \N{} evaluates to a
13956              * single code point; we handle those like any other literal.  The
13957              * reason that the multicharacter case is handled here and not as
13958              * part of the EXACtish code is because of quantifiers.  In
13959              * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13960              * this way makes that Just Happen. dmq.
13961              * join_exact() will join this up with adjacent EXACTish nodes
13962              * later on, if appropriate. */
13963             ++RExC_parse;
13964             if (grok_bslash_N(pRExC_state,
13965                               &ret,     /* Want a regnode returned */
13966                               NULL,     /* Fail if evaluates to a single code
13967                                            point */
13968                               NULL,     /* Don't need a count of how many code
13969                                            points */
13970                               flagp,
13971                               RExC_strict,
13972                               depth)
13973             ) {
13974                 break;
13975             }
13976
13977             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13978
13979             /* Here, evaluates to a single code point.  Go get that */
13980             RExC_parse = parse_start;
13981             goto defchar;
13982
13983         case 'k':    /* Handle \k<NAME> and \k'NAME' and \k{NAME} */
13984       parse_named_seq:  /* Also handle non-numeric \g{...} */
13985         {
13986             char ch;
13987             if (   RExC_parse >= RExC_end - 1
13988                 || ((   ch = RExC_parse[1]) != '<'
13989                                       && ch != '\''
13990                                       && ch != '{'))
13991             {
13992                 RExC_parse++;
13993                 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13994                 vFAIL2("Sequence %.2s... not terminated", parse_start);
13995             } else {
13996                 RExC_parse += 2;
13997                 if (ch == '{') {
13998                     while (isBLANK(*RExC_parse)) {
13999                         RExC_parse++;
14000                     }
14001                 }
14002                 ret = handle_named_backref(pRExC_state,
14003                                            flagp,
14004                                            parse_start,
14005                                            (ch == '<')
14006                                            ? '>'
14007                                            : (ch == '{')
14008                                              ? '}'
14009                                              : '\'');
14010             }
14011             break;
14012         }
14013         case 'g':
14014         case '1': case '2': case '3': case '4':
14015         case '5': case '6': case '7': case '8': case '9':
14016             {
14017                 I32 num;
14018                 char * endbrace = NULL;
14019                 char * s = RExC_parse;
14020                 char * e = RExC_end;
14021
14022                 if (*s == 'g') {
14023                     bool isrel = 0;
14024
14025                     s++;
14026                     if (*s == '{') {
14027                         endbrace = (char *) memchr(s, '}', RExC_end - s);
14028                         if (! endbrace ) {
14029
14030                             /* Missing '}'.  Position after the number to give
14031                              * a better indication to the user of where the
14032                              * problem is. */
14033                             s++;
14034                             if (*s == '-') {
14035                                 s++;
14036                             }
14037
14038                             /* If it looks to be a name and not a number, go
14039                              * handle it there */
14040                             if (! isDIGIT(*s)) {
14041                                 goto parse_named_seq;
14042                             }
14043
14044                             do {
14045                                 s++;
14046                             } while isDIGIT(*s);
14047
14048                             RExC_parse = s;
14049                             vFAIL("Unterminated \\g{...} pattern");
14050                         }
14051
14052                         s++;    /* Past the '{' */
14053
14054                         while (isBLANK(*s)) {
14055                             s++;
14056                         }
14057
14058                         /* Ignore trailing blanks */
14059                         e = endbrace;
14060                         while (s < e && isBLANK(*(e - 1))) {
14061                             e--;
14062                         }
14063                     }
14064
14065                     /* Here, have isolated the meat of the construct from any
14066                      * surrounding braces */
14067
14068                     if (*s == '-') {
14069                         isrel = 1;
14070                         s++;
14071                     }
14072
14073                     if (endbrace && !isDIGIT(*s)) {
14074                         goto parse_named_seq;
14075                     }
14076
14077                     RExC_parse = s;
14078                     num = S_backref_value(RExC_parse, RExC_end);
14079                     if (num == 0)
14080                         vFAIL("Reference to invalid group 0");
14081                     else if (num == I32_MAX) {
14082                          if (isDIGIT(*RExC_parse))
14083                             vFAIL("Reference to nonexistent group");
14084                         else
14085                             vFAIL("Unterminated \\g... pattern");
14086                     }
14087
14088                     if (isrel) {
14089                         num = RExC_npar - num;
14090                         if (num < 1)
14091                             vFAIL("Reference to nonexistent or unclosed group");
14092                     }
14093                 }
14094                 else {
14095                     num = S_backref_value(RExC_parse, RExC_end);
14096                     /* bare \NNN might be backref or octal - if it is larger
14097                      * than or equal RExC_npar then it is assumed to be an
14098                      * octal escape. Note RExC_npar is +1 from the actual
14099                      * number of parens. */
14100                     /* Note we do NOT check if num == I32_MAX here, as that is
14101                      * handled by the RExC_npar check */
14102
14103                     if (    /* any numeric escape < 10 is always a backref */
14104                            num > 9
14105                             /* any numeric escape < RExC_npar is a backref */
14106                         && num >= RExC_npar
14107                             /* cannot be an octal escape if it starts with [89]
14108                              * */
14109                         && ! inRANGE(*RExC_parse, '8', '9')
14110                     ) {
14111                         /* Probably not meant to be a backref, instead likely
14112                          * to be an octal character escape, e.g. \35 or \777.
14113                          * The above logic should make it obvious why using
14114                          * octal escapes in patterns is problematic. - Yves */
14115                         RExC_parse = parse_start;
14116                         goto defchar;
14117                     }
14118                 }
14119
14120                 /* At this point RExC_parse points at a numeric escape like
14121                  * \12 or \88 or the digits in \g{34} or \g34 or something
14122                  * similar, which we should NOT treat as an octal escape. It
14123                  * may or may not be a valid backref escape. For instance
14124                  * \88888888 is unlikely to be a valid backref.
14125                  *
14126                  * We've already figured out what value the digits represent.
14127                  * Now, move the parse to beyond them. */
14128                 if (endbrace) {
14129                     RExC_parse = endbrace + 1;
14130                 }
14131                 else while (isDIGIT(*RExC_parse)) {
14132                     RExC_parse++;
14133                 }
14134
14135                 if (num >= (I32)RExC_npar) {
14136
14137                     /* It might be a forward reference; we can't fail until we
14138                      * know, by completing the parse to get all the groups, and
14139                      * then reparsing */
14140                     if (ALL_PARENS_COUNTED)  {
14141                         if (num >= RExC_total_parens)  {
14142                             vFAIL("Reference to nonexistent group");
14143                         }
14144                     }
14145                     else {
14146                         REQUIRE_PARENS_PASS;
14147                     }
14148                 }
14149                 RExC_sawback = 1;
14150                 ret = reganode(pRExC_state,
14151                                ((! FOLD)
14152                                  ? REF
14153                                  : (ASCII_FOLD_RESTRICTED)
14154                                    ? REFFA
14155                                    : (AT_LEAST_UNI_SEMANTICS)
14156                                      ? REFFU
14157                                      : (LOC)
14158                                        ? REFFL
14159                                        : REFF),
14160                                 num);
14161                 if (OP(REGNODE_p(ret)) == REFF) {
14162                     RExC_seen_d_op = TRUE;
14163                 }
14164                 *flagp |= HASWIDTH;
14165
14166                 /* override incorrect value set in reganode MJD */
14167                 Set_Node_Offset(REGNODE_p(ret), parse_start);
14168                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
14169                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14170                                         FALSE /* Don't force to /x */ );
14171             }
14172             break;
14173         case '\0':
14174             if (RExC_parse >= RExC_end)
14175                 FAIL("Trailing \\");
14176             /* FALLTHROUGH */
14177         default:
14178             /* Do not generate "unrecognized" warnings here, we fall
14179                back into the quick-grab loop below */
14180             RExC_parse = parse_start;
14181             goto defchar;
14182         } /* end of switch on a \foo sequence */
14183         break;
14184
14185     case '#':
14186
14187         /* '#' comments should have been spaced over before this function was
14188          * called */
14189         assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
14190         /*
14191         if (RExC_flags & RXf_PMf_EXTENDED) {
14192             RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
14193             if (RExC_parse < RExC_end)
14194                 goto tryagain;
14195         }
14196         */
14197
14198         /* FALLTHROUGH */
14199
14200     default:
14201           defchar: {
14202
14203             /* Here, we have determined that the next thing is probably a
14204              * literal character.  RExC_parse points to the first byte of its
14205              * definition.  (It still may be an escape sequence that evaluates
14206              * to a single character) */
14207
14208             STRLEN len = 0;
14209             UV ender = 0;
14210             char *p;
14211             char *s, *old_s = NULL, *old_old_s = NULL;
14212             char *s0;
14213             U32 max_string_len = 255;
14214
14215             /* We may have to reparse the node, artificially stopping filling
14216              * it early, based on info gleaned in the first parse.  This
14217              * variable gives where we stop.  Make it above the normal stopping
14218              * place first time through; otherwise it would stop too early */
14219             U32 upper_fill = max_string_len + 1;
14220
14221             /* We start out as an EXACT node, even if under /i, until we find a
14222              * character which is in a fold.  The algorithm now segregates into
14223              * separate nodes, characters that fold from those that don't under
14224              * /i.  (This hopefully will create nodes that are fixed strings
14225              * even under /i, giving the optimizer something to grab on to.)
14226              * So, if a node has something in it and the next character is in
14227              * the opposite category, that node is closed up, and the function
14228              * returns.  Then regatom is called again, and a new node is
14229              * created for the new category. */
14230             U8 node_type = EXACT;
14231
14232             /* Assume the node will be fully used; the excess is given back at
14233              * the end.  Under /i, we may need to temporarily add the fold of
14234              * an extra character or two at the end to check for splitting
14235              * multi-char folds, so allocate extra space for that.   We can't
14236              * make any other length assumptions, as a byte input sequence
14237              * could shrink down. */
14238             Ptrdiff_t current_string_nodes = STR_SZ(max_string_len
14239                                                  + ((! FOLD)
14240                                                     ? 0
14241                                                     : 2 * ((UTF)
14242                                                            ? UTF8_MAXBYTES_CASE
14243                         /* Max non-UTF-8 expansion is 2 */ : 2)));
14244
14245             bool next_is_quantifier;
14246             char * oldp = NULL;
14247
14248             /* We can convert EXACTF nodes to EXACTFU if they contain only
14249              * characters that match identically regardless of the target
14250              * string's UTF8ness.  The reason to do this is that EXACTF is not
14251              * trie-able, EXACTFU is, and EXACTFU requires fewer operations at
14252              * runtime.
14253              *
14254              * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
14255              * contain only above-Latin1 characters (hence must be in UTF8),
14256              * which don't participate in folds with Latin1-range characters,
14257              * as the latter's folds aren't known until runtime. */
14258             bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
14259
14260             /* Single-character EXACTish nodes are almost always SIMPLE.  This
14261              * allows us to override this as encountered */
14262             U8 maybe_SIMPLE = SIMPLE;
14263
14264             /* Does this node contain something that can't match unless the
14265              * target string is (also) in UTF-8 */
14266             bool requires_utf8_target = FALSE;
14267
14268             /* The sequence 'ss' is problematic in non-UTF-8 patterns. */
14269             bool has_ss = FALSE;
14270
14271             /* So is the MICRO SIGN */
14272             bool has_micro_sign = FALSE;
14273
14274             /* Set when we fill up the current node and there is still more
14275              * text to process */
14276             bool overflowed;
14277
14278             /* Allocate an EXACT node.  The node_type may change below to
14279              * another EXACTish node, but since the size of the node doesn't
14280              * change, it works */
14281             ret = regnode_guts(pRExC_state, node_type, current_string_nodes,
14282                                                                     "exact");
14283             FILL_NODE(ret, node_type);
14284             RExC_emit++;
14285
14286             s = STRING(REGNODE_p(ret));
14287
14288             s0 = s;
14289
14290           reparse:
14291
14292             p = RExC_parse;
14293             len = 0;
14294             s = s0;
14295             node_type = EXACT;
14296             oldp = NULL;
14297             maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
14298             maybe_SIMPLE = SIMPLE;
14299             requires_utf8_target = FALSE;
14300             has_ss = FALSE;
14301             has_micro_sign = FALSE;
14302
14303           continue_parse:
14304
14305             /* This breaks under rare circumstances.  If folding, we do not
14306              * want to split a node at a character that is a non-final in a
14307              * multi-char fold, as an input string could just happen to want to
14308              * match across the node boundary.  The code at the end of the loop
14309              * looks for this, and backs off until it finds not such a
14310              * character, but it is possible (though extremely, extremely
14311              * unlikely) for all characters in the node to be non-final fold
14312              * ones, in which case we just leave the node fully filled, and
14313              * hope that it doesn't match the string in just the wrong place */
14314
14315             assert( ! UTF     /* Is at the beginning of a character */
14316                    || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
14317                    || UTF8_IS_START(UCHARAT(RExC_parse)));
14318
14319             overflowed = FALSE;
14320
14321             /* Here, we have a literal character.  Find the maximal string of
14322              * them in the input that we can fit into a single EXACTish node.
14323              * We quit at the first non-literal or when the node gets full, or
14324              * under /i the categorization of folding/non-folding character
14325              * changes */
14326             while (p < RExC_end && len < upper_fill) {
14327
14328                 /* In most cases each iteration adds one byte to the output.
14329                  * The exceptions override this */
14330                 Size_t added_len = 1;
14331
14332                 oldp = p;
14333                 old_old_s = old_s;
14334                 old_s = s;
14335
14336                 /* White space has already been ignored */
14337                 assert(   (RExC_flags & RXf_PMf_EXTENDED) == 0
14338                        || ! is_PATWS_safe((p), RExC_end, UTF));
14339
14340                 switch ((U8)*p) {
14341                   const char* message;
14342                   U32 packed_warn;
14343                   U8 grok_c_char;
14344
14345                 case '^':
14346                 case '$':
14347                 case '.':
14348                 case '[':
14349                 case '(':
14350                 case ')':
14351                 case '|':
14352                     goto loopdone;
14353                 case '\\':
14354                     /* Literal Escapes Switch
14355
14356                        This switch is meant to handle escape sequences that
14357                        resolve to a literal character.
14358
14359                        Every escape sequence that represents something
14360                        else, like an assertion or a char class, is handled
14361                        in the switch marked 'Special Escapes' above in this
14362                        routine, but also has an entry here as anything that
14363                        isn't explicitly mentioned here will be treated as
14364                        an unescaped equivalent literal.
14365                     */
14366
14367                     switch ((U8)*++p) {
14368
14369                     /* These are all the special escapes. */
14370                     case 'A':             /* Start assertion */
14371                     case 'b': case 'B':   /* Word-boundary assertion*/
14372                     case 'C':             /* Single char !DANGEROUS! */
14373                     case 'd': case 'D':   /* digit class */
14374                     case 'g': case 'G':   /* generic-backref, pos assertion */
14375                     case 'h': case 'H':   /* HORIZWS */
14376                     case 'k': case 'K':   /* named backref, keep marker */
14377                     case 'p': case 'P':   /* Unicode property */
14378                               case 'R':   /* LNBREAK */
14379                     case 's': case 'S':   /* space class */
14380                     case 'v': case 'V':   /* VERTWS */
14381                     case 'w': case 'W':   /* word class */
14382                     case 'X':             /* eXtended Unicode "combining
14383                                              character sequence" */
14384                     case 'z': case 'Z':   /* End of line/string assertion */
14385                         --p;
14386                         goto loopdone;
14387
14388                     /* Anything after here is an escape that resolves to a
14389                        literal. (Except digits, which may or may not)
14390                      */
14391                     case 'n':
14392                         ender = '\n';
14393                         p++;
14394                         break;
14395                     case 'N': /* Handle a single-code point named character. */
14396                         RExC_parse = p + 1;
14397                         if (! grok_bslash_N(pRExC_state,
14398                                             NULL,   /* Fail if evaluates to
14399                                                        anything other than a
14400                                                        single code point */
14401                                             &ender, /* The returned single code
14402                                                        point */
14403                                             NULL,   /* Don't need a count of
14404                                                        how many code points */
14405                                             flagp,
14406                                             RExC_strict,
14407                                             depth)
14408                         ) {
14409                             if (*flagp & NEED_UTF8)
14410                                 FAIL("panic: grok_bslash_N set NEED_UTF8");
14411                             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
14412
14413                             /* Here, it wasn't a single code point.  Go close
14414                              * up this EXACTish node.  The switch() prior to
14415                              * this switch handles the other cases */
14416                             RExC_parse = p = oldp;
14417                             goto loopdone;
14418                         }
14419                         p = RExC_parse;
14420                         RExC_parse = parse_start;
14421
14422                         /* The \N{} means the pattern, if previously /d,
14423                          * becomes /u.  That means it can't be an EXACTF node,
14424                          * but an EXACTFU */
14425                         if (node_type == EXACTF) {
14426                             node_type = EXACTFU;
14427
14428                             /* If the node already contains something that
14429                              * differs between EXACTF and EXACTFU, reparse it
14430                              * as EXACTFU */
14431                             if (! maybe_exactfu) {
14432                                 len = 0;
14433                                 s = s0;
14434                                 goto reparse;
14435                             }
14436                         }
14437
14438                         break;
14439                     case 'r':
14440                         ender = '\r';
14441                         p++;
14442                         break;
14443                     case 't':
14444                         ender = '\t';
14445                         p++;
14446                         break;
14447                     case 'f':
14448                         ender = '\f';
14449                         p++;
14450                         break;
14451                     case 'e':
14452                         ender = ESC_NATIVE;
14453                         p++;
14454                         break;
14455                     case 'a':
14456                         ender = '\a';
14457                         p++;
14458                         break;
14459                     case 'o':
14460                         if (! grok_bslash_o(&p,
14461                                             RExC_end,
14462                                             &ender,
14463                                             &message,
14464                                             &packed_warn,
14465                                             (bool) RExC_strict,
14466                                             FALSE, /* No illegal cp's */
14467                                             UTF))
14468                         {
14469                             RExC_parse = p; /* going to die anyway; point to
14470                                                exact spot of failure */
14471                             vFAIL(message);
14472                         }
14473
14474                         if (message && TO_OUTPUT_WARNINGS(p)) {
14475                             warn_non_literal_string(p, packed_warn, message);
14476                         }
14477                         break;
14478                     case 'x':
14479                         if (! grok_bslash_x(&p,
14480                                             RExC_end,
14481                                             &ender,
14482                                             &message,
14483                                             &packed_warn,
14484                                             (bool) RExC_strict,
14485                                             FALSE, /* No illegal cp's */
14486                                             UTF))
14487                         {
14488                             RExC_parse = p;     /* going to die anyway; point
14489                                                    to exact spot of failure */
14490                             vFAIL(message);
14491                         }
14492
14493                         if (message && TO_OUTPUT_WARNINGS(p)) {
14494                             warn_non_literal_string(p, packed_warn, message);
14495                         }
14496
14497 #ifdef EBCDIC
14498                         if (ender < 0x100) {
14499                             if (RExC_recode_x_to_native) {
14500                                 ender = LATIN1_TO_NATIVE(ender);
14501                             }
14502                         }
14503 #endif
14504                         break;
14505                     case 'c':
14506                         p++;
14507                         if (! grok_bslash_c(*p, &grok_c_char,
14508                                             &message, &packed_warn))
14509                         {
14510                             /* going to die anyway; point to exact spot of
14511                              * failure */
14512                             RExC_parse = p + ((UTF)
14513                                               ? UTF8_SAFE_SKIP(p, RExC_end)
14514                                               : 1);
14515                             vFAIL(message);
14516                         }
14517
14518                         ender = grok_c_char;
14519                         p++;
14520                         if (message && TO_OUTPUT_WARNINGS(p)) {
14521                             warn_non_literal_string(p, packed_warn, message);
14522                         }
14523
14524                         break;
14525                     case '8': case '9': /* must be a backreference */
14526                         --p;
14527                         /* we have an escape like \8 which cannot be an octal escape
14528                          * so we exit the loop, and let the outer loop handle this
14529                          * escape which may or may not be a legitimate backref. */
14530                         goto loopdone;
14531                     case '1': case '2': case '3':case '4':
14532                     case '5': case '6': case '7':
14533
14534                         /* When we parse backslash escapes there is ambiguity
14535                          * between backreferences and octal escapes. Any escape
14536                          * from \1 - \9 is a backreference, any multi-digit
14537                          * escape which does not start with 0 and which when
14538                          * evaluated as decimal could refer to an already
14539                          * parsed capture buffer is a back reference. Anything
14540                          * else is octal.
14541                          *
14542                          * Note this implies that \118 could be interpreted as
14543                          * 118 OR as "\11" . "8" depending on whether there
14544                          * were 118 capture buffers defined already in the
14545                          * pattern.  */
14546
14547                         /* NOTE, RExC_npar is 1 more than the actual number of
14548                          * parens we have seen so far, hence the "<" as opposed
14549                          * to "<=" */
14550                         if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
14551                         {  /* Not to be treated as an octal constant, go
14552                                    find backref */
14553                             p = oldp;
14554                             goto loopdone;
14555                         }
14556                         /* FALLTHROUGH */
14557                     case '0':
14558                         {
14559                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT
14560                                       | PERL_SCAN_NOTIFY_ILLDIGIT;
14561                             STRLEN numlen = 3;
14562                             ender = grok_oct(p, &numlen, &flags, NULL);
14563                             p += numlen;
14564                             if (  (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
14565                                 && isDIGIT(*p)  /* like \08, \178 */
14566                                 && ckWARN(WARN_REGEXP))
14567                             {
14568                                 reg_warn_non_literal_string(
14569                                      p + 1,
14570                                      form_alien_digit_msg(8, numlen, p,
14571                                                         RExC_end, UTF, FALSE));
14572                             }
14573                         }
14574                         break;
14575                     case '\0':
14576                         if (p >= RExC_end)
14577                             FAIL("Trailing \\");
14578                         /* FALLTHROUGH */
14579                     default:
14580                         if (isALPHANUMERIC(*p)) {
14581                             /* An alpha followed by '{' is going to fail next
14582                              * iteration, so don't output this warning in that
14583                              * case */
14584                             if (! isALPHA(*p) || *(p + 1) != '{') {
14585                                 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14586                                                   " passed through", p);
14587                             }
14588                         }
14589                         goto normal_default;
14590                     } /* End of switch on '\' */
14591                     break;
14592                 case '{':
14593                     /* Trying to gain new uses for '{' without breaking too
14594                      * much existing code is hard.  The solution currently
14595                      * adopted is:
14596                      *  1)  If there is no ambiguity that a '{' should always
14597                      *      be taken literally, at the start of a construct, we
14598                      *      just do so.
14599                      *  2)  If the literal '{' conflicts with our desired use
14600                      *      of it as a metacharacter, we die.  The deprecation
14601                      *      cycles for this have come and gone.
14602                      *  3)  If there is ambiguity, we raise a simple warning.
14603                      *      This could happen, for example, if the user
14604                      *      intended it to introduce a quantifier, but slightly
14605                      *      misspelled the quantifier.  Without this warning,
14606                      *      the quantifier would silently be taken as a literal
14607                      *      string of characters instead of a meta construct */
14608                     if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14609                         if (      RExC_strict
14610                             || (  p > parse_start + 1
14611                                 && isALPHA_A(*(p - 1))
14612                                 && *(p - 2) == '\\'))
14613                         {
14614                             RExC_parse = p + 1;
14615                             vFAIL("Unescaped left brace in regex is "
14616                                   "illegal here");
14617                         }
14618                         ckWARNreg(p + 1, "Unescaped left brace in regex is"
14619                                          " passed through");
14620                     }
14621                     goto normal_default;
14622                 case '}':
14623                 case ']':
14624                     if (p > RExC_parse && RExC_strict) {
14625                         ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14626                     }
14627                     /*FALLTHROUGH*/
14628                 default:    /* A literal character */
14629                   normal_default:
14630                     if (! UTF8_IS_INVARIANT(*p) && UTF) {
14631                         STRLEN numlen;
14632                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14633                                                &numlen, UTF8_ALLOW_DEFAULT);
14634                         p += numlen;
14635                     }
14636                     else
14637                         ender = (U8) *p++;
14638                     break;
14639                 } /* End of switch on the literal */
14640
14641                 /* Here, have looked at the literal character, and <ender>
14642                  * contains its ordinal; <p> points to the character after it.
14643                  * */
14644
14645                 if (ender > 255) {
14646                     REQUIRE_UTF8(flagp);
14647                     if (   UNICODE_IS_PERL_EXTENDED(ender)
14648                         && TO_OUTPUT_WARNINGS(p))
14649                     {
14650                         ckWARN2_non_literal_string(p,
14651                                                    packWARN(WARN_PORTABLE),
14652                                                    PL_extended_cp_format,
14653                                                    ender);
14654                     }
14655                 }
14656
14657                 /* We need to check if the next non-ignored thing is a
14658                  * quantifier.  Move <p> to after anything that should be
14659                  * ignored, which, as a side effect, positions <p> for the next
14660                  * loop iteration */
14661                 skip_to_be_ignored_text(pRExC_state, &p,
14662                                         FALSE /* Don't force to /x */ );
14663
14664                 /* If the next thing is a quantifier, it applies to this
14665                  * character only, which means that this character has to be in
14666                  * its own node and can't just be appended to the string in an
14667                  * existing node, so if there are already other characters in
14668                  * the node, close the node with just them, and set up to do
14669                  * this character again next time through, when it will be the
14670                  * only thing in its new node */
14671
14672                 next_is_quantifier =    LIKELY(p < RExC_end)
14673                                      && UNLIKELY(isQUANTIFIER(p, RExC_end));
14674
14675                 if (next_is_quantifier && LIKELY(len)) {
14676                     p = oldp;
14677                     goto loopdone;
14678                 }
14679
14680                 /* Ready to add 'ender' to the node */
14681
14682                 if (! FOLD) {  /* The simple case, just append the literal */
14683                   not_fold_common:
14684
14685                     /* Don't output if it would overflow */
14686                     if (UNLIKELY(len > max_string_len - ((UTF)
14687                                                       ? UVCHR_SKIP(ender)
14688                                                       : 1)))
14689                     {
14690                         overflowed = TRUE;
14691                         break;
14692                     }
14693
14694                     if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14695                         *(s++) = (char) ender;
14696                     }
14697                     else {
14698                         U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14699                         added_len = (char *) new_s - s;
14700                         s = (char *) new_s;
14701
14702                         if (ender > 255)  {
14703                             requires_utf8_target = TRUE;
14704                         }
14705                     }
14706                 }
14707                 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14708
14709                     /* Here are folding under /l, and the code point is
14710                      * problematic.  If this is the first character in the
14711                      * node, change the node type to folding.   Otherwise, if
14712                      * this is the first problematic character, close up the
14713                      * existing node, so can start a new node with this one */
14714                     if (! len) {
14715                         node_type = EXACTFL;
14716                         RExC_contains_locale = 1;
14717                     }
14718                     else if (node_type == EXACT) {
14719                         p = oldp;
14720                         goto loopdone;
14721                     }
14722
14723                     /* This problematic code point means we can't simplify
14724                      * things */
14725                     maybe_exactfu = FALSE;
14726
14727                     /* Although these two characters have folds that are
14728                      * locale-problematic, they also have folds to above Latin1
14729                      * that aren't a problem.  Doing these now helps at
14730                      * runtime. */
14731                     if (UNLIKELY(   ender == GREEK_CAPITAL_LETTER_MU
14732                                  || ender == LATIN_CAPITAL_LETTER_SHARP_S))
14733                     {
14734                         goto fold_anyway;
14735                     }
14736
14737                     /* Here, we are adding a problematic fold character.
14738                      * "Problematic" in this context means that its fold isn't
14739                      * known until runtime.  (The non-problematic code points
14740                      * are the above-Latin1 ones that fold to also all
14741                      * above-Latin1.  Their folds don't vary no matter what the
14742                      * locale is.) But here we have characters whose fold
14743                      * depends on the locale.  We just add in the unfolded
14744                      * character, and wait until runtime to fold it */
14745                     goto not_fold_common;
14746                 }
14747                 else /* regular fold; see if actually is in a fold */
14748                      if (   (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14749                          || (ender > 255
14750                             && ! _invlist_contains_cp(PL_in_some_fold, ender)))
14751                 {
14752                     /* Here, folding, but the character isn't in a fold.
14753                      *
14754                      * Start a new node if previous characters in the node were
14755                      * folded */
14756                     if (len && node_type != EXACT) {
14757                         p = oldp;
14758                         goto loopdone;
14759                     }
14760
14761                     /* Here, continuing a node with non-folded characters.  Add
14762                      * this one */
14763                     goto not_fold_common;
14764                 }
14765                 else {  /* Here, does participate in some fold */
14766
14767                     /* If this is the first character in the node, change its
14768                      * type to folding.  Otherwise, if this is the first
14769                      * folding character in the node, close up the existing
14770                      * node, so can start a new node with this one.  */
14771                     if (! len) {
14772                         node_type = compute_EXACTish(pRExC_state);
14773                     }
14774                     else if (node_type == EXACT) {
14775                         p = oldp;
14776                         goto loopdone;
14777                     }
14778
14779                     if (UTF) {  /* Alway use the folded value for UTF-8
14780                                    patterns */
14781                         if (UVCHR_IS_INVARIANT(ender)) {
14782                             if (UNLIKELY(len + 1 > max_string_len)) {
14783                                 overflowed = TRUE;
14784                                 break;
14785                             }
14786
14787                             *(s)++ = (U8) toFOLD(ender);
14788                         }
14789                         else {
14790                             UV folded;
14791
14792                           fold_anyway:
14793                             folded = _to_uni_fold_flags(
14794                                     ender,
14795                                     (U8 *) s,  /* We have allocated extra space
14796                                                   in 's' so can't run off the
14797                                                   end */
14798                                     &added_len,
14799                                     FOLD_FLAGS_FULL
14800                                   | ((   ASCII_FOLD_RESTRICTED
14801                                       || node_type == EXACTFL)
14802                                     ? FOLD_FLAGS_NOMIX_ASCII
14803                                     : 0));
14804                             if (UNLIKELY(len + added_len > max_string_len)) {
14805                                 overflowed = TRUE;
14806                                 break;
14807                             }
14808
14809                             s += added_len;
14810
14811                             if (   folded > 255
14812                                 && LIKELY(folded != GREEK_SMALL_LETTER_MU))
14813                             {
14814                                 /* U+B5 folds to the MU, so its possible for a
14815                                  * non-UTF-8 target to match it */
14816                                 requires_utf8_target = TRUE;
14817                             }
14818                         }
14819                     }
14820                     else { /* Here is non-UTF8. */
14821
14822                         /* The fold will be one or (rarely) two characters.
14823                          * Check that there's room for at least a single one
14824                          * before setting any flags, etc.  Because otherwise an
14825                          * overflowing character could cause a flag to be set
14826                          * even though it doesn't end up in this node.  (For
14827                          * the two character fold, we check again, before
14828                          * setting any flags) */
14829                         if (UNLIKELY(len + 1 > max_string_len)) {
14830                             overflowed = TRUE;
14831                             break;
14832                         }
14833
14834 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
14835    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
14836                                       || UNICODE_DOT_DOT_VERSION > 0)
14837
14838                         /* On non-ancient Unicodes, check for the only possible
14839                          * multi-char fold  */
14840                         if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14841
14842                             /* This potential multi-char fold means the node
14843                              * can't be simple (because it could match more
14844                              * than a single char).  And in some cases it will
14845                              * match 'ss', so set that flag */
14846                             maybe_SIMPLE = 0;
14847                             has_ss = TRUE;
14848
14849                             /* It can't change to be an EXACTFU (unless already
14850                              * is one).  We fold it iff under /u rules. */
14851                             if (node_type != EXACTFU) {
14852                                 maybe_exactfu = FALSE;
14853                             }
14854                             else {
14855                                 if (UNLIKELY(len + 2 > max_string_len)) {
14856                                     overflowed = TRUE;
14857                                     break;
14858                                 }
14859
14860                                 *(s++) = 's';
14861                                 *(s++) = 's';
14862                                 added_len = 2;
14863
14864                                 goto done_with_this_char;
14865                             }
14866                         }
14867                         else if (   UNLIKELY(isALPHA_FOLD_EQ(ender, 's'))
14868                                  && LIKELY(len > 0)
14869                                  && UNLIKELY(isALPHA_FOLD_EQ(*(s-1), 's')))
14870                         {
14871                             /* Also, the sequence 'ss' is special when not
14872                              * under /u.  If the target string is UTF-8, it
14873                              * should match SHARP S; otherwise it won't.  So,
14874                              * here we have to exclude the possibility of this
14875                              * node moving to /u.*/
14876                             has_ss = TRUE;
14877                             maybe_exactfu = FALSE;
14878                         }
14879 #endif
14880                         /* Here, the fold will be a single character */
14881
14882                         if (UNLIKELY(ender == MICRO_SIGN)) {
14883                             has_micro_sign = TRUE;
14884                         }
14885                         else if (PL_fold[ender] != PL_fold_latin1[ender]) {
14886
14887                             /* If the character's fold differs between /d and
14888                              * /u, this can't change to be an EXACTFU node */
14889                             maybe_exactfu = FALSE;
14890                         }
14891
14892                         *(s++) = (DEPENDS_SEMANTICS)
14893                                  ? (char) toFOLD(ender)
14894
14895                                    /* Under /u, the fold of any character in
14896                                     * the 0-255 range happens to be its
14897                                     * lowercase equivalent, except for LATIN
14898                                     * SMALL LETTER SHARP S, which was handled
14899                                     * above, and the MICRO SIGN, whose fold
14900                                     * requires UTF-8 to represent.  */
14901                                  : (char) toLOWER_L1(ender);
14902                     }
14903                 } /* End of adding current character to the node */
14904
14905               done_with_this_char:
14906
14907                 len += added_len;
14908
14909                 if (next_is_quantifier) {
14910
14911                     /* Here, the next input is a quantifier, and to get here,
14912                      * the current character is the only one in the node. */
14913                     goto loopdone;
14914                 }
14915
14916             } /* End of loop through literal characters */
14917
14918             /* Here we have either exhausted the input or run out of room in
14919              * the node.  If the former, we are done.  (If we encountered a
14920              * character that can't be in the node, transfer is made directly
14921              * to <loopdone>, and so we wouldn't have fallen off the end of the
14922              * loop.)  */
14923             if (LIKELY(! overflowed)) {
14924                 goto loopdone;
14925             }
14926
14927             /* Here we have run out of room.  We can grow plain EXACT and
14928              * LEXACT nodes.  If the pattern is gigantic enough, though,
14929              * eventually we'll have to artificially chunk the pattern into
14930              * multiple nodes. */
14931             if (! LOC && (node_type == EXACT || node_type == LEXACT)) {
14932                 Size_t overhead = 1 + regarglen[OP(REGNODE_p(ret))];
14933                 Size_t overhead_expansion = 0;
14934                 char temp[256];
14935                 Size_t max_nodes_for_string;
14936                 Size_t achievable;
14937                 SSize_t delta;
14938
14939                 /* Here we couldn't fit the final character in the current
14940                  * node, so it will have to be reparsed, no matter what else we
14941                  * do */
14942                 p = oldp;
14943
14944                 /* If would have overflowed a regular EXACT node, switch
14945                  * instead to an LEXACT.  The code below is structured so that
14946                  * the actual growing code is common to changing from an EXACT
14947                  * or just increasing the LEXACT size.  This means that we have
14948                  * to save the string in the EXACT case before growing, and
14949                  * then copy it afterwards to its new location */
14950                 if (node_type == EXACT) {
14951                     overhead_expansion = regarglen[LEXACT] - regarglen[EXACT];
14952                     RExC_emit += overhead_expansion;
14953                     Copy(s0, temp, len, char);
14954                 }
14955
14956                 /* Ready to grow.  If it was a plain EXACT, the string was
14957                  * saved, and the first few bytes of it overwritten by adding
14958                  * an argument field.  We assume, as we do elsewhere in this
14959                  * file, that one byte of remaining input will translate into
14960                  * one byte of output, and if that's too small, we grow again,
14961                  * if too large the excess memory is freed at the end */
14962
14963                 max_nodes_for_string = U16_MAX - overhead - overhead_expansion;
14964                 achievable = MIN(max_nodes_for_string,
14965                                  current_string_nodes + STR_SZ(RExC_end - p));
14966                 delta = achievable - current_string_nodes;
14967
14968                 /* If there is just no more room, go finish up this chunk of
14969                  * the pattern. */
14970                 if (delta <= 0) {
14971                     goto loopdone;
14972                 }
14973
14974                 change_engine_size(pRExC_state, delta + overhead_expansion);
14975                 current_string_nodes += delta;
14976                 max_string_len
14977                            = sizeof(struct regnode) * current_string_nodes;
14978                 upper_fill = max_string_len + 1;
14979
14980                 /* If the length was small, we know this was originally an
14981                  * EXACT node now converted to LEXACT, and the string has to be
14982                  * restored.  Otherwise the string was untouched.  260 is just
14983                  * a number safely above 255 so don't have to worry about
14984                  * getting it precise */
14985                 if (len < 260) {
14986                     node_type = LEXACT;
14987                     FILL_NODE(ret, node_type);
14988                     s0 = STRING(REGNODE_p(ret));
14989                     Copy(temp, s0, len, char);
14990                     s = s0 + len;
14991                 }
14992
14993                 goto continue_parse;
14994             }
14995             else if (FOLD) {
14996                 bool splittable = FALSE;
14997                 bool backed_up = FALSE;
14998                 char * e;       /* should this be U8? */
14999                 char * s_start; /* should this be U8? */
15000
15001                 /* Here is /i.  Running out of room creates a problem if we are
15002                  * folding, and the split happens in the middle of a
15003                  * multi-character fold, as a match that should have occurred,
15004                  * won't, due to the way nodes are matched, and our artificial
15005                  * boundary.  So back off until we aren't splitting such a
15006                  * fold.  If there is no such place to back off to, we end up
15007                  * taking the entire node as-is.  This can happen if the node
15008                  * consists entirely of 'f' or entirely of 's' characters (or
15009                  * things that fold to them) as 'ff' and 'ss' are
15010                  * multi-character folds.
15011                  *
15012                  * The Unicode standard says that multi character folds consist
15013                  * of either two or three characters.  That means we would be
15014                  * splitting one if the final character in the node is at the
15015                  * beginning of either type, or is the second of a three
15016                  * character fold.
15017                  *
15018                  * At this point:
15019                  *  ender     is the code point of the character that won't fit
15020                  *            in the node
15021                  *  s         points to just beyond the final byte in the node.
15022                  *            It's where we would place ender if there were
15023                  *            room, and where in fact we do place ender's fold
15024                  *            in the code below, as we've over-allocated space
15025                  *            for s0 (hence s) to allow for this
15026                  *  e         starts at 's' and advances as we append things.
15027                  *  old_s     is the same as 's'.  (If ender had fit, 's' would
15028                  *            have been advanced to beyond it).
15029                  *  old_old_s points to the beginning byte of the final
15030                  *            character in the node
15031                  *  p         points to the beginning byte in the input of the
15032                  *            character beyond 'ender'.
15033                  *  oldp      points to the beginning byte in the input of
15034                  *            'ender'.
15035                  *
15036                  * In the case of /il, we haven't folded anything that could be
15037                  * affected by the locale.  That means only above-Latin1
15038                  * characters that fold to other above-latin1 characters get
15039                  * folded at compile time.  To check where a good place to
15040                  * split nodes is, everything in it will have to be folded.
15041                  * The boolean 'maybe_exactfu' keeps track in /il if there are
15042                  * any unfolded characters in the node. */
15043                 bool need_to_fold_loc = LOC && ! maybe_exactfu;
15044
15045                 /* If we do need to fold the node, we need a place to store the
15046                  * folded copy, and a way to map back to the unfolded original
15047                  * */
15048                 char * locfold_buf = NULL;
15049                 Size_t * loc_correspondence = NULL;
15050
15051                 if (! need_to_fold_loc) {   /* The normal case.  Just
15052                                                initialize to the actual node */
15053                     e = s;
15054                     s_start = s0;
15055                     s = old_old_s;  /* Point to the beginning of the final char
15056                                        that fits in the node */
15057                 }
15058                 else {
15059
15060                     /* Here, we have filled a /il node, and there are unfolded
15061                      * characters in it.  If the runtime locale turns out to be
15062                      * UTF-8, there are possible multi-character folds, just
15063                      * like when not under /l.  The node hence can't terminate
15064                      * in the middle of such a fold.  To determine this, we
15065                      * have to create a folded copy of this node.  That means
15066                      * reparsing the node, folding everything assuming a UTF-8
15067                      * locale.  (If at runtime it isn't such a locale, the
15068                      * actions here wouldn't have been necessary, but we have
15069                      * to assume the worst case.)  If we find we need to back
15070                      * off the folded string, we do so, and then map that
15071                      * position back to the original unfolded node, which then
15072                      * gets output, truncated at that spot */
15073
15074                     char * redo_p = RExC_parse;
15075                     char * redo_e;
15076                     char * old_redo_e;
15077
15078                     /* Allow enough space assuming a single byte input folds to
15079                      * a single byte output, plus assume that the two unparsed
15080                      * characters (that we may need) fold to the largest number
15081                      * of bytes possible, plus extra for one more worst case
15082                      * scenario.  In the loop below, if we start eating into
15083                      * that final spare space, we enlarge this initial space */
15084                     Size_t size = max_string_len + (3 * UTF8_MAXBYTES_CASE) + 1;
15085
15086                     Newxz(locfold_buf, size, char);
15087                     Newxz(loc_correspondence, size, Size_t);
15088
15089                     /* Redo this node's parse, folding into 'locfold_buf' */
15090                     redo_p = RExC_parse;
15091                     old_redo_e = redo_e = locfold_buf;
15092                     while (redo_p <= oldp) {
15093
15094                         old_redo_e = redo_e;
15095                         loc_correspondence[redo_e - locfold_buf]
15096                                                         = redo_p - RExC_parse;
15097
15098                         if (UTF) {
15099                             Size_t added_len;
15100
15101                             (void) _to_utf8_fold_flags((U8 *) redo_p,
15102                                                        (U8 *) RExC_end,
15103                                                        (U8 *) redo_e,
15104                                                        &added_len,
15105                                                        FOLD_FLAGS_FULL);
15106                             redo_e += added_len;
15107                             redo_p += UTF8SKIP(redo_p);
15108                         }
15109                         else {
15110
15111                             /* Note that if this code is run on some ancient
15112                              * Unicode versions, SHARP S doesn't fold to 'ss',
15113                              * but rather than clutter the code with #ifdef's,
15114                              * as is done above, we ignore that possibility.
15115                              * This is ok because this code doesn't affect what
15116                              * gets matched, but merely where the node gets
15117                              * split */
15118                             if (UCHARAT(redo_p) != LATIN_SMALL_LETTER_SHARP_S) {
15119                                 *redo_e++ = toLOWER_L1(UCHARAT(redo_p));
15120                             }
15121                             else {
15122                                 *redo_e++ = 's';
15123                                 *redo_e++ = 's';
15124                             }
15125                             redo_p++;
15126                         }
15127
15128
15129                         /* If we're getting so close to the end that a
15130                          * worst-case fold in the next character would cause us
15131                          * to overflow, increase, assuming one byte output byte
15132                          * per one byte input one, plus room for another worst
15133                          * case fold */
15134                         if (   redo_p <= oldp
15135                             && redo_e > locfold_buf + size
15136                                                     - (UTF8_MAXBYTES_CASE + 1))
15137                         {
15138                             Size_t new_size = size
15139                                             + (oldp - redo_p)
15140                                             + UTF8_MAXBYTES_CASE + 1;
15141                             Ptrdiff_t e_offset = redo_e - locfold_buf;
15142
15143                             Renew(locfold_buf, new_size, char);
15144                             Renew(loc_correspondence, new_size, Size_t);
15145                             size = new_size;
15146
15147                             redo_e = locfold_buf + e_offset;
15148                         }
15149                     }
15150
15151                     /* Set so that things are in terms of the folded, temporary
15152                      * string */
15153                     s = old_redo_e;
15154                     s_start = locfold_buf;
15155                     e = redo_e;
15156
15157                 }
15158
15159                 /* Here, we have 's', 's_start' and 'e' set up to point to the
15160                  * input that goes into the node, folded.
15161                  *
15162                  * If the final character of the node and the fold of ender
15163                  * form the first two characters of a three character fold, we
15164                  * need to peek ahead at the next (unparsed) character in the
15165                  * input to determine if the three actually do form such a
15166                  * fold.  Just looking at that character is not generally
15167                  * sufficient, as it could be, for example, an escape sequence
15168                  * that evaluates to something else, and it needs to be folded.
15169                  *
15170                  * khw originally thought to just go through the parse loop one
15171                  * extra time, but that doesn't work easily as that iteration
15172                  * could cause things to think that the parse is over and to
15173                  * goto loopdone.  The character could be a '$' for example, or
15174                  * the character beyond could be a quantifier, and other
15175                  * glitches as well.
15176                  *
15177                  * The solution used here for peeking ahead is to look at that
15178                  * next character.  If it isn't ASCII punctuation, then it will
15179                  * be something that would continue on in an EXACTish node if
15180                  * there were space.  We append the fold of it to s, having
15181                  * reserved enough room in s0 for the purpose.  If we can't
15182                  * reasonably peek ahead, we instead assume the worst case:
15183                  * that it is something that would form the completion of a
15184                  * multi-char fold.
15185                  *
15186                  * If we can't split between s and ender, we work backwards
15187                  * character-by-character down to s0.  At each current point
15188                  * see if we are at the beginning of a multi-char fold.  If so,
15189                  * that means we would be splitting the fold across nodes, and
15190                  * so we back up one and try again.
15191                  *
15192                  * If we're not at the beginning, we still could be at the
15193                  * final two characters of a (rare) three character fold.  We
15194                  * check if the sequence starting at the character before the
15195                  * current position (and including the current and next
15196                  * characters) is a three character fold.  If not, the node can
15197                  * be split here.  If it is, we have to backup two characters
15198                  * and try again.
15199                  *
15200                  * Otherwise, the node can be split at the current position.
15201                  *
15202                  * The same logic is used for UTF-8 patterns and not */
15203                 if (UTF) {
15204                     Size_t added_len;
15205
15206                     /* Append the fold of ender */
15207                     (void) _to_uni_fold_flags(
15208                         ender,
15209                         (U8 *) e,
15210                         &added_len,
15211                         FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
15212                                         ? FOLD_FLAGS_NOMIX_ASCII
15213                                         : 0));
15214                     e += added_len;
15215
15216                     /* 's' and the character folded to by ender may be the
15217                      * first two of a three-character fold, in which case the
15218                      * node should not be split here.  That may mean examining
15219                      * the so-far unparsed character starting at 'p'.  But if
15220                      * ender folded to more than one character, we already have
15221                      * three characters to look at.  Also, we first check if
15222                      * the sequence consisting of s and the next character form
15223                      * the first two of some three character fold.  If not,
15224                      * there's no need to peek ahead. */
15225                     if (   added_len <= UTF8SKIP(e - added_len)
15226                         && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_utf8_safe(s, e)))
15227                     {
15228                         /* Here, the two do form the beginning of a potential
15229                          * three character fold.  The unexamined character may
15230                          * or may not complete it.  Peek at it.  It might be
15231                          * something that ends the node or an escape sequence,
15232                          * in which case we don't know without a lot of work
15233                          * what it evaluates to, so we have to assume the worst
15234                          * case: that it does complete the fold, and so we
15235                          * can't split here.  All such instances  will have
15236                          * that character be an ASCII punctuation character,
15237                          * like a backslash.  So, for that case, backup one and
15238                          * drop down to try at that position */
15239                         if (isPUNCT(*p)) {
15240                             s = (char *) utf8_hop_back((U8 *) s, -1,
15241                                        (U8 *) s_start);
15242                             backed_up = TRUE;
15243                         }
15244                         else {
15245                             /* Here, since it's not punctuation, it must be a
15246                              * real character, and we can append its fold to
15247                              * 'e' (having deliberately reserved enough space
15248                              * for this eventuality) and drop down to check if
15249                              * the three actually do form a folded sequence */
15250                             (void) _to_utf8_fold_flags(
15251                                 (U8 *) p, (U8 *) RExC_end,
15252                                 (U8 *) e,
15253                                 &added_len,
15254                                 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
15255                                                 ? FOLD_FLAGS_NOMIX_ASCII
15256                                                 : 0));
15257                             e += added_len;
15258                         }
15259                     }
15260
15261                     /* Here, we either have three characters available in
15262                      * sequence starting at 's', or we have two characters and
15263                      * know that the following one can't possibly be part of a
15264                      * three character fold.  We go through the node backwards
15265                      * until we find a place where we can split it without
15266                      * breaking apart a multi-character fold.  At any given
15267                      * point we have to worry about if such a fold begins at
15268                      * the current 's', and also if a three-character fold
15269                      * begins at s-1, (containing s and s+1).  Splitting in
15270                      * either case would break apart a fold */
15271                     do {
15272                         char *prev_s = (char *) utf8_hop_back((U8 *) s, -1,
15273                                                             (U8 *) s_start);
15274
15275                         /* If is a multi-char fold, can't split here.  Backup
15276                          * one char and try again */
15277                         if (UNLIKELY(is_MULTI_CHAR_FOLD_utf8_safe(s, e))) {
15278                             s = prev_s;
15279                             backed_up = TRUE;
15280                             continue;
15281                         }
15282
15283                         /* If the two characters beginning at 's' are part of a
15284                          * three character fold starting at the character
15285                          * before s, we can't split either before or after s.
15286                          * Backup two chars and try again */
15287                         if (   LIKELY(s > s_start)
15288                             && UNLIKELY(is_THREE_CHAR_FOLD_utf8_safe(prev_s, e)))
15289                         {
15290                             s = prev_s;
15291                             s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s_start);
15292                             backed_up = TRUE;
15293                             continue;
15294                         }
15295
15296                         /* Here there's no multi-char fold between s and the
15297                          * next character following it.  We can split */
15298                         splittable = TRUE;
15299                         break;
15300
15301                     } while (s > s_start); /* End of loops backing up through the node */
15302
15303                     /* Here we either couldn't find a place to split the node,
15304                      * or else we broke out of the loop setting 'splittable' to
15305                      * true.  In the latter case, the place to split is between
15306                      * the first and second characters in the sequence starting
15307                      * at 's' */
15308                     if (splittable) {
15309                         s += UTF8SKIP(s);
15310                     }
15311                 }
15312                 else {  /* Pattern not UTF-8 */
15313                     if (   ender != LATIN_SMALL_LETTER_SHARP_S
15314                         || ASCII_FOLD_RESTRICTED)
15315                     {
15316                         assert( toLOWER_L1(ender) < 256 );
15317                         *e++ = (char)(toLOWER_L1(ender)); /* should e and the cast be U8? */
15318                     }
15319                     else {
15320                         *e++ = 's';
15321                         *e++ = 's';
15322                     }
15323
15324                     if (   e - s  <= 1
15325                         && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_latin1_safe(s, e)))
15326                     {
15327                         if (isPUNCT(*p)) {
15328                             s--;
15329                             backed_up = TRUE;
15330                         }
15331                         else {
15332                             if (   UCHARAT(p) != LATIN_SMALL_LETTER_SHARP_S
15333                                 || ASCII_FOLD_RESTRICTED)
15334                             {
15335                                 assert( toLOWER_L1(ender) < 256 );
15336                                 *e++ = (char)(toLOWER_L1(ender)); /* should e and the cast be U8? */
15337                             }
15338                             else {
15339                                 *e++ = 's';
15340                                 *e++ = 's';
15341                             }
15342                         }
15343                     }
15344
15345                     do {
15346                         if (UNLIKELY(is_MULTI_CHAR_FOLD_latin1_safe(s, e))) {
15347                             s--;
15348                             backed_up = TRUE;
15349                             continue;
15350                         }
15351
15352                         if (   LIKELY(s > s_start)
15353                             && UNLIKELY(is_THREE_CHAR_FOLD_latin1_safe(s - 1, e)))
15354                         {
15355                             s -= 2;
15356                             backed_up = TRUE;
15357                             continue;
15358                         }
15359
15360                         splittable = TRUE;
15361                         break;
15362
15363                     } while (s > s_start);
15364
15365                     if (splittable) {
15366                         s++;
15367                     }
15368                 }
15369
15370                 /* Here, we are done backing up.  If we didn't backup at all
15371                  * (the likely case), just proceed */
15372                 if (backed_up) {
15373
15374                    /* If we did find a place to split, reparse the entire node
15375                     * stopping where we have calculated. */
15376                     if (splittable) {
15377
15378                        /* If we created a temporary folded string under /l, we
15379                         * have to map that back to the original */
15380                         if (need_to_fold_loc) {
15381                             upper_fill = loc_correspondence[s - s_start];
15382                             if (upper_fill == 0) {
15383                                 FAIL2("panic: loc_correspondence[%d] is 0",
15384                                       (int) (s - s_start));
15385                             }
15386                             Safefree(locfold_buf);
15387                             Safefree(loc_correspondence);
15388                         }
15389                         else {
15390                             upper_fill = s - s0;
15391                         }
15392                         goto reparse;
15393                     }
15394
15395                     /* Here the node consists entirely of non-final multi-char
15396                      * folds.  (Likely it is all 'f's or all 's's.)  There's no
15397                      * decent place to split it, so give up and just take the
15398                      * whole thing */
15399                     len = old_s - s0;
15400                 }
15401
15402                 if (need_to_fold_loc) {
15403                     Safefree(locfold_buf);
15404                     Safefree(loc_correspondence);
15405                 }
15406             }   /* End of verifying node ends with an appropriate char */
15407
15408             /* We need to start the next node at the character that didn't fit
15409              * in this one */
15410             p = oldp;
15411
15412           loopdone:   /* Jumped to when encounters something that shouldn't be
15413                          in the node */
15414
15415             /* Free up any over-allocated space; cast is to silence bogus
15416              * warning in MS VC */
15417             change_engine_size(pRExC_state,
15418                         - (Ptrdiff_t) (current_string_nodes - STR_SZ(len)));
15419
15420             /* I (khw) don't know if you can get here with zero length, but the
15421              * old code handled this situation by creating a zero-length EXACT
15422              * node.  Might as well be NOTHING instead */
15423             if (len == 0) {
15424                 OP(REGNODE_p(ret)) = NOTHING;
15425             }
15426             else {
15427
15428                 /* If the node type is EXACT here, check to see if it
15429                  * should be EXACTL, or EXACT_REQ8. */
15430                 if (node_type == EXACT) {
15431                     if (LOC) {
15432                         node_type = EXACTL;
15433                     }
15434                     else if (requires_utf8_target) {
15435                         node_type = EXACT_REQ8;
15436                     }
15437                 }
15438                 else if (node_type == LEXACT) {
15439                     if (requires_utf8_target) {
15440                         node_type = LEXACT_REQ8;
15441                     }
15442                 }
15443                 else if (FOLD) {
15444                     if (    UNLIKELY(has_micro_sign || has_ss)
15445                         && (node_type == EXACTFU || (   node_type == EXACTF
15446                                                      && maybe_exactfu)))
15447                     {   /* These two conditions are problematic in non-UTF-8
15448                            EXACTFU nodes. */
15449                         assert(! UTF);
15450                         node_type = EXACTFUP;
15451                     }
15452                     else if (node_type == EXACTFL) {
15453
15454                         /* 'maybe_exactfu' is deliberately set above to
15455                          * indicate this node type, where all code points in it
15456                          * are above 255 */
15457                         if (maybe_exactfu) {
15458                             node_type = EXACTFLU8;
15459                         }
15460                         else if (UNLIKELY(
15461                              _invlist_contains_cp(PL_HasMultiCharFold, ender)))
15462                         {
15463                             /* A character that folds to more than one will
15464                              * match multiple characters, so can't be SIMPLE.
15465                              * We don't have to worry about this with EXACTFLU8
15466                              * nodes just above, as they have already been
15467                              * folded (since the fold doesn't vary at run
15468                              * time).  Here, if the final character in the node
15469                              * folds to multiple, it can't be simple.  (This
15470                              * only has an effect if the node has only a single
15471                              * character, hence the final one, as elsewhere we
15472                              * turn off simple for nodes whose length > 1 */
15473                             maybe_SIMPLE = 0;
15474                         }
15475                     }
15476                     else if (node_type == EXACTF) {  /* Means is /di */
15477
15478                         /* This intermediate variable is needed solely because
15479                          * the asserts in the macro where used exceed Win32's
15480                          * literal string capacity */
15481                         char first_char = * STRING(REGNODE_p(ret));
15482
15483                         /* If 'maybe_exactfu' is clear, then we need to stay
15484                          * /di.  If it is set, it means there are no code
15485                          * points that match differently depending on UTF8ness
15486                          * of the target string, so it can become an EXACTFU
15487                          * node */
15488                         if (! maybe_exactfu) {
15489                             RExC_seen_d_op = TRUE;
15490                         }
15491                         else if (   isALPHA_FOLD_EQ(first_char, 's')
15492                                  || isALPHA_FOLD_EQ(ender, 's'))
15493                         {
15494                             /* But, if the node begins or ends in an 's' we
15495                              * have to defer changing it into an EXACTFU, as
15496                              * the node could later get joined with another one
15497                              * that ends or begins with 's' creating an 'ss'
15498                              * sequence which would then wrongly match the
15499                              * sharp s without the target being UTF-8.  We
15500                              * create a special node that we resolve later when
15501                              * we join nodes together */
15502
15503                             node_type = EXACTFU_S_EDGE;
15504                         }
15505                         else {
15506                             node_type = EXACTFU;
15507                         }
15508                     }
15509
15510                     if (requires_utf8_target && node_type == EXACTFU) {
15511                         node_type = EXACTFU_REQ8;
15512                     }
15513                 }
15514
15515                 OP(REGNODE_p(ret)) = node_type;
15516                 setSTR_LEN(REGNODE_p(ret), len);
15517                 RExC_emit += STR_SZ(len);
15518
15519                 /* If the node isn't a single character, it can't be SIMPLE */
15520                 if (len > (Size_t) ((UTF) ? UTF8SKIP(STRING(REGNODE_p(ret))) : 1)) {
15521                     maybe_SIMPLE = 0;
15522                 }
15523
15524                 *flagp |= HASWIDTH | maybe_SIMPLE;
15525             }
15526
15527             Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
15528             RExC_parse = p;
15529
15530             {
15531                 /* len is STRLEN which is unsigned, need to copy to signed */
15532                 IV iv = len;
15533                 if (iv < 0)
15534                     vFAIL("Internal disaster");
15535             }
15536
15537         } /* End of label 'defchar:' */
15538         break;
15539     } /* End of giant switch on input character */
15540
15541     /* Position parse to next real character */
15542     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15543                                             FALSE /* Don't force to /x */ );
15544     if (   *RExC_parse == '{'
15545         && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse, RExC_end, NULL))
15546     {
15547         if (RExC_strict) {
15548             RExC_parse++;
15549             vFAIL("Unescaped left brace in regex is illegal here");
15550         }
15551         ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
15552                                   " passed through");
15553     }
15554
15555     return(ret);
15556 }
15557
15558
15559 STATIC void
15560 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
15561 {
15562     /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'.  It
15563      * sets up the bitmap and any flags, removing those code points from the
15564      * inversion list, setting it to NULL should it become completely empty */
15565
15566
15567     PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
15568     assert(PL_regkind[OP(node)] == ANYOF);
15569
15570     /* There is no bitmap for this node type */
15571     if (inRANGE(OP(node), ANYOFH, ANYOFRb)) {
15572         return;
15573     }
15574
15575     ANYOF_BITMAP_ZERO(node);
15576     if (*invlist_ptr) {
15577
15578         /* This gets set if we actually need to modify things */
15579         bool change_invlist = FALSE;
15580
15581         UV start, end;
15582
15583         /* Start looking through *invlist_ptr */
15584         invlist_iterinit(*invlist_ptr);
15585         while (invlist_iternext(*invlist_ptr, &start, &end)) {
15586             UV high;
15587             int i;
15588
15589             if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
15590                 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
15591             }
15592
15593             /* Quit if are above what we should change */
15594             if (start >= NUM_ANYOF_CODE_POINTS) {
15595                 break;
15596             }
15597
15598             change_invlist = TRUE;
15599
15600             /* Set all the bits in the range, up to the max that we are doing */
15601             high = (end < NUM_ANYOF_CODE_POINTS - 1)
15602                    ? end
15603                    : NUM_ANYOF_CODE_POINTS - 1;
15604             for (i = start; i <= (int) high; i++) {
15605                 ANYOF_BITMAP_SET(node, i);
15606             }
15607         }
15608         invlist_iterfinish(*invlist_ptr);
15609
15610         /* Done with loop; remove any code points that are in the bitmap from
15611          * *invlist_ptr; similarly for code points above the bitmap if we have
15612          * a flag to match all of them anyways */
15613         if (change_invlist) {
15614             _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
15615         }
15616         if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
15617             _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
15618         }
15619
15620         /* If have completely emptied it, remove it completely */
15621         if (_invlist_len(*invlist_ptr) == 0) {
15622             SvREFCNT_dec_NN(*invlist_ptr);
15623             *invlist_ptr = NULL;
15624         }
15625     }
15626 }
15627
15628 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
15629    Character classes ([:foo:]) can also be negated ([:^foo:]).
15630    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
15631    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
15632    but trigger failures because they are currently unimplemented. */
15633
15634 #define POSIXCC_DONE(c)   ((c) == ':')
15635 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
15636 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
15637 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
15638
15639 #define WARNING_PREFIX              "Assuming NOT a POSIX class since "
15640 #define NO_BLANKS_POSIX_WARNING     "no blanks are allowed in one"
15641 #define SEMI_COLON_POSIX_WARNING    "a semi-colon was found instead of a colon"
15642
15643 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
15644
15645 /* 'posix_warnings' and 'warn_text' are names of variables in the following
15646  * routine. q.v. */
15647 #define ADD_POSIX_WARNING(p, text)  STMT_START {                            \
15648         if (posix_warnings) {                                               \
15649             if (! RExC_warn_text ) RExC_warn_text =                         \
15650                                          (AV *) sv_2mortal((SV *) newAV()); \
15651             av_push(RExC_warn_text, Perl_newSVpvf(aTHX_                     \
15652                                              WARNING_PREFIX                 \
15653                                              text                           \
15654                                              REPORT_LOCATION,               \
15655                                              REPORT_LOCATION_ARGS(p)));     \
15656         }                                                                   \
15657     } STMT_END
15658 #define CLEAR_POSIX_WARNINGS()                                              \
15659     STMT_START {                                                            \
15660         if (posix_warnings && RExC_warn_text)                               \
15661             av_clear(RExC_warn_text);                                       \
15662     } STMT_END
15663
15664 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret)                                \
15665     STMT_START {                                                            \
15666         CLEAR_POSIX_WARNINGS();                                             \
15667         return ret;                                                         \
15668     } STMT_END
15669
15670 STATIC int
15671 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
15672
15673     const char * const s,      /* Where the putative posix class begins.
15674                                   Normally, this is one past the '['.  This
15675                                   parameter exists so it can be somewhere
15676                                   besides RExC_parse. */
15677     char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
15678                                   NULL */
15679     AV ** posix_warnings,      /* Where to place any generated warnings, or
15680                                   NULL */
15681     const bool check_only      /* Don't die if error */
15682 )
15683 {
15684     /* This parses what the caller thinks may be one of the three POSIX
15685      * constructs:
15686      *  1) a character class, like [:blank:]
15687      *  2) a collating symbol, like [. .]
15688      *  3) an equivalence class, like [= =]
15689      * In the latter two cases, it croaks if it finds a syntactically legal
15690      * one, as these are not handled by Perl.
15691      *
15692      * The main purpose is to look for a POSIX character class.  It returns:
15693      *  a) the class number
15694      *      if it is a completely syntactically and semantically legal class.
15695      *      'updated_parse_ptr', if not NULL, is set to point to just after the
15696      *      closing ']' of the class
15697      *  b) OOB_NAMEDCLASS
15698      *      if it appears that one of the three POSIX constructs was meant, but
15699      *      its specification was somehow defective.  'updated_parse_ptr', if
15700      *      not NULL, is set to point to the character just after the end
15701      *      character of the class.  See below for handling of warnings.
15702      *  c) NOT_MEANT_TO_BE_A_POSIX_CLASS
15703      *      if it  doesn't appear that a POSIX construct was intended.
15704      *      'updated_parse_ptr' is not changed.  No warnings nor errors are
15705      *      raised.
15706      *
15707      * In b) there may be errors or warnings generated.  If 'check_only' is
15708      * TRUE, then any errors are discarded.  Warnings are returned to the
15709      * caller via an AV* created into '*posix_warnings' if it is not NULL.  If
15710      * instead it is NULL, warnings are suppressed.
15711      *
15712      * The reason for this function, and its complexity is that a bracketed
15713      * character class can contain just about anything.  But it's easy to
15714      * mistype the very specific posix class syntax but yielding a valid
15715      * regular bracketed class, so it silently gets compiled into something
15716      * quite unintended.
15717      *
15718      * The solution adopted here maintains backward compatibility except that
15719      * it adds a warning if it looks like a posix class was intended but
15720      * improperly specified.  The warning is not raised unless what is input
15721      * very closely resembles one of the 14 legal posix classes.  To do this,
15722      * it uses fuzzy parsing.  It calculates how many single-character edits it
15723      * would take to transform what was input into a legal posix class.  Only
15724      * if that number is quite small does it think that the intention was a
15725      * posix class.  Obviously these are heuristics, and there will be cases
15726      * where it errs on one side or another, and they can be tweaked as
15727      * experience informs.
15728      *
15729      * The syntax for a legal posix class is:
15730      *
15731      * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
15732      *
15733      * What this routine considers syntactically to be an intended posix class
15734      * is this (the comments indicate some restrictions that the pattern
15735      * doesn't show):
15736      *
15737      *  qr/(?x: \[?                         # The left bracket, possibly
15738      *                                      # omitted
15739      *          \h*                         # possibly followed by blanks
15740      *          (?: \^ \h* )?               # possibly a misplaced caret
15741      *          [:;]?                       # The opening class character,
15742      *                                      # possibly omitted.  A typo
15743      *                                      # semi-colon can also be used.
15744      *          \h*
15745      *          \^?                         # possibly a correctly placed
15746      *                                      # caret, but not if there was also
15747      *                                      # a misplaced one
15748      *          \h*
15749      *          .{3,15}                     # The class name.  If there are
15750      *                                      # deviations from the legal syntax,
15751      *                                      # its edit distance must be close
15752      *                                      # to a real class name in order
15753      *                                      # for it to be considered to be
15754      *                                      # an intended posix class.
15755      *          \h*
15756      *          [[:punct:]]?                # The closing class character,
15757      *                                      # possibly omitted.  If not a colon
15758      *                                      # nor semi colon, the class name
15759      *                                      # must be even closer to a valid
15760      *                                      # one
15761      *          \h*
15762      *          \]?                         # The right bracket, possibly
15763      *                                      # omitted.
15764      *     )/
15765      *
15766      * In the above, \h must be ASCII-only.
15767      *
15768      * These are heuristics, and can be tweaked as field experience dictates.
15769      * There will be cases when someone didn't intend to specify a posix class
15770      * that this warns as being so.  The goal is to minimize these, while
15771      * maximizing the catching of things intended to be a posix class that
15772      * aren't parsed as such.
15773      */
15774
15775     const char* p             = s;
15776     const char * const e      = RExC_end;
15777     unsigned complement       = 0;      /* If to complement the class */
15778     bool found_problem        = FALSE;  /* Assume OK until proven otherwise */
15779     bool has_opening_bracket  = FALSE;
15780     bool has_opening_colon    = FALSE;
15781     int class_number          = OOB_NAMEDCLASS; /* Out-of-bounds until find
15782                                                    valid class */
15783     const char * possible_end = NULL;   /* used for a 2nd parse pass */
15784     const char* name_start;             /* ptr to class name first char */
15785
15786     /* If the number of single-character typos the input name is away from a
15787      * legal name is no more than this number, it is considered to have meant
15788      * the legal name */
15789     int max_distance          = 2;
15790
15791     /* to store the name.  The size determines the maximum length before we
15792      * decide that no posix class was intended.  Should be at least
15793      * sizeof("alphanumeric") */
15794     UV input_text[15];
15795     STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
15796
15797     PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
15798
15799     CLEAR_POSIX_WARNINGS();
15800
15801     if (p >= e) {
15802         return NOT_MEANT_TO_BE_A_POSIX_CLASS;
15803     }
15804
15805     if (*(p - 1) != '[') {
15806         ADD_POSIX_WARNING(p, "it doesn't start with a '['");
15807         found_problem = TRUE;
15808     }
15809     else {
15810         has_opening_bracket = TRUE;
15811     }
15812
15813     /* They could be confused and think you can put spaces between the
15814      * components */
15815     if (isBLANK(*p)) {
15816         found_problem = TRUE;
15817
15818         do {
15819             p++;
15820         } while (p < e && isBLANK(*p));
15821
15822         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15823     }
15824
15825     /* For [. .] and [= =].  These are quite different internally from [: :],
15826      * so they are handled separately.  */
15827     if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
15828                                             and 1 for at least one char in it
15829                                           */
15830     {
15831         const char open_char  = *p;
15832         const char * temp_ptr = p + 1;
15833
15834         /* These two constructs are not handled by perl, and if we find a
15835          * syntactically valid one, we croak.  khw, who wrote this code, finds
15836          * this explanation of them very unclear:
15837          * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
15838          * And searching the rest of the internet wasn't very helpful either.
15839          * It looks like just about any byte can be in these constructs,
15840          * depending on the locale.  But unless the pattern is being compiled
15841          * under /l, which is very rare, Perl runs under the C or POSIX locale.
15842          * In that case, it looks like [= =] isn't allowed at all, and that
15843          * [. .] could be any single code point, but for longer strings the
15844          * constituent characters would have to be the ASCII alphabetics plus
15845          * the minus-hyphen.  Any sensible locale definition would limit itself
15846          * to these.  And any portable one definitely should.  Trying to parse
15847          * the general case is a nightmare (see [perl #127604]).  So, this code
15848          * looks only for interiors of these constructs that match:
15849          *      qr/.|[-\w]{2,}/
15850          * Using \w relaxes the apparent rules a little, without adding much
15851          * danger of mistaking something else for one of these constructs.
15852          *
15853          * [. .] in some implementations described on the internet is usable to
15854          * escape a character that otherwise is special in bracketed character
15855          * classes.  For example [.].] means a literal right bracket instead of
15856          * the ending of the class
15857          *
15858          * [= =] can legitimately contain a [. .] construct, but we don't
15859          * handle this case, as that [. .] construct will later get parsed
15860          * itself and croak then.  And [= =] is checked for even when not under
15861          * /l, as Perl has long done so.
15862          *
15863          * The code below relies on there being a trailing NUL, so it doesn't
15864          * have to keep checking if the parse ptr < e.
15865          */
15866         if (temp_ptr[1] == open_char) {
15867             temp_ptr++;
15868         }
15869         else while (    temp_ptr < e
15870                     && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
15871         {
15872             temp_ptr++;
15873         }
15874
15875         if (*temp_ptr == open_char) {
15876             temp_ptr++;
15877             if (*temp_ptr == ']') {
15878                 temp_ptr++;
15879                 if (! found_problem && ! check_only) {
15880                     RExC_parse = (char *) temp_ptr;
15881                     vFAIL3("POSIX syntax [%c %c] is reserved for future "
15882                             "extensions", open_char, open_char);
15883                 }
15884
15885                 /* Here, the syntax wasn't completely valid, or else the call
15886                  * is to check-only */
15887                 if (updated_parse_ptr) {
15888                     *updated_parse_ptr = (char *) temp_ptr;
15889                 }
15890
15891                 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
15892             }
15893         }
15894
15895         /* If we find something that started out to look like one of these
15896          * constructs, but isn't, we continue below so that it can be checked
15897          * for being a class name with a typo of '.' or '=' instead of a colon.
15898          * */
15899     }
15900
15901     /* Here, we think there is a possibility that a [: :] class was meant, and
15902      * we have the first real character.  It could be they think the '^' comes
15903      * first */
15904     if (*p == '^') {
15905         found_problem = TRUE;
15906         ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
15907         complement = 1;
15908         p++;
15909
15910         if (isBLANK(*p)) {
15911             found_problem = TRUE;
15912
15913             do {
15914                 p++;
15915             } while (p < e && isBLANK(*p));
15916
15917             ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15918         }
15919     }
15920
15921     /* But the first character should be a colon, which they could have easily
15922      * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
15923      * distinguish from a colon, so treat that as a colon).  */
15924     if (*p == ':') {
15925         p++;
15926         has_opening_colon = TRUE;
15927     }
15928     else if (*p == ';') {
15929         found_problem = TRUE;
15930         p++;
15931         ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15932         has_opening_colon = TRUE;
15933     }
15934     else {
15935         found_problem = TRUE;
15936         ADD_POSIX_WARNING(p, "there must be a starting ':'");
15937
15938         /* Consider an initial punctuation (not one of the recognized ones) to
15939          * be a left terminator */
15940         if (*p != '^' && *p != ']' && isPUNCT(*p)) {
15941             p++;
15942         }
15943     }
15944
15945     /* They may think that you can put spaces between the components */
15946     if (isBLANK(*p)) {
15947         found_problem = TRUE;
15948
15949         do {
15950             p++;
15951         } while (p < e && isBLANK(*p));
15952
15953         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15954     }
15955
15956     if (*p == '^') {
15957
15958         /* We consider something like [^:^alnum:]] to not have been intended to
15959          * be a posix class, but XXX maybe we should */
15960         if (complement) {
15961             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15962         }
15963
15964         complement = 1;
15965         p++;
15966     }
15967
15968     /* Again, they may think that you can put spaces between the components */
15969     if (isBLANK(*p)) {
15970         found_problem = TRUE;
15971
15972         do {
15973             p++;
15974         } while (p < e && isBLANK(*p));
15975
15976         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15977     }
15978
15979     if (*p == ']') {
15980
15981         /* XXX This ']' may be a typo, and something else was meant.  But
15982          * treating it as such creates enough complications, that that
15983          * possibility isn't currently considered here.  So we assume that the
15984          * ']' is what is intended, and if we've already found an initial '[',
15985          * this leaves this construct looking like [:] or [:^], which almost
15986          * certainly weren't intended to be posix classes */
15987         if (has_opening_bracket) {
15988             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15989         }
15990
15991         /* But this function can be called when we parse the colon for
15992          * something like qr/[alpha:]]/, so we back up to look for the
15993          * beginning */
15994         p--;
15995
15996         if (*p == ';') {
15997             found_problem = TRUE;
15998             ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15999         }
16000         else if (*p != ':') {
16001
16002             /* XXX We are currently very restrictive here, so this code doesn't
16003              * consider the possibility that, say, /[alpha.]]/ was intended to
16004              * be a posix class. */
16005             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16006         }
16007
16008         /* Here we have something like 'foo:]'.  There was no initial colon,
16009          * and we back up over 'foo.  XXX Unlike the going forward case, we
16010          * don't handle typos of non-word chars in the middle */
16011         has_opening_colon = FALSE;
16012         p--;
16013
16014         while (p > RExC_start && isWORDCHAR(*p)) {
16015             p--;
16016         }
16017         p++;
16018
16019         /* Here, we have positioned ourselves to where we think the first
16020          * character in the potential class is */
16021     }
16022
16023     /* Now the interior really starts.  There are certain key characters that
16024      * can end the interior, or these could just be typos.  To catch both
16025      * cases, we may have to do two passes.  In the first pass, we keep on
16026      * going unless we come to a sequence that matches
16027      *      qr/ [[:punct:]] [[:blank:]]* \] /xa
16028      * This means it takes a sequence to end the pass, so two typos in a row if
16029      * that wasn't what was intended.  If the class is perfectly formed, just
16030      * this one pass is needed.  We also stop if there are too many characters
16031      * being accumulated, but this number is deliberately set higher than any
16032      * real class.  It is set high enough so that someone who thinks that
16033      * 'alphanumeric' is a correct name would get warned that it wasn't.
16034      * While doing the pass, we keep track of where the key characters were in
16035      * it.  If we don't find an end to the class, and one of the key characters
16036      * was found, we redo the pass, but stop when we get to that character.
16037      * Thus the key character was considered a typo in the first pass, but a
16038      * terminator in the second.  If two key characters are found, we stop at
16039      * the second one in the first pass.  Again this can miss two typos, but
16040      * catches a single one
16041      *
16042      * In the first pass, 'possible_end' starts as NULL, and then gets set to
16043      * point to the first key character.  For the second pass, it starts as -1.
16044      * */
16045
16046     name_start = p;
16047   parse_name:
16048     {
16049         bool has_blank               = FALSE;
16050         bool has_upper               = FALSE;
16051         bool has_terminating_colon   = FALSE;
16052         bool has_terminating_bracket = FALSE;
16053         bool has_semi_colon          = FALSE;
16054         unsigned int name_len        = 0;
16055         int punct_count              = 0;
16056
16057         while (p < e) {
16058
16059             /* Squeeze out blanks when looking up the class name below */
16060             if (isBLANK(*p) ) {
16061                 has_blank = TRUE;
16062                 found_problem = TRUE;
16063                 p++;
16064                 continue;
16065             }
16066
16067             /* The name will end with a punctuation */
16068             if (isPUNCT(*p)) {
16069                 const char * peek = p + 1;
16070
16071                 /* Treat any non-']' punctuation followed by a ']' (possibly
16072                  * with intervening blanks) as trying to terminate the class.
16073                  * ']]' is very likely to mean a class was intended (but
16074                  * missing the colon), but the warning message that gets
16075                  * generated shows the error position better if we exit the
16076                  * loop at the bottom (eventually), so skip it here. */
16077                 if (*p != ']') {
16078                     if (peek < e && isBLANK(*peek)) {
16079                         has_blank = TRUE;
16080                         found_problem = TRUE;
16081                         do {
16082                             peek++;
16083                         } while (peek < e && isBLANK(*peek));
16084                     }
16085
16086                     if (peek < e && *peek == ']') {
16087                         has_terminating_bracket = TRUE;
16088                         if (*p == ':') {
16089                             has_terminating_colon = TRUE;
16090                         }
16091                         else if (*p == ';') {
16092                             has_semi_colon = TRUE;
16093                             has_terminating_colon = TRUE;
16094                         }
16095                         else {
16096                             found_problem = TRUE;
16097                         }
16098                         p = peek + 1;
16099                         goto try_posix;
16100                     }
16101                 }
16102
16103                 /* Here we have punctuation we thought didn't end the class.
16104                  * Keep track of the position of the key characters that are
16105                  * more likely to have been class-enders */
16106                 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
16107
16108                     /* Allow just one such possible class-ender not actually
16109                      * ending the class. */
16110                     if (possible_end) {
16111                         break;
16112                     }
16113                     possible_end = p;
16114                 }
16115
16116                 /* If we have too many punctuation characters, no use in
16117                  * keeping going */
16118                 if (++punct_count > max_distance) {
16119                     break;
16120                 }
16121
16122                 /* Treat the punctuation as a typo. */
16123                 input_text[name_len++] = *p;
16124                 p++;
16125             }
16126             else if (isUPPER(*p)) { /* Use lowercase for lookup */
16127                 input_text[name_len++] = toLOWER(*p);
16128                 has_upper = TRUE;
16129                 found_problem = TRUE;
16130                 p++;
16131             } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
16132                 input_text[name_len++] = *p;
16133                 p++;
16134             }
16135             else {
16136                 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
16137                 p+= UTF8SKIP(p);
16138             }
16139
16140             /* The declaration of 'input_text' is how long we allow a potential
16141              * class name to be, before saying they didn't mean a class name at
16142              * all */
16143             if (name_len >= C_ARRAY_LENGTH(input_text)) {
16144                 break;
16145             }
16146         }
16147
16148         /* We get to here when the possible class name hasn't been properly
16149          * terminated before:
16150          *   1) we ran off the end of the pattern; or
16151          *   2) found two characters, each of which might have been intended to
16152          *      be the name's terminator
16153          *   3) found so many punctuation characters in the purported name,
16154          *      that the edit distance to a valid one is exceeded
16155          *   4) we decided it was more characters than anyone could have
16156          *      intended to be one. */
16157
16158         found_problem = TRUE;
16159
16160         /* In the final two cases, we know that looking up what we've
16161          * accumulated won't lead to a match, even a fuzzy one. */
16162         if (   name_len >= C_ARRAY_LENGTH(input_text)
16163             || punct_count > max_distance)
16164         {
16165             /* If there was an intermediate key character that could have been
16166              * an intended end, redo the parse, but stop there */
16167             if (possible_end && possible_end != (char *) -1) {
16168                 possible_end = (char *) -1; /* Special signal value to say
16169                                                we've done a first pass */
16170                 p = name_start;
16171                 goto parse_name;
16172             }
16173
16174             /* Otherwise, it can't have meant to have been a class */
16175             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16176         }
16177
16178         /* If we ran off the end, and the final character was a punctuation
16179          * one, back up one, to look at that final one just below.  Later, we
16180          * will restore the parse pointer if appropriate */
16181         if (name_len && p == e && isPUNCT(*(p-1))) {
16182             p--;
16183             name_len--;
16184         }
16185
16186         if (p < e && isPUNCT(*p)) {
16187             if (*p == ']') {
16188                 has_terminating_bracket = TRUE;
16189
16190                 /* If this is a 2nd ']', and the first one is just below this
16191                  * one, consider that to be the real terminator.  This gives a
16192                  * uniform and better positioning for the warning message  */
16193                 if (   possible_end
16194                     && possible_end != (char *) -1
16195                     && *possible_end == ']'
16196                     && name_len && input_text[name_len - 1] == ']')
16197                 {
16198                     name_len--;
16199                     p = possible_end;
16200
16201                     /* And this is actually equivalent to having done the 2nd
16202                      * pass now, so set it to not try again */
16203                     possible_end = (char *) -1;
16204                 }
16205             }
16206             else {
16207                 if (*p == ':') {
16208                     has_terminating_colon = TRUE;
16209                 }
16210                 else if (*p == ';') {
16211                     has_semi_colon = TRUE;
16212                     has_terminating_colon = TRUE;
16213                 }
16214                 p++;
16215             }
16216         }
16217
16218     try_posix:
16219
16220         /* Here, we have a class name to look up.  We can short circuit the
16221          * stuff below for short names that can't possibly be meant to be a
16222          * class name.  (We can do this on the first pass, as any second pass
16223          * will yield an even shorter name) */
16224         if (name_len < 3) {
16225             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16226         }
16227
16228         /* Find which class it is.  Initially switch on the length of the name.
16229          * */
16230         switch (name_len) {
16231             case 4:
16232                 if (memEQs(name_start, 4, "word")) {
16233                     /* this is not POSIX, this is the Perl \w */
16234                     class_number = ANYOF_WORDCHAR;
16235                 }
16236                 break;
16237             case 5:
16238                 /* Names all of length 5: alnum alpha ascii blank cntrl digit
16239                  *                        graph lower print punct space upper
16240                  * Offset 4 gives the best switch position.  */
16241                 switch (name_start[4]) {
16242                     case 'a':
16243                         if (memBEGINs(name_start, 5, "alph")) /* alpha */
16244                             class_number = ANYOF_ALPHA;
16245                         break;
16246                     case 'e':
16247                         if (memBEGINs(name_start, 5, "spac")) /* space */
16248                             class_number = ANYOF_SPACE;
16249                         break;
16250                     case 'h':
16251                         if (memBEGINs(name_start, 5, "grap")) /* graph */
16252                             class_number = ANYOF_GRAPH;
16253                         break;
16254                     case 'i':
16255                         if (memBEGINs(name_start, 5, "asci")) /* ascii */
16256                             class_number = ANYOF_ASCII;
16257                         break;
16258                     case 'k':
16259                         if (memBEGINs(name_start, 5, "blan")) /* blank */
16260                             class_number = ANYOF_BLANK;
16261                         break;
16262                     case 'l':
16263                         if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
16264                             class_number = ANYOF_CNTRL;
16265                         break;
16266                     case 'm':
16267                         if (memBEGINs(name_start, 5, "alnu")) /* alnum */
16268                             class_number = ANYOF_ALPHANUMERIC;
16269                         break;
16270                     case 'r':
16271                         if (memBEGINs(name_start, 5, "lowe")) /* lower */
16272                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
16273                         else if (memBEGINs(name_start, 5, "uppe")) /* upper */
16274                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
16275                         break;
16276                     case 't':
16277                         if (memBEGINs(name_start, 5, "digi")) /* digit */
16278                             class_number = ANYOF_DIGIT;
16279                         else if (memBEGINs(name_start, 5, "prin")) /* print */
16280                             class_number = ANYOF_PRINT;
16281                         else if (memBEGINs(name_start, 5, "punc")) /* punct */
16282                             class_number = ANYOF_PUNCT;
16283                         break;
16284                 }
16285                 break;
16286             case 6:
16287                 if (memEQs(name_start, 6, "xdigit"))
16288                     class_number = ANYOF_XDIGIT;
16289                 break;
16290         }
16291
16292         /* If the name exactly matches a posix class name the class number will
16293          * here be set to it, and the input almost certainly was meant to be a
16294          * posix class, so we can skip further checking.  If instead the syntax
16295          * is exactly correct, but the name isn't one of the legal ones, we
16296          * will return that as an error below.  But if neither of these apply,
16297          * it could be that no posix class was intended at all, or that one
16298          * was, but there was a typo.  We tease these apart by doing fuzzy
16299          * matching on the name */
16300         if (class_number == OOB_NAMEDCLASS && found_problem) {
16301             const UV posix_names[][6] = {
16302                                                 { 'a', 'l', 'n', 'u', 'm' },
16303                                                 { 'a', 'l', 'p', 'h', 'a' },
16304                                                 { 'a', 's', 'c', 'i', 'i' },
16305                                                 { 'b', 'l', 'a', 'n', 'k' },
16306                                                 { 'c', 'n', 't', 'r', 'l' },
16307                                                 { 'd', 'i', 'g', 'i', 't' },
16308                                                 { 'g', 'r', 'a', 'p', 'h' },
16309                                                 { 'l', 'o', 'w', 'e', 'r' },
16310                                                 { 'p', 'r', 'i', 'n', 't' },
16311                                                 { 'p', 'u', 'n', 'c', 't' },
16312                                                 { 's', 'p', 'a', 'c', 'e' },
16313                                                 { 'u', 'p', 'p', 'e', 'r' },
16314                                                 { 'w', 'o', 'r', 'd' },
16315                                                 { 'x', 'd', 'i', 'g', 'i', 't' }
16316                                             };
16317             /* The names of the above all have added NULs to make them the same
16318              * size, so we need to also have the real lengths */
16319             const UV posix_name_lengths[] = {
16320                                                 sizeof("alnum") - 1,
16321                                                 sizeof("alpha") - 1,
16322                                                 sizeof("ascii") - 1,
16323                                                 sizeof("blank") - 1,
16324                                                 sizeof("cntrl") - 1,
16325                                                 sizeof("digit") - 1,
16326                                                 sizeof("graph") - 1,
16327                                                 sizeof("lower") - 1,
16328                                                 sizeof("print") - 1,
16329                                                 sizeof("punct") - 1,
16330                                                 sizeof("space") - 1,
16331                                                 sizeof("upper") - 1,
16332                                                 sizeof("word")  - 1,
16333                                                 sizeof("xdigit")- 1
16334                                             };
16335             unsigned int i;
16336             int temp_max = max_distance;    /* Use a temporary, so if we
16337                                                reparse, we haven't changed the
16338                                                outer one */
16339
16340             /* Use a smaller max edit distance if we are missing one of the
16341              * delimiters */
16342             if (   has_opening_bracket + has_opening_colon < 2
16343                 || has_terminating_bracket + has_terminating_colon < 2)
16344             {
16345                 temp_max--;
16346             }
16347
16348             /* See if the input name is close to a legal one */
16349             for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
16350
16351                 /* Short circuit call if the lengths are too far apart to be
16352                  * able to match */
16353                 if (abs( (int) (name_len - posix_name_lengths[i]))
16354                     > temp_max)
16355                 {
16356                     continue;
16357                 }
16358
16359                 if (edit_distance(input_text,
16360                                   posix_names[i],
16361                                   name_len,
16362                                   posix_name_lengths[i],
16363                                   temp_max
16364                                  )
16365                     > -1)
16366                 { /* If it is close, it probably was intended to be a class */
16367                     goto probably_meant_to_be;
16368                 }
16369             }
16370
16371             /* Here the input name is not close enough to a valid class name
16372              * for us to consider it to be intended to be a posix class.  If
16373              * we haven't already done so, and the parse found a character that
16374              * could have been terminators for the name, but which we absorbed
16375              * as typos during the first pass, repeat the parse, signalling it
16376              * to stop at that character */
16377             if (possible_end && possible_end != (char *) -1) {
16378                 possible_end = (char *) -1;
16379                 p = name_start;
16380                 goto parse_name;
16381             }
16382
16383             /* Here neither pass found a close-enough class name */
16384             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16385         }
16386
16387     probably_meant_to_be:
16388
16389         /* Here we think that a posix specification was intended.  Update any
16390          * parse pointer */
16391         if (updated_parse_ptr) {
16392             *updated_parse_ptr = (char *) p;
16393         }
16394
16395         /* If a posix class name was intended but incorrectly specified, we
16396          * output or return the warnings */
16397         if (found_problem) {
16398
16399             /* We set flags for these issues in the parse loop above instead of
16400              * adding them to the list of warnings, because we can parse it
16401              * twice, and we only want one warning instance */
16402             if (has_upper) {
16403                 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
16404             }
16405             if (has_blank) {
16406                 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
16407             }
16408             if (has_semi_colon) {
16409                 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
16410             }
16411             else if (! has_terminating_colon) {
16412                 ADD_POSIX_WARNING(p, "there is no terminating ':'");
16413             }
16414             if (! has_terminating_bracket) {
16415                 ADD_POSIX_WARNING(p, "there is no terminating ']'");
16416             }
16417
16418             if (   posix_warnings
16419                 && RExC_warn_text
16420                 && av_count(RExC_warn_text) > 0)
16421             {
16422                 *posix_warnings = RExC_warn_text;
16423             }
16424         }
16425         else if (class_number != OOB_NAMEDCLASS) {
16426             /* If it is a known class, return the class.  The class number
16427              * #defines are structured so each complement is +1 to the normal
16428              * one */
16429             CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
16430         }
16431         else if (! check_only) {
16432
16433             /* Here, it is an unrecognized class.  This is an error (unless the
16434             * call is to check only, which we've already handled above) */
16435             const char * const complement_string = (complement)
16436                                                    ? "^"
16437                                                    : "";
16438             RExC_parse = (char *) p;
16439             vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
16440                         complement_string,
16441                         UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
16442         }
16443     }
16444
16445     return OOB_NAMEDCLASS;
16446 }
16447 #undef ADD_POSIX_WARNING
16448
16449 STATIC unsigned  int
16450 S_regex_set_precedence(const U8 my_operator) {
16451
16452     /* Returns the precedence in the (?[...]) construct of the input operator,
16453      * specified by its character representation.  The precedence follows
16454      * general Perl rules, but it extends this so that ')' and ']' have (low)
16455      * precedence even though they aren't really operators */
16456
16457     switch (my_operator) {
16458         case '!':
16459             return 5;
16460         case '&':
16461             return 4;
16462         case '^':
16463         case '|':
16464         case '+':
16465         case '-':
16466             return 3;
16467         case ')':
16468             return 2;
16469         case ']':
16470             return 1;
16471     }
16472
16473     NOT_REACHED; /* NOTREACHED */
16474     return 0;   /* Silence compiler warning */
16475 }
16476
16477 STATIC regnode_offset
16478 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
16479                     I32 *flagp, U32 depth,
16480                     char * const oregcomp_parse)
16481 {
16482     /* Handle the (?[...]) construct to do set operations */
16483
16484     U8 curchar;                     /* Current character being parsed */
16485     UV start, end;                  /* End points of code point ranges */
16486     SV* final = NULL;               /* The end result inversion list */
16487     SV* result_string;              /* 'final' stringified */
16488     AV* stack;                      /* stack of operators and operands not yet
16489                                        resolved */
16490     AV* fence_stack = NULL;         /* A stack containing the positions in
16491                                        'stack' of where the undealt-with left
16492                                        parens would be if they were actually
16493                                        put there */
16494     /* The 'volatile' is a workaround for an optimiser bug
16495      * in Solaris Studio 12.3. See RT #127455 */
16496     volatile IV fence = 0;          /* Position of where most recent undealt-
16497                                        with left paren in stack is; -1 if none.
16498                                      */
16499     STRLEN len;                     /* Temporary */
16500     regnode_offset node;            /* Temporary, and final regnode returned by
16501                                        this function */
16502     const bool save_fold = FOLD;    /* Temporary */
16503     char *save_end, *save_parse;    /* Temporaries */
16504     const bool in_locale = LOC;     /* we turn off /l during processing */
16505
16506     DECLARE_AND_GET_RE_DEBUG_FLAGS;
16507
16508     PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
16509     PERL_UNUSED_ARG(oregcomp_parse); /* Only for Set_Node_Length */
16510
16511     DEBUG_PARSE("xcls");
16512
16513     if (in_locale) {
16514         set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
16515     }
16516
16517     /* The use of this operator implies /u.  This is required so that the
16518      * compile time values are valid in all runtime cases */
16519     REQUIRE_UNI_RULES(flagp, 0);
16520
16521     ckWARNexperimental(RExC_parse,
16522                        WARN_EXPERIMENTAL__REGEX_SETS,
16523                        "The regex_sets feature is experimental");
16524
16525     /* Everything in this construct is a metacharacter.  Operands begin with
16526      * either a '\' (for an escape sequence), or a '[' for a bracketed
16527      * character class.  Any other character should be an operator, or
16528      * parenthesis for grouping.  Both types of operands are handled by calling
16529      * regclass() to parse them.  It is called with a parameter to indicate to
16530      * return the computed inversion list.  The parsing here is implemented via
16531      * a stack.  Each entry on the stack is a single character representing one
16532      * of the operators; or else a pointer to an operand inversion list. */
16533
16534 #define IS_OPERATOR(a) SvIOK(a)
16535 #define IS_OPERAND(a)  (! IS_OPERATOR(a))
16536
16537     /* The stack is kept in Łukasiewicz order.  (That's pronounced similar
16538      * to luke-a-shave-itch (or -itz), but people who didn't want to bother
16539      * with pronouncing it called it Reverse Polish instead, but now that YOU
16540      * know how to pronounce it you can use the correct term, thus giving due
16541      * credit to the person who invented it, and impressing your geek friends.
16542      * Wikipedia says that the pronounciation of "Ł" has been changing so that
16543      * it is now more like an English initial W (as in wonk) than an L.)
16544      *
16545      * This means that, for example, 'a | b & c' is stored on the stack as
16546      *
16547      * c  [4]
16548      * b  [3]
16549      * &  [2]
16550      * a  [1]
16551      * |  [0]
16552      *
16553      * where the numbers in brackets give the stack [array] element number.
16554      * In this implementation, parentheses are not stored on the stack.
16555      * Instead a '(' creates a "fence" so that the part of the stack below the
16556      * fence is invisible except to the corresponding ')' (this allows us to
16557      * replace testing for parens, by using instead subtraction of the fence
16558      * position).  As new operands are processed they are pushed onto the stack
16559      * (except as noted in the next paragraph).  New operators of higher
16560      * precedence than the current final one are inserted on the stack before
16561      * the lhs operand (so that when the rhs is pushed next, everything will be
16562      * in the correct positions shown above.  When an operator of equal or
16563      * lower precedence is encountered in parsing, all the stacked operations
16564      * of equal or higher precedence are evaluated, leaving the result as the
16565      * top entry on the stack.  This makes higher precedence operations
16566      * evaluate before lower precedence ones, and causes operations of equal
16567      * precedence to left associate.
16568      *
16569      * The only unary operator '!' is immediately pushed onto the stack when
16570      * encountered.  When an operand is encountered, if the top of the stack is
16571      * a '!", the complement is immediately performed, and the '!' popped.  The
16572      * resulting value is treated as a new operand, and the logic in the
16573      * previous paragraph is executed.  Thus in the expression
16574      *      [a] + ! [b]
16575      * the stack looks like
16576      *
16577      * !
16578      * a
16579      * +
16580      *
16581      * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
16582      * becomes
16583      *
16584      * !b
16585      * a
16586      * +
16587      *
16588      * A ')' is treated as an operator with lower precedence than all the
16589      * aforementioned ones, which causes all operations on the stack above the
16590      * corresponding '(' to be evaluated down to a single resultant operand.
16591      * Then the fence for the '(' is removed, and the operand goes through the
16592      * algorithm above, without the fence.
16593      *
16594      * A separate stack is kept of the fence positions, so that the position of
16595      * the latest so-far unbalanced '(' is at the top of it.
16596      *
16597      * The ']' ending the construct is treated as the lowest operator of all,
16598      * so that everything gets evaluated down to a single operand, which is the
16599      * result */
16600
16601     sv_2mortal((SV *)(stack = newAV()));
16602     sv_2mortal((SV *)(fence_stack = newAV()));
16603
16604     while (RExC_parse < RExC_end) {
16605         I32 top_index;              /* Index of top-most element in 'stack' */
16606         SV** top_ptr;               /* Pointer to top 'stack' element */
16607         SV* current = NULL;         /* To contain the current inversion list
16608                                        operand */
16609         SV* only_to_avoid_leaks;
16610
16611         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
16612                                 TRUE /* Force /x */ );
16613         if (RExC_parse >= RExC_end) {   /* Fail */
16614             break;
16615         }
16616
16617         curchar = UCHARAT(RExC_parse);
16618
16619 redo_curchar:
16620
16621 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16622                     /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
16623         DEBUG_U(dump_regex_sets_structures(pRExC_state,
16624                                            stack, fence, fence_stack));
16625 #endif
16626
16627         top_index = av_tindex_skip_len_mg(stack);
16628
16629         switch (curchar) {
16630             SV** stacked_ptr;       /* Ptr to something already on 'stack' */
16631             char stacked_operator;  /* The topmost operator on the 'stack'. */
16632             SV* lhs;                /* Operand to the left of the operator */
16633             SV* rhs;                /* Operand to the right of the operator */
16634             SV* fence_ptr;          /* Pointer to top element of the fence
16635                                        stack */
16636             case '(':
16637
16638                 if (   RExC_parse < RExC_end - 2
16639                     && UCHARAT(RExC_parse + 1) == '?'
16640                     && UCHARAT(RExC_parse + 2) == '^')
16641                 {
16642                     const regnode_offset orig_emit = RExC_emit;
16643                     SV * resultant_invlist;
16644
16645                     /* If is a '(?^', could be an embedded '(?^flags:(?[...])'.
16646                      * This happens when we have some thing like
16647                      *
16648                      *   my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
16649                      *   ...
16650                      *   qr/(?[ \p{Digit} & $thai_or_lao ])/;
16651                      *
16652                      * Here we would be handling the interpolated
16653                      * '$thai_or_lao'.  We handle this by a recursive call to
16654                      * reg which returns the inversion list the
16655                      * interpolated expression evaluates to.  Actually, the
16656                      * return is a special regnode containing a pointer to that
16657                      * inversion list.  If the return isn't that regnode alone,
16658                      * we know that this wasn't such an interpolation, which is
16659                      * an error: we need to get a single inversion list back
16660                      * from the recursion */
16661
16662                     RExC_parse++;
16663                     RExC_sets_depth++;
16664
16665                     node = reg(pRExC_state, 2, flagp, depth+1);
16666                     RETURN_FAIL_ON_RESTART(*flagp, flagp);
16667
16668                     if (   OP(REGNODE_p(node)) != REGEX_SET
16669                            /* If more than a single node returned, the nested
16670                             * parens evaluated to more than just a (?[...]),
16671                             * which isn't legal */
16672                         || RExC_emit != orig_emit
16673                                       + NODE_STEP_REGNODE
16674                                       + regarglen[REGEX_SET])
16675                     {
16676                         vFAIL("Expecting interpolated extended charclass");
16677                     }
16678                     resultant_invlist = (SV *) ARGp(REGNODE_p(node));
16679                     current = invlist_clone(resultant_invlist, NULL);
16680                     SvREFCNT_dec(resultant_invlist);
16681
16682                     RExC_sets_depth--;
16683                     RExC_emit = orig_emit;
16684                     goto handle_operand;
16685                 }
16686
16687                 /* A regular '('.  Look behind for illegal syntax */
16688                 if (top_index - fence >= 0) {
16689                     /* If the top entry on the stack is an operator, it had
16690                      * better be a '!', otherwise the entry below the top
16691                      * operand should be an operator */
16692                     if (   ! (top_ptr = av_fetch(stack, top_index, FALSE))
16693                         || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
16694                         || (   IS_OPERAND(*top_ptr)
16695                             && (   top_index - fence < 1
16696                                 || ! (stacked_ptr = av_fetch(stack,
16697                                                              top_index - 1,
16698                                                              FALSE))
16699                                 || ! IS_OPERATOR(*stacked_ptr))))
16700                     {
16701                         RExC_parse++;
16702                         vFAIL("Unexpected '(' with no preceding operator");
16703                     }
16704                 }
16705
16706                 /* Stack the position of this undealt-with left paren */
16707                 av_push(fence_stack, newSViv(fence));
16708                 fence = top_index + 1;
16709                 break;
16710
16711             case '\\':
16712                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16713                  * multi-char folds are allowed.  */
16714                 if (!regclass(pRExC_state, flagp, depth+1,
16715                               TRUE, /* means parse just the next thing */
16716                               FALSE, /* don't allow multi-char folds */
16717                               FALSE, /* don't silence non-portable warnings.  */
16718                               TRUE,  /* strict */
16719                               FALSE, /* Require return to be an ANYOF */
16720                               &current))
16721                 {
16722                     RETURN_FAIL_ON_RESTART(*flagp, flagp);
16723                     goto regclass_failed;
16724                 }
16725
16726                 assert(current);
16727
16728                 /* regclass() will return with parsing just the \ sequence,
16729                  * leaving the parse pointer at the next thing to parse */
16730                 RExC_parse--;
16731                 goto handle_operand;
16732
16733             case '[':   /* Is a bracketed character class */
16734             {
16735                 /* See if this is a [:posix:] class. */
16736                 bool is_posix_class = (OOB_NAMEDCLASS
16737                             < handle_possible_posix(pRExC_state,
16738                                                 RExC_parse + 1,
16739                                                 NULL,
16740                                                 NULL,
16741                                                 TRUE /* checking only */));
16742                 /* If it is a posix class, leave the parse pointer at the '['
16743                  * to fool regclass() into thinking it is part of a
16744                  * '[[:posix:]]'. */
16745                 if (! is_posix_class) {
16746                     RExC_parse++;
16747                 }
16748
16749                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16750                  * multi-char folds are allowed.  */
16751                 if (!regclass(pRExC_state, flagp, depth+1,
16752                                 is_posix_class, /* parse the whole char
16753                                                     class only if not a
16754                                                     posix class */
16755                                 FALSE, /* don't allow multi-char folds */
16756                                 TRUE, /* silence non-portable warnings. */
16757                                 TRUE, /* strict */
16758                                 FALSE, /* Require return to be an ANYOF */
16759                                 &current))
16760                 {
16761                     RETURN_FAIL_ON_RESTART(*flagp, flagp);
16762                     goto regclass_failed;
16763                 }
16764
16765                 assert(current);
16766
16767                 /* function call leaves parse pointing to the ']', except if we
16768                  * faked it */
16769                 if (is_posix_class) {
16770                     RExC_parse--;
16771                 }
16772
16773                 goto handle_operand;
16774             }
16775
16776             case ']':
16777                 if (top_index >= 1) {
16778                     goto join_operators;
16779                 }
16780
16781                 /* Only a single operand on the stack: are done */
16782                 goto done;
16783
16784             case ')':
16785                 if (av_tindex_skip_len_mg(fence_stack) < 0) {
16786                     if (UCHARAT(RExC_parse - 1) == ']')  {
16787                         break;
16788                     }
16789                     RExC_parse++;
16790                     vFAIL("Unexpected ')'");
16791                 }
16792
16793                 /* If nothing after the fence, is missing an operand */
16794                 if (top_index - fence < 0) {
16795                     RExC_parse++;
16796                     goto bad_syntax;
16797                 }
16798                 /* If at least two things on the stack, treat this as an
16799                   * operator */
16800                 if (top_index - fence >= 1) {
16801                     goto join_operators;
16802                 }
16803
16804                 /* Here only a single thing on the fenced stack, and there is a
16805                  * fence.  Get rid of it */
16806                 fence_ptr = av_pop(fence_stack);
16807                 assert(fence_ptr);
16808                 fence = SvIV(fence_ptr);
16809                 SvREFCNT_dec_NN(fence_ptr);
16810                 fence_ptr = NULL;
16811
16812                 if (fence < 0) {
16813                     fence = 0;
16814                 }
16815
16816                 /* Having gotten rid of the fence, we pop the operand at the
16817                  * stack top and process it as a newly encountered operand */
16818                 current = av_pop(stack);
16819                 if (IS_OPERAND(current)) {
16820                     goto handle_operand;
16821                 }
16822
16823                 RExC_parse++;
16824                 goto bad_syntax;
16825
16826             case '&':
16827             case '|':
16828             case '+':
16829             case '-':
16830             case '^':
16831
16832                 /* These binary operators should have a left operand already
16833                  * parsed */
16834                 if (   top_index - fence < 0
16835                     || top_index - fence == 1
16836                     || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
16837                     || ! IS_OPERAND(*top_ptr))
16838                 {
16839                     goto unexpected_binary;
16840                 }
16841
16842                 /* If only the one operand is on the part of the stack visible
16843                  * to us, we just place this operator in the proper position */
16844                 if (top_index - fence < 2) {
16845
16846                     /* Place the operator before the operand */
16847
16848                     SV* lhs = av_pop(stack);
16849                     av_push(stack, newSVuv(curchar));
16850                     av_push(stack, lhs);
16851                     break;
16852                 }
16853
16854                 /* But if there is something else on the stack, we need to
16855                  * process it before this new operator if and only if the
16856                  * stacked operation has equal or higher precedence than the
16857                  * new one */
16858
16859              join_operators:
16860
16861                 /* The operator on the stack is supposed to be below both its
16862                  * operands */
16863                 if (   ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
16864                     || IS_OPERAND(*stacked_ptr))
16865                 {
16866                     /* But if not, it's legal and indicates we are completely
16867                      * done if and only if we're currently processing a ']',
16868                      * which should be the final thing in the expression */
16869                     if (curchar == ']') {
16870                         goto done;
16871                     }
16872
16873                   unexpected_binary:
16874                     RExC_parse++;
16875                     vFAIL2("Unexpected binary operator '%c' with no "
16876                            "preceding operand", curchar);
16877                 }
16878                 stacked_operator = (char) SvUV(*stacked_ptr);
16879
16880                 if (regex_set_precedence(curchar)
16881                     > regex_set_precedence(stacked_operator))
16882                 {
16883                     /* Here, the new operator has higher precedence than the
16884                      * stacked one.  This means we need to add the new one to
16885                      * the stack to await its rhs operand (and maybe more
16886                      * stuff).  We put it before the lhs operand, leaving
16887                      * untouched the stacked operator and everything below it
16888                      * */
16889                     lhs = av_pop(stack);
16890                     assert(IS_OPERAND(lhs));
16891
16892                     av_push(stack, newSVuv(curchar));
16893                     av_push(stack, lhs);
16894                     break;
16895                 }
16896
16897                 /* Here, the new operator has equal or lower precedence than
16898                  * what's already there.  This means the operation already
16899                  * there should be performed now, before the new one. */
16900
16901                 rhs = av_pop(stack);
16902                 if (! IS_OPERAND(rhs)) {
16903
16904                     /* This can happen when a ! is not followed by an operand,
16905                      * like in /(?[\t &!])/ */
16906                     goto bad_syntax;
16907                 }
16908
16909                 lhs = av_pop(stack);
16910
16911                 if (! IS_OPERAND(lhs)) {
16912
16913                     /* This can happen when there is an empty (), like in
16914                      * /(?[[0]+()+])/ */
16915                     goto bad_syntax;
16916                 }
16917
16918                 switch (stacked_operator) {
16919                     case '&':
16920                         _invlist_intersection(lhs, rhs, &rhs);
16921                         break;
16922
16923                     case '|':
16924                     case '+':
16925                         _invlist_union(lhs, rhs, &rhs);
16926                         break;
16927
16928                     case '-':
16929                         _invlist_subtract(lhs, rhs, &rhs);
16930                         break;
16931
16932                     case '^':   /* The union minus the intersection */
16933                     {
16934                         SV* i = NULL;
16935                         SV* u = NULL;
16936
16937                         _invlist_union(lhs, rhs, &u);
16938                         _invlist_intersection(lhs, rhs, &i);
16939                         _invlist_subtract(u, i, &rhs);
16940                         SvREFCNT_dec_NN(i);
16941                         SvREFCNT_dec_NN(u);
16942                         break;
16943                     }
16944                 }
16945                 SvREFCNT_dec(lhs);
16946
16947                 /* Here, the higher precedence operation has been done, and the
16948                  * result is in 'rhs'.  We overwrite the stacked operator with
16949                  * the result.  Then we redo this code to either push the new
16950                  * operator onto the stack or perform any higher precedence
16951                  * stacked operation */
16952                 only_to_avoid_leaks = av_pop(stack);
16953                 SvREFCNT_dec(only_to_avoid_leaks);
16954                 av_push(stack, rhs);
16955                 goto redo_curchar;
16956
16957             case '!':   /* Highest priority, right associative */
16958
16959                 /* If what's already at the top of the stack is another '!",
16960                  * they just cancel each other out */
16961                 if (   (top_ptr = av_fetch(stack, top_index, FALSE))
16962                     && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
16963                 {
16964                     only_to_avoid_leaks = av_pop(stack);
16965                     SvREFCNT_dec(only_to_avoid_leaks);
16966                 }
16967                 else { /* Otherwise, since it's right associative, just push
16968                           onto the stack */
16969                     av_push(stack, newSVuv(curchar));
16970                 }
16971                 break;
16972
16973             default:
16974                 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16975                 if (RExC_parse >= RExC_end) {
16976                     break;
16977                 }
16978                 vFAIL("Unexpected character");
16979
16980           handle_operand:
16981
16982             /* Here 'current' is the operand.  If something is already on the
16983              * stack, we have to check if it is a !.  But first, the code above
16984              * may have altered the stack in the time since we earlier set
16985              * 'top_index'.  */
16986
16987             top_index = av_tindex_skip_len_mg(stack);
16988             if (top_index - fence >= 0) {
16989                 /* If the top entry on the stack is an operator, it had better
16990                  * be a '!', otherwise the entry below the top operand should
16991                  * be an operator */
16992                 top_ptr = av_fetch(stack, top_index, FALSE);
16993                 assert(top_ptr);
16994                 if (IS_OPERATOR(*top_ptr)) {
16995
16996                     /* The only permissible operator at the top of the stack is
16997                      * '!', which is applied immediately to this operand. */
16998                     curchar = (char) SvUV(*top_ptr);
16999                     if (curchar != '!') {
17000                         SvREFCNT_dec(current);
17001                         vFAIL2("Unexpected binary operator '%c' with no "
17002                                 "preceding operand", curchar);
17003                     }
17004
17005                     _invlist_invert(current);
17006
17007                     only_to_avoid_leaks = av_pop(stack);
17008                     SvREFCNT_dec(only_to_avoid_leaks);
17009
17010                     /* And we redo with the inverted operand.  This allows
17011                      * handling multiple ! in a row */
17012                     goto handle_operand;
17013                 }
17014                           /* Single operand is ok only for the non-binary ')'
17015                            * operator */
17016                 else if ((top_index - fence == 0 && curchar != ')')
17017                          || (top_index - fence > 0
17018                              && (! (stacked_ptr = av_fetch(stack,
17019                                                            top_index - 1,
17020                                                            FALSE))
17021                                  || IS_OPERAND(*stacked_ptr))))
17022                 {
17023                     SvREFCNT_dec(current);
17024                     vFAIL("Operand with no preceding operator");
17025                 }
17026             }
17027
17028             /* Here there was nothing on the stack or the top element was
17029              * another operand.  Just add this new one */
17030             av_push(stack, current);
17031
17032         } /* End of switch on next parse token */
17033
17034         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
17035     } /* End of loop parsing through the construct */
17036
17037     vFAIL("Syntax error in (?[...])");
17038
17039   done:
17040
17041     if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
17042         if (RExC_parse < RExC_end) {
17043             RExC_parse++;
17044         }
17045
17046         vFAIL("Unexpected ']' with no following ')' in (?[...");
17047     }
17048
17049     if (av_tindex_skip_len_mg(fence_stack) >= 0) {
17050         vFAIL("Unmatched (");
17051     }
17052
17053     if (av_tindex_skip_len_mg(stack) < 0   /* Was empty */
17054         || ((final = av_pop(stack)) == NULL)
17055         || ! IS_OPERAND(final)
17056         || ! is_invlist(final)
17057         || av_tindex_skip_len_mg(stack) >= 0)  /* More left on stack */
17058     {
17059       bad_syntax:
17060         SvREFCNT_dec(final);
17061         vFAIL("Incomplete expression within '(?[ ])'");
17062     }
17063
17064     /* Here, 'final' is the resultant inversion list from evaluating the
17065      * expression.  Return it if so requested */
17066     if (return_invlist) {
17067         *return_invlist = final;
17068         return END;
17069     }
17070
17071     if (RExC_sets_depth) {  /* If within a recursive call, return in a special
17072                                regnode */
17073         RExC_parse++;
17074         node = regpnode(pRExC_state, REGEX_SET, final);
17075     }
17076     else {
17077
17078         /* Otherwise generate a resultant node, based on 'final'.  regclass()
17079          * is expecting a string of ranges and individual code points */
17080         invlist_iterinit(final);
17081         result_string = newSVpvs("");
17082         while (invlist_iternext(final, &start, &end)) {
17083             if (start == end) {
17084                 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
17085             }
17086             else {
17087                 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%"
17088                                                         UVXf "}", start, end);
17089             }
17090         }
17091
17092         /* About to generate an ANYOF (or similar) node from the inversion list
17093          * we have calculated */
17094         save_parse = RExC_parse;
17095         RExC_parse = SvPV(result_string, len);
17096         save_end = RExC_end;
17097         RExC_end = RExC_parse + len;
17098         TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
17099
17100         /* We turn off folding around the call, as the class we have
17101          * constructed already has all folding taken into consideration, and we
17102          * don't want regclass() to add to that */
17103         RExC_flags &= ~RXf_PMf_FOLD;
17104         /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
17105          * folds are allowed.  */
17106         node = regclass(pRExC_state, flagp, depth+1,
17107                         FALSE, /* means parse the whole char class */
17108                         FALSE, /* don't allow multi-char folds */
17109                         TRUE, /* silence non-portable warnings.  The above may
17110                                  very well have generated non-portable code
17111                                  points, but they're valid on this machine */
17112                         FALSE, /* similarly, no need for strict */
17113
17114                         /* We can optimize into something besides an ANYOF,
17115                          * except under /l, which needs to be ANYOF because of
17116                          * runtime checks for locale sanity, etc */
17117                     ! in_locale,
17118                         NULL
17119                     );
17120
17121         RESTORE_WARNINGS;
17122         RExC_parse = save_parse + 1;
17123         RExC_end = save_end;
17124         SvREFCNT_dec_NN(final);
17125         SvREFCNT_dec_NN(result_string);
17126
17127         if (save_fold) {
17128             RExC_flags |= RXf_PMf_FOLD;
17129         }
17130
17131         if (!node) {
17132             RETURN_FAIL_ON_RESTART(*flagp, flagp);
17133             goto regclass_failed;
17134         }
17135
17136         /* Fix up the node type if we are in locale.  (We have pretended we are
17137          * under /u for the purposes of regclass(), as this construct will only
17138          * work under UTF-8 locales.  But now we change the opcode to be ANYOFL
17139          * (so as to cause any warnings about bad locales to be output in
17140          * regexec.c), and add the flag that indicates to check if not in a
17141          * UTF-8 locale.  The reason we above forbid optimization into
17142          * something other than an ANYOF node is simply to minimize the number
17143          * of code changes in regexec.c.  Otherwise we would have to create new
17144          * EXACTish node types and deal with them.  This decision could be
17145          * revisited should this construct become popular.
17146          *
17147          * (One might think we could look at the resulting ANYOF node and
17148          * suppress the flag if everything is above 255, as those would be
17149          * UTF-8 only, but this isn't true, as the components that led to that
17150          * result could have been locale-affected, and just happen to cancel
17151          * each other out under UTF-8 locales.) */
17152         if (in_locale) {
17153             set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
17154
17155             assert(OP(REGNODE_p(node)) == ANYOF);
17156
17157             OP(REGNODE_p(node)) = ANYOFL;
17158             ANYOF_FLAGS(REGNODE_p(node))
17159                     |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
17160         }
17161     }
17162
17163     nextchar(pRExC_state);
17164     Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
17165     return node;
17166
17167   regclass_failed:
17168     FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf,
17169                                                                 (UV) *flagp);
17170 }
17171
17172 #ifdef ENABLE_REGEX_SETS_DEBUGGING
17173
17174 STATIC void
17175 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
17176                              AV * stack, const IV fence, AV * fence_stack)
17177 {   /* Dumps the stacks in handle_regex_sets() */
17178
17179     const SSize_t stack_top = av_tindex_skip_len_mg(stack);
17180     const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
17181     SSize_t i;
17182
17183     PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
17184
17185     PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
17186
17187     if (stack_top < 0) {
17188         PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
17189     }
17190     else {
17191         PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
17192         for (i = stack_top; i >= 0; i--) {
17193             SV ** element_ptr = av_fetch(stack, i, FALSE);
17194             if (! element_ptr) {
17195             }
17196
17197             if (IS_OPERATOR(*element_ptr)) {
17198                 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
17199                                             (int) i, (int) SvIV(*element_ptr));
17200             }
17201             else {
17202                 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
17203                 sv_dump(*element_ptr);
17204             }
17205         }
17206     }
17207
17208     if (fence_stack_top < 0) {
17209         PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
17210     }
17211     else {
17212         PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
17213         for (i = fence_stack_top; i >= 0; i--) {
17214             SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
17215             if (! element_ptr) {
17216             }
17217
17218             PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
17219                                             (int) i, (int) SvIV(*element_ptr));
17220         }
17221     }
17222 }
17223
17224 #endif
17225
17226 #undef IS_OPERATOR
17227 #undef IS_OPERAND
17228
17229 STATIC void
17230 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
17231 {
17232     /* This adds the Latin1/above-Latin1 folding rules.
17233      *
17234      * This should be called only for a Latin1-range code points, cp, which is
17235      * known to be involved in a simple fold with other code points above
17236      * Latin1.  It would give false results if /aa has been specified.
17237      * Multi-char folds are outside the scope of this, and must be handled
17238      * specially. */
17239
17240     PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
17241
17242     assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
17243
17244     /* The rules that are valid for all Unicode versions are hard-coded in */
17245     switch (cp) {
17246         case 'k':
17247         case 'K':
17248           *invlist =
17249              add_cp_to_invlist(*invlist, KELVIN_SIGN);
17250             break;
17251         case 's':
17252         case 'S':
17253           *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
17254             break;
17255         case MICRO_SIGN:
17256           *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
17257           *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
17258             break;
17259         case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
17260         case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
17261           *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
17262             break;
17263         case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
17264           *invlist = add_cp_to_invlist(*invlist,
17265                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
17266             break;
17267
17268         default:    /* Other code points are checked against the data for the
17269                        current Unicode version */
17270           {
17271             Size_t folds_count;
17272             U32 first_fold;
17273             const U32 * remaining_folds;
17274             UV folded_cp;
17275
17276             if (isASCII(cp)) {
17277                 folded_cp = toFOLD(cp);
17278             }
17279             else {
17280                 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
17281                 Size_t dummy_len;
17282                 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
17283             }
17284
17285             if (folded_cp > 255) {
17286                 *invlist = add_cp_to_invlist(*invlist, folded_cp);
17287             }
17288
17289             folds_count = _inverse_folds(folded_cp, &first_fold,
17290                                                     &remaining_folds);
17291             if (folds_count == 0) {
17292
17293                 /* Use deprecated warning to increase the chances of this being
17294                  * output */
17295                 ckWARN2reg_d(RExC_parse,
17296                         "Perl folding rules are not up-to-date for 0x%02X;"
17297                         " please use the perlbug utility to report;", cp);
17298             }
17299             else {
17300                 unsigned int i;
17301
17302                 if (first_fold > 255) {
17303                     *invlist = add_cp_to_invlist(*invlist, first_fold);
17304                 }
17305                 for (i = 0; i < folds_count - 1; i++) {
17306                     if (remaining_folds[i] > 255) {
17307                         *invlist = add_cp_to_invlist(*invlist,
17308                                                     remaining_folds[i]);
17309                     }
17310                 }
17311             }
17312             break;
17313          }
17314     }
17315 }
17316
17317 STATIC void
17318 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
17319 {
17320     /* Output the elements of the array given by '*posix_warnings' as REGEXP
17321      * warnings. */
17322
17323     SV * msg;
17324     const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
17325
17326     PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
17327
17328     if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
17329         CLEAR_POSIX_WARNINGS();
17330         return;
17331     }
17332
17333     while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
17334         if (first_is_fatal) {           /* Avoid leaking this */
17335             av_undef(posix_warnings);   /* This isn't necessary if the
17336                                             array is mortal, but is a
17337                                             fail-safe */
17338             (void) sv_2mortal(msg);
17339             PREPARE_TO_DIE;
17340         }
17341         Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
17342         SvREFCNT_dec_NN(msg);
17343     }
17344
17345     UPDATE_WARNINGS_LOC(RExC_parse);
17346 }
17347
17348 PERL_STATIC_INLINE Size_t
17349 S_find_first_differing_byte_pos(const U8 * s1, const U8 * s2, const Size_t max)
17350 {
17351     const U8 * const start = s1;
17352     const U8 * const send = start + max;
17353
17354     PERL_ARGS_ASSERT_FIND_FIRST_DIFFERING_BYTE_POS;
17355
17356     while (s1 < send && *s1  == *s2) {
17357         s1++; s2++;
17358     }
17359
17360     return s1 - start;
17361 }
17362
17363
17364 STATIC AV *
17365 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
17366 {
17367     /* This adds the string scalar <multi_string> to the array
17368      * <multi_char_matches>.  <multi_string> is known to have exactly
17369      * <cp_count> code points in it.  This is used when constructing a
17370      * bracketed character class and we find something that needs to match more
17371      * than a single character.
17372      *
17373      * <multi_char_matches> is actually an array of arrays.  Each top-level
17374      * element is an array that contains all the strings known so far that are
17375      * the same length.  And that length (in number of code points) is the same
17376      * as the index of the top-level array.  Hence, the [2] element is an
17377      * array, each element thereof is a string containing TWO code points;
17378      * while element [3] is for strings of THREE characters, and so on.  Since
17379      * this is for multi-char strings there can never be a [0] nor [1] element.
17380      *
17381      * When we rewrite the character class below, we will do so such that the
17382      * longest strings are written first, so that it prefers the longest
17383      * matching strings first.  This is done even if it turns out that any
17384      * quantifier is non-greedy, out of this programmer's (khw) laziness.  Tom
17385      * Christiansen has agreed that this is ok.  This makes the test for the
17386      * ligature 'ffi' come before the test for 'ff', for example */
17387
17388     AV* this_array;
17389     AV** this_array_ptr;
17390
17391     PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
17392
17393     if (! multi_char_matches) {
17394         multi_char_matches = newAV();
17395     }
17396
17397     if (av_exists(multi_char_matches, cp_count)) {
17398         this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
17399         this_array = *this_array_ptr;
17400     }
17401     else {
17402         this_array = newAV();
17403         av_store(multi_char_matches, cp_count,
17404                  (SV*) this_array);
17405     }
17406     av_push(this_array, multi_string);
17407
17408     return multi_char_matches;
17409 }
17410
17411 /* The names of properties whose definitions are not known at compile time are
17412  * stored in this SV, after a constant heading.  So if the length has been
17413  * changed since initialization, then there is a run-time definition. */
17414 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION                            \
17415                                         (SvCUR(listsv) != initial_listsv_len)
17416
17417 /* There is a restricted set of white space characters that are legal when
17418  * ignoring white space in a bracketed character class.  This generates the
17419  * code to skip them.
17420  *
17421  * There is a line below that uses the same white space criteria but is outside
17422  * this macro.  Both here and there must use the same definition */
17423 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p, stop_p)                  \
17424     STMT_START {                                                        \
17425         if (do_skip) {                                                  \
17426             while (p < stop_p && isBLANK_A(UCHARAT(p)))                 \
17427             {                                                           \
17428                 p++;                                                    \
17429             }                                                           \
17430         }                                                               \
17431     } STMT_END
17432
17433 STATIC regnode_offset
17434 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
17435                  const bool stop_at_1,  /* Just parse the next thing, don't
17436                                            look for a full character class */
17437                  bool allow_mutiple_chars,
17438                  const bool silence_non_portable,   /* Don't output warnings
17439                                                        about too large
17440                                                        characters */
17441                  const bool strict,
17442                  bool optimizable,                  /* ? Allow a non-ANYOF return
17443                                                        node */
17444                  SV** ret_invlist  /* Return an inversion list, not a node */
17445           )
17446 {
17447     /* parse a bracketed class specification.  Most of these will produce an
17448      * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
17449      * EXACTFish node; [[:ascii:]], a POSIXA node; etc.  It is more complex
17450      * under /i with multi-character folds: it will be rewritten following the
17451      * paradigm of this example, where the <multi-fold>s are characters which
17452      * fold to multiple character sequences:
17453      *      /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
17454      * gets effectively rewritten as:
17455      *      /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
17456      * reg() gets called (recursively) on the rewritten version, and this
17457      * function will return what it constructs.  (Actually the <multi-fold>s
17458      * aren't physically removed from the [abcdefghi], it's just that they are
17459      * ignored in the recursion by means of a flag:
17460      * <RExC_in_multi_char_class>.)
17461      *
17462      * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
17463      * characters, with the corresponding bit set if that character is in the
17464      * list.  For characters above this, an inversion list is used.  There
17465      * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
17466      * determinable at compile time
17467      *
17468      * On success, returns the offset at which any next node should be placed
17469      * into the regex engine program being compiled.
17470      *
17471      * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
17472      * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
17473      * UTF-8
17474      */
17475
17476     UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
17477     IV range = 0;
17478     UV value = OOB_UNICODE, save_value = OOB_UNICODE;
17479     regnode_offset ret = -1;    /* Initialized to an illegal value */
17480     STRLEN numlen;
17481     int namedclass = OOB_NAMEDCLASS;
17482     char *rangebegin = NULL;
17483     SV *listsv = NULL;      /* List of \p{user-defined} whose definitions
17484                                aren't available at the time this was called */
17485     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
17486                                       than just initialized.  */
17487     SV* properties = NULL;    /* Code points that match \p{} \P{} */
17488     SV* posixes = NULL;     /* Code points that match classes like [:word:],
17489                                extended beyond the Latin1 range.  These have to
17490                                be kept separate from other code points for much
17491                                of this function because their handling  is
17492                                different under /i, and for most classes under
17493                                /d as well */
17494     SV* nposixes = NULL;    /* Similarly for [:^word:].  These are kept
17495                                separate for a while from the non-complemented
17496                                versions because of complications with /d
17497                                matching */
17498     SV* simple_posixes = NULL; /* But under some conditions, the classes can be
17499                                   treated more simply than the general case,
17500                                   leading to less compilation and execution
17501                                   work */
17502     UV element_count = 0;   /* Number of distinct elements in the class.
17503                                Optimizations may be possible if this is tiny */
17504     AV * multi_char_matches = NULL; /* Code points that fold to more than one
17505                                        character; used under /i */
17506     UV n;
17507     char * stop_ptr = RExC_end;    /* where to stop parsing */
17508
17509     /* ignore unescaped whitespace? */
17510     const bool skip_white = cBOOL(   ret_invlist
17511                                   || (RExC_flags & RXf_PMf_EXTENDED_MORE));
17512
17513     /* inversion list of code points this node matches only when the target
17514      * string is in UTF-8.  These are all non-ASCII, < 256.  (Because is under
17515      * /d) */
17516     SV* upper_latin1_only_utf8_matches = NULL;
17517
17518     /* Inversion list of code points this node matches regardless of things
17519      * like locale, folding, utf8ness of the target string */
17520     SV* cp_list = NULL;
17521
17522     /* Like cp_list, but code points on this list need to be checked for things
17523      * that fold to/from them under /i */
17524     SV* cp_foldable_list = NULL;
17525
17526     /* Like cp_list, but code points on this list are valid only when the
17527      * runtime locale is UTF-8 */
17528     SV* only_utf8_locale_list = NULL;
17529
17530     /* In a range, if one of the endpoints is non-character-set portable,
17531      * meaning that it hard-codes a code point that may mean a different
17532      * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
17533      * mnemonic '\t' which each mean the same character no matter which
17534      * character set the platform is on. */
17535     unsigned int non_portable_endpoint = 0;
17536
17537     /* Is the range unicode? which means on a platform that isn't 1-1 native
17538      * to Unicode (i.e. non-ASCII), each code point in it should be considered
17539      * to be a Unicode value.  */
17540     bool unicode_range = FALSE;
17541     bool invert = FALSE;    /* Is this class to be complemented */
17542
17543     bool warn_super = ALWAYS_WARN_SUPER;
17544
17545     const char * orig_parse = RExC_parse;
17546
17547     /* This variable is used to mark where the end in the input is of something
17548      * that looks like a POSIX construct but isn't.  During the parse, when
17549      * something looks like it could be such a construct is encountered, it is
17550      * checked for being one, but not if we've already checked this area of the
17551      * input.  Only after this position is reached do we check again */
17552     char *not_posix_region_end = RExC_parse - 1;
17553
17554     AV* posix_warnings = NULL;
17555     const bool do_posix_warnings = ckWARN(WARN_REGEXP);
17556     U8 op = ANYOF;    /* The returned node-type, initialized to the expected
17557                          type. */
17558     U8 anyof_flags = 0;   /* flag bits if the node is an ANYOF-type */
17559     U32 posixl = 0;       /* bit field of posix classes matched under /l */
17560
17561
17562 /* Flags as to what things aren't knowable until runtime.  (Note that these are
17563  * mutually exclusive.) */
17564 #define HAS_USER_DEFINED_PROPERTY 0x01   /* /u any user-defined properties that
17565                                             haven't been defined as of yet */
17566 #define HAS_D_RUNTIME_DEPENDENCY  0x02   /* /d if the target being matched is
17567                                             UTF-8 or not */
17568 #define HAS_L_RUNTIME_DEPENDENCY   0x04 /* /l what the posix classes match and
17569                                             what gets folded */
17570     U32 has_runtime_dependency = 0;     /* OR of the above flags */
17571
17572     DECLARE_AND_GET_RE_DEBUG_FLAGS;
17573
17574     PERL_ARGS_ASSERT_REGCLASS;
17575 #ifndef DEBUGGING
17576     PERL_UNUSED_ARG(depth);
17577 #endif
17578
17579     assert(! (ret_invlist && allow_mutiple_chars));
17580
17581     /* If wants an inversion list returned, we can't optimize to something
17582      * else. */
17583     if (ret_invlist) {
17584         optimizable = FALSE;
17585     }
17586
17587     DEBUG_PARSE("clas");
17588
17589 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */      \
17590     || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0          \
17591                                    && UNICODE_DOT_DOT_VERSION == 0)
17592     allow_mutiple_chars = FALSE;
17593 #endif
17594
17595     /* We include the /i status at the beginning of this so that we can
17596      * know it at runtime */
17597     listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
17598     initial_listsv_len = SvCUR(listsv);
17599     SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated.  */
17600
17601     SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse, RExC_end);
17602
17603     assert(RExC_parse <= RExC_end);
17604
17605     if (UCHARAT(RExC_parse) == '^') {   /* Complement the class */
17606         RExC_parse++;
17607         invert = TRUE;
17608         allow_mutiple_chars = FALSE;
17609         MARK_NAUGHTY(1);
17610         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse, RExC_end);
17611     }
17612
17613     /* Check that they didn't say [:posix:] instead of [[:posix:]] */
17614     if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
17615         int maybe_class = handle_possible_posix(pRExC_state,
17616                                                 RExC_parse,
17617                                                 &not_posix_region_end,
17618                                                 NULL,
17619                                                 TRUE /* checking only */);
17620         if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
17621             ckWARN4reg(not_posix_region_end,
17622                     "POSIX syntax [%c %c] belongs inside character classes%s",
17623                     *RExC_parse, *RExC_parse,
17624                     (maybe_class == OOB_NAMEDCLASS)
17625                     ? ((POSIXCC_NOTYET(*RExC_parse))
17626                         ? " (but this one isn't implemented)"
17627                         : " (but this one isn't fully valid)")
17628                     : ""
17629                     );
17630         }
17631     }
17632
17633     /* If the caller wants us to just parse a single element, accomplish this
17634      * by faking the loop ending condition */
17635     if (stop_at_1 && RExC_end > RExC_parse) {
17636         stop_ptr = RExC_parse + 1;
17637     }
17638
17639     /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
17640     if (UCHARAT(RExC_parse) == ']')
17641         goto charclassloop;
17642
17643     while (1) {
17644
17645         if (   posix_warnings
17646             && av_tindex_skip_len_mg(posix_warnings) >= 0
17647             && RExC_parse > not_posix_region_end)
17648         {
17649             /* Warnings about posix class issues are considered tentative until
17650              * we are far enough along in the parse that we can no longer
17651              * change our mind, at which point we output them.  This is done
17652              * each time through the loop so that a later class won't zap them
17653              * before they have been dealt with. */
17654             output_posix_warnings(pRExC_state, posix_warnings);
17655         }
17656
17657         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse, RExC_end);
17658
17659         if  (RExC_parse >= stop_ptr) {
17660             break;
17661         }
17662
17663         if  (UCHARAT(RExC_parse) == ']') {
17664             break;
17665         }
17666
17667       charclassloop:
17668
17669         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
17670         save_value = value;
17671         save_prevvalue = prevvalue;
17672
17673         if (!range) {
17674             rangebegin = RExC_parse;
17675             element_count++;
17676             non_portable_endpoint = 0;
17677         }
17678         if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
17679             value = utf8n_to_uvchr((U8*)RExC_parse,
17680                                    RExC_end - RExC_parse,
17681                                    &numlen, UTF8_ALLOW_DEFAULT);
17682             RExC_parse += numlen;
17683         }
17684         else
17685             value = UCHARAT(RExC_parse++);
17686
17687         if (value == '[') {
17688             char * posix_class_end;
17689             namedclass = handle_possible_posix(pRExC_state,
17690                                                RExC_parse,
17691                                                &posix_class_end,
17692                                                do_posix_warnings ? &posix_warnings : NULL,
17693                                                FALSE    /* die if error */);
17694             if (namedclass > OOB_NAMEDCLASS) {
17695
17696                 /* If there was an earlier attempt to parse this particular
17697                  * posix class, and it failed, it was a false alarm, as this
17698                  * successful one proves */
17699                 if (   posix_warnings
17700                     && av_tindex_skip_len_mg(posix_warnings) >= 0
17701                     && not_posix_region_end >= RExC_parse
17702                     && not_posix_region_end <= posix_class_end)
17703                 {
17704                     av_undef(posix_warnings);
17705                 }
17706
17707                 RExC_parse = posix_class_end;
17708             }
17709             else if (namedclass == OOB_NAMEDCLASS) {
17710                 not_posix_region_end = posix_class_end;
17711             }
17712             else {
17713                 namedclass = OOB_NAMEDCLASS;
17714             }
17715         }
17716         else if (   RExC_parse - 1 > not_posix_region_end
17717                  && MAYBE_POSIXCC(value))
17718         {
17719             (void) handle_possible_posix(
17720                         pRExC_state,
17721                         RExC_parse - 1,  /* -1 because parse has already been
17722                                             advanced */
17723                         &not_posix_region_end,
17724                         do_posix_warnings ? &posix_warnings : NULL,
17725                         TRUE /* checking only */);
17726         }
17727         else if (  strict && ! skip_white
17728                  && (   _generic_isCC(value, _CC_VERTSPACE)
17729                      || is_VERTWS_cp_high(value)))
17730         {
17731             vFAIL("Literal vertical space in [] is illegal except under /x");
17732         }
17733         else if (value == '\\') {
17734             /* Is a backslash; get the code point of the char after it */
17735
17736             if (RExC_parse >= RExC_end) {
17737                 vFAIL("Unmatched [");
17738             }
17739
17740             if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
17741                 value = utf8n_to_uvchr((U8*)RExC_parse,
17742                                    RExC_end - RExC_parse,
17743                                    &numlen, UTF8_ALLOW_DEFAULT);
17744                 RExC_parse += numlen;
17745             }
17746             else
17747                 value = UCHARAT(RExC_parse++);
17748
17749             /* Some compilers cannot handle switching on 64-bit integer
17750              * values, therefore value cannot be an UV.  Yes, this will
17751              * be a problem later if we want switch on Unicode.
17752              * A similar issue a little bit later when switching on
17753              * namedclass. --jhi */
17754
17755             /* If the \ is escaping white space when white space is being
17756              * skipped, it means that that white space is wanted literally, and
17757              * is already in 'value'.  Otherwise, need to translate the escape
17758              * into what it signifies. */
17759             if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
17760                 const char * message;
17761                 U32 packed_warn;
17762                 U8 grok_c_char;
17763
17764             case 'w':   namedclass = ANYOF_WORDCHAR;    break;
17765             case 'W':   namedclass = ANYOF_NWORDCHAR;   break;
17766             case 's':   namedclass = ANYOF_SPACE;       break;
17767             case 'S':   namedclass = ANYOF_NSPACE;      break;
17768             case 'd':   namedclass = ANYOF_DIGIT;       break;
17769             case 'D':   namedclass = ANYOF_NDIGIT;      break;
17770             case 'v':   namedclass = ANYOF_VERTWS;      break;
17771             case 'V':   namedclass = ANYOF_NVERTWS;     break;
17772             case 'h':   namedclass = ANYOF_HORIZWS;     break;
17773             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
17774             case 'N':  /* Handle \N{NAME} in class */
17775                 {
17776                     const char * const backslash_N_beg = RExC_parse - 2;
17777                     int cp_count;
17778
17779                     if (! grok_bslash_N(pRExC_state,
17780                                         NULL,      /* No regnode */
17781                                         &value,    /* Yes single value */
17782                                         &cp_count, /* Multiple code pt count */
17783                                         flagp,
17784                                         strict,
17785                                         depth)
17786                     ) {
17787
17788                         if (*flagp & NEED_UTF8)
17789                             FAIL("panic: grok_bslash_N set NEED_UTF8");
17790
17791                         RETURN_FAIL_ON_RESTART_FLAGP(flagp);
17792
17793                         if (cp_count < 0) {
17794                             vFAIL("\\N in a character class must be a named character: \\N{...}");
17795                         }
17796                         else if (cp_count == 0) {
17797                             ckWARNreg(RExC_parse,
17798                               "Ignoring zero length \\N{} in character class");
17799                         }
17800                         else { /* cp_count > 1 */
17801                             assert(cp_count > 1);
17802                             if (! RExC_in_multi_char_class) {
17803                                 if ( ! allow_mutiple_chars
17804                                     || invert
17805                                     || range
17806                                     || *RExC_parse == '-')
17807                                 {
17808                                     if (strict) {
17809                                         RExC_parse--;
17810                                         vFAIL("\\N{} here is restricted to one character");
17811                                     }
17812                                     ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
17813                                     break; /* <value> contains the first code
17814                                               point. Drop out of the switch to
17815                                               process it */
17816                                 }
17817                                 else {
17818                                     SV * multi_char_N = newSVpvn(backslash_N_beg,
17819                                                  RExC_parse - backslash_N_beg);
17820                                     multi_char_matches
17821                                         = add_multi_match(multi_char_matches,
17822                                                           multi_char_N,
17823                                                           cp_count);
17824                                 }
17825                             }
17826                         } /* End of cp_count != 1 */
17827
17828                         /* This element should not be processed further in this
17829                          * class */
17830                         element_count--;
17831                         value = save_value;
17832                         prevvalue = save_prevvalue;
17833                         continue;   /* Back to top of loop to get next char */
17834                     }
17835
17836                     /* Here, is a single code point, and <value> contains it */
17837                     unicode_range = TRUE;   /* \N{} are Unicode */
17838                 }
17839                 break;
17840             case 'p':
17841             case 'P':
17842                 {
17843                 char *e;
17844
17845                 if (RExC_pm_flags & PMf_WILDCARD) {
17846                     RExC_parse++;
17847                     /* diag_listed_as: Use of %s is not allowed in Unicode
17848                        property wildcard subpatterns in regex; marked by <--
17849                        HERE in m/%s/ */
17850                     vFAIL3("Use of '\\%c%c' is not allowed in Unicode property"
17851                            " wildcard subpatterns", (char) value, *(RExC_parse - 1));
17852                 }
17853
17854                 /* \p means they want Unicode semantics */
17855                 REQUIRE_UNI_RULES(flagp, 0);
17856
17857                 if (RExC_parse >= RExC_end)
17858                     vFAIL2("Empty \\%c", (U8)value);
17859                 if (*RExC_parse == '{') {
17860                     const U8 c = (U8)value;
17861                     e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
17862                     if (!e) {
17863                         RExC_parse++;
17864                         vFAIL2("Missing right brace on \\%c{}", c);
17865                     }
17866
17867                     RExC_parse++;
17868
17869                     /* White space is allowed adjacent to the braces and after
17870                      * any '^', even when not under /x */
17871                     while (isSPACE(*RExC_parse)) {
17872                          RExC_parse++;
17873                     }
17874
17875                     if (UCHARAT(RExC_parse) == '^') {
17876
17877                         /* toggle.  (The rhs xor gets the single bit that
17878                          * differs between P and p; the other xor inverts just
17879                          * that bit) */
17880                         value ^= 'P' ^ 'p';
17881
17882                         RExC_parse++;
17883                         while (isSPACE(*RExC_parse)) {
17884                             RExC_parse++;
17885                         }
17886                     }
17887
17888                     if (e == RExC_parse)
17889                         vFAIL2("Empty \\%c{}", c);
17890
17891                     n = e - RExC_parse;
17892                     while (isSPACE(*(RExC_parse + n - 1)))
17893                         n--;
17894
17895                 }   /* The \p isn't immediately followed by a '{' */
17896                 else if (! isALPHA(*RExC_parse)) {
17897                     RExC_parse += (UTF)
17898                                   ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17899                                   : 1;
17900                     vFAIL2("Character following \\%c must be '{' or a "
17901                            "single-character Unicode property name",
17902                            (U8) value);
17903                 }
17904                 else {
17905                     e = RExC_parse;
17906                     n = 1;
17907                 }
17908                 {
17909                     char* name = RExC_parse;
17910
17911                     /* Any message returned about expanding the definition */
17912                     SV* msg = newSVpvs_flags("", SVs_TEMP);
17913
17914                     /* If set TRUE, the property is user-defined as opposed to
17915                      * official Unicode */
17916                     bool user_defined = FALSE;
17917                     AV * strings = NULL;
17918
17919                     SV * prop_definition = parse_uniprop_string(
17920                                             name, n, UTF, FOLD,
17921                                             FALSE, /* This is compile-time */
17922
17923                                             /* We can't defer this defn when
17924                                              * the full result is required in
17925                                              * this call */
17926                                             ! cBOOL(ret_invlist),
17927
17928                                             &strings,
17929                                             &user_defined,
17930                                             msg,
17931                                             0 /* Base level */
17932                                            );
17933                     if (SvCUR(msg)) {   /* Assumes any error causes a msg */
17934                         assert(prop_definition == NULL);
17935                         RExC_parse = e + 1;
17936                         if (SvUTF8(msg)) {  /* msg being UTF-8 makes the whole
17937                                                thing so, or else the display is
17938                                                mojibake */
17939                             RExC_utf8 = TRUE;
17940                         }
17941                         /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
17942                         vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
17943                                     SvCUR(msg), SvPVX(msg)));
17944                     }
17945
17946                     assert(prop_definition || strings);
17947
17948                     if (strings) {
17949                         if (ret_invlist) {
17950                             if (! prop_definition) {
17951                                 RExC_parse = e + 1;
17952                                 vFAIL("Unicode string properties are not implemented in (?[...])");
17953                             }
17954                             else {
17955                                 ckWARNreg(e + 1,
17956                                     "Using just the single character results"
17957                                     " returned by \\p{} in (?[...])");
17958                             }
17959                         }
17960                         else if (! RExC_in_multi_char_class) {
17961                             if (invert ^ (value == 'P')) {
17962                                 RExC_parse = e + 1;
17963                                 vFAIL("Inverting a character class which contains"
17964                                     " a multi-character sequence is illegal");
17965                             }
17966
17967                             /* For each multi-character string ... */
17968                             while (av_count(strings) > 0) {
17969                                 /* ... Each entry is itself an array of code
17970                                 * points. */
17971                                 AV * this_string = (AV *) av_shift( strings);
17972                                 STRLEN cp_count = av_count(this_string);
17973                                 SV * final = newSV(cp_count * 4);
17974                                 SvPVCLEAR(final);
17975
17976                                 /* Create another string of sequences of \x{...} */
17977                                 while (av_count(this_string) > 0) {
17978                                     SV * character = av_shift(this_string);
17979                                     UV cp = SvUV(character);
17980
17981                                     if (cp > 255) {
17982                                         REQUIRE_UTF8(flagp);
17983                                     }
17984                                     Perl_sv_catpvf(aTHX_ final, "\\x{%" UVXf "}",
17985                                                                         cp);
17986                                     SvREFCNT_dec_NN(character);
17987                                 }
17988                                 SvREFCNT_dec_NN(this_string);
17989
17990                                 /* And add that to the list of such things */
17991                                 multi_char_matches
17992                                             = add_multi_match(multi_char_matches,
17993                                                             final,
17994                                                             cp_count);
17995                             }
17996                         }
17997                         SvREFCNT_dec_NN(strings);
17998                     }
17999
18000                     if (! prop_definition) {    /* If we got only a string,
18001                                                    this iteration didn't really
18002                                                    find a character */
18003                         element_count--;
18004                     }
18005                     else if (! is_invlist(prop_definition)) {
18006
18007                         /* Here, the definition isn't known, so we have gotten
18008                          * returned a string that will be evaluated if and when
18009                          * encountered at runtime.  We add it to the list of
18010                          * such properties, along with whether it should be
18011                          * complemented or not */
18012                         if (value == 'P') {
18013                             sv_catpvs(listsv, "!");
18014                         }
18015                         else {
18016                             sv_catpvs(listsv, "+");
18017                         }
18018                         sv_catsv(listsv, prop_definition);
18019
18020                         has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
18021
18022                         /* We don't know yet what this matches, so have to flag
18023                          * it */
18024                         anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
18025                     }
18026                     else {
18027                         assert (prop_definition && is_invlist(prop_definition));
18028
18029                         /* Here we do have the complete property definition
18030                          *
18031                          * Temporary workaround for [perl #133136].  For this
18032                          * precise input that is in the .t that is failing,
18033                          * load utf8.pm, which is what the test wants, so that
18034                          * that .t passes */
18035                         if (     memEQs(RExC_start, e + 1 - RExC_start,
18036                                         "foo\\p{Alnum}")
18037                             && ! hv_common(GvHVn(PL_incgv),
18038                                            NULL,
18039                                            "utf8.pm", sizeof("utf8.pm") - 1,
18040                                            0, HV_FETCH_ISEXISTS, NULL, 0))
18041                         {
18042                             require_pv("utf8.pm");
18043                         }
18044
18045                         if (! user_defined &&
18046                             /* We warn on matching an above-Unicode code point
18047                              * if the match would return true, except don't
18048                              * warn for \p{All}, which has exactly one element
18049                              * = 0 */
18050                             (_invlist_contains_cp(prop_definition, 0x110000)
18051                                 && (! (_invlist_len(prop_definition) == 1
18052                                        && *invlist_array(prop_definition) == 0))))
18053                         {
18054                             warn_super = TRUE;
18055                         }
18056
18057                         /* Invert if asking for the complement */
18058                         if (value == 'P') {
18059                             _invlist_union_complement_2nd(properties,
18060                                                           prop_definition,
18061                                                           &properties);
18062                         }
18063                         else {
18064                             _invlist_union(properties, prop_definition, &properties);
18065                         }
18066                     }
18067                 }
18068
18069                 RExC_parse = e + 1;
18070                 namedclass = ANYOF_UNIPROP;  /* no official name, but it's
18071                                                 named */
18072                 }
18073                 break;
18074             case 'n':   value = '\n';                   break;
18075             case 'r':   value = '\r';                   break;
18076             case 't':   value = '\t';                   break;
18077             case 'f':   value = '\f';                   break;
18078             case 'b':   value = '\b';                   break;
18079             case 'e':   value = ESC_NATIVE;             break;
18080             case 'a':   value = '\a';                   break;
18081             case 'o':
18082                 RExC_parse--;   /* function expects to be pointed at the 'o' */
18083                 if (! grok_bslash_o(&RExC_parse,
18084                                             RExC_end,
18085                                             &value,
18086                                             &message,
18087                                             &packed_warn,
18088                                             strict,
18089                                             cBOOL(range), /* MAX_UV allowed for range
18090                                                       upper limit */
18091                                             UTF))
18092                 {
18093                     vFAIL(message);
18094                 }
18095                 else if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
18096                     warn_non_literal_string(RExC_parse, packed_warn, message);
18097                 }
18098
18099                 if (value < 256) {
18100                     non_portable_endpoint++;
18101                 }
18102                 break;
18103             case 'x':
18104                 RExC_parse--;   /* function expects to be pointed at the 'x' */
18105                 if (!  grok_bslash_x(&RExC_parse,
18106                                             RExC_end,
18107                                             &value,
18108                                             &message,
18109                                             &packed_warn,
18110                                             strict,
18111                                             cBOOL(range), /* MAX_UV allowed for range
18112                                                       upper limit */
18113                                             UTF))
18114                 {
18115                     vFAIL(message);
18116                 }
18117                 else if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
18118                     warn_non_literal_string(RExC_parse, packed_warn, message);
18119                 }
18120
18121                 if (value < 256) {
18122                     non_portable_endpoint++;
18123                 }
18124                 break;
18125             case 'c':
18126                 if (! grok_bslash_c(*RExC_parse, &grok_c_char, &message,
18127                                                                 &packed_warn))
18128                 {
18129                     /* going to die anyway; point to exact spot of
18130                         * failure */
18131                     RExC_parse += (UTF)
18132                                   ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
18133                                   : 1;
18134                     vFAIL(message);
18135                 }
18136
18137                 value = grok_c_char;
18138                 RExC_parse++;
18139                 if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
18140                     warn_non_literal_string(RExC_parse, packed_warn, message);
18141                 }
18142
18143                 non_portable_endpoint++;
18144                 break;
18145             case '0': case '1': case '2': case '3': case '4':
18146             case '5': case '6': case '7':
18147                 {
18148                     /* Take 1-3 octal digits */
18149                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT
18150                               | PERL_SCAN_NOTIFY_ILLDIGIT;
18151                     numlen = (strict) ? 4 : 3;
18152                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
18153                     RExC_parse += numlen;
18154                     if (numlen != 3) {
18155                         if (strict) {
18156                             RExC_parse += (UTF)
18157                                           ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
18158                                           : 1;
18159                             vFAIL("Need exactly 3 octal digits");
18160                         }
18161                         else if (  (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
18162                                  && RExC_parse < RExC_end
18163                                  && isDIGIT(*RExC_parse)
18164                                  && ckWARN(WARN_REGEXP))
18165                         {
18166                             reg_warn_non_literal_string(
18167                                  RExC_parse + 1,
18168                                  form_alien_digit_msg(8, numlen, RExC_parse,
18169                                                         RExC_end, UTF, FALSE));
18170                         }
18171                     }
18172                     if (value < 256) {
18173                         non_portable_endpoint++;
18174                     }
18175                     break;
18176                 }
18177             default:
18178                 /* Allow \_ to not give an error */
18179                 if (isWORDCHAR(value) && value != '_') {
18180                     if (strict) {
18181                         vFAIL2("Unrecognized escape \\%c in character class",
18182                                (int)value);
18183                     }
18184                     else {
18185                         ckWARN2reg(RExC_parse,
18186                             "Unrecognized escape \\%c in character class passed through",
18187                             (int)value);
18188                     }
18189                 }
18190                 break;
18191             }   /* End of switch on char following backslash */
18192         } /* end of handling backslash escape sequences */
18193
18194         /* Here, we have the current token in 'value' */
18195
18196         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
18197             U8 classnum;
18198
18199             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
18200              * literal, as is the character that began the false range, i.e.
18201              * the 'a' in the examples */
18202             if (range) {
18203                 const int w = (RExC_parse >= rangebegin)
18204                                 ? RExC_parse - rangebegin
18205                                 : 0;
18206                 if (strict) {
18207                     vFAIL2utf8f(
18208                         "False [] range \"%" UTF8f "\"",
18209                         UTF8fARG(UTF, w, rangebegin));
18210                 }
18211                 else {
18212                     ckWARN2reg(RExC_parse,
18213                         "False [] range \"%" UTF8f "\"",
18214                         UTF8fARG(UTF, w, rangebegin));
18215                     cp_list = add_cp_to_invlist(cp_list, '-');
18216                     cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
18217                                                             prevvalue);
18218                 }
18219
18220                 range = 0; /* this was not a true range */
18221                 element_count += 2; /* So counts for three values */
18222             }
18223
18224             classnum = namedclass_to_classnum(namedclass);
18225
18226             if (LOC && namedclass < ANYOF_POSIXL_MAX
18227 #ifndef HAS_ISASCII
18228                 && classnum != _CC_ASCII
18229 #endif
18230             ) {
18231                 SV* scratch_list = NULL;
18232
18233                 /* What the Posix classes (like \w, [:space:]) match isn't
18234                  * generally knowable under locale until actual match time.  A
18235                  * special node is used for these which has extra space for a
18236                  * bitmap, with a bit reserved for each named class that is to
18237                  * be matched against.  (This isn't needed for \p{} and
18238                  * pseudo-classes, as they are not affected by locale, and
18239                  * hence are dealt with separately.)  However, if a named class
18240                  * and its complement are both present, then it matches
18241                  * everything, and there is no runtime dependency.  Odd numbers
18242                  * are the complements of the next lower number, so xor works.
18243                  * (Note that something like [\w\D] should match everything,
18244                  * because \d should be a proper subset of \w.  But rather than
18245                  * trust that the locale is well behaved, we leave this to
18246                  * runtime to sort out) */
18247                 if (POSIXL_TEST(posixl, namedclass ^ 1)) {
18248                     cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX);
18249                     POSIXL_ZERO(posixl);
18250                     has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY;
18251                     anyof_flags &= ~ANYOF_MATCHES_POSIXL;
18252                     continue;   /* We could ignore the rest of the class, but
18253                                    best to parse it for any errors */
18254                 }
18255                 else { /* Here, isn't the complement of any already parsed
18256                           class */
18257                     POSIXL_SET(posixl, namedclass);
18258                     has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18259                     anyof_flags |= ANYOF_MATCHES_POSIXL;
18260
18261                     /* The above-Latin1 characters are not subject to locale
18262                      * rules.  Just add them to the unconditionally-matched
18263                      * list */
18264
18265                     /* Get the list of the above-Latin1 code points this
18266                      * matches */
18267                     _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
18268                                             PL_XPosix_ptrs[classnum],
18269
18270                                             /* Odd numbers are complements,
18271                                              * like NDIGIT, NASCII, ... */
18272                                             namedclass % 2 != 0,
18273                                             &scratch_list);
18274                     /* Checking if 'cp_list' is NULL first saves an extra
18275                      * clone.  Its reference count will be decremented at the
18276                      * next union, etc, or if this is the only instance, at the
18277                      * end of the routine */
18278                     if (! cp_list) {
18279                         cp_list = scratch_list;
18280                     }
18281                     else {
18282                         _invlist_union(cp_list, scratch_list, &cp_list);
18283                         SvREFCNT_dec_NN(scratch_list);
18284                     }
18285                     continue;   /* Go get next character */
18286                 }
18287             }
18288             else {
18289
18290                 /* Here, is not /l, or is a POSIX class for which /l doesn't
18291                  * matter (or is a Unicode property, which is skipped here). */
18292                 if (namedclass >= ANYOF_POSIXL_MAX) {  /* If a special class */
18293                     if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
18294
18295                         /* Here, should be \h, \H, \v, or \V.  None of /d, /i
18296                          * nor /l make a difference in what these match,
18297                          * therefore we just add what they match to cp_list. */
18298                         if (classnum != _CC_VERTSPACE) {
18299                             assert(   namedclass == ANYOF_HORIZWS
18300                                    || namedclass == ANYOF_NHORIZWS);
18301
18302                             /* It turns out that \h is just a synonym for
18303                              * XPosixBlank */
18304                             classnum = _CC_BLANK;
18305                         }
18306
18307                         _invlist_union_maybe_complement_2nd(
18308                                 cp_list,
18309                                 PL_XPosix_ptrs[classnum],
18310                                 namedclass % 2 != 0,    /* Complement if odd
18311                                                           (NHORIZWS, NVERTWS)
18312                                                         */
18313                                 &cp_list);
18314                     }
18315                 }
18316                 else if (   AT_LEAST_UNI_SEMANTICS
18317                          || classnum == _CC_ASCII
18318                          || (DEPENDS_SEMANTICS && (   classnum == _CC_DIGIT
18319                                                    || classnum == _CC_XDIGIT)))
18320                 {
18321                     /* We usually have to worry about /d affecting what POSIX
18322                      * classes match, with special code needed because we won't
18323                      * know until runtime what all matches.  But there is no
18324                      * extra work needed under /u and /a; and [:ascii:] is
18325                      * unaffected by /d; and :digit: and :xdigit: don't have
18326                      * runtime differences under /d.  So we can special case
18327                      * these, and avoid some extra work below, and at runtime.
18328                      * */
18329                     _invlist_union_maybe_complement_2nd(
18330                                                      simple_posixes,
18331                                                       ((AT_LEAST_ASCII_RESTRICTED)
18332                                                        ? PL_Posix_ptrs[classnum]
18333                                                        : PL_XPosix_ptrs[classnum]),
18334                                                      namedclass % 2 != 0,
18335                                                      &simple_posixes);
18336                 }
18337                 else {  /* Garden variety class.  If is NUPPER, NALPHA, ...
18338                            complement and use nposixes */
18339                     SV** posixes_ptr = namedclass % 2 == 0
18340                                        ? &posixes
18341                                        : &nposixes;
18342                     _invlist_union_maybe_complement_2nd(
18343                                                      *posixes_ptr,
18344                                                      PL_XPosix_ptrs[classnum],
18345                                                      namedclass % 2 != 0,
18346                                                      posixes_ptr);
18347                 }
18348             }
18349         } /* end of namedclass \blah */
18350
18351         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse, RExC_end);
18352
18353         /* If 'range' is set, 'value' is the ending of a range--check its
18354          * validity.  (If value isn't a single code point in the case of a
18355          * range, we should have figured that out above in the code that
18356          * catches false ranges).  Later, we will handle each individual code
18357          * point in the range.  If 'range' isn't set, this could be the
18358          * beginning of a range, so check for that by looking ahead to see if
18359          * the next real character to be processed is the range indicator--the
18360          * minus sign */
18361
18362         if (range) {
18363 #ifdef EBCDIC
18364             /* For unicode ranges, we have to test that the Unicode as opposed
18365              * to the native values are not decreasing.  (Above 255, there is
18366              * no difference between native and Unicode) */
18367             if (unicode_range && prevvalue < 255 && value < 255) {
18368                 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
18369                     goto backwards_range;
18370                 }
18371             }
18372             else
18373 #endif
18374             if (prevvalue > value) /* b-a */ {
18375                 int w;
18376 #ifdef EBCDIC
18377               backwards_range:
18378 #endif
18379                 w = RExC_parse - rangebegin;
18380                 vFAIL2utf8f(
18381                     "Invalid [] range \"%" UTF8f "\"",
18382                     UTF8fARG(UTF, w, rangebegin));
18383                 NOT_REACHED; /* NOTREACHED */
18384             }
18385         }
18386         else {
18387             prevvalue = value; /* save the beginning of the potential range */
18388             if (! stop_at_1     /* Can't be a range if parsing just one thing */
18389                 && *RExC_parse == '-')
18390             {
18391                 char* next_char_ptr = RExC_parse + 1;
18392
18393                 /* Get the next real char after the '-' */
18394                 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr, RExC_end);
18395
18396                 /* If the '-' is at the end of the class (just before the ']',
18397                  * it is a literal minus; otherwise it is a range */
18398                 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
18399                     RExC_parse = next_char_ptr;
18400
18401                     /* a bad range like \w-, [:word:]- ? */
18402                     if (namedclass > OOB_NAMEDCLASS) {
18403                         if (strict || ckWARN(WARN_REGEXP)) {
18404                             const int w = RExC_parse >= rangebegin
18405                                           ?  RExC_parse - rangebegin
18406                                           : 0;
18407                             if (strict) {
18408                                 vFAIL4("False [] range \"%*.*s\"",
18409                                     w, w, rangebegin);
18410                             }
18411                             else {
18412                                 vWARN4(RExC_parse,
18413                                     "False [] range \"%*.*s\"",
18414                                     w, w, rangebegin);
18415                             }
18416                         }
18417                         cp_list = add_cp_to_invlist(cp_list, '-');
18418                         element_count++;
18419                     } else
18420                         range = 1;      /* yeah, it's a range! */
18421                     continue;   /* but do it the next time */
18422                 }
18423             }
18424         }
18425
18426         if (namedclass > OOB_NAMEDCLASS) {
18427             continue;
18428         }
18429
18430         /* Here, we have a single value this time through the loop, and
18431          * <prevvalue> is the beginning of the range, if any; or <value> if
18432          * not. */
18433
18434         /* non-Latin1 code point implies unicode semantics. */
18435         if (value > 255) {
18436             if (value > MAX_LEGAL_CP && (   value != UV_MAX
18437                                          || prevvalue > MAX_LEGAL_CP))
18438             {
18439                 vFAIL(form_cp_too_large_msg(16, NULL, 0, value));
18440             }
18441             REQUIRE_UNI_RULES(flagp, 0);
18442             if (  ! silence_non_portable
18443                 &&  UNICODE_IS_PERL_EXTENDED(value)
18444                 &&  TO_OUTPUT_WARNINGS(RExC_parse))
18445             {
18446                 ckWARN2_non_literal_string(RExC_parse,
18447                                            packWARN(WARN_PORTABLE),
18448                                            PL_extended_cp_format,
18449                                            value);
18450             }
18451         }
18452
18453         /* Ready to process either the single value, or the completed range.
18454          * For single-valued non-inverted ranges, we consider the possibility
18455          * of multi-char folds.  (We made a conscious decision to not do this
18456          * for the other cases because it can often lead to non-intuitive
18457          * results.  For example, you have the peculiar case that:
18458          *  "s s" =~ /^[^\xDF]+$/i => Y
18459          *  "ss"  =~ /^[^\xDF]+$/i => N
18460          *
18461          * See [perl #89750] */
18462         if (FOLD && allow_mutiple_chars && value == prevvalue) {
18463             if (    value == LATIN_SMALL_LETTER_SHARP_S
18464                 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
18465                                                         value)))
18466             {
18467                 /* Here <value> is indeed a multi-char fold.  Get what it is */
18468
18469                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18470                 STRLEN foldlen;
18471
18472                 UV folded = _to_uni_fold_flags(
18473                                 value,
18474                                 foldbuf,
18475                                 &foldlen,
18476                                 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
18477                                                    ? FOLD_FLAGS_NOMIX_ASCII
18478                                                    : 0)
18479                                 );
18480
18481                 /* Here, <folded> should be the first character of the
18482                  * multi-char fold of <value>, with <foldbuf> containing the
18483                  * whole thing.  But, if this fold is not allowed (because of
18484                  * the flags), <fold> will be the same as <value>, and should
18485                  * be processed like any other character, so skip the special
18486                  * handling */
18487                 if (folded != value) {
18488
18489                     /* Skip if we are recursed, currently parsing the class
18490                      * again.  Otherwise add this character to the list of
18491                      * multi-char folds. */
18492                     if (! RExC_in_multi_char_class) {
18493                         STRLEN cp_count = utf8_length(foldbuf,
18494                                                       foldbuf + foldlen);
18495                         SV* multi_fold = sv_2mortal(newSVpvs(""));
18496
18497                         Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
18498
18499                         multi_char_matches
18500                                         = add_multi_match(multi_char_matches,
18501                                                           multi_fold,
18502                                                           cp_count);
18503
18504                     }
18505
18506                     /* This element should not be processed further in this
18507                      * class */
18508                     element_count--;
18509                     value = save_value;
18510                     prevvalue = save_prevvalue;
18511                     continue;
18512                 }
18513             }
18514         }
18515
18516         if (strict && ckWARN(WARN_REGEXP)) {
18517             if (range) {
18518
18519                 /* If the range starts above 255, everything is portable and
18520                  * likely to be so for any forseeable character set, so don't
18521                  * warn. */
18522                 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
18523                     vWARN(RExC_parse, "Both or neither range ends should be Unicode");
18524                 }
18525                 else if (prevvalue != value) {
18526
18527                     /* Under strict, ranges that stop and/or end in an ASCII
18528                      * printable should have each end point be a portable value
18529                      * for it (preferably like 'A', but we don't warn if it is
18530                      * a (portable) Unicode name or code point), and the range
18531                      * must be all digits or all letters of the same case.
18532                      * Otherwise, the range is non-portable and unclear as to
18533                      * what it contains */
18534                     if (             (isPRINT_A(prevvalue) || isPRINT_A(value))
18535                         && (          non_portable_endpoint
18536                             || ! (   (isDIGIT_A(prevvalue) && isDIGIT_A(value))
18537                                   || (isLOWER_A(prevvalue) && isLOWER_A(value))
18538                                   || (isUPPER_A(prevvalue) && isUPPER_A(value))
18539                     ))) {
18540                         vWARN(RExC_parse, "Ranges of ASCII printables should"
18541                                           " be some subset of \"0-9\","
18542                                           " \"A-Z\", or \"a-z\"");
18543                     }
18544                     else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
18545                         SSize_t index_start;
18546                         SSize_t index_final;
18547
18548                         /* But the nature of Unicode and languages mean we
18549                          * can't do the same checks for above-ASCII ranges,
18550                          * except in the case of digit ones.  These should
18551                          * contain only digits from the same group of 10.  The
18552                          * ASCII case is handled just above.  Hence here, the
18553                          * range could be a range of digits.  First some
18554                          * unlikely special cases.  Grandfather in that a range
18555                          * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
18556                          * if its starting value is one of the 10 digits prior
18557                          * to it.  This is because it is an alternate way of
18558                          * writing 19D1, and some people may expect it to be in
18559                          * that group.  But it is bad, because it won't give
18560                          * the expected results.  In Unicode 5.2 it was
18561                          * considered to be in that group (of 11, hence), but
18562                          * this was fixed in the next version */
18563
18564                         if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
18565                             goto warn_bad_digit_range;
18566                         }
18567                         else if (UNLIKELY(   prevvalue >= 0x1D7CE
18568                                           &&     value <= 0x1D7FF))
18569                         {
18570                             /* This is the only other case currently in Unicode
18571                              * where the algorithm below fails.  The code
18572                              * points just above are the end points of a single
18573                              * range containing only decimal digits.  It is 5
18574                              * different series of 0-9.  All other ranges of
18575                              * digits currently in Unicode are just a single
18576                              * series.  (And mktables will notify us if a later
18577                              * Unicode version breaks this.)
18578                              *
18579                              * If the range being checked is at most 9 long,
18580                              * and the digit values represented are in
18581                              * numerical order, they are from the same series.
18582                              * */
18583                             if (         value - prevvalue > 9
18584                                 ||    (((    value - 0x1D7CE) % 10)
18585                                      <= (prevvalue - 0x1D7CE) % 10))
18586                             {
18587                                 goto warn_bad_digit_range;
18588                             }
18589                         }
18590                         else {
18591
18592                             /* For all other ranges of digits in Unicode, the
18593                              * algorithm is just to check if both end points
18594                              * are in the same series, which is the same range.
18595                              * */
18596                             index_start = _invlist_search(
18597                                                     PL_XPosix_ptrs[_CC_DIGIT],
18598                                                     prevvalue);
18599
18600                             /* Warn if the range starts and ends with a digit,
18601                              * and they are not in the same group of 10. */
18602                             if (   index_start >= 0
18603                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
18604                                 && (index_final =
18605                                     _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
18606                                                     value)) != index_start
18607                                 && index_final >= 0
18608                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
18609                             {
18610                               warn_bad_digit_range:
18611                                 vWARN(RExC_parse, "Ranges of digits should be"
18612                                                   " from the same group of"
18613                                                   " 10");
18614                             }
18615                         }
18616                     }
18617                 }
18618             }
18619             if ((! range || prevvalue == value) && non_portable_endpoint) {
18620                 if (isPRINT_A(value)) {
18621                     char literal[3];
18622                     unsigned d = 0;
18623                     if (isBACKSLASHED_PUNCT(value)) {
18624                         literal[d++] = '\\';
18625                     }
18626                     literal[d++] = (char) value;
18627                     literal[d++] = '\0';
18628
18629                     vWARN4(RExC_parse,
18630                            "\"%.*s\" is more clearly written simply as \"%s\"",
18631                            (int) (RExC_parse - rangebegin),
18632                            rangebegin,
18633                            literal
18634                         );
18635                 }
18636                 else if (isMNEMONIC_CNTRL(value)) {
18637                     vWARN4(RExC_parse,
18638                            "\"%.*s\" is more clearly written simply as \"%s\"",
18639                            (int) (RExC_parse - rangebegin),
18640                            rangebegin,
18641                            cntrl_to_mnemonic((U8) value)
18642                         );
18643                 }
18644             }
18645         }
18646
18647         /* Deal with this element of the class */
18648
18649 #ifndef EBCDIC
18650         cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18651                                                     prevvalue, value);
18652 #else
18653         /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
18654          * that don't require special handling, we can just add the range like
18655          * we do for ASCII platforms */
18656         if ((UNLIKELY(prevvalue == 0) && value >= 255)
18657             || ! (prevvalue < 256
18658                     && (unicode_range
18659                         || (! non_portable_endpoint
18660                             && ((isLOWER_A(prevvalue) && isLOWER_A(value))
18661                                 || (isUPPER_A(prevvalue)
18662                                     && isUPPER_A(value)))))))
18663         {
18664             cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18665                                                         prevvalue, value);
18666         }
18667         else {
18668             /* Here, requires special handling.  This can be because it is a
18669              * range whose code points are considered to be Unicode, and so
18670              * must be individually translated into native, or because its a
18671              * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
18672              * EBCDIC, but we have defined them to include only the "expected"
18673              * upper or lower case ASCII alphabetics.  Subranges above 255 are
18674              * the same in native and Unicode, so can be added as a range */
18675             U8 start = NATIVE_TO_LATIN1(prevvalue);
18676             unsigned j;
18677             U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
18678             for (j = start; j <= end; j++) {
18679                 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
18680             }
18681             if (value > 255) {
18682                 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18683                                                             256, value);
18684             }
18685         }
18686 #endif
18687
18688         range = 0; /* this range (if it was one) is done now */
18689     } /* End of loop through all the text within the brackets */
18690
18691     if (   posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
18692         output_posix_warnings(pRExC_state, posix_warnings);
18693     }
18694
18695     /* If anything in the class expands to more than one character, we have to
18696      * deal with them by building up a substitute parse string, and recursively
18697      * calling reg() on it, instead of proceeding */
18698     if (multi_char_matches) {
18699         SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
18700         I32 cp_count;
18701         STRLEN len;
18702         char *save_end = RExC_end;
18703         char *save_parse = RExC_parse;
18704         char *save_start = RExC_start;
18705         Size_t constructed_prefix_len = 0; /* This gives the length of the
18706                                               constructed portion of the
18707                                               substitute parse. */
18708         bool first_time = TRUE;     /* First multi-char occurrence doesn't get
18709                                        a "|" */
18710         I32 reg_flags;
18711
18712         assert(! invert);
18713         /* Only one level of recursion allowed */
18714         assert(RExC_copy_start_in_constructed == RExC_precomp);
18715
18716 #if 0   /* Have decided not to deal with multi-char folds in inverted classes,
18717            because too confusing */
18718         if (invert) {
18719             sv_catpvs(substitute_parse, "(?:");
18720         }
18721 #endif
18722
18723         /* Look at the longest strings first */
18724         for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
18725                         cp_count > 0;
18726                         cp_count--)
18727         {
18728
18729             if (av_exists(multi_char_matches, cp_count)) {
18730                 AV** this_array_ptr;
18731                 SV* this_sequence;
18732
18733                 this_array_ptr = (AV**) av_fetch(multi_char_matches,
18734                                                  cp_count, FALSE);
18735                 while ((this_sequence = av_pop(*this_array_ptr)) !=
18736                                                                 &PL_sv_undef)
18737                 {
18738                     if (! first_time) {
18739                         sv_catpvs(substitute_parse, "|");
18740                     }
18741                     first_time = FALSE;
18742
18743                     sv_catpv(substitute_parse, SvPVX(this_sequence));
18744                 }
18745             }
18746         }
18747
18748         /* If the character class contains anything else besides these
18749          * multi-character strings, have to include it in recursive parsing */
18750         if (element_count) {
18751             bool has_l_bracket = orig_parse > RExC_start && *(orig_parse - 1) == '[';
18752
18753             sv_catpvs(substitute_parse, "|");
18754             if (has_l_bracket) {    /* Add an [ if the original had one */
18755                 sv_catpvs(substitute_parse, "[");
18756             }
18757             constructed_prefix_len = SvCUR(substitute_parse);
18758             sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
18759
18760             /* Put in a closing ']' to match any opening one, but not if going
18761              * off the end, as otherwise we are adding something that really
18762              * isn't there */
18763             if (has_l_bracket && RExC_parse < RExC_end) {
18764                 sv_catpvs(substitute_parse, "]");
18765             }
18766         }
18767
18768         sv_catpvs(substitute_parse, ")");
18769 #if 0
18770         if (invert) {
18771             /* This is a way to get the parse to skip forward a whole named
18772              * sequence instead of matching the 2nd character when it fails the
18773              * first */
18774             sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
18775         }
18776 #endif
18777
18778         /* Set up the data structure so that any errors will be properly
18779          * reported.  See the comments at the definition of
18780          * REPORT_LOCATION_ARGS for details */
18781         RExC_copy_start_in_input = (char *) orig_parse;
18782         RExC_start = RExC_parse = SvPV(substitute_parse, len);
18783         RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
18784         RExC_end = RExC_parse + len;
18785         RExC_in_multi_char_class = 1;
18786
18787         ret = reg(pRExC_state, 1, &reg_flags, depth+1);
18788
18789         *flagp |= reg_flags & (HASWIDTH|SIMPLE|POSTPONED|RESTART_PARSE|NEED_UTF8);
18790
18791         /* And restore so can parse the rest of the pattern */
18792         RExC_parse = save_parse;
18793         RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
18794         RExC_end = save_end;
18795         RExC_in_multi_char_class = 0;
18796         SvREFCNT_dec_NN(multi_char_matches);
18797         SvREFCNT_dec(properties);
18798         SvREFCNT_dec(cp_list);
18799         SvREFCNT_dec(simple_posixes);
18800         SvREFCNT_dec(posixes);
18801         SvREFCNT_dec(nposixes);
18802         SvREFCNT_dec(cp_foldable_list);
18803         return ret;
18804     }
18805
18806     /* If folding, we calculate all characters that could fold to or from the
18807      * ones already on the list */
18808     if (cp_foldable_list) {
18809         if (FOLD) {
18810             UV start, end;      /* End points of code point ranges */
18811
18812             SV* fold_intersection = NULL;
18813             SV** use_list;
18814
18815             /* Our calculated list will be for Unicode rules.  For locale
18816              * matching, we have to keep a separate list that is consulted at
18817              * runtime only when the locale indicates Unicode rules (and we
18818              * don't include potential matches in the ASCII/Latin1 range, as
18819              * any code point could fold to any other, based on the run-time
18820              * locale).   For non-locale, we just use the general list */
18821             if (LOC) {
18822                 use_list = &only_utf8_locale_list;
18823             }
18824             else {
18825                 use_list = &cp_list;
18826             }
18827
18828             /* Only the characters in this class that participate in folds need
18829              * be checked.  Get the intersection of this class and all the
18830              * possible characters that are foldable.  This can quickly narrow
18831              * down a large class */
18832             _invlist_intersection(PL_in_some_fold, cp_foldable_list,
18833                                   &fold_intersection);
18834
18835             /* Now look at the foldable characters in this class individually */
18836             invlist_iterinit(fold_intersection);
18837             while (invlist_iternext(fold_intersection, &start, &end)) {
18838                 UV j;
18839                 UV folded;
18840
18841                 /* Look at every character in the range */
18842                 for (j = start; j <= end; j++) {
18843                     U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18844                     STRLEN foldlen;
18845                     unsigned int k;
18846                     Size_t folds_count;
18847                     U32 first_fold;
18848                     const U32 * remaining_folds;
18849
18850                     if (j < 256) {
18851
18852                         /* Under /l, we don't know what code points below 256
18853                          * fold to, except we do know the MICRO SIGN folds to
18854                          * an above-255 character if the locale is UTF-8, so we
18855                          * add it to the special list (in *use_list)  Otherwise
18856                          * we know now what things can match, though some folds
18857                          * are valid under /d only if the target is UTF-8.
18858                          * Those go in a separate list */
18859                         if (      IS_IN_SOME_FOLD_L1(j)
18860                             && ! (LOC && j != MICRO_SIGN))
18861                         {
18862
18863                             /* ASCII is always matched; non-ASCII is matched
18864                              * only under Unicode rules (which could happen
18865                              * under /l if the locale is a UTF-8 one */
18866                             if (isASCII(j) || ! DEPENDS_SEMANTICS) {
18867                                 *use_list = add_cp_to_invlist(*use_list,
18868                                                             PL_fold_latin1[j]);
18869                             }
18870                             else if (j != PL_fold_latin1[j]) {
18871                                 upper_latin1_only_utf8_matches
18872                                         = add_cp_to_invlist(
18873                                                 upper_latin1_only_utf8_matches,
18874                                                 PL_fold_latin1[j]);
18875                             }
18876                         }
18877
18878                         if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
18879                             && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
18880                         {
18881                             add_above_Latin1_folds(pRExC_state,
18882                                                    (U8) j,
18883                                                    use_list);
18884                         }
18885                         continue;
18886                     }
18887
18888                     /* Here is an above Latin1 character.  We don't have the
18889                      * rules hard-coded for it.  First, get its fold.  This is
18890                      * the simple fold, as the multi-character folds have been
18891                      * handled earlier and separated out */
18892                     folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
18893                                                         (ASCII_FOLD_RESTRICTED)
18894                                                         ? FOLD_FLAGS_NOMIX_ASCII
18895                                                         : 0);
18896
18897                     /* Single character fold of above Latin1.  Add everything
18898                      * in its fold closure to the list that this node should
18899                      * match. */
18900                     folds_count = _inverse_folds(folded, &first_fold,
18901                                                     &remaining_folds);
18902                     for (k = 0; k <= folds_count; k++) {
18903                         UV c = (k == 0)     /* First time through use itself */
18904                                 ? folded
18905                                 : (k == 1)  /* 2nd time use, the first fold */
18906                                    ? first_fold
18907
18908                                      /* Then the remaining ones */
18909                                    : remaining_folds[k-2];
18910
18911                         /* /aa doesn't allow folds between ASCII and non- */
18912                         if ((   ASCII_FOLD_RESTRICTED
18913                             && (isASCII(c) != isASCII(j))))
18914                         {
18915                             continue;
18916                         }
18917
18918                         /* Folds under /l which cross the 255/256 boundary are
18919                          * added to a separate list.  (These are valid only
18920                          * when the locale is UTF-8.) */
18921                         if (c < 256 && LOC) {
18922                             *use_list = add_cp_to_invlist(*use_list, c);
18923                             continue;
18924                         }
18925
18926                         if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
18927                         {
18928                             cp_list = add_cp_to_invlist(cp_list, c);
18929                         }
18930                         else {
18931                             /* Similarly folds involving non-ascii Latin1
18932                              * characters under /d are added to their list */
18933                             upper_latin1_only_utf8_matches
18934                                     = add_cp_to_invlist(
18935                                                 upper_latin1_only_utf8_matches,
18936                                                 c);
18937                         }
18938                     }
18939                 }
18940             }
18941             SvREFCNT_dec_NN(fold_intersection);
18942         }
18943
18944         /* Now that we have finished adding all the folds, there is no reason
18945          * to keep the foldable list separate */
18946         _invlist_union(cp_list, cp_foldable_list, &cp_list);
18947         SvREFCNT_dec_NN(cp_foldable_list);
18948     }
18949
18950     /* And combine the result (if any) with any inversion lists from posix
18951      * classes.  The lists are kept separate up to now because we don't want to
18952      * fold the classes */
18953     if (simple_posixes) {   /* These are the classes known to be unaffected by
18954                                /a, /aa, and /d */
18955         if (cp_list) {
18956             _invlist_union(cp_list, simple_posixes, &cp_list);
18957             SvREFCNT_dec_NN(simple_posixes);
18958         }
18959         else {
18960             cp_list = simple_posixes;
18961         }
18962     }
18963     if (posixes || nposixes) {
18964         if (! DEPENDS_SEMANTICS) {
18965
18966             /* For everything but /d, we can just add the current 'posixes' and
18967              * 'nposixes' to the main list */
18968             if (posixes) {
18969                 if (cp_list) {
18970                     _invlist_union(cp_list, posixes, &cp_list);
18971                     SvREFCNT_dec_NN(posixes);
18972                 }
18973                 else {
18974                     cp_list = posixes;
18975                 }
18976             }
18977             if (nposixes) {
18978                 if (cp_list) {
18979                     _invlist_union(cp_list, nposixes, &cp_list);
18980                     SvREFCNT_dec_NN(nposixes);
18981                 }
18982                 else {
18983                     cp_list = nposixes;
18984                 }
18985             }
18986         }
18987         else {
18988             /* Under /d, things like \w match upper Latin1 characters only if
18989              * the target string is in UTF-8.  But things like \W match all the
18990              * upper Latin1 characters if the target string is not in UTF-8.
18991              *
18992              * Handle the case with something like \W separately */
18993             if (nposixes) {
18994                 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
18995
18996                 /* A complemented posix class matches all upper Latin1
18997                  * characters if not in UTF-8.  And it matches just certain
18998                  * ones when in UTF-8.  That means those certain ones are
18999                  * matched regardless, so can just be added to the
19000                  * unconditional list */
19001                 if (cp_list) {
19002                     _invlist_union(cp_list, nposixes, &cp_list);
19003                     SvREFCNT_dec_NN(nposixes);
19004                     nposixes = NULL;
19005                 }
19006                 else {
19007                     cp_list = nposixes;
19008                 }
19009
19010                 /* Likewise for 'posixes' */
19011                 _invlist_union(posixes, cp_list, &cp_list);
19012                 SvREFCNT_dec(posixes);
19013
19014                 /* Likewise for anything else in the range that matched only
19015                  * under UTF-8 */
19016                 if (upper_latin1_only_utf8_matches) {
19017                     _invlist_union(cp_list,
19018                                    upper_latin1_only_utf8_matches,
19019                                    &cp_list);
19020                     SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
19021                     upper_latin1_only_utf8_matches = NULL;
19022                 }
19023
19024                 /* If we don't match all the upper Latin1 characters regardless
19025                  * of UTF-8ness, we have to set a flag to match the rest when
19026                  * not in UTF-8 */
19027                 _invlist_subtract(only_non_utf8_list, cp_list,
19028                                   &only_non_utf8_list);
19029                 if (_invlist_len(only_non_utf8_list) != 0) {
19030                     anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
19031                 }
19032                 SvREFCNT_dec_NN(only_non_utf8_list);
19033             }
19034             else {
19035                 /* Here there were no complemented posix classes.  That means
19036                  * the upper Latin1 characters in 'posixes' match only when the
19037                  * target string is in UTF-8.  So we have to add them to the
19038                  * list of those types of code points, while adding the
19039                  * remainder to the unconditional list.
19040                  *
19041                  * First calculate what they are */
19042                 SV* nonascii_but_latin1_properties = NULL;
19043                 _invlist_intersection(posixes, PL_UpperLatin1,
19044                                       &nonascii_but_latin1_properties);
19045
19046                 /* And add them to the final list of such characters. */
19047                 _invlist_union(upper_latin1_only_utf8_matches,
19048                                nonascii_but_latin1_properties,
19049                                &upper_latin1_only_utf8_matches);
19050
19051                 /* Remove them from what now becomes the unconditional list */
19052                 _invlist_subtract(posixes, nonascii_but_latin1_properties,
19053                                   &posixes);
19054
19055                 /* And add those unconditional ones to the final list */
19056                 if (cp_list) {
19057                     _invlist_union(cp_list, posixes, &cp_list);
19058                     SvREFCNT_dec_NN(posixes);
19059                     posixes = NULL;
19060                 }
19061                 else {
19062                     cp_list = posixes;
19063                 }
19064
19065                 SvREFCNT_dec(nonascii_but_latin1_properties);
19066
19067                 /* Get rid of any characters from the conditional list that we
19068                  * now know are matched unconditionally, which may make that
19069                  * list empty */
19070                 _invlist_subtract(upper_latin1_only_utf8_matches,
19071                                   cp_list,
19072                                   &upper_latin1_only_utf8_matches);
19073                 if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
19074                     SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
19075                     upper_latin1_only_utf8_matches = NULL;
19076                 }
19077             }
19078         }
19079     }
19080
19081     /* And combine the result (if any) with any inversion list from properties.
19082      * The lists are kept separate up to now so that we can distinguish the two
19083      * in regards to matching above-Unicode.  A run-time warning is generated
19084      * if a Unicode property is matched against a non-Unicode code point. But,
19085      * we allow user-defined properties to match anything, without any warning,
19086      * and we also suppress the warning if there is a portion of the character
19087      * class that isn't a Unicode property, and which matches above Unicode, \W
19088      * or [\x{110000}] for example.
19089      * (Note that in this case, unlike the Posix one above, there is no
19090      * <upper_latin1_only_utf8_matches>, because having a Unicode property
19091      * forces Unicode semantics */
19092     if (properties) {
19093         if (cp_list) {
19094
19095             /* If it matters to the final outcome, see if a non-property
19096              * component of the class matches above Unicode.  If so, the
19097              * warning gets suppressed.  This is true even if just a single
19098              * such code point is specified, as, though not strictly correct if
19099              * another such code point is matched against, the fact that they
19100              * are using above-Unicode code points indicates they should know
19101              * the issues involved */
19102             if (warn_super) {
19103                 warn_super = ! (invert
19104                                ^ (UNICODE_IS_SUPER(invlist_highest(cp_list))));
19105             }
19106
19107             _invlist_union(properties, cp_list, &cp_list);
19108             SvREFCNT_dec_NN(properties);
19109         }
19110         else {
19111             cp_list = properties;
19112         }
19113
19114         if (warn_super) {
19115             anyof_flags
19116              |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
19117
19118             /* Because an ANYOF node is the only one that warns, this node
19119              * can't be optimized into something else */
19120             optimizable = FALSE;
19121         }
19122     }
19123
19124     /* Here, we have calculated what code points should be in the character
19125      * class.
19126      *
19127      * Now we can see about various optimizations.  Fold calculation (which we
19128      * did above) needs to take place before inversion.  Otherwise /[^k]/i
19129      * would invert to include K, which under /i would match k, which it
19130      * shouldn't.  Therefore we can't invert folded locale now, as it won't be
19131      * folded until runtime */
19132
19133     /* If we didn't do folding, it's because some information isn't available
19134      * until runtime; set the run-time fold flag for these  We know to set the
19135      * flag if we have a non-NULL list for UTF-8 locales, or the class matches
19136      * at least one 0-255 range code point */
19137     if (LOC && FOLD) {
19138
19139         /* Some things on the list might be unconditionally included because of
19140          * other components.  Remove them, and clean up the list if it goes to
19141          * 0 elements */
19142         if (only_utf8_locale_list && cp_list) {
19143             _invlist_subtract(only_utf8_locale_list, cp_list,
19144                               &only_utf8_locale_list);
19145
19146             if (_invlist_len(only_utf8_locale_list) == 0) {
19147                 SvREFCNT_dec_NN(only_utf8_locale_list);
19148                 only_utf8_locale_list = NULL;
19149             }
19150         }
19151         if (    only_utf8_locale_list
19152             || (cp_list && (   _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
19153                             || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
19154         {
19155             has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
19156             anyof_flags
19157                  |= ANYOFL_FOLD
19158                  |  ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
19159         }
19160         else if (cp_list && invlist_lowest(cp_list) < 256) {
19161             /* If nothing is below 256, has no locale dependency; otherwise it
19162              * does */
19163             anyof_flags |= ANYOFL_FOLD;
19164             has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
19165         }
19166     }
19167     else if (   DEPENDS_SEMANTICS
19168              && (    upper_latin1_only_utf8_matches
19169                  || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
19170     {
19171         RExC_seen_d_op = TRUE;
19172         has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
19173     }
19174
19175     /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
19176      * compile time. */
19177     if (     cp_list
19178         &&   invert
19179         && ! has_runtime_dependency)
19180     {
19181         _invlist_invert(cp_list);
19182
19183         /* Clear the invert flag since have just done it here */
19184         invert = FALSE;
19185     }
19186
19187     /* All possible optimizations below still have these characteristics.
19188      * (Multi-char folds aren't SIMPLE, but they don't get this far in this
19189      * routine) */
19190     *flagp |= HASWIDTH|SIMPLE;
19191
19192     if (ret_invlist) {
19193         *ret_invlist = cp_list;
19194
19195         return (cp_list) ? RExC_emit : 0;
19196     }
19197
19198     if (anyof_flags & ANYOF_LOCALE_FLAGS) {
19199         RExC_contains_locale = 1;
19200     }
19201
19202     if (optimizable) {
19203
19204         /* Some character classes are equivalent to other nodes.  Such nodes
19205          * take up less room, and some nodes require fewer operations to
19206          * execute, than ANYOF nodes.  EXACTish nodes may be joinable with
19207          * adjacent nodes to improve efficiency. */
19208         op = optimize_regclass(pRExC_state, cp_list,
19209                                             only_utf8_locale_list,
19210                                             upper_latin1_only_utf8_matches,
19211                                             has_runtime_dependency,
19212                                             posixl,
19213                                             &anyof_flags, &invert, &ret, flagp);
19214         RETURN_FAIL_ON_RESTART_FLAGP(flagp);
19215
19216         /* If optimized to something else and emitted, clean up and return */
19217         if (ret >= 0) {
19218             Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
19219                                                    RExC_parse - orig_parse);;
19220             SvREFCNT_dec(cp_list);;
19221             SvREFCNT_dec(only_utf8_locale_list);
19222             SvREFCNT_dec(upper_latin1_only_utf8_matches);
19223             return ret;
19224         }
19225
19226         /* If no optimization was found, an END was returned and we will now
19227          * emit an ANYOF */
19228         if (op == END) {
19229             op = ANYOF;
19230         }
19231     }
19232
19233     /* Here are going to emit an ANYOF; set the particular type */
19234     if (op == ANYOF) {
19235         if (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY) {
19236             op = ANYOFD;
19237         }
19238         else if (posixl) {
19239             op = ANYOFPOSIXL;
19240         }
19241         else if (LOC) {
19242             op = ANYOFL;
19243         }
19244     }
19245
19246     ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
19247     FILL_NODE(ret, op);        /* We set the argument later */
19248     RExC_emit += 1 + regarglen[op];
19249     ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
19250
19251     /* Here, <cp_list> contains all the code points we can determine at
19252      * compile time that match under all conditions.  Go through it, and
19253      * for things that belong in the bitmap, put them there, and delete from
19254      * <cp_list>.  While we are at it, see if everything above 255 is in the
19255      * list, and if so, set a flag to speed up execution */
19256
19257     populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
19258
19259     if (posixl) {
19260         ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
19261     }
19262
19263     if (invert) {
19264         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
19265     }
19266
19267     /* Here, the bitmap has been populated with all the Latin1 code points that
19268      * always match.  Can now add to the overall list those that match only
19269      * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
19270      * */
19271     if (upper_latin1_only_utf8_matches) {
19272         if (cp_list) {
19273             _invlist_union(cp_list,
19274                            upper_latin1_only_utf8_matches,
19275                            &cp_list);
19276             SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
19277         }
19278         else {
19279             cp_list = upper_latin1_only_utf8_matches;
19280         }
19281         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
19282     }
19283
19284     set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19285                   (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
19286                    ? listsv
19287                    : NULL,
19288                   only_utf8_locale_list);
19289
19290     SvREFCNT_dec(cp_list);;
19291     SvREFCNT_dec(only_utf8_locale_list);
19292     return ret;
19293 }
19294
19295 STATIC U8
19296 S_optimize_regclass(pTHX_
19297                     RExC_state_t *pRExC_state,
19298                     SV * cp_list,
19299                     SV* only_utf8_locale_list,
19300                     SV* upper_latin1_only_utf8_matches,
19301                     const U32 has_runtime_dependency,
19302                     const U32 posixl,
19303                     U8  * anyof_flags,
19304                     bool * invert,
19305                     regnode_offset * ret,
19306                     I32 *flagp
19307                   )
19308 {
19309     /* This function exists just to make S_regclass() smaller.  It extracts out
19310      * the code that looks for potential optimizations away from a full generic
19311      * ANYOF node.  The parameter names are the same as the corresponding
19312      * variables in S_regclass.
19313      *
19314      * It returns the new op (the impossible END one if no optimization found)
19315      * and sets *ret to any created regnode.  If the new op is sufficiently
19316      * like plain ANYOF, it leaves *ret unchanged for allocation in S_regclass.
19317      *
19318      * Certain of the parameters may be updated as a result of the changes
19319      * herein */
19320
19321     U8 op = END;    /* The returned node-type, initialized to an impossible
19322                       one. */
19323     UV value;
19324     PERL_UINT_FAST8_T i;
19325     UV partial_cp_count = 0;
19326     UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
19327     UV   end[MAX_FOLD_FROMS+1] = { 0 };
19328     bool single_range = FALSE;
19329
19330     PERL_ARGS_ASSERT_OPTIMIZE_REGCLASS;
19331
19332     if (cp_list) { /* Count the code points in enough ranges that we would see
19333                       all the ones possible in any fold in this version of
19334                       Unicode */
19335
19336         invlist_iterinit(cp_list);
19337         for (i = 0; i <= MAX_FOLD_FROMS; i++) {
19338             if (! invlist_iternext(cp_list, &start[i], &end[i])) {
19339                 break;
19340             }
19341             partial_cp_count += end[i] - start[i] + 1;
19342         }
19343
19344         if (i == 1) {
19345             single_range = TRUE;
19346         }
19347         invlist_iterfinish(cp_list);
19348
19349         /* If we know at compile time that this matches every possible code
19350          * point, any run-time dependencies don't matter */
19351     if (start[0] == 0 && end[0] == UV_MAX) {
19352         if (*invert) {
19353             goto return_OPFAIL;
19354         }
19355         else {
19356             goto return_SANY;
19357         }
19358     }
19359     }
19360
19361     /* Similarly, for /l posix classes, if both a class and its complement
19362      * match, any run-time dependencies don't matter */
19363     if (posixl) {
19364         int namedclass;
19365         for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX; namedclass += 2) {
19366             if (   POSIXL_TEST(posixl, namedclass)      /* class */
19367                 && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
19368             {
19369                 if (*invert) {
19370                     goto return_OPFAIL;
19371                 }
19372                 else {
19373                     goto return_SANY;
19374                 }
19375                 return op;
19376             }
19377         }
19378
19379         /* For well-behaved locales, some classes are subsets of others, so
19380          * complementing the subset and including the non-complemented superset
19381          * should match everything, like [\D[:alnum:]], and
19382          * [[:^alpha:][:alnum:]], but some implementations of locales are
19383          * buggy, and khw thinks its a bad idea to have optimization change
19384          * behavior, even if it avoids an OS bug in a given case */
19385
19386 #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
19387
19388         /* If is a single posix /l class, can optimize to just that op.  Such a
19389          * node will not match anything in the Latin1 range, as that is not
19390          * determinable until runtime, but will match whatever the class does
19391          * outside that range.  (Note that some classes won't match anything
19392          * outside the range, like [:ascii:]) */
19393         if (   isSINGLE_BIT_SET(posixl)
19394             && (partial_cp_count == 0 || start[0] > 255))
19395         {
19396             U8 classnum;
19397             SV * class_above_latin1 = NULL;
19398             bool already_inverted;
19399             bool are_equivalent;
19400
19401
19402             namedclass = single_1bit_pos32(posixl);
19403             classnum = namedclass_to_classnum(namedclass);
19404
19405             /* The named classes are such that the inverted number is one
19406              * larger than the non-inverted one */
19407             already_inverted = namedclass - classnum_to_namedclass(classnum);
19408
19409             /* Create an inversion list of the official property, inverted if
19410              * the constructed node list is inverted, and restricted to only
19411              * the above latin1 code points, which are the only ones known at
19412              * compile time */
19413             _invlist_intersection_maybe_complement_2nd(
19414                                                 PL_AboveLatin1,
19415                                                 PL_XPosix_ptrs[classnum],
19416                                                 already_inverted,
19417                                                 &class_above_latin1);
19418             are_equivalent = _invlistEQ(class_above_latin1, cp_list, FALSE);
19419             SvREFCNT_dec_NN(class_above_latin1);
19420
19421             if (are_equivalent) {
19422
19423                 /* Resolve the run-time inversion flag with this possibly
19424                  * inverted class */
19425                 *invert = *invert ^ already_inverted;
19426
19427                 op = POSIXL + *invert * (NPOSIXL - POSIXL);
19428                 *ret = reg_node(pRExC_state, op);
19429                 FLAGS(REGNODE_p(*ret)) = classnum;
19430                 return op;
19431             }
19432         }
19433     }
19434
19435     /* khw can't think of any other possible transformation involving these. */
19436     if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
19437         return END;
19438     }
19439
19440     if (! has_runtime_dependency) {
19441
19442         /* If the list is empty, nothing matches.  This happens, for example,
19443          * when a Unicode property that doesn't match anything is the only
19444          * element in the character class (perluniprops.pod notes such
19445          * properties). */
19446         if (partial_cp_count == 0) {
19447             if (*invert) {
19448                 goto return_SANY;
19449             }
19450             else {
19451                 goto return_OPFAIL;
19452             }
19453         }
19454
19455         /* If matches everything but \n */
19456         if (   start[0] == 0 && end[0] == '\n' - 1
19457             && start[1] == '\n' + 1 && end[1] == UV_MAX)
19458         {
19459             assert (! *invert);
19460             op = REG_ANY;
19461             *ret = reg_node(pRExC_state, op);
19462             MARK_NAUGHTY(1);
19463             return op;
19464         }
19465     }
19466
19467     /* Next see if can optimize classes that contain just a few code points
19468      * into an EXACTish node.  The reason to do this is to let the optimizer
19469      * join this node with adjacent EXACTish ones, and ANYOF nodes require
19470      * runtime conversion to code point from UTF-8, which we'd like to avoid.
19471      *
19472      * An EXACTFish node can be generated even if not under /i, and vice versa.
19473      * But care must be taken.  An EXACTFish node has to be such that it only
19474      * matches precisely the code points in the class, but we want to generate
19475      * the least restrictive one that does that, to increase the odds of being
19476      * able to join with an adjacent node.  For example, if the class contains
19477      * [kK], we have to make it an EXACTFAA node to prevent the KELVIN SIGN
19478      * from matching.  Whether we are under /i or not is irrelevant in this
19479      * case.  Less obvious is the pattern qr/[\x{02BC}]n/i.  U+02BC is MODIFIER
19480      * LETTER APOSTROPHE. That is supposed to match the single character U+0149
19481      * LATIN SMALL LETTER N PRECEDED BY APOSTROPHE.  And so even though there
19482      * is no simple fold that includes \X{02BC}, there is a multi-char fold
19483      * that does, and so the node generated for it must be an EXACTFish one.
19484      * On the other hand qr/:/i should generate a plain EXACT node since the
19485      * colon participates in no fold whatsoever, and having it be EXACT tells
19486      * the optimizer the target string cannot match unless it has a colon in
19487      * it. */
19488     if (   ! posixl
19489         && ! *invert
19490
19491             /* Only try if there are no more code points in the class than in
19492              * the max possible fold */
19493         &&   inRANGE(partial_cp_count, 1, MAX_FOLD_FROMS + 1))
19494     {
19495         /* We can always make a single code point class into an EXACTish node.
19496          * */
19497         if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches) {
19498             if (LOC) {
19499
19500                 /* Here is /l:  Use EXACTL, except if there is a fold not known
19501                  * until runtime so shows as only a single code point here.
19502                  * For code points above 255, we know which can cause problems
19503                  * by having a potential fold to the Latin1 range. */
19504                 if (  ! FOLD
19505                     || (     start[0] > 255
19506                         && ! is_PROBLEMATIC_LOCALE_FOLD_cp(start[0])))
19507                 {
19508                     op = EXACTL;
19509                 }
19510                 else {
19511                     op = EXACTFL;
19512                 }
19513             }
19514             else if (! FOLD) { /* Not /l and not /i */
19515                 op = (start[0] < 256) ? EXACT : EXACT_REQ8;
19516             }
19517             else if (start[0] < 256) { /* /i, not /l, and the code point is
19518                                           small */
19519
19520                 /* Under /i, it gets a little tricky.  A code point that
19521                  * doesn't participate in a fold should be an EXACT node.  We
19522                  * know this one isn't the result of a simple fold, or there'd
19523                  * be more than one code point in the list, but it could be
19524                  * part of a multi-character fold.  In that case we better not
19525                  * create an EXACT node, as we would wrongly be telling the
19526                  * optimizer that this code point must be in the target string,
19527                  * and that is wrong.  This is because if the sequence around
19528                  * this code point forms a multi-char fold, what needs to be in
19529                  * the string could be the code point that folds to the
19530                  * sequence.
19531                  *
19532                  * This handles the case of below-255 code points, as we have
19533                  * an easy look up for those.  The next clause handles the
19534                  * above-256 one */
19535                 op = IS_IN_SOME_FOLD_L1(start[0])
19536                      ? EXACTFU
19537                      : EXACT;
19538             }
19539             else {  /* /i, larger code point.  Since we are under /i, and have
19540                        just this code point, we know that it can't fold to
19541                        something else, so PL_InMultiCharFold applies to it */
19542                 op = (_invlist_contains_cp(PL_InMultiCharFold, start[0]))
19543                          ? EXACTFU_REQ8
19544                          : EXACT_REQ8;
19545                 }
19546
19547                 value = start[0];
19548         }
19549         else if (  ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
19550                  && _invlist_contains_cp(PL_in_some_fold, start[0]))
19551         {
19552             /* Here, the only runtime dependency, if any, is from /d, and the
19553              * class matches more than one code point, and the lowest code
19554              * point participates in some fold.  It might be that the other
19555              * code points are /i equivalent to this one, and hence they would
19556              * be representable by an EXACTFish node.  Above, we eliminated
19557              * classes that contain too many code points to be EXACTFish, with
19558              * the test for MAX_FOLD_FROMS
19559              *
19560              * First, special case the ASCII fold pairs, like 'B' and 'b'.  We
19561              * do this because we have EXACTFAA at our disposal for the ASCII
19562              * range */
19563             if (partial_cp_count == 2 && isASCII(start[0])) {
19564
19565                 /* The only ASCII characters that participate in folds are
19566                  * alphabetics */
19567                 assert(isALPHA(start[0]));
19568                 if (   end[0] == start[0]   /* First range is a single
19569                                                character, so 2nd exists */
19570                     && isALPHA_FOLD_EQ(start[0], start[1]))
19571                 {
19572                     /* Here, is part of an ASCII fold pair */
19573
19574                     if (   ASCII_FOLD_RESTRICTED
19575                         || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
19576                     {
19577                         /* If the second clause just above was true, it means
19578                          * we can't be under /i, or else the list would have
19579                          * included more than this fold pair.  Therefore we
19580                          * have to exclude the possibility of whatever else it
19581                          * is that folds to these, by using EXACTFAA */
19582                         op = EXACTFAA;
19583                     }
19584                     else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
19585
19586                         /* Here, there's no simple fold that start[0] is part
19587                          * of, but there is a multi-character one.  If we are
19588                          * not under /i, we want to exclude that possibility;
19589                          * if under /i, we want to include it */
19590                         op = (FOLD) ? EXACTFU : EXACTFAA;
19591                     }
19592                     else {
19593
19594                         /* Here, the only possible fold start[0] particpates in
19595                          * is with start[1].  /i or not isn't relevant */
19596                         op = EXACTFU;
19597                     }
19598
19599                     value = toFOLD(start[0]);
19600                 }
19601             }
19602             else if (  ! upper_latin1_only_utf8_matches
19603                      || (   _invlist_len(upper_latin1_only_utf8_matches) == 2
19604                          && PL_fold_latin1[
19605                            invlist_highest(upper_latin1_only_utf8_matches)]
19606                          == start[0]))
19607             {
19608                 /* Here, the smallest character is non-ascii or there are more
19609                  * than 2 code points matched by this node.  Also, we either
19610                  * don't have /d UTF-8 dependent matches, or if we do, they
19611                  * look like they could be a single character that is the fold
19612                  * of the lowest one is in the always-match list.  This test
19613                  * quickly excludes most of the false positives when there are
19614                  * /d UTF-8 depdendent matches.  These are like LATIN CAPITAL
19615                  * LETTER A WITH GRAVE matching LATIN SMALL LETTER A WITH GRAVE
19616                  * iff the target string is UTF-8.  (We don't have to worry
19617                  * above about exceeding the array bounds of PL_fold_latin1[]
19618                  * because any code point in 'upper_latin1_only_utf8_matches'
19619                  * is below 256.)
19620                  *
19621                  * EXACTFAA would apply only to pairs (hence exactly 2 code
19622                  * points) in the ASCII range, so we can't use it here to
19623                  * artificially restrict the fold domain, so we check if the
19624                  * class does or does not match some EXACTFish node.  Further,
19625                  * if we aren't under /i, and and the folded-to character is
19626                  * part of a multi-character fold, we can't do this
19627                  * optimization, as the sequence around it could be that
19628                  * multi-character fold, and we don't here know the context, so
19629                  * we have to assume it is that multi-char fold, to prevent
19630                  * potential bugs.
19631                  *
19632                  * To do the general case, we first find the fold of the lowest
19633                  * code point (which may be higher than that lowest unfolded
19634                  * one), then find everything that folds to it.  (The data
19635                  * structure we have only maps from the folded code points, so
19636                  * we have to do the earlier step.) */
19637
19638                 Size_t foldlen;
19639                 U8 foldbuf[UTF8_MAXBYTES_CASE];
19640                 UV folded = _to_uni_fold_flags(start[0], foldbuf, &foldlen, 0);
19641                 U32 first_fold;
19642                 const U32 * remaining_folds;
19643                 Size_t folds_to_this_cp_count = _inverse_folds(
19644                                                             folded,
19645                                                             &first_fold,
19646                                                             &remaining_folds);
19647                 Size_t folds_count = folds_to_this_cp_count + 1;
19648                 SV * fold_list = _new_invlist(folds_count);
19649                 unsigned int i;
19650
19651                 /* If there are UTF-8 dependent matches, create a temporary
19652                  * list of what this node matches, including them. */
19653                 SV * all_cp_list = NULL;
19654                 SV ** use_this_list = &cp_list;
19655
19656                 if (upper_latin1_only_utf8_matches) {
19657                     all_cp_list = _new_invlist(0);
19658                     use_this_list = &all_cp_list;
19659                     _invlist_union(cp_list,
19660                                    upper_latin1_only_utf8_matches,
19661                                    use_this_list);
19662                 }
19663
19664                 /* Having gotten everything that participates in the fold
19665                  * containing the lowest code point, we turn that into an
19666                  * inversion list, making sure everything is included. */
19667                 fold_list = add_cp_to_invlist(fold_list, start[0]);
19668                 fold_list = add_cp_to_invlist(fold_list, folded);
19669                 if (folds_to_this_cp_count > 0) {
19670                     fold_list = add_cp_to_invlist(fold_list, first_fold);
19671                     for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
19672                         fold_list = add_cp_to_invlist(fold_list,
19673                                                     remaining_folds[i]);
19674                     }
19675                 }
19676
19677                 /* If the fold list is identical to what's in this ANYOF node,
19678                  * the node can be represented by an EXACTFish one instead */
19679                 if (_invlistEQ(*use_this_list, fold_list,
19680                                0 /* Don't complement */ )
19681                 ) {
19682
19683                     /* But, we have to be careful, as mentioned above.  Just
19684                      * the right sequence of characters could match this if it
19685                      * is part of a multi-character fold.  That IS what we want
19686                      * if we are under /i.  But it ISN'T what we want if not
19687                      * under /i, as it could match when it shouldn't.  So, when
19688                      * we aren't under /i and this character participates in a
19689                      * multi-char fold, we don't optimize into an EXACTFish
19690                      * node.  So, for each case below we have to check if we
19691                      * are folding, and if not, if it is not part of a
19692                      * multi-char fold.  */
19693                     if (start[0] > 255) {    /* Highish code point */
19694                         if (FOLD || ! _invlist_contains_cp(
19695                                                    PL_InMultiCharFold, folded))
19696                         {
19697                             op = (LOC)
19698                                  ? EXACTFLU8
19699                                  : (ASCII_FOLD_RESTRICTED)
19700                                    ? EXACTFAA
19701                                    : EXACTFU_REQ8;
19702                             value = folded;
19703                         }
19704                     }   /* Below, the lowest code point < 256 */
19705                     else if (    FOLD
19706                              &&  folded == 's'
19707                              &&  DEPENDS_SEMANTICS)
19708                     {   /* An EXACTF node containing a single character 's',
19709                            can be an EXACTFU if it doesn't get joined with an
19710                            adjacent 's' */
19711                         op = EXACTFU_S_EDGE;
19712                         value = folded;
19713                     }
19714                     else if (     FOLD
19715                              || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
19716                     {
19717                         if (upper_latin1_only_utf8_matches) {
19718                             op = EXACTF;
19719
19720                             /* We can't use the fold, as that only matches
19721                              * under UTF-8 */
19722                             value = start[0];
19723                         }
19724                         else if (     UNLIKELY(start[0] == MICRO_SIGN)
19725                                  && ! UTF)
19726                         {   /* EXACTFUP is a special node for this character */
19727                             op = (ASCII_FOLD_RESTRICTED)
19728                                  ? EXACTFAA
19729                                  : EXACTFUP;
19730                             value = MICRO_SIGN;
19731                         }
19732                         else if (     ASCII_FOLD_RESTRICTED
19733                                  && ! isASCII(start[0]))
19734                         {   /* For ASCII under /iaa, we can use EXACTFU below
19735                              */
19736                             op = EXACTFAA;
19737                             value = folded;
19738                         }
19739                         else {
19740                             op = EXACTFU;
19741                             value = folded;
19742                         }
19743                     }
19744                 }
19745
19746                 SvREFCNT_dec_NN(fold_list);
19747                 SvREFCNT_dec(all_cp_list);
19748             }
19749         }
19750
19751         if (op != END) {
19752             U8 len;
19753
19754             /* Here, we have calculated what EXACTish node to use.  Have to
19755              * convert to UTF-8 if not already there */
19756             if (value > 255) {
19757                 if (! UTF) {
19758                     SvREFCNT_dec(cp_list);;
19759                     REQUIRE_UTF8(flagp);
19760                 }
19761
19762                 /* This is a kludge to the special casing issues with this
19763                  * ligature under /aa.  FB05 should fold to FB06, but the call
19764                  * above to _to_uni_fold_flags() didn't find this, as it didn't
19765                  * use the /aa restriction in order to not miss other folds
19766                  * that would be affected.  This is the only instance likely to
19767                  * ever be a problem in all of Unicode.  So special case it. */
19768                 if (   value == LATIN_SMALL_LIGATURE_LONG_S_T
19769                     && ASCII_FOLD_RESTRICTED)
19770                 {
19771                     value = LATIN_SMALL_LIGATURE_ST;
19772                 }
19773             }
19774
19775             len = (UTF) ? UVCHR_SKIP(value) : 1;
19776
19777             *ret = regnode_guts(pRExC_state, op, len, "exact");
19778             FILL_NODE(*ret, op);
19779             RExC_emit += 1 + STR_SZ(len);
19780             setSTR_LEN(REGNODE_p(*ret), len);
19781             if (len == 1) {
19782                 *STRINGs(REGNODE_p(*ret)) = (U8) value;
19783             }
19784             else {
19785                 uvchr_to_utf8((U8 *) STRINGs(REGNODE_p(*ret)), value);
19786             }
19787             return op;
19788         }
19789     }
19790
19791     if (! has_runtime_dependency) {
19792
19793         /* See if this can be turned into an ANYOFM node.  Think about the bit
19794          * patterns in two different bytes.  In some positions, the bits in
19795          * each will be 1; and in other positions both will be 0; and in some
19796          * positions the bit will be 1 in one byte, and 0 in the other.  Let
19797          * 'n' be the number of positions where the bits differ.  We create a
19798          * mask which has exactly 'n' 0 bits, each in a position where the two
19799          * bytes differ.  Now take the set of all bytes that when ANDed with
19800          * the mask yield the same result.  That set has 2**n elements, and is
19801          * representable by just two 8 bit numbers: the result and the mask.
19802          * Importantly, matching the set can be vectorized by creating a word
19803          * full of the result bytes, and a word full of the mask bytes,
19804          * yielding a significant speed up.  Here, see if this node matches
19805          * such a set.  As a concrete example consider [01], and the byte
19806          * representing '0' which is 0x30 on ASCII machines.  It has the bits
19807          * 0011 0000.  Take the mask 1111 1110.  If we AND 0x31 and 0x30 with
19808          * that mask we get 0x30.  Any other bytes ANDed yield something else.
19809          * So [01], which is a common usage, is optimizable into ANYOFM, and
19810          * can benefit from the speed up.  We can only do this on UTF-8
19811          * invariant bytes, because they have the same bit patterns under UTF-8
19812          * as not. */
19813         PERL_UINT_FAST8_T inverted = 0;
19814
19815         /* Highest possible UTF-8 invariant is 7F on ASCII platforms; FF on
19816          * EBCDIC */
19817         const PERL_UINT_FAST8_T max_permissible
19818                                     = nBIT_UMAX(7 + ONE_IF_EBCDIC_ZERO_IF_NOT);
19819
19820         /* If doesn't fit the criteria for ANYOFM, invert and try again.  If
19821          * that works we will instead later generate an NANYOFM, and invert
19822          * back when through */
19823         if (invlist_highest(cp_list) > max_permissible) {
19824             _invlist_invert(cp_list);
19825             inverted = 1;
19826         }
19827
19828         if (invlist_highest(cp_list) <= max_permissible) {
19829             UV this_start, this_end;
19830             UV lowest_cp = UV_MAX;  /* init'ed to suppress compiler warn */
19831             U8 bits_differing = 0;
19832             Size_t full_cp_count = 0;
19833             bool first_time = TRUE;
19834
19835             /* Go through the bytes and find the bit positions that differ */
19836             invlist_iterinit(cp_list);
19837             while (invlist_iternext(cp_list, &this_start, &this_end)) {
19838                 unsigned int i = this_start;
19839
19840                 if (first_time) {
19841                     if (! UVCHR_IS_INVARIANT(i)) {
19842                         goto done_anyofm;
19843                     }
19844
19845                     first_time = FALSE;
19846                     lowest_cp = this_start;
19847
19848                     /* We have set up the code point to compare with.  Don't
19849                      * compare it with itself */
19850                     i++;
19851                 }
19852
19853                 /* Find the bit positions that differ from the lowest code
19854                  * point in the node.  Keep track of all such positions by
19855                  * OR'ing */
19856                 for (; i <= this_end; i++) {
19857                     if (! UVCHR_IS_INVARIANT(i)) {
19858                         goto done_anyofm;
19859                     }
19860
19861                     bits_differing  |= i ^ lowest_cp;
19862                 }
19863
19864                 full_cp_count += this_end - this_start + 1;
19865             }
19866
19867             /* At the end of the loop, we count how many bits differ from the
19868              * bits in lowest code point, call the count 'd'.  If the set we
19869              * found contains 2**d elements, it is the closure of all code
19870              * points that differ only in those bit positions.  To convince
19871              * yourself of that, first note that the number in the closure must
19872              * be a power of 2, which we test for.  The only way we could have
19873              * that count and it be some differing set, is if we got some code
19874              * points that don't differ from the lowest code point in any
19875              * position, but do differ from each other in some other position.
19876              * That means one code point has a 1 in that position, and another
19877              * has a 0.  But that would mean that one of them differs from the
19878              * lowest code point in that position, which possibility we've
19879              * already excluded.  */
19880             if (  (inverted || full_cp_count > 1)
19881                 && full_cp_count == 1U << PL_bitcount[bits_differing])
19882             {
19883                 U8 ANYOFM_mask;
19884
19885                 op = ANYOFM + inverted;;
19886
19887                 /* We need to make the bits that differ be 0's */
19888                 ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
19889
19890                 /* The argument is the lowest code point */
19891                 *ret = reganode(pRExC_state, op, lowest_cp);
19892                 FLAGS(REGNODE_p(*ret)) = ANYOFM_mask;
19893             }
19894
19895           done_anyofm:
19896             invlist_iterfinish(cp_list);
19897         }
19898
19899         if (inverted) {
19900             _invlist_invert(cp_list);
19901         }
19902
19903         if (op != END) {
19904             return op;
19905         }
19906
19907         /* XXX We could create an ANYOFR_LOW node here if we saved above if all
19908          * were invariants, it wasn't inverted, and there is a single range.
19909          * This would be faster than some of the posix nodes we create below
19910          * like /\d/a, but would be twice the size.  Without having actually
19911          * measured the gain, khw doesn't think the tradeoff is really worth it
19912          * */
19913     }
19914
19915     if (! (*anyof_flags & ANYOF_LOCALE_FLAGS)) {
19916         PERL_UINT_FAST8_T type;
19917         SV * intersection = NULL;
19918         SV* d_invlist = NULL;
19919
19920         /* See if this matches any of the POSIX classes.  The POSIXA and POSIXD
19921          * ones are about the same speed as ANYOF ops, but take less room; the
19922          * ones that have above-Latin1 code point matches are somewhat faster
19923          * than ANYOF. */
19924
19925         for (type = POSIXA; type >= POSIXD; type--) {
19926             int posix_class;
19927
19928             if (type == POSIXL) {   /* But not /l posix classes */
19929                 continue;
19930             }
19931
19932             for (posix_class = 0;
19933                  posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
19934                  posix_class++)
19935             {
19936                 SV** our_code_points = &cp_list;
19937                 SV** official_code_points;
19938                 int try_inverted;
19939
19940                 if (type == POSIXA) {
19941                     official_code_points = &PL_Posix_ptrs[posix_class];
19942                 }
19943                 else {
19944                     official_code_points = &PL_XPosix_ptrs[posix_class];
19945                 }
19946
19947                 /* Skip non-existent classes of this type.  e.g. \v only has an
19948                  * entry in PL_XPosix_ptrs */
19949                 if (! *official_code_points) {
19950                     continue;
19951                 }
19952
19953                 /* Try both the regular class, and its inversion */
19954                 for (try_inverted = 0; try_inverted < 2; try_inverted++) {
19955                     bool this_inverted = *invert ^ try_inverted;
19956
19957                     if (type != POSIXD) {
19958
19959                         /* This class that isn't /d can't match if we have /d
19960                          * dependencies */
19961                         if (has_runtime_dependency
19962                                                 & HAS_D_RUNTIME_DEPENDENCY)
19963                         {
19964                             continue;
19965                         }
19966                     }
19967                     else /* is /d */ if (! this_inverted) {
19968
19969                         /* /d classes don't match anything non-ASCII below 256
19970                          * unconditionally (which cp_list contains) */
19971                         _invlist_intersection(cp_list, PL_UpperLatin1,
19972                                                        &intersection);
19973                         if (_invlist_len(intersection) != 0) {
19974                             continue;
19975                         }
19976
19977                         SvREFCNT_dec(d_invlist);
19978                         d_invlist = invlist_clone(cp_list, NULL);
19979
19980                         /* But under UTF-8 it turns into using /u rules.  Add
19981                          * the things it matches under these conditions so that
19982                          * we check below that these are identical to what the
19983                          * tested class should match */
19984                         if (upper_latin1_only_utf8_matches) {
19985                             _invlist_union(
19986                                         d_invlist,
19987                                         upper_latin1_only_utf8_matches,
19988                                         &d_invlist);
19989                         }
19990                         our_code_points = &d_invlist;
19991                     }
19992                     else {  /* POSIXD, inverted.  If this doesn't have this
19993                                flag set, it isn't /d. */
19994                         if (! (*anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
19995                         {
19996                             continue;
19997                         }
19998                         our_code_points = &cp_list;
19999                     }
20000
20001                     /* Here, have weeded out some things.  We want to see if
20002                      * the list of characters this node contains
20003                      * ('*our_code_points') precisely matches those of the
20004                      * class we are currently checking against
20005                      * ('*official_code_points'). */
20006                     if (_invlistEQ(*our_code_points,
20007                                    *official_code_points,
20008                                    try_inverted))
20009                     {
20010                         /* Here, they precisely match.  Optimize this ANYOF
20011                          * node into its equivalent POSIX one of the correct
20012                          * type, possibly inverted */
20013                         op = (try_inverted)
20014                             ? type + NPOSIXA - POSIXA
20015                             : type;
20016                         *ret = reg_node(pRExC_state, op);
20017                         FLAGS(REGNODE_p(*ret)) = posix_class;
20018                         SvREFCNT_dec(d_invlist);
20019                         SvREFCNT_dec(intersection);
20020                         return op;
20021                     }
20022                 }
20023             }
20024         }
20025         SvREFCNT_dec(d_invlist);
20026         SvREFCNT_dec(intersection);
20027     }
20028
20029     /* If it is a single contiguous range, ANYOFR is an efficient regnode, both
20030      * in size and speed.  Currently, a 20 bit range base (smallest code point
20031      * in the range), and a 12 bit maximum delta are packed into a 32 bit word.
20032      * This allows for using it on all of the Unicode code points except for
20033      * the highest plane, which is only for private use code points.  khw
20034      * doubts that a bigger delta is likely in real world applications */
20035     if (     single_range
20036         && ! has_runtime_dependency
20037         &&   *anyof_flags == 0
20038         &&   start[0] < (1 << ANYOFR_BASE_BITS)
20039         &&   end[0] - start[0]
20040                 < ((1U << (sizeof(((struct regnode_1 *)NULL)->arg1)
20041                                * CHARBITS - ANYOFR_BASE_BITS))))
20042
20043     {
20044         U8 low_utf8[UTF8_MAXBYTES+1];
20045         U8 high_utf8[UTF8_MAXBYTES+1];
20046
20047         op = ANYOFR;
20048         *ret = reganode(pRExC_state, op,
20049                         (start[0] | (end[0] - start[0]) << ANYOFR_BASE_BITS));
20050
20051         /* Place the lowest UTF-8 start byte in the flags field, so as to allow
20052          * efficient ruling out at run time of many possible inputs.  */
20053         (void) uvchr_to_utf8(low_utf8, start[0]);
20054         (void) uvchr_to_utf8(high_utf8, end[0]);
20055
20056         /* If all code points share the same first byte, this can be an
20057          * ANYOFRb.  Otherwise store the lowest UTF-8 start byte which can
20058          * quickly rule out many inputs at run-time without having to compute
20059          * the code point from UTF-8.  For EBCDIC, we use I8, as not doing that
20060          * transformation would not rule out nearly so many things */
20061         if (low_utf8[0] == high_utf8[0]) {
20062             op = ANYOFRb;
20063             OP(REGNODE_p(*ret)) = op;
20064             ANYOF_FLAGS(REGNODE_p(*ret)) = low_utf8[0];
20065         }
20066         else {
20067             ANYOF_FLAGS(REGNODE_p(*ret)) = NATIVE_UTF8_TO_I8(low_utf8[0]);
20068         }
20069
20070         return op;
20071     }
20072
20073     /* If didn't find an optimization and there is no need for a bitmap,
20074      * optimize to indicate that */
20075     if (     start[0] >= NUM_ANYOF_CODE_POINTS
20076         && ! LOC
20077         && ! upper_latin1_only_utf8_matches
20078         &&   *anyof_flags == 0)
20079     {
20080         U8 low_utf8[UTF8_MAXBYTES+1];
20081         UV highest_cp = invlist_highest(cp_list);
20082
20083         /* Currently the maximum allowed code point by the system is IV_MAX.
20084          * Higher ones are reserved for future internal use.  This particular
20085          * regnode can be used for higher ones, but we can't calculate the code
20086          * point of those.  IV_MAX suffices though, as it will be a large first
20087          * byte */
20088         Size_t low_len = uvchr_to_utf8(low_utf8, MIN(start[0], IV_MAX))
20089                        - low_utf8;
20090
20091         /* We store the lowest possible first byte of the UTF-8 representation,
20092          * using the flags field.  This allows for quick ruling out of some
20093          * inputs without having to convert from UTF-8 to code point.  For
20094          * EBCDIC, we use I8, as not doing that transformation would not rule
20095          * out nearly so many things */
20096         *anyof_flags = NATIVE_UTF8_TO_I8(low_utf8[0]);
20097
20098         op = ANYOFH;
20099
20100         /* If the first UTF-8 start byte for the highest code point in the
20101          * range is suitably small, we may be able to get an upper bound as
20102          * well */
20103         if (highest_cp <= IV_MAX) {
20104             U8 high_utf8[UTF8_MAXBYTES+1];
20105             Size_t high_len = uvchr_to_utf8(high_utf8, highest_cp) - high_utf8;
20106
20107             /* If the lowest and highest are the same, we can get an exact
20108              * first byte instead of a just minimum or even a sequence of exact
20109              * leading bytes.  We signal these with different regnodes */
20110             if (low_utf8[0] == high_utf8[0]) {
20111                 Size_t len = find_first_differing_byte_pos(low_utf8,
20112                                                            high_utf8,
20113                                                    MIN(low_len, high_len));
20114
20115                 if (len == 1) {
20116
20117                     /* No need to convert to I8 for EBCDIC as this is an exact
20118                      * match */
20119                     *anyof_flags = low_utf8[0];
20120                     op = ANYOFHb;
20121                 }
20122                 else {
20123                     op = ANYOFHs;
20124                     *ret = regnode_guts(pRExC_state, op,
20125                                        regarglen[op] + STR_SZ(len),
20126                                        "anyofhs");
20127                     FILL_NODE(*ret, op);
20128                     ((struct regnode_anyofhs *) REGNODE_p(*ret))->str_len
20129                                                                     = len;
20130                     Copy(low_utf8,  /* Add the common bytes */
20131                     ((struct regnode_anyofhs *) REGNODE_p(*ret))->string,
20132                        len, U8);
20133                     RExC_emit += NODE_SZ_STR(REGNODE_p(*ret));
20134                     set_ANYOF_arg(pRExC_state, REGNODE_p(*ret), cp_list,
20135                                               NULL, only_utf8_locale_list);
20136                     return op;
20137                 }
20138             }
20139             else if (NATIVE_UTF8_TO_I8(high_utf8[0]) <= MAX_ANYOF_HRx_BYTE) {
20140
20141                 /* Here, the high byte is not the same as the low, but is small
20142                  * enough that its reasonable to have a loose upper bound,
20143                  * which is packed in with the strict lower bound.  See
20144                  * comments at the definition of MAX_ANYOF_HRx_BYTE.  On EBCDIC
20145                  * platforms, I8 is used.  On ASCII platforms I8 is the same
20146                  * thing as UTF-8 */
20147
20148                 U8 bits = 0;
20149                 U8 max_range_diff = MAX_ANYOF_HRx_BYTE - *anyof_flags;
20150                 U8 range_diff = NATIVE_UTF8_TO_I8(high_utf8[0])
20151                             - *anyof_flags;
20152
20153                 if (range_diff <= max_range_diff / 8) {
20154                     bits = 3;
20155                 }
20156                 else if (range_diff <= max_range_diff / 4) {
20157                     bits = 2;
20158                 }
20159                 else if (range_diff <= max_range_diff / 2) {
20160                     bits = 1;
20161                 }
20162                 *anyof_flags = (*anyof_flags - 0xC0) << 2 | bits;
20163                 op = ANYOFHr;
20164             }
20165         }
20166     }
20167
20168     return op;
20169
20170   return_OPFAIL:
20171     op = OPFAIL;
20172     *ret = reganode(pRExC_state, op, 0);
20173     return op;
20174
20175   return_SANY:
20176     op = SANY;
20177     *ret = reg_node(pRExC_state, op);
20178     MARK_NAUGHTY(1);
20179     return op;
20180 }
20181
20182 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
20183
20184 STATIC void
20185 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
20186                 regnode* const node,
20187                 SV* const cp_list,
20188                 SV* const runtime_defns,
20189                 SV* const only_utf8_locale_list)
20190 {
20191     /* Sets the arg field of an ANYOF-type node 'node', using information about
20192      * the node passed-in.  If there is nothing outside the node's bitmap, the
20193      * arg is set to ANYOF_ONLY_HAS_BITMAP.  Otherwise, it sets the argument to
20194      * the count returned by add_data(), having allocated and stored an array,
20195      * av, as follows:
20196      *
20197      *  av[0] stores the inversion list defining this class as far as known at
20198      *        this time, or PL_sv_undef if nothing definite is now known.
20199      *  av[1] stores the inversion list of code points that match only if the
20200      *        current locale is UTF-8, or if none, PL_sv_undef if there is an
20201      *        av[2], or no entry otherwise.
20202      *  av[2] stores the list of user-defined properties whose subroutine
20203      *        definitions aren't known at this time, or no entry if none. */
20204
20205     UV n;
20206
20207     PERL_ARGS_ASSERT_SET_ANYOF_ARG;
20208
20209     if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
20210         assert(! (ANYOF_FLAGS(node)
20211                 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
20212         ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
20213     }
20214     else {
20215         AV * const av = newAV();
20216         SV *rv;
20217
20218         if (cp_list) {
20219             av_store(av, INVLIST_INDEX, SvREFCNT_inc_NN(cp_list));
20220         }
20221
20222         /* (Note that if any of this changes, the size calculations in
20223          * S_optimize_regclass() might need to be updated.) */
20224
20225         if (only_utf8_locale_list) {
20226             av_store(av, ONLY_LOCALE_MATCHES_INDEX,
20227                                      SvREFCNT_inc_NN(only_utf8_locale_list));
20228         }
20229
20230         if (runtime_defns) {
20231             av_store(av, DEFERRED_USER_DEFINED_INDEX,
20232                          SvREFCNT_inc_NN(runtime_defns));
20233         }
20234
20235         rv = newRV_noinc(MUTABLE_SV(av));
20236         n = add_data(pRExC_state, STR_WITH_LEN("s"));
20237         RExC_rxi->data->data[n] = (void*)rv;
20238         ARG_SET(node, n);
20239     }
20240 }
20241
20242 SV *
20243
20244 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
20245 Perl_get_regclass_nonbitmap_data(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV** only_utf8_locale_ptr, SV** output_invlist)
20246 #else
20247 Perl_get_re_gclass_nonbitmap_data(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV** only_utf8_locale_ptr, SV** output_invlist)
20248 #endif
20249
20250 {
20251     /* For internal core use only.
20252      * Returns the inversion list for the input 'node' in the regex 'prog'.
20253      * If <doinit> is 'true', will attempt to create the inversion list if not
20254      *    already done.
20255      * If <listsvp> is non-null, will return the printable contents of the
20256      *    property definition.  This can be used to get debugging information
20257      *    even before the inversion list exists, by calling this function with
20258      *    'doinit' set to false, in which case the components that will be used
20259      *    to eventually create the inversion list are returned  (in a printable
20260      *    form).
20261      * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
20262      *    store an inversion list of code points that should match only if the
20263      *    execution-time locale is a UTF-8 one.
20264      * If <output_invlist> is not NULL, it is where this routine is to store an
20265      *    inversion list of the code points that would be instead returned in
20266      *    <listsvp> if this were NULL.  Thus, what gets output in <listsvp>
20267      *    when this parameter is used, is just the non-code point data that
20268      *    will go into creating the inversion list.  This currently should be just
20269      *    user-defined properties whose definitions were not known at compile
20270      *    time.  Using this parameter allows for easier manipulation of the
20271      *    inversion list's data by the caller.  It is illegal to call this
20272      *    function with this parameter set, but not <listsvp>
20273      *
20274      * Tied intimately to how S_set_ANYOF_arg sets up the data structure.  Note
20275      * that, in spite of this function's name, the inversion list it returns
20276      * may include the bitmap data as well */
20277
20278     SV *si  = NULL;         /* Input initialization string */
20279     SV* invlist = NULL;
20280
20281     RXi_GET_DECL(prog, progi);
20282     const struct reg_data * const data = prog ? progi->data : NULL;
20283
20284 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
20285     PERL_ARGS_ASSERT_GET_REGCLASS_NONBITMAP_DATA;
20286 #else
20287     PERL_ARGS_ASSERT_GET_RE_GCLASS_NONBITMAP_DATA;
20288 #endif
20289     assert(! output_invlist || listsvp);
20290
20291     if (data && data->count) {
20292         const U32 n = ARG(node);
20293
20294         if (data->what[n] == 's') {
20295             SV * const rv = MUTABLE_SV(data->data[n]);
20296             AV * const av = MUTABLE_AV(SvRV(rv));
20297             SV **const ary = AvARRAY(av);
20298
20299             invlist = ary[INVLIST_INDEX];
20300
20301             if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
20302                 *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
20303             }
20304
20305             if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
20306                 si = ary[DEFERRED_USER_DEFINED_INDEX];
20307             }
20308
20309             if (doinit && (si || invlist)) {
20310                 if (si) {
20311                     bool user_defined;
20312                     SV * msg = newSVpvs_flags("", SVs_TEMP);
20313
20314                     SV * prop_definition = handle_user_defined_property(
20315                             "", 0, FALSE,   /* There is no \p{}, \P{} */
20316                             SvPVX_const(si)[1] - '0',   /* /i or not has been
20317                                                            stored here for just
20318                                                            this occasion */
20319                             TRUE,           /* run time */
20320                             FALSE,          /* This call must find the defn */
20321                             si,             /* The property definition  */
20322                             &user_defined,
20323                             msg,
20324                             0               /* base level call */
20325                            );
20326
20327                     if (SvCUR(msg)) {
20328                         assert(prop_definition == NULL);
20329
20330                         Perl_croak(aTHX_ "%" UTF8f,
20331                                 UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
20332                     }
20333
20334                     if (invlist) {
20335                         _invlist_union(invlist, prop_definition, &invlist);
20336                         SvREFCNT_dec_NN(prop_definition);
20337                     }
20338                     else {
20339                         invlist = prop_definition;
20340                     }
20341
20342                     STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
20343                     STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
20344
20345                     ary[INVLIST_INDEX] = invlist;
20346                     av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
20347                                  ? ONLY_LOCALE_MATCHES_INDEX
20348                                  : INVLIST_INDEX);
20349                     si = NULL;
20350                 }
20351             }
20352         }
20353     }
20354
20355     /* If requested, return a printable version of what this ANYOF node matches
20356      * */
20357     if (listsvp) {
20358         SV* matches_string = NULL;
20359
20360         /* This function can be called at compile-time, before everything gets
20361          * resolved, in which case we return the currently best available
20362          * information, which is the string that will eventually be used to do
20363          * that resolving, 'si' */
20364         if (si) {
20365             /* Here, we only have 'si' (and possibly some passed-in data in
20366              * 'invlist', which is handled below)  If the caller only wants
20367              * 'si', use that.  */
20368             if (! output_invlist) {
20369                 matches_string = newSVsv(si);
20370             }
20371             else {
20372                 /* But if the caller wants an inversion list of the node, we
20373                  * need to parse 'si' and place as much as possible in the
20374                  * desired output inversion list, making 'matches_string' only
20375                  * contain the currently unresolvable things */
20376                 const char *si_string = SvPVX(si);
20377                 STRLEN remaining = SvCUR(si);
20378                 UV prev_cp = 0;
20379                 U8 count = 0;
20380
20381                 /* Ignore everything before and including the first new-line */
20382                 si_string = (const char *) memchr(si_string, '\n', SvCUR(si));
20383                 assert (si_string != NULL);
20384                 si_string++;
20385                 remaining = SvPVX(si) + SvCUR(si) - si_string;
20386
20387                 while (remaining > 0) {
20388
20389                     /* The data consists of just strings defining user-defined
20390                      * property names, but in prior incarnations, and perhaps
20391                      * somehow from pluggable regex engines, it could still
20392                      * hold hex code point definitions, all of which should be
20393                      * legal (or it wouldn't have gotten this far).  Each
20394                      * component of a range would be separated by a tab, and
20395                      * each range by a new-line.  If these are found, instead
20396                      * add them to the inversion list */
20397                     I32 grok_flags =  PERL_SCAN_SILENT_ILLDIGIT
20398                                      |PERL_SCAN_SILENT_NON_PORTABLE;
20399                     STRLEN len = remaining;
20400                     UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
20401
20402                     /* If the hex decode routine found something, it should go
20403                      * up to the next \n */
20404                     if (   *(si_string + len) == '\n') {
20405                         if (count) {    /* 2nd code point on line */
20406                             *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
20407                         }
20408                         else {
20409                             *output_invlist = add_cp_to_invlist(*output_invlist, cp);
20410                         }
20411                         count = 0;
20412                         goto prepare_for_next_iteration;
20413                     }
20414
20415                     /* If the hex decode was instead for the lower range limit,
20416                      * save it, and go parse the upper range limit */
20417                     if (*(si_string + len) == '\t') {
20418                         assert(count == 0);
20419
20420                         prev_cp = cp;
20421                         count = 1;
20422                       prepare_for_next_iteration:
20423                         si_string += len + 1;
20424                         remaining -= len + 1;
20425                         continue;
20426                     }
20427
20428                     /* Here, didn't find a legal hex number.  Just add the text
20429                      * from here up to the next \n, omitting any trailing
20430                      * markers. */
20431
20432                     remaining -= len;
20433                     len = strcspn(si_string,
20434                                         DEFERRED_COULD_BE_OFFICIAL_MARKERs "\n");
20435                     remaining -= len;
20436                     if (matches_string) {
20437                         sv_catpvn(matches_string, si_string, len);
20438                     }
20439                     else {
20440                         matches_string = newSVpvn(si_string, len);
20441                     }
20442                     sv_catpvs(matches_string, " ");
20443
20444                     si_string += len;
20445                     if (   remaining
20446                         && UCHARAT(si_string)
20447                                             == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
20448                     {
20449                         si_string++;
20450                         remaining--;
20451                     }
20452                     if (remaining && UCHARAT(si_string) == '\n') {
20453                         si_string++;
20454                         remaining--;
20455                     }
20456                 } /* end of loop through the text */
20457
20458                 assert(matches_string);
20459                 if (SvCUR(matches_string)) {  /* Get rid of trailing blank */
20460                     SvCUR_set(matches_string, SvCUR(matches_string) - 1);
20461                 }
20462             } /* end of has an 'si' */
20463         }
20464
20465         /* Add the stuff that's already known */
20466         if (invlist) {
20467
20468             /* Again, if the caller doesn't want the output inversion list, put
20469              * everything in 'matches-string' */
20470             if (! output_invlist) {
20471                 if ( ! matches_string) {
20472                     matches_string = newSVpvs("\n");
20473                 }
20474                 sv_catsv(matches_string, invlist_contents(invlist,
20475                                                   TRUE /* traditional style */
20476                                                   ));
20477             }
20478             else if (! *output_invlist) {
20479                 *output_invlist = invlist_clone(invlist, NULL);
20480             }
20481             else {
20482                 _invlist_union(*output_invlist, invlist, output_invlist);
20483             }
20484         }
20485
20486         *listsvp = matches_string;
20487     }
20488
20489     return invlist;
20490 }
20491
20492 /* reg_skipcomment()
20493
20494    Absorbs an /x style # comment from the input stream,
20495    returning a pointer to the first character beyond the comment, or if the
20496    comment terminates the pattern without anything following it, this returns
20497    one past the final character of the pattern (in other words, RExC_end) and
20498    sets the REG_RUN_ON_COMMENT_SEEN flag.
20499
20500    Note it's the callers responsibility to ensure that we are
20501    actually in /x mode
20502
20503 */
20504
20505 PERL_STATIC_INLINE char*
20506 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
20507 {
20508     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
20509
20510     assert(*p == '#');
20511
20512     while (p < RExC_end) {
20513         if (*(++p) == '\n') {
20514             return p+1;
20515         }
20516     }
20517
20518     /* we ran off the end of the pattern without ending the comment, so we have
20519      * to add an \n when wrapping */
20520     RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
20521     return p;
20522 }
20523
20524 STATIC void
20525 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
20526                                 char ** p,
20527                                 const bool force_to_xmod
20528                          )
20529 {
20530     /* If the text at the current parse position '*p' is a '(?#...)' comment,
20531      * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
20532      * is /x whitespace, advance '*p' so that on exit it points to the first
20533      * byte past all such white space and comments */
20534
20535     const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
20536
20537     PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
20538
20539     assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
20540
20541     for (;;) {
20542         if (RExC_end - (*p) >= 3
20543             && *(*p)     == '('
20544             && *(*p + 1) == '?'
20545             && *(*p + 2) == '#')
20546         {
20547             while (*(*p) != ')') {
20548                 if ((*p) == RExC_end)
20549                     FAIL("Sequence (?#... not terminated");
20550                 (*p)++;
20551             }
20552             (*p)++;
20553             continue;
20554         }
20555
20556         if (use_xmod) {
20557             const char * save_p = *p;
20558             while ((*p) < RExC_end) {
20559                 STRLEN len;
20560                 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
20561                     (*p) += len;
20562                 }
20563                 else if (*(*p) == '#') {
20564                     (*p) = reg_skipcomment(pRExC_state, (*p));
20565                 }
20566                 else {
20567                     break;
20568                 }
20569             }
20570             if (*p != save_p) {
20571                 continue;
20572             }
20573         }
20574
20575         break;
20576     }
20577
20578     return;
20579 }
20580
20581 /* nextchar()
20582
20583    Advances the parse position by one byte, unless that byte is the beginning
20584    of a '(?#...)' style comment, or is /x whitespace and /x is in effect.  In
20585    those two cases, the parse position is advanced beyond all such comments and
20586    white space.
20587
20588    This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
20589 */
20590
20591 STATIC void
20592 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
20593 {
20594     PERL_ARGS_ASSERT_NEXTCHAR;
20595
20596     if (RExC_parse < RExC_end) {
20597         assert(   ! UTF
20598                || UTF8_IS_INVARIANT(*RExC_parse)
20599                || UTF8_IS_START(*RExC_parse));
20600
20601         RExC_parse += (UTF)
20602                       ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
20603                       : 1;
20604
20605         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
20606                                 FALSE /* Don't force /x */ );
20607     }
20608 }
20609
20610 STATIC void
20611 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
20612 {
20613     /* 'size' is the delta number of smallest regnode equivalents to add or
20614      * subtract from the current memory allocated to the regex engine being
20615      * constructed. */
20616
20617     PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
20618
20619     RExC_size += size;
20620
20621     Renewc(RExC_rxi,
20622            sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
20623                                                 /* +1 for REG_MAGIC */
20624            char,
20625            regexp_internal);
20626     if ( RExC_rxi == NULL )
20627         FAIL("Regexp out of space");
20628     RXi_SET(RExC_rx, RExC_rxi);
20629
20630     RExC_emit_start = RExC_rxi->program;
20631     if (size > 0) {
20632         Zero(REGNODE_p(RExC_emit), size, regnode);
20633     }
20634
20635 #ifdef RE_TRACK_PATTERN_OFFSETS
20636     Renew(RExC_offsets, 2*RExC_size+1, U32);
20637     if (size > 0) {
20638         Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
20639     }
20640     RExC_offsets[0] = RExC_size;
20641 #endif
20642 }
20643
20644 STATIC regnode_offset
20645 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
20646 {
20647     /* Allocate a regnode for 'op', with 'extra_size' extra (smallest) regnode
20648      * equivalents space.  It aligns and increments RExC_size
20649      *
20650      * It returns the regnode's offset into the regex engine program */
20651
20652     const regnode_offset ret = RExC_emit;
20653
20654     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20655
20656     PERL_ARGS_ASSERT_REGNODE_GUTS;
20657
20658     SIZE_ALIGN(RExC_size);
20659     change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
20660     NODE_ALIGN_FILL(REGNODE_p(ret));
20661 #ifndef RE_TRACK_PATTERN_OFFSETS
20662     PERL_UNUSED_ARG(name);
20663     PERL_UNUSED_ARG(op);
20664 #else
20665     assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
20666
20667     if (RExC_offsets) {         /* MJD */
20668         MJD_OFFSET_DEBUG(
20669               ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
20670               name, __LINE__,
20671               PL_reg_name[op],
20672               (UV)(RExC_emit) > RExC_offsets[0]
20673                 ? "Overwriting end of array!\n" : "OK",
20674               (UV)(RExC_emit),
20675               (UV)(RExC_parse - RExC_start),
20676               (UV)RExC_offsets[0]));
20677         Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
20678     }
20679 #endif
20680     return(ret);
20681 }
20682
20683 /*
20684 - reg_node - emit a node
20685 */
20686 STATIC regnode_offset /* Location. */
20687 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
20688 {
20689     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
20690     regnode_offset ptr = ret;
20691
20692     PERL_ARGS_ASSERT_REG_NODE;
20693
20694     assert(regarglen[op] == 0);
20695
20696     FILL_ADVANCE_NODE(ptr, op);
20697     RExC_emit = ptr;
20698     return(ret);
20699 }
20700
20701 /*
20702 - reganode - emit a node with an argument
20703 */
20704 STATIC regnode_offset /* Location. */
20705 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
20706 {
20707     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
20708     regnode_offset ptr = ret;
20709
20710     PERL_ARGS_ASSERT_REGANODE;
20711
20712     /* ANYOF are special cased to allow non-length 1 args */
20713     assert(regarglen[op] == 1);
20714
20715     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
20716     RExC_emit = ptr;
20717     return(ret);
20718 }
20719
20720 /*
20721 - regpnode - emit a temporary node with a SV* argument
20722 */
20723 STATIC regnode_offset /* Location. */
20724 S_regpnode(pTHX_ RExC_state_t *pRExC_state, U8 op, SV * arg)
20725 {
20726     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "regpnode");
20727     regnode_offset ptr = ret;
20728
20729     PERL_ARGS_ASSERT_REGPNODE;
20730
20731     FILL_ADVANCE_NODE_ARGp(ptr, op, arg);
20732     RExC_emit = ptr;
20733     return(ret);
20734 }
20735
20736 STATIC regnode_offset
20737 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
20738 {
20739     /* emit a node with U32 and I32 arguments */
20740
20741     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
20742     regnode_offset ptr = ret;
20743
20744     PERL_ARGS_ASSERT_REG2LANODE;
20745
20746     assert(regarglen[op] == 2);
20747
20748     FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
20749     RExC_emit = ptr;
20750     return(ret);
20751 }
20752
20753 /*
20754 - reginsert - insert an operator in front of already-emitted operand
20755 *
20756 * That means that on exit 'operand' is the offset of the newly inserted
20757 * operator, and the original operand has been relocated.
20758 *
20759 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
20760 * set up NEXT_OFF() of the inserted node if needed. Something like this:
20761 *
20762 *   reginsert(pRExC, OPFAIL, orig_emit, depth+1);
20763 *   NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
20764 *
20765 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
20766 */
20767 STATIC void
20768 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
20769                   const regnode_offset operand, const U32 depth)
20770 {
20771     regnode *src;
20772     regnode *dst;
20773     regnode *place;
20774     const int offset = regarglen[(U8)op];
20775     const int size = NODE_STEP_REGNODE + offset;
20776     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20777
20778     PERL_ARGS_ASSERT_REGINSERT;
20779     PERL_UNUSED_CONTEXT;
20780     PERL_UNUSED_ARG(depth);
20781 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
20782     DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
20783     assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
20784                                     studying. If this is wrong then we need to adjust RExC_recurse
20785                                     below like we do with RExC_open_parens/RExC_close_parens. */
20786     change_engine_size(pRExC_state, (Ptrdiff_t) size);
20787     src = REGNODE_p(RExC_emit);
20788     RExC_emit += size;
20789     dst = REGNODE_p(RExC_emit);
20790
20791     /* If we are in a "count the parentheses" pass, the numbers are unreliable,
20792      * and [perl #133871] shows this can lead to problems, so skip this
20793      * realignment of parens until a later pass when they are reliable */
20794     if (! IN_PARENS_PASS && RExC_open_parens) {
20795         int paren;
20796         /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
20797         /* remember that RExC_npar is rex->nparens + 1,
20798          * iow it is 1 more than the number of parens seen in
20799          * the pattern so far. */
20800         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
20801             /* note, RExC_open_parens[0] is the start of the
20802              * regex, it can't move. RExC_close_parens[0] is the end
20803              * of the regex, it *can* move. */
20804             if ( paren && RExC_open_parens[paren] >= operand ) {
20805                 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
20806                 RExC_open_parens[paren] += size;
20807             } else {
20808                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
20809             }
20810             if ( RExC_close_parens[paren] >= operand ) {
20811                 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
20812                 RExC_close_parens[paren] += size;
20813             } else {
20814                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
20815             }
20816         }
20817     }
20818     if (RExC_end_op)
20819         RExC_end_op += size;
20820
20821     while (src > REGNODE_p(operand)) {
20822         StructCopy(--src, --dst, regnode);
20823 #ifdef RE_TRACK_PATTERN_OFFSETS
20824         if (RExC_offsets) {     /* MJD 20010112 */
20825             MJD_OFFSET_DEBUG(
20826                  ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
20827                   "reginsert",
20828                   __LINE__,
20829                   PL_reg_name[op],
20830                   (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
20831                     ? "Overwriting end of array!\n" : "OK",
20832                   (UV)REGNODE_OFFSET(src),
20833                   (UV)REGNODE_OFFSET(dst),
20834                   (UV)RExC_offsets[0]));
20835             Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
20836             Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
20837         }
20838 #endif
20839     }
20840
20841     place = REGNODE_p(operand); /* Op node, where operand used to be. */
20842 #ifdef RE_TRACK_PATTERN_OFFSETS
20843     if (RExC_offsets) {         /* MJD */
20844         MJD_OFFSET_DEBUG(
20845               ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
20846               "reginsert",
20847               __LINE__,
20848               PL_reg_name[op],
20849               (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
20850               ? "Overwriting end of array!\n" : "OK",
20851               (UV)REGNODE_OFFSET(place),
20852               (UV)(RExC_parse - RExC_start),
20853               (UV)RExC_offsets[0]));
20854         Set_Node_Offset(place, RExC_parse);
20855         Set_Node_Length(place, 1);
20856     }
20857 #endif
20858     src = NEXTOPER(place);
20859     FLAGS(place) = 0;
20860     FILL_NODE(operand, op);
20861
20862     /* Zero out any arguments in the new node */
20863     Zero(src, offset, regnode);
20864 }
20865
20866 /*
20867 - regtail - set the next-pointer at the end of a node chain of p to val.  If
20868             that value won't fit in the space available, instead returns FALSE.
20869             (Except asserts if we can't fit in the largest space the regex
20870             engine is designed for.)
20871 - SEE ALSO: regtail_study
20872 */
20873 STATIC bool
20874 S_regtail(pTHX_ RExC_state_t * pRExC_state,
20875                 const regnode_offset p,
20876                 const regnode_offset val,
20877                 const U32 depth)
20878 {
20879     regnode_offset scan;
20880     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20881
20882     PERL_ARGS_ASSERT_REGTAIL;
20883 #ifndef DEBUGGING
20884     PERL_UNUSED_ARG(depth);
20885 #endif
20886
20887     /* The final node in the chain is the first one with a nonzero next pointer
20888      * */
20889     scan = (regnode_offset) p;
20890     for (;;) {
20891         regnode * const temp = regnext(REGNODE_p(scan));
20892         DEBUG_PARSE_r({
20893             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
20894             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20895             Perl_re_printf( aTHX_  "~ %s (%zu) %s %s\n",
20896                 SvPV_nolen_const(RExC_mysv), scan,
20897                     (temp == NULL ? "->" : ""),
20898                     (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
20899             );
20900         });
20901         if (temp == NULL)
20902             break;
20903         scan = REGNODE_OFFSET(temp);
20904     }
20905
20906     /* Populate this node's next pointer */
20907     assert(val >= scan);
20908     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20909         assert((UV) (val - scan) <= U32_MAX);
20910         ARG_SET(REGNODE_p(scan), val - scan);
20911     }
20912     else {
20913         if (val - scan > U16_MAX) {
20914             /* Populate this with something that won't loop and will likely
20915              * lead to a crash if the caller ignores the failure return, and
20916              * execution continues */
20917             NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20918             return FALSE;
20919         }
20920         NEXT_OFF(REGNODE_p(scan)) = val - scan;
20921     }
20922
20923     return TRUE;
20924 }
20925
20926 #ifdef DEBUGGING
20927 /*
20928 - regtail_study - set the next-pointer at the end of a node chain of p to val.
20929 - Look for optimizable sequences at the same time.
20930 - currently only looks for EXACT chains.
20931
20932 This is experimental code. The idea is to use this routine to perform
20933 in place optimizations on branches and groups as they are constructed,
20934 with the long term intention of removing optimization from study_chunk so
20935 that it is purely analytical.
20936
20937 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
20938 to control which is which.
20939
20940 This used to return a value that was ignored.  It was a problem that it is
20941 #ifdef'd to be another function that didn't return a value.  khw has changed it
20942 so both currently return a pass/fail return.
20943
20944 */
20945 /* TODO: All four parms should be const */
20946
20947 STATIC bool
20948 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
20949                       const regnode_offset val, U32 depth)
20950 {
20951     regnode_offset scan;
20952     U8 exact = PSEUDO;
20953 #ifdef EXPERIMENTAL_INPLACESCAN
20954     I32 min = 0;
20955 #endif
20956     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20957
20958     PERL_ARGS_ASSERT_REGTAIL_STUDY;
20959
20960
20961     /* Find last node. */
20962
20963     scan = p;
20964     for (;;) {
20965         regnode * const temp = regnext(REGNODE_p(scan));
20966 #ifdef EXPERIMENTAL_INPLACESCAN
20967         if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
20968             bool unfolded_multi_char;   /* Unexamined in this routine */
20969             if (join_exact(pRExC_state, scan, &min,
20970                            &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
20971                 return TRUE; /* Was return EXACT */
20972         }
20973 #endif
20974         if ( exact ) {
20975             if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
20976                 if (exact == PSEUDO )
20977                     exact= OP(REGNODE_p(scan));
20978                 else if (exact != OP(REGNODE_p(scan)) )
20979                     exact= 0;
20980             }
20981             else if (OP(REGNODE_p(scan)) != NOTHING) {
20982                 exact= 0;
20983             }
20984         }
20985         DEBUG_PARSE_r({
20986             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
20987             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20988             Perl_re_printf( aTHX_  "~ %s (%zu) -> %s\n",
20989                 SvPV_nolen_const(RExC_mysv),
20990                 scan,
20991                 PL_reg_name[exact]);
20992         });
20993         if (temp == NULL)
20994             break;
20995         scan = REGNODE_OFFSET(temp);
20996     }
20997     DEBUG_PARSE_r({
20998         DEBUG_PARSE_MSG("");
20999         regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
21000         Perl_re_printf( aTHX_
21001                       "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
21002                       SvPV_nolen_const(RExC_mysv),
21003                       (IV)val,
21004                       (IV)(val - scan)
21005         );
21006     });
21007     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
21008         assert((UV) (val - scan) <= U32_MAX);
21009         ARG_SET(REGNODE_p(scan), val - scan);
21010     }
21011     else {
21012         if (val - scan > U16_MAX) {
21013             /* Populate this with something that won't loop and will likely
21014              * lead to a crash if the caller ignores the failure return, and
21015              * execution continues */
21016             NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
21017             return FALSE;
21018         }
21019         NEXT_OFF(REGNODE_p(scan)) = val - scan;
21020     }
21021
21022     return TRUE; /* Was 'return exact' */
21023 }
21024 #endif
21025
21026 STATIC SV*
21027 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
21028
21029     /* Returns an inversion list of all the code points matched by the
21030      * ANYOFM/NANYOFM node 'n' */
21031
21032     SV * cp_list = _new_invlist(-1);
21033     const U8 lowest = (U8) ARG(n);
21034     unsigned int i;
21035     U8 count = 0;
21036     U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
21037
21038     PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
21039
21040     /* Starting with the lowest code point, any code point that ANDed with the
21041      * mask yields the lowest code point is in the set */
21042     for (i = lowest; i <= 0xFF; i++) {
21043         if ((i & FLAGS(n)) == ARG(n)) {
21044             cp_list = add_cp_to_invlist(cp_list, i);
21045             count++;
21046
21047             /* We know how many code points (a power of two) that are in the
21048              * set.  No use looking once we've got that number */
21049             if (count >= needed) break;
21050         }
21051     }
21052
21053     if (OP(n) == NANYOFM) {
21054         _invlist_invert(cp_list);
21055     }
21056     return cp_list;
21057 }
21058
21059 /*
21060  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
21061  */
21062 #ifdef DEBUGGING
21063
21064 static void
21065 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
21066 {
21067     int bit;
21068     int set=0;
21069
21070     ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
21071
21072     for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
21073         if (flags & (1<<bit)) {
21074             if (!set++ && lead)
21075                 Perl_re_printf( aTHX_  "%s", lead);
21076             Perl_re_printf( aTHX_  "%s ", PL_reg_intflags_name[bit]);
21077         }
21078     }
21079     if (lead)  {
21080         if (set)
21081             Perl_re_printf( aTHX_  "\n");
21082         else
21083             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
21084     }
21085 }
21086
21087 static void
21088 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
21089 {
21090     int bit;
21091     int set=0;
21092     regex_charset cs;
21093
21094     ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
21095
21096     for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
21097         if (flags & (1<<bit)) {
21098             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
21099                 continue;
21100             }
21101             if (!set++ && lead)
21102                 Perl_re_printf( aTHX_  "%s", lead);
21103             Perl_re_printf( aTHX_  "%s ", PL_reg_extflags_name[bit]);
21104         }
21105     }
21106     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
21107             if (!set++ && lead) {
21108                 Perl_re_printf( aTHX_  "%s", lead);
21109             }
21110             switch (cs) {
21111                 case REGEX_UNICODE_CHARSET:
21112                     Perl_re_printf( aTHX_  "UNICODE");
21113                     break;
21114                 case REGEX_LOCALE_CHARSET:
21115                     Perl_re_printf( aTHX_  "LOCALE");
21116                     break;
21117                 case REGEX_ASCII_RESTRICTED_CHARSET:
21118                     Perl_re_printf( aTHX_  "ASCII-RESTRICTED");
21119                     break;
21120                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
21121                     Perl_re_printf( aTHX_  "ASCII-MORE_RESTRICTED");
21122                     break;
21123                 default:
21124                     Perl_re_printf( aTHX_  "UNKNOWN CHARACTER SET");
21125                     break;
21126             }
21127     }
21128     if (lead)  {
21129         if (set)
21130             Perl_re_printf( aTHX_  "\n");
21131         else
21132             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
21133     }
21134 }
21135 #endif
21136
21137 void
21138 Perl_regdump(pTHX_ const regexp *r)
21139 {
21140 #ifdef DEBUGGING
21141     int i;
21142     SV * const sv = sv_newmortal();
21143     SV *dsv= sv_newmortal();
21144     RXi_GET_DECL(r, ri);
21145     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21146
21147     PERL_ARGS_ASSERT_REGDUMP;
21148
21149     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
21150
21151     /* Header fields of interest. */
21152     for (i = 0; i < 2; i++) {
21153         if (r->substrs->data[i].substr) {
21154             RE_PV_QUOTED_DECL(s, 0, dsv,
21155                             SvPVX_const(r->substrs->data[i].substr),
21156                             RE_SV_DUMPLEN(r->substrs->data[i].substr),
21157                             PL_dump_re_max_len);
21158             Perl_re_printf( aTHX_
21159                           "%s %s%s at %" IVdf "..%" UVuf " ",
21160                           i ? "floating" : "anchored",
21161                           s,
21162                           RE_SV_TAIL(r->substrs->data[i].substr),
21163                           (IV)r->substrs->data[i].min_offset,
21164                           (UV)r->substrs->data[i].max_offset);
21165         }
21166         else if (r->substrs->data[i].utf8_substr) {
21167             RE_PV_QUOTED_DECL(s, 1, dsv,
21168                             SvPVX_const(r->substrs->data[i].utf8_substr),
21169                             RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
21170                             30);
21171             Perl_re_printf( aTHX_
21172                           "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
21173                           i ? "floating" : "anchored",
21174                           s,
21175                           RE_SV_TAIL(r->substrs->data[i].utf8_substr),
21176                           (IV)r->substrs->data[i].min_offset,
21177                           (UV)r->substrs->data[i].max_offset);
21178         }
21179     }
21180
21181     if (r->check_substr || r->check_utf8)
21182         Perl_re_printf( aTHX_
21183                       (const char *)
21184                       (   r->check_substr == r->substrs->data[1].substr
21185                        && r->check_utf8   == r->substrs->data[1].utf8_substr
21186                        ? "(checking floating" : "(checking anchored"));
21187     if (r->intflags & PREGf_NOSCAN)
21188         Perl_re_printf( aTHX_  " noscan");
21189     if (r->extflags & RXf_CHECK_ALL)
21190         Perl_re_printf( aTHX_  " isall");
21191     if (r->check_substr || r->check_utf8)
21192         Perl_re_printf( aTHX_  ") ");
21193
21194     if (ri->regstclass) {
21195         regprop(r, sv, ri->regstclass, NULL, NULL);
21196         Perl_re_printf( aTHX_  "stclass %s ", SvPVX_const(sv));
21197     }
21198     if (r->intflags & PREGf_ANCH) {
21199         Perl_re_printf( aTHX_  "anchored");
21200         if (r->intflags & PREGf_ANCH_MBOL)
21201             Perl_re_printf( aTHX_  "(MBOL)");
21202         if (r->intflags & PREGf_ANCH_SBOL)
21203             Perl_re_printf( aTHX_  "(SBOL)");
21204         if (r->intflags & PREGf_ANCH_GPOS)
21205             Perl_re_printf( aTHX_  "(GPOS)");
21206         Perl_re_printf( aTHX_ " ");
21207     }
21208     if (r->intflags & PREGf_GPOS_SEEN)
21209         Perl_re_printf( aTHX_  "GPOS:%" UVuf " ", (UV)r->gofs);
21210     if (r->intflags & PREGf_SKIP)
21211         Perl_re_printf( aTHX_  "plus ");
21212     if (r->intflags & PREGf_IMPLICIT)
21213         Perl_re_printf( aTHX_  "implicit ");
21214     Perl_re_printf( aTHX_  "minlen %" IVdf " ", (IV)r->minlen);
21215     if (r->extflags & RXf_EVAL_SEEN)
21216         Perl_re_printf( aTHX_  "with eval ");
21217     Perl_re_printf( aTHX_  "\n");
21218     DEBUG_FLAGS_r({
21219         regdump_extflags("r->extflags: ", r->extflags);
21220         regdump_intflags("r->intflags: ", r->intflags);
21221     });
21222 #else
21223     PERL_ARGS_ASSERT_REGDUMP;
21224     PERL_UNUSED_CONTEXT;
21225     PERL_UNUSED_ARG(r);
21226 #endif  /* DEBUGGING */
21227 }
21228
21229 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
21230 #ifdef DEBUGGING
21231
21232 #  if   _CC_WORDCHAR != 0 || _CC_DIGIT != 1        || _CC_ALPHA != 2    \
21233      || _CC_LOWER != 3    || _CC_UPPER != 4        || _CC_PUNCT != 5    \
21234      || _CC_PRINT != 6    || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8    \
21235      || _CC_CASED != 9    || _CC_SPACE != 10       || _CC_BLANK != 11   \
21236      || _CC_XDIGIT != 12  || _CC_CNTRL != 13       || _CC_ASCII != 14   \
21237      || _CC_VERTSPACE != 15
21238 #   error Need to adjust order of anyofs[]
21239 #  endif
21240 static const char * const anyofs[] = {
21241     "\\w",
21242     "\\W",
21243     "\\d",
21244     "\\D",
21245     "[:alpha:]",
21246     "[:^alpha:]",
21247     "[:lower:]",
21248     "[:^lower:]",
21249     "[:upper:]",
21250     "[:^upper:]",
21251     "[:punct:]",
21252     "[:^punct:]",
21253     "[:print:]",
21254     "[:^print:]",
21255     "[:alnum:]",
21256     "[:^alnum:]",
21257     "[:graph:]",
21258     "[:^graph:]",
21259     "[:cased:]",
21260     "[:^cased:]",
21261     "\\s",
21262     "\\S",
21263     "[:blank:]",
21264     "[:^blank:]",
21265     "[:xdigit:]",
21266     "[:^xdigit:]",
21267     "[:cntrl:]",
21268     "[:^cntrl:]",
21269     "[:ascii:]",
21270     "[:^ascii:]",
21271     "\\v",
21272     "\\V"
21273 };
21274 #endif
21275
21276 /*
21277 - regprop - printable representation of opcode, with run time support
21278 */
21279
21280 void
21281 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
21282 {
21283 #ifdef DEBUGGING
21284     int k;
21285     RXi_GET_DECL(prog, progi);
21286     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21287
21288     PERL_ARGS_ASSERT_REGPROP;
21289
21290     SvPVCLEAR(sv);
21291
21292     if (OP(o) > REGNODE_MAX) {          /* regnode.type is unsigned */
21293         if (pRExC_state) {  /* This gives more info, if we have it */
21294             FAIL3("panic: corrupted regexp opcode %d > %d",
21295                   (int)OP(o), (int)REGNODE_MAX);
21296         }
21297         else {
21298             Perl_croak(aTHX_ "panic: corrupted regexp opcode %d > %d",
21299                              (int)OP(o), (int)REGNODE_MAX);
21300         }
21301     }
21302     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
21303
21304     k = PL_regkind[OP(o)];
21305
21306     if (k == EXACT) {
21307         sv_catpvs(sv, " ");
21308         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
21309          * is a crude hack but it may be the best for now since
21310          * we have no flag "this EXACTish node was UTF-8"
21311          * --jhi */
21312         pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
21313                   PL_colors[0], PL_colors[1],
21314                   PERL_PV_ESCAPE_UNI_DETECT |
21315                   PERL_PV_ESCAPE_NONASCII   |
21316                   PERL_PV_PRETTY_ELLIPSES   |
21317                   PERL_PV_PRETTY_LTGT       |
21318                   PERL_PV_PRETTY_NOCLEAR
21319                   );
21320     } else if (k == TRIE) {
21321         /* print the details of the trie in dumpuntil instead, as
21322          * progi->data isn't available here */
21323         const char op = OP(o);
21324         const U32 n = ARG(o);
21325         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
21326                (reg_ac_data *)progi->data->data[n] :
21327                NULL;
21328         const reg_trie_data * const trie
21329             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
21330
21331         Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
21332         DEBUG_TRIE_COMPILE_r({
21333           if (trie->jump)
21334             sv_catpvs(sv, "(JUMP)");
21335           Perl_sv_catpvf(aTHX_ sv,
21336             "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
21337             (UV)trie->startstate,
21338             (IV)trie->statecount-1, /* -1 because of the unused 0 element */
21339             (UV)trie->wordcount,
21340             (UV)trie->minlen,
21341             (UV)trie->maxlen,
21342             (UV)TRIE_CHARCOUNT(trie),
21343             (UV)trie->uniquecharcount
21344           );
21345         });
21346         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
21347             sv_catpvs(sv, "[");
21348             (void) put_charclass_bitmap_innards(sv,
21349                                                 ((IS_ANYOF_TRIE(op))
21350                                                  ? ANYOF_BITMAP(o)
21351                                                  : TRIE_BITMAP(trie)),
21352                                                 NULL,
21353                                                 NULL,
21354                                                 NULL,
21355                                                 0,
21356                                                 FALSE
21357                                                );
21358             sv_catpvs(sv, "]");
21359         }
21360     } else if (k == CURLY) {
21361         U32 lo = ARG1(o), hi = ARG2(o);
21362         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
21363             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
21364         Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
21365         if (hi == REG_INFTY)
21366             sv_catpvs(sv, "INFTY");
21367         else
21368             Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
21369         sv_catpvs(sv, "}");
21370     }
21371     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
21372         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
21373     else if (k == REF || k == OPEN || k == CLOSE
21374              || k == GROUPP || OP(o)==ACCEPT)
21375     {
21376         AV *name_list= NULL;
21377         U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
21378         Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno);        /* Parenth number */
21379         if ( RXp_PAREN_NAMES(prog) ) {
21380             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
21381         } else if ( pRExC_state ) {
21382             name_list= RExC_paren_name_list;
21383         }
21384         if (name_list) {
21385             if ( k != REF || (OP(o) < REFN)) {
21386                 SV **name= av_fetch(name_list, parno, 0 );
21387                 if (name)
21388                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21389             }
21390             else {
21391                 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
21392                 I32 *nums=(I32*)SvPVX(sv_dat);
21393                 SV **name= av_fetch(name_list, nums[0], 0 );
21394                 I32 n;
21395                 if (name) {
21396                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
21397                         Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
21398                                     (n ? "," : ""), (IV)nums[n]);
21399                     }
21400                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21401                 }
21402             }
21403         }
21404         if ( k == REF && reginfo) {
21405             U32 n = ARG(o);  /* which paren pair */
21406             I32 ln = prog->offs[n].start;
21407             if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
21408                 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
21409             else if (ln == prog->offs[n].end)
21410                 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
21411             else {
21412                 const char *s = reginfo->strbeg + ln;
21413                 Perl_sv_catpvf(aTHX_ sv, ": ");
21414                 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
21415                     PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
21416             }
21417         }
21418     } else if (k == GOSUB) {
21419         AV *name_list= NULL;
21420         if ( RXp_PAREN_NAMES(prog) ) {
21421             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
21422         } else if ( pRExC_state ) {
21423             name_list= RExC_paren_name_list;
21424         }
21425
21426         /* Paren and offset */
21427         Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
21428                 (int)((o + (int)ARG2L(o)) - progi->program) );
21429         if (name_list) {
21430             SV **name= av_fetch(name_list, ARG(o), 0 );
21431             if (name)
21432                 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21433         }
21434     }
21435     else if (k == LOGICAL)
21436         /* 2: embedded, otherwise 1 */
21437         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
21438     else if (k == ANYOF || k == ANYOFR) {
21439         U8 flags;
21440         char * bitmap;
21441         U32 arg;
21442         bool do_sep = FALSE;    /* Do we need to separate various components of
21443                                    the output? */
21444         /* Set if there is still an unresolved user-defined property */
21445         SV *unresolved                = NULL;
21446
21447         /* Things that are ignored except when the runtime locale is UTF-8 */
21448         SV *only_utf8_locale_invlist = NULL;
21449
21450         /* Code points that don't fit in the bitmap */
21451         SV *nonbitmap_invlist = NULL;
21452
21453         /* And things that aren't in the bitmap, but are small enough to be */
21454         SV* bitmap_range_not_in_bitmap = NULL;
21455
21456         bool inverted;
21457
21458         if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21459             flags = 0;
21460             bitmap = NULL;
21461             arg = 0;
21462         }
21463         else {
21464             flags = ANYOF_FLAGS(o);
21465             bitmap = ANYOF_BITMAP(o);
21466             arg = ARG(o);
21467         }
21468
21469         if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
21470             if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
21471                 sv_catpvs(sv, "{utf8-locale-reqd}");
21472             }
21473             if (flags & ANYOFL_FOLD) {
21474                 sv_catpvs(sv, "{i}");
21475             }
21476         }
21477
21478         inverted = flags & ANYOF_INVERT;
21479
21480         /* If there is stuff outside the bitmap, get it */
21481         if (arg != ANYOF_ONLY_HAS_BITMAP) {
21482             if (inRANGE(OP(o), ANYOFR, ANYOFRb)) {
21483                 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
21484                                             ANYOFRbase(o),
21485                                             ANYOFRbase(o) + ANYOFRdelta(o));
21486             }
21487             else {
21488 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
21489                 (void) get_regclass_nonbitmap_data(prog, o, FALSE,
21490                                                 &unresolved,
21491                                                 &only_utf8_locale_invlist,
21492                                                 &nonbitmap_invlist);
21493 #else
21494                 (void) get_re_gclass_nonbitmap_data(prog, o, FALSE,
21495                                                 &unresolved,
21496                                                 &only_utf8_locale_invlist,
21497                                                 &nonbitmap_invlist);
21498 #endif
21499             }
21500
21501             /* The non-bitmap data may contain stuff that could fit in the
21502              * bitmap.  This could come from a user-defined property being
21503              * finally resolved when this call was done; or much more likely
21504              * because there are matches that require UTF-8 to be valid, and so
21505              * aren't in the bitmap (or ANYOFR).  This is teased apart later */
21506             _invlist_intersection(nonbitmap_invlist,
21507                                   PL_InBitmap,
21508                                   &bitmap_range_not_in_bitmap);
21509             /* Leave just the things that don't fit into the bitmap */
21510             _invlist_subtract(nonbitmap_invlist,
21511                               PL_InBitmap,
21512                               &nonbitmap_invlist);
21513         }
21514
21515         /* Obey this flag to add all above-the-bitmap code points */
21516         if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
21517             nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
21518                                                       NUM_ANYOF_CODE_POINTS,
21519                                                       UV_MAX);
21520         }
21521
21522         /* Ready to start outputting.  First, the initial left bracket */
21523         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21524
21525         /* ANYOFH by definition doesn't have anything that will fit inside the
21526          * bitmap;  ANYOFR may or may not. */
21527         if (  ! inRANGE(OP(o), ANYOFH, ANYOFHr)
21528             && (   ! inRANGE(OP(o), ANYOFR, ANYOFRb)
21529                 ||   ANYOFRbase(o) < NUM_ANYOF_CODE_POINTS))
21530         {
21531             /* Then all the things that could fit in the bitmap */
21532             do_sep = put_charclass_bitmap_innards(sv,
21533                                                   bitmap,
21534                                                   bitmap_range_not_in_bitmap,
21535                                                   only_utf8_locale_invlist,
21536                                                   o,
21537                                                   flags,
21538
21539                                                   /* Can't try inverting for a
21540                                                    * better display if there
21541                                                    * are things that haven't
21542                                                    * been resolved */
21543                                                   unresolved != NULL
21544                                             || inRANGE(OP(o), ANYOFR, ANYOFRb));
21545             SvREFCNT_dec(bitmap_range_not_in_bitmap);
21546
21547             /* If there are user-defined properties which haven't been defined
21548              * yet, output them.  If the result is not to be inverted, it is
21549              * clearest to output them in a separate [] from the bitmap range
21550              * stuff.  If the result is to be complemented, we have to show
21551              * everything in one [], as the inversion applies to the whole
21552              * thing.  Use {braces} to separate them from anything in the
21553              * bitmap and anything above the bitmap. */
21554             if (unresolved) {
21555                 if (inverted) {
21556                     if (! do_sep) { /* If didn't output anything in the bitmap
21557                                      */
21558                         sv_catpvs(sv, "^");
21559                     }
21560                     sv_catpvs(sv, "{");
21561                 }
21562                 else if (do_sep) {
21563                     Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
21564                                                       PL_colors[0]);
21565                 }
21566                 sv_catsv(sv, unresolved);
21567                 if (inverted) {
21568                     sv_catpvs(sv, "}");
21569                 }
21570                 do_sep = ! inverted;
21571             }
21572         }
21573
21574         /* And, finally, add the above-the-bitmap stuff */
21575         if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
21576             SV* contents;
21577
21578             /* See if truncation size is overridden */
21579             const STRLEN dump_len = (PL_dump_re_max_len > 256)
21580                                     ? PL_dump_re_max_len
21581                                     : 256;
21582
21583             /* This is output in a separate [] */
21584             if (do_sep) {
21585                 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
21586             }
21587
21588             /* And, for easy of understanding, it is shown in the
21589              * uncomplemented form if possible.  The one exception being if
21590              * there are unresolved items, where the inversion has to be
21591              * delayed until runtime */
21592             if (inverted && ! unresolved) {
21593                 _invlist_invert(nonbitmap_invlist);
21594                 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
21595             }
21596
21597             contents = invlist_contents(nonbitmap_invlist,
21598                                         FALSE /* output suitable for catsv */
21599                                        );
21600
21601             /* If the output is shorter than the permissible maximum, just do it. */
21602             if (SvCUR(contents) <= dump_len) {
21603                 sv_catsv(sv, contents);
21604             }
21605             else {
21606                 const char * contents_string = SvPVX(contents);
21607                 STRLEN i = dump_len;
21608
21609                 /* Otherwise, start at the permissible max and work back to the
21610                  * first break possibility */
21611                 while (i > 0 && contents_string[i] != ' ') {
21612                     i--;
21613                 }
21614                 if (i == 0) {       /* Fail-safe.  Use the max if we couldn't
21615                                        find a legal break */
21616                     i = dump_len;
21617                 }
21618
21619                 sv_catpvn(sv, contents_string, i);
21620                 sv_catpvs(sv, "...");
21621             }
21622
21623             SvREFCNT_dec_NN(contents);
21624             SvREFCNT_dec_NN(nonbitmap_invlist);
21625         }
21626
21627         /* And finally the matching, closing ']' */
21628         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21629
21630         if (OP(o) == ANYOFHs) {
21631             Perl_sv_catpvf(aTHX_ sv, " (Leading UTF-8 bytes=%s", _byte_dump_string((U8 *) ((struct regnode_anyofhs *) o)->string, FLAGS(o), 1));
21632         }
21633         else if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21634             U8 lowest = (OP(o) != ANYOFHr)
21635                          ? FLAGS(o)
21636                          : LOWEST_ANYOF_HRx_BYTE(FLAGS(o));
21637             U8 highest = (OP(o) == ANYOFHr)
21638                          ? HIGHEST_ANYOF_HRx_BYTE(FLAGS(o))
21639                          : (OP(o) == ANYOFH || OP(o) == ANYOFR)
21640                            ? 0xFF
21641                            : lowest;
21642 #ifndef EBCDIC
21643             if (OP(o) != ANYOFR || ! isASCII(ANYOFRbase(o) + ANYOFRdelta(o)))
21644 #endif
21645             {
21646                 Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=%02X", lowest);
21647                 if (lowest != highest) {
21648                     Perl_sv_catpvf(aTHX_ sv, "-%02X", highest);
21649                 }
21650                 Perl_sv_catpvf(aTHX_ sv, ")");
21651             }
21652         }
21653
21654         SvREFCNT_dec(unresolved);
21655     }
21656     else if (k == ANYOFM) {
21657         SV * cp_list = get_ANYOFM_contents(o);
21658
21659         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21660         if (OP(o) == NANYOFM) {
21661             _invlist_invert(cp_list);
21662         }
21663
21664         put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, 0, TRUE);
21665         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21666
21667         SvREFCNT_dec(cp_list);
21668     }
21669     else if (k == POSIXD || k == NPOSIXD) {
21670         U8 index = FLAGS(o) * 2;
21671         if (index < C_ARRAY_LENGTH(anyofs)) {
21672             if (*anyofs[index] != '[')  {
21673                 sv_catpvs(sv, "[");
21674             }
21675             sv_catpv(sv, anyofs[index]);
21676             if (*anyofs[index] != '[')  {
21677                 sv_catpvs(sv, "]");
21678             }
21679         }
21680         else {
21681             Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
21682         }
21683     }
21684     else if (k == BOUND || k == NBOUND) {
21685         /* Must be synced with order of 'bound_type' in regcomp.h */
21686         const char * const bounds[] = {
21687             "",      /* Traditional */
21688             "{gcb}",
21689             "{lb}",
21690             "{sb}",
21691             "{wb}"
21692         };
21693         assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
21694         sv_catpv(sv, bounds[FLAGS(o)]);
21695     }
21696     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) {
21697         Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags));
21698         if (o->next_off) {
21699             Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off);
21700         }
21701         Perl_sv_catpvf(aTHX_ sv, "]");
21702     }
21703     else if (OP(o) == SBOL)
21704         Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
21705
21706     /* add on the verb argument if there is one */
21707     if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
21708         if ( ARG(o) )
21709             Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
21710                        SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
21711         else
21712             sv_catpvs(sv, ":NULL");
21713     }
21714 #else
21715     PERL_UNUSED_CONTEXT;
21716     PERL_UNUSED_ARG(sv);
21717     PERL_UNUSED_ARG(o);
21718     PERL_UNUSED_ARG(prog);
21719     PERL_UNUSED_ARG(reginfo);
21720     PERL_UNUSED_ARG(pRExC_state);
21721 #endif  /* DEBUGGING */
21722 }
21723
21724
21725
21726 SV *
21727 Perl_re_intuit_string(pTHX_ REGEXP * const r)
21728 {                               /* Assume that RE_INTUIT is set */
21729     /* Returns an SV containing a string that must appear in the target for it
21730      * to match, or NULL if nothing is known that must match.
21731      *
21732      * CAUTION: the SV can be freed during execution of the regex engine */
21733
21734     struct regexp *const prog = ReANY(r);
21735     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21736
21737     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
21738     PERL_UNUSED_CONTEXT;
21739
21740     DEBUG_COMPILE_r(
21741         {
21742             if (prog->maxlen > 0) {
21743                 const char * const s = SvPV_nolen_const(RX_UTF8(r)
21744                       ? prog->check_utf8 : prog->check_substr);
21745
21746                 if (!PL_colorset) reginitcolors();
21747                 Perl_re_printf( aTHX_
21748                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
21749                       PL_colors[4],
21750                       RX_UTF8(r) ? "utf8 " : "",
21751                       PL_colors[5], PL_colors[0],
21752                       s,
21753                       PL_colors[1],
21754                       (strlen(s) > PL_dump_re_max_len ? "..." : ""));
21755             }
21756         } );
21757
21758     /* use UTF8 check substring if regexp pattern itself is in UTF8 */
21759     return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
21760 }
21761
21762 /*
21763    pregfree()
21764
21765    handles refcounting and freeing the perl core regexp structure. When
21766    it is necessary to actually free the structure the first thing it
21767    does is call the 'free' method of the regexp_engine associated to
21768    the regexp, allowing the handling of the void *pprivate; member
21769    first. (This routine is not overridable by extensions, which is why
21770    the extensions free is called first.)
21771
21772    See regdupe and regdupe_internal if you change anything here.
21773 */
21774 #ifndef PERL_IN_XSUB_RE
21775 void
21776 Perl_pregfree(pTHX_ REGEXP *r)
21777 {
21778     SvREFCNT_dec(r);
21779 }
21780
21781 void
21782 Perl_pregfree2(pTHX_ REGEXP *rx)
21783 {
21784     struct regexp *const r = ReANY(rx);
21785     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21786
21787     PERL_ARGS_ASSERT_PREGFREE2;
21788
21789     if (! r)
21790         return;
21791
21792     if (r->mother_re) {
21793         ReREFCNT_dec(r->mother_re);
21794     } else {
21795         CALLREGFREE_PVT(rx); /* free the private data */
21796         SvREFCNT_dec(RXp_PAREN_NAMES(r));
21797     }
21798     if (r->substrs) {
21799         int i;
21800         for (i = 0; i < 2; i++) {
21801             SvREFCNT_dec(r->substrs->data[i].substr);
21802             SvREFCNT_dec(r->substrs->data[i].utf8_substr);
21803         }
21804         Safefree(r->substrs);
21805     }
21806     RX_MATCH_COPY_FREE(rx);
21807 #ifdef PERL_ANY_COW
21808     SvREFCNT_dec(r->saved_copy);
21809 #endif
21810     Safefree(r->offs);
21811     SvREFCNT_dec(r->qr_anoncv);
21812     if (r->recurse_locinput)
21813         Safefree(r->recurse_locinput);
21814 }
21815
21816
21817 /*  reg_temp_copy()
21818
21819     Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
21820     except that dsv will be created if NULL.
21821
21822     This function is used in two main ways. First to implement
21823         $r = qr/....; $s = $$r;
21824
21825     Secondly, it is used as a hacky workaround to the structural issue of
21826     match results
21827     being stored in the regexp structure which is in turn stored in
21828     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
21829     could be PL_curpm in multiple contexts, and could require multiple
21830     result sets being associated with the pattern simultaneously, such
21831     as when doing a recursive match with (??{$qr})
21832
21833     The solution is to make a lightweight copy of the regexp structure
21834     when a qr// is returned from the code executed by (??{$qr}) this
21835     lightweight copy doesn't actually own any of its data except for
21836     the starp/end and the actual regexp structure itself.
21837
21838 */
21839
21840
21841 REGEXP *
21842 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
21843 {
21844     struct regexp *drx;
21845     struct regexp *const srx = ReANY(ssv);
21846     const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
21847
21848     PERL_ARGS_ASSERT_REG_TEMP_COPY;
21849
21850     if (!dsv)
21851         dsv = (REGEXP*) newSV_type(SVt_REGEXP);
21852     else {
21853         assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV));
21854
21855         /* our only valid caller, sv_setsv_flags(), should have done
21856          * a SV_CHECK_THINKFIRST_COW_DROP() by now */
21857         assert(!SvOOK(dsv));
21858         assert(!SvIsCOW(dsv));
21859         assert(!SvROK(dsv));
21860
21861         if (SvPVX_const(dsv)) {
21862             if (SvLEN(dsv))
21863                 Safefree(SvPVX(dsv));
21864             SvPVX(dsv) = NULL;
21865         }
21866         SvLEN_set(dsv, 0);
21867         SvCUR_set(dsv, 0);
21868         SvOK_off((SV *)dsv);
21869
21870         if (islv) {
21871             /* For PVLVs, the head (sv_any) points to an XPVLV, while
21872              * the LV's xpvlenu_rx will point to a regexp body, which
21873              * we allocate here */
21874             REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
21875             assert(!SvPVX(dsv));
21876             ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
21877             temp->sv_any = NULL;
21878             SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
21879             SvREFCNT_dec_NN(temp);
21880             /* SvCUR still resides in the xpvlv struct, so the regexp copy-
21881                ing below will not set it. */
21882             SvCUR_set(dsv, SvCUR(ssv));
21883         }
21884     }
21885     /* This ensures that SvTHINKFIRST(sv) is true, and hence that
21886        sv_force_normal(sv) is called.  */
21887     SvFAKE_on(dsv);
21888     drx = ReANY(dsv);
21889
21890     SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
21891     SvPV_set(dsv, RX_WRAPPED(ssv));
21892     /* We share the same string buffer as the original regexp, on which we
21893        hold a reference count, incremented when mother_re is set below.
21894        The string pointer is copied here, being part of the regexp struct.
21895      */
21896     memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
21897            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
21898     if (!islv)
21899         SvLEN_set(dsv, 0);
21900     if (srx->offs) {
21901         const I32 npar = srx->nparens+1;
21902         Newx(drx->offs, npar, regexp_paren_pair);
21903         Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
21904     }
21905     if (srx->substrs) {
21906         int i;
21907         Newx(drx->substrs, 1, struct reg_substr_data);
21908         StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
21909
21910         for (i = 0; i < 2; i++) {
21911             SvREFCNT_inc_void(drx->substrs->data[i].substr);
21912             SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
21913         }
21914
21915         /* check_substr and check_utf8, if non-NULL, point to either their
21916            anchored or float namesakes, and don't hold a second reference.  */
21917     }
21918     RX_MATCH_COPIED_off(dsv);
21919 #ifdef PERL_ANY_COW
21920     drx->saved_copy = NULL;
21921 #endif
21922     drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
21923     SvREFCNT_inc_void(drx->qr_anoncv);
21924     if (srx->recurse_locinput)
21925         Newx(drx->recurse_locinput, srx->nparens + 1, char *);
21926
21927     return dsv;
21928 }
21929 #endif
21930
21931
21932 /* regfree_internal()
21933
21934    Free the private data in a regexp. This is overloadable by
21935    extensions. Perl takes care of the regexp structure in pregfree(),
21936    this covers the *pprivate pointer which technically perl doesn't
21937    know about, however of course we have to handle the
21938    regexp_internal structure when no extension is in use.
21939
21940    Note this is called before freeing anything in the regexp
21941    structure.
21942  */
21943
21944 void
21945 Perl_regfree_internal(pTHX_ REGEXP * const rx)
21946 {
21947     struct regexp *const r = ReANY(rx);
21948     RXi_GET_DECL(r, ri);
21949     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21950
21951     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
21952
21953     if (! ri) {
21954         return;
21955     }
21956
21957     DEBUG_COMPILE_r({
21958         if (!PL_colorset)
21959             reginitcolors();
21960         {
21961             SV *dsv= sv_newmortal();
21962             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
21963                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
21964             Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
21965                 PL_colors[4], PL_colors[5], s);
21966         }
21967     });
21968
21969 #ifdef RE_TRACK_PATTERN_OFFSETS
21970     if (ri->u.offsets)
21971         Safefree(ri->u.offsets);             /* 20010421 MJD */
21972 #endif
21973     if (ri->code_blocks)
21974         S_free_codeblocks(aTHX_ ri->code_blocks);
21975
21976     if (ri->data) {
21977         int n = ri->data->count;
21978
21979         while (--n >= 0) {
21980           /* If you add a ->what type here, update the comment in regcomp.h */
21981             switch (ri->data->what[n]) {
21982             case 'a':
21983             case 'r':
21984             case 's':
21985             case 'S':
21986             case 'u':
21987                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
21988                 break;
21989             case 'f':
21990                 Safefree(ri->data->data[n]);
21991                 break;
21992             case 'l':
21993             case 'L':
21994                 break;
21995             case 'T':
21996                 { /* Aho Corasick add-on structure for a trie node.
21997                      Used in stclass optimization only */
21998                     U32 refcount;
21999                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
22000                     OP_REFCNT_LOCK;
22001                     refcount = --aho->refcount;
22002                     OP_REFCNT_UNLOCK;
22003                     if ( !refcount ) {
22004                         PerlMemShared_free(aho->states);
22005                         PerlMemShared_free(aho->fail);
22006                          /* do this last!!!! */
22007                         PerlMemShared_free(ri->data->data[n]);
22008                         /* we should only ever get called once, so
22009                          * assert as much, and also guard the free
22010                          * which /might/ happen twice. At the least
22011                          * it will make code anlyzers happy and it
22012                          * doesn't cost much. - Yves */
22013                         assert(ri->regstclass);
22014                         if (ri->regstclass) {
22015                             PerlMemShared_free(ri->regstclass);
22016                             ri->regstclass = 0;
22017                         }
22018                     }
22019                 }
22020                 break;
22021             case 't':
22022                 {
22023                     /* trie structure. */
22024                     U32 refcount;
22025                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
22026                     OP_REFCNT_LOCK;
22027                     refcount = --trie->refcount;
22028                     OP_REFCNT_UNLOCK;
22029                     if ( !refcount ) {
22030                         PerlMemShared_free(trie->charmap);
22031                         PerlMemShared_free(trie->states);
22032                         PerlMemShared_free(trie->trans);
22033                         if (trie->bitmap)
22034                             PerlMemShared_free(trie->bitmap);
22035                         if (trie->jump)
22036                             PerlMemShared_free(trie->jump);
22037                         PerlMemShared_free(trie->wordinfo);
22038                         /* do this last!!!! */
22039                         PerlMemShared_free(ri->data->data[n]);
22040                     }
22041                 }
22042                 break;
22043             default:
22044                 Perl_croak(aTHX_ "panic: regfree data code '%c'",
22045                                                     ri->data->what[n]);
22046             }
22047         }
22048         Safefree(ri->data->what);
22049         Safefree(ri->data);
22050     }
22051
22052     Safefree(ri);
22053 }
22054
22055 #define av_dup_inc(s, t)        MUTABLE_AV(sv_dup_inc((const SV *)s, t))
22056 #define hv_dup_inc(s, t)        MUTABLE_HV(sv_dup_inc((const SV *)s, t))
22057 #define SAVEPVN(p, n)   ((p) ? savepvn(p, n) : NULL)
22058
22059 /*
22060 =for apidoc re_dup_guts
22061 Duplicate a regexp.
22062
22063 This routine is expected to clone a given regexp structure. It is only
22064 compiled under USE_ITHREADS.
22065
22066 After all of the core data stored in struct regexp is duplicated
22067 the C<regexp_engine.dupe> method is used to copy any private data
22068 stored in the *pprivate pointer. This allows extensions to handle
22069 any duplication they need to do.
22070
22071 =cut
22072
22073    See pregfree() and regfree_internal() if you change anything here.
22074 */
22075 #if defined(USE_ITHREADS)
22076 #ifndef PERL_IN_XSUB_RE
22077 void
22078 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
22079 {
22080     I32 npar;
22081     const struct regexp *r = ReANY(sstr);
22082     struct regexp *ret = ReANY(dstr);
22083
22084     PERL_ARGS_ASSERT_RE_DUP_GUTS;
22085
22086     npar = r->nparens+1;
22087     Newx(ret->offs, npar, regexp_paren_pair);
22088     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
22089
22090     if (ret->substrs) {
22091         /* Do it this way to avoid reading from *r after the StructCopy().
22092            That way, if any of the sv_dup_inc()s dislodge *r from the L1
22093            cache, it doesn't matter.  */
22094         int i;
22095         const bool anchored = r->check_substr
22096             ? r->check_substr == r->substrs->data[0].substr
22097             : r->check_utf8   == r->substrs->data[0].utf8_substr;
22098         Newx(ret->substrs, 1, struct reg_substr_data);
22099         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
22100
22101         for (i = 0; i < 2; i++) {
22102             ret->substrs->data[i].substr =
22103                         sv_dup_inc(ret->substrs->data[i].substr, param);
22104             ret->substrs->data[i].utf8_substr =
22105                         sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
22106         }
22107
22108         /* check_substr and check_utf8, if non-NULL, point to either their
22109            anchored or float namesakes, and don't hold a second reference.  */
22110
22111         if (ret->check_substr) {
22112             if (anchored) {
22113                 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
22114
22115                 ret->check_substr = ret->substrs->data[0].substr;
22116                 ret->check_utf8   = ret->substrs->data[0].utf8_substr;
22117             } else {
22118                 assert(r->check_substr == r->substrs->data[1].substr);
22119                 assert(r->check_utf8   == r->substrs->data[1].utf8_substr);
22120
22121                 ret->check_substr = ret->substrs->data[1].substr;
22122                 ret->check_utf8   = ret->substrs->data[1].utf8_substr;
22123             }
22124         } else if (ret->check_utf8) {
22125             if (anchored) {
22126                 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
22127             } else {
22128                 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
22129             }
22130         }
22131     }
22132
22133     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
22134     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
22135     if (r->recurse_locinput)
22136         Newx(ret->recurse_locinput, r->nparens + 1, char *);
22137
22138     if (ret->pprivate)
22139         RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
22140
22141     if (RX_MATCH_COPIED(dstr))
22142         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
22143     else
22144         ret->subbeg = NULL;
22145 #ifdef PERL_ANY_COW
22146     ret->saved_copy = NULL;
22147 #endif
22148
22149     /* Whether mother_re be set or no, we need to copy the string.  We
22150        cannot refrain from copying it when the storage points directly to
22151        our mother regexp, because that's
22152                1: a buffer in a different thread
22153                2: something we no longer hold a reference on
22154                so we need to copy it locally.  */
22155     RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
22156     /* set malloced length to a non-zero value so it will be freed
22157      * (otherwise in combination with SVf_FAKE it looks like an alien
22158      * buffer). It doesn't have to be the actual malloced size, since it
22159      * should never be grown */
22160     SvLEN_set(dstr, SvCUR(sstr)+1);
22161     ret->mother_re   = NULL;
22162 }
22163 #endif /* PERL_IN_XSUB_RE */
22164
22165 /*
22166    regdupe_internal()
22167
22168    This is the internal complement to regdupe() which is used to copy
22169    the structure pointed to by the *pprivate pointer in the regexp.
22170    This is the core version of the extension overridable cloning hook.
22171    The regexp structure being duplicated will be copied by perl prior
22172    to this and will be provided as the regexp *r argument, however
22173    with the /old/ structures pprivate pointer value. Thus this routine
22174    may override any copying normally done by perl.
22175
22176    It returns a pointer to the new regexp_internal structure.
22177 */
22178
22179 void *
22180 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
22181 {
22182     struct regexp *const r = ReANY(rx);
22183     regexp_internal *reti;
22184     int len;
22185     RXi_GET_DECL(r, ri);
22186
22187     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
22188
22189     len = ProgLen(ri);
22190
22191     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
22192           char, regexp_internal);
22193     Copy(ri->program, reti->program, len+1, regnode);
22194
22195
22196     if (ri->code_blocks) {
22197         int n;
22198         Newx(reti->code_blocks, 1, struct reg_code_blocks);
22199         Newx(reti->code_blocks->cb, ri->code_blocks->count,
22200                     struct reg_code_block);
22201         Copy(ri->code_blocks->cb, reti->code_blocks->cb,
22202              ri->code_blocks->count, struct reg_code_block);
22203         for (n = 0; n < ri->code_blocks->count; n++)
22204              reti->code_blocks->cb[n].src_regex = (REGEXP*)
22205                     sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
22206         reti->code_blocks->count = ri->code_blocks->count;
22207         reti->code_blocks->refcnt = 1;
22208     }
22209     else
22210         reti->code_blocks = NULL;
22211
22212     reti->regstclass = NULL;
22213
22214     if (ri->data) {
22215         struct reg_data *d;
22216         const int count = ri->data->count;
22217         int i;
22218
22219         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
22220                 char, struct reg_data);
22221         Newx(d->what, count, U8);
22222
22223         d->count = count;
22224         for (i = 0; i < count; i++) {
22225             d->what[i] = ri->data->what[i];
22226             switch (d->what[i]) {
22227                 /* see also regcomp.h and regfree_internal() */
22228             case 'a': /* actually an AV, but the dup function is identical.
22229                          values seem to be "plain sv's" generally. */
22230             case 'r': /* a compiled regex (but still just another SV) */
22231             case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
22232                          this use case should go away, the code could have used
22233                          'a' instead - see S_set_ANYOF_arg() for array contents. */
22234             case 'S': /* actually an SV, but the dup function is identical.  */
22235             case 'u': /* actually an HV, but the dup function is identical.
22236                          values are "plain sv's" */
22237                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
22238                 break;
22239             case 'f':
22240                 /* Synthetic Start Class - "Fake" charclass we generate to optimize
22241                  * patterns which could start with several different things. Pre-TRIE
22242                  * this was more important than it is now, however this still helps
22243                  * in some places, for instance /x?a+/ might produce a SSC equivalent
22244                  * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
22245                  * in regexec.c
22246                  */
22247                 /* This is cheating. */
22248                 Newx(d->data[i], 1, regnode_ssc);
22249                 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
22250                 reti->regstclass = (regnode*)d->data[i];
22251                 break;
22252             case 'T':
22253                 /* AHO-CORASICK fail table */
22254                 /* Trie stclasses are readonly and can thus be shared
22255                  * without duplication. We free the stclass in pregfree
22256                  * when the corresponding reg_ac_data struct is freed.
22257                  */
22258                 reti->regstclass= ri->regstclass;
22259                 /* FALLTHROUGH */
22260             case 't':
22261                 /* TRIE transition table */
22262                 OP_REFCNT_LOCK;
22263                 ((reg_trie_data*)ri->data->data[i])->refcount++;
22264                 OP_REFCNT_UNLOCK;
22265                 /* FALLTHROUGH */
22266             case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
22267             case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
22268                          is not from another regexp */
22269                 d->data[i] = ri->data->data[i];
22270                 break;
22271             default:
22272                 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
22273                                                            ri->data->what[i]);
22274             }
22275         }
22276
22277         reti->data = d;
22278     }
22279     else
22280         reti->data = NULL;
22281
22282     reti->name_list_idx = ri->name_list_idx;
22283
22284 #ifdef RE_TRACK_PATTERN_OFFSETS
22285     if (ri->u.offsets) {
22286         Newx(reti->u.offsets, 2*len+1, U32);
22287         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
22288     }
22289 #else
22290     SetProgLen(reti, len);
22291 #endif
22292
22293     return (void*)reti;
22294 }
22295
22296 #endif    /* USE_ITHREADS */
22297
22298 #ifndef PERL_IN_XSUB_RE
22299
22300 /*
22301  - regnext - dig the "next" pointer out of a node
22302  */
22303 regnode *
22304 Perl_regnext(pTHX_ regnode *p)
22305 {
22306     I32 offset;
22307
22308     if (!p)
22309         return(NULL);
22310
22311     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
22312         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
22313                                                 (int)OP(p), (int)REGNODE_MAX);
22314     }
22315
22316     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
22317     if (offset == 0)
22318         return(NULL);
22319
22320     return(p+offset);
22321 }
22322
22323 #endif
22324
22325 STATIC void
22326 S_re_croak(pTHX_ bool utf8, const char* pat,...)
22327 {
22328     va_list args;
22329     STRLEN len = strlen(pat);
22330     char buf[512];
22331     SV *msv;
22332     const char *message;
22333
22334     PERL_ARGS_ASSERT_RE_CROAK;
22335
22336     if (len > 510)
22337         len = 510;
22338     Copy(pat, buf, len , char);
22339     buf[len] = '\n';
22340     buf[len + 1] = '\0';
22341     va_start(args, pat);
22342     msv = vmess(buf, &args);
22343     va_end(args);
22344     message = SvPV_const(msv, len);
22345     if (len > 512)
22346         len = 512;
22347     Copy(message, buf, len , char);
22348     /* len-1 to avoid \n */
22349     Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, len-1, buf));
22350 }
22351
22352 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
22353
22354 #ifndef PERL_IN_XSUB_RE
22355 void
22356 Perl_save_re_context(pTHX)
22357 {
22358     I32 nparens = -1;
22359     I32 i;
22360
22361     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
22362
22363     if (PL_curpm) {
22364         const REGEXP * const rx = PM_GETRE(PL_curpm);
22365         if (rx)
22366             nparens = RX_NPARENS(rx);
22367     }
22368
22369     /* RT #124109. This is a complete hack; in the SWASHNEW case we know
22370      * that PL_curpm will be null, but that utf8.pm and the modules it
22371      * loads will only use $1..$3.
22372      * The t/porting/re_context.t test file checks this assumption.
22373      */
22374     if (nparens == -1)
22375         nparens = 3;
22376
22377     for (i = 1; i <= nparens; i++) {
22378         char digits[TYPE_CHARS(long)];
22379         const STRLEN len = my_snprintf(digits, sizeof(digits),
22380                                        "%lu", (long)i);
22381         GV *const *const gvp
22382             = (GV**)hv_fetch(PL_defstash, digits, len, 0);
22383
22384         if (gvp) {
22385             GV * const gv = *gvp;
22386             if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
22387                 save_scalar(gv);
22388         }
22389     }
22390 }
22391 #endif
22392
22393 #ifdef DEBUGGING
22394
22395 STATIC void
22396 S_put_code_point(pTHX_ SV *sv, UV c)
22397 {
22398     PERL_ARGS_ASSERT_PUT_CODE_POINT;
22399
22400     if (c > 255) {
22401         Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
22402     }
22403     else if (isPRINT(c)) {
22404         const char string = (char) c;
22405
22406         /* We use {phrase} as metanotation in the class, so also escape literal
22407          * braces */
22408         if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
22409             sv_catpvs(sv, "\\");
22410         sv_catpvn(sv, &string, 1);
22411     }
22412     else if (isMNEMONIC_CNTRL(c)) {
22413         Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
22414     }
22415     else {
22416         Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
22417     }
22418 }
22419
22420 STATIC void
22421 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
22422 {
22423     /* Appends to 'sv' a displayable version of the range of code points from
22424      * 'start' to 'end'.  Mnemonics (like '\r') are used for the few controls
22425      * that have them, when they occur at the beginning or end of the range.
22426      * It uses hex to output the remaining code points, unless 'allow_literals'
22427      * is true, in which case the printable ASCII ones are output as-is (though
22428      * some of these will be escaped by put_code_point()).
22429      *
22430      * NOTE:  This is designed only for printing ranges of code points that fit
22431      *        inside an ANYOF bitmap.  Higher code points are simply suppressed
22432      */
22433
22434     const unsigned int min_range_count = 3;
22435
22436     assert(start <= end);
22437
22438     PERL_ARGS_ASSERT_PUT_RANGE;
22439
22440     while (start <= end) {
22441         UV this_end;
22442         const char * format;
22443
22444         if (    end - start < min_range_count
22445             && (end - start <= 2 || (isPRINT_A(start) && isPRINT_A(end))))
22446         {
22447             /* Output a range of 1 or 2 chars individually, or longer ranges
22448              * when printable */
22449             for (; start <= end; start++) {
22450                 put_code_point(sv, start);
22451             }
22452             break;
22453         }
22454
22455         /* If permitted by the input options, and there is a possibility that
22456          * this range contains a printable literal, look to see if there is
22457          * one. */
22458         if (allow_literals && start <= MAX_PRINT_A) {
22459
22460             /* If the character at the beginning of the range isn't an ASCII
22461              * printable, effectively split the range into two parts:
22462              *  1) the portion before the first such printable,
22463              *  2) the rest
22464              * and output them separately. */
22465             if (! isPRINT_A(start)) {
22466                 UV temp_end = start + 1;
22467
22468                 /* There is no point looking beyond the final possible
22469                  * printable, in MAX_PRINT_A */
22470                 UV max = MIN(end, MAX_PRINT_A);
22471
22472                 while (temp_end <= max && ! isPRINT_A(temp_end)) {
22473                     temp_end++;
22474                 }
22475
22476                 /* Here, temp_end points to one beyond the first printable if
22477                  * found, or to one beyond 'max' if not.  If none found, make
22478                  * sure that we use the entire range */
22479                 if (temp_end > MAX_PRINT_A) {
22480                     temp_end = end + 1;
22481                 }
22482
22483                 /* Output the first part of the split range: the part that
22484                  * doesn't have printables, with the parameter set to not look
22485                  * for literals (otherwise we would infinitely recurse) */
22486                 put_range(sv, start, temp_end - 1, FALSE);
22487
22488                 /* The 2nd part of the range (if any) starts here. */
22489                 start = temp_end;
22490
22491                 /* We do a continue, instead of dropping down, because even if
22492                  * the 2nd part is non-empty, it could be so short that we want
22493                  * to output it as individual characters, as tested for at the
22494                  * top of this loop.  */
22495                 continue;
22496             }
22497
22498             /* Here, 'start' is a printable ASCII.  If it is an alphanumeric,
22499              * output a sub-range of just the digits or letters, then process
22500              * the remaining portion as usual. */
22501             if (isALPHANUMERIC_A(start)) {
22502                 UV mask = (isDIGIT_A(start))
22503                            ? _CC_DIGIT
22504                              : isUPPER_A(start)
22505                                ? _CC_UPPER
22506                                : _CC_LOWER;
22507                 UV temp_end = start + 1;
22508
22509                 /* Find the end of the sub-range that includes just the
22510                  * characters in the same class as the first character in it */
22511                 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
22512                     temp_end++;
22513                 }
22514                 temp_end--;
22515
22516                 /* For short ranges, don't duplicate the code above to output
22517                  * them; just call recursively */
22518                 if (temp_end - start < min_range_count) {
22519                     put_range(sv, start, temp_end, FALSE);
22520                 }
22521                 else {  /* Output as a range */
22522                     put_code_point(sv, start);
22523                     sv_catpvs(sv, "-");
22524                     put_code_point(sv, temp_end);
22525                 }
22526                 start = temp_end + 1;
22527                 continue;
22528             }
22529
22530             /* We output any other printables as individual characters */
22531             if (isPUNCT_A(start) || isSPACE_A(start)) {
22532                 while (start <= end && (isPUNCT_A(start)
22533                                         || isSPACE_A(start)))
22534                 {
22535                     put_code_point(sv, start);
22536                     start++;
22537                 }
22538                 continue;
22539             }
22540         } /* End of looking for literals */
22541
22542         /* Here is not to output as a literal.  Some control characters have
22543          * mnemonic names.  Split off any of those at the beginning and end of
22544          * the range to print mnemonically.  It isn't possible for many of
22545          * these to be in a row, so this won't overwhelm with output */
22546         if (   start <= end
22547             && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
22548         {
22549             while (isMNEMONIC_CNTRL(start) && start <= end) {
22550                 put_code_point(sv, start);
22551                 start++;
22552             }
22553
22554             /* If this didn't take care of the whole range ... */
22555             if (start <= end) {
22556
22557                 /* Look backwards from the end to find the final non-mnemonic
22558                  * */
22559                 UV temp_end = end;
22560                 while (isMNEMONIC_CNTRL(temp_end)) {
22561                     temp_end--;
22562                 }
22563
22564                 /* And separately output the interior range that doesn't start
22565                  * or end with mnemonics */
22566                 put_range(sv, start, temp_end, FALSE);
22567
22568                 /* Then output the mnemonic trailing controls */
22569                 start = temp_end + 1;
22570                 while (start <= end) {
22571                     put_code_point(sv, start);
22572                     start++;
22573                 }
22574                 break;
22575             }
22576         }
22577
22578         /* As a final resort, output the range or subrange as hex. */
22579
22580         if (start >= NUM_ANYOF_CODE_POINTS) {
22581             this_end = end;
22582         }
22583         else {  /* Have to split range at the bitmap boundary */
22584             this_end = (end < NUM_ANYOF_CODE_POINTS)
22585                         ? end
22586                         : NUM_ANYOF_CODE_POINTS - 1;
22587         }
22588 #if NUM_ANYOF_CODE_POINTS > 256
22589         format = (this_end < 256)
22590                  ? "\\x%02" UVXf "-\\x%02" UVXf
22591                  : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
22592 #else
22593         format = "\\x%02" UVXf "-\\x%02" UVXf;
22594 #endif
22595         GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
22596         Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
22597         GCC_DIAG_RESTORE_STMT;
22598         break;
22599     }
22600 }
22601
22602 STATIC void
22603 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
22604 {
22605     /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
22606      * 'invlist' */
22607
22608     UV start, end;
22609     bool allow_literals = TRUE;
22610
22611     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
22612
22613     /* Generally, it is more readable if printable characters are output as
22614      * literals, but if a range (nearly) spans all of them, it's best to output
22615      * it as a single range.  This code will use a single range if all but 2
22616      * ASCII printables are in it */
22617     invlist_iterinit(invlist);
22618     while (invlist_iternext(invlist, &start, &end)) {
22619
22620         /* If the range starts beyond the final printable, it doesn't have any
22621          * in it */
22622         if (start > MAX_PRINT_A) {
22623             break;
22624         }
22625
22626         /* In both ASCII and EBCDIC, a SPACE is the lowest printable.  To span
22627          * all but two, the range must start and end no later than 2 from
22628          * either end */
22629         if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
22630             if (end > MAX_PRINT_A) {
22631                 end = MAX_PRINT_A;
22632             }
22633             if (start < ' ') {
22634                 start = ' ';
22635             }
22636             if (end - start >= MAX_PRINT_A - ' ' - 2) {
22637                 allow_literals = FALSE;
22638             }
22639             break;
22640         }
22641     }
22642     invlist_iterfinish(invlist);
22643
22644     /* Here we have figured things out.  Output each range */
22645     invlist_iterinit(invlist);
22646     while (invlist_iternext(invlist, &start, &end)) {
22647         if (start >= NUM_ANYOF_CODE_POINTS) {
22648             break;
22649         }
22650         put_range(sv, start, end, allow_literals);
22651     }
22652     invlist_iterfinish(invlist);
22653
22654     return;
22655 }
22656
22657 STATIC SV*
22658 S_put_charclass_bitmap_innards_common(pTHX_
22659         SV* invlist,            /* The bitmap */
22660         SV* posixes,            /* Under /l, things like [:word:], \S */
22661         SV* only_utf8,          /* Under /d, matches iff the target is UTF-8 */
22662         SV* not_utf8,           /* /d, matches iff the target isn't UTF-8 */
22663         SV* only_utf8_locale,   /* Under /l, matches if the locale is UTF-8 */
22664         const bool invert       /* Is the result to be inverted? */
22665 )
22666 {
22667     /* Create and return an SV containing a displayable version of the bitmap
22668      * and associated information determined by the input parameters.  If the
22669      * output would have been only the inversion indicator '^', NULL is instead
22670      * returned. */
22671
22672     SV * output;
22673
22674     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
22675
22676     if (invert) {
22677         output = newSVpvs("^");
22678     }
22679     else {
22680         output = newSVpvs("");
22681     }
22682
22683     /* First, the code points in the bitmap that are unconditionally there */
22684     put_charclass_bitmap_innards_invlist(output, invlist);
22685
22686     /* Traditionally, these have been placed after the main code points */
22687     if (posixes) {
22688         sv_catsv(output, posixes);
22689     }
22690
22691     if (only_utf8 && _invlist_len(only_utf8)) {
22692         Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
22693         put_charclass_bitmap_innards_invlist(output, only_utf8);
22694     }
22695
22696     if (not_utf8 && _invlist_len(not_utf8)) {
22697         Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
22698         put_charclass_bitmap_innards_invlist(output, not_utf8);
22699     }
22700
22701     if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
22702         Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
22703         put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
22704
22705         /* This is the only list in this routine that can legally contain code
22706          * points outside the bitmap range.  The call just above to
22707          * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
22708          * output them here.  There's about a half-dozen possible, and none in
22709          * contiguous ranges longer than 2 */
22710         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22711             UV start, end;
22712             SV* above_bitmap = NULL;
22713
22714             _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
22715
22716             invlist_iterinit(above_bitmap);
22717             while (invlist_iternext(above_bitmap, &start, &end)) {
22718                 UV i;
22719
22720                 for (i = start; i <= end; i++) {
22721                     put_code_point(output, i);
22722                 }
22723             }
22724             invlist_iterfinish(above_bitmap);
22725             SvREFCNT_dec_NN(above_bitmap);
22726         }
22727     }
22728
22729     if (invert && SvCUR(output) == 1) {
22730         return NULL;
22731     }
22732
22733     return output;
22734 }
22735
22736 STATIC bool
22737 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
22738                                      char *bitmap,
22739                                      SV *nonbitmap_invlist,
22740                                      SV *only_utf8_locale_invlist,
22741                                      const regnode * const node,
22742                                      const U8 flags,
22743                                      const bool force_as_is_display)
22744 {
22745     /* Appends to 'sv' a displayable version of the innards of the bracketed
22746      * character class defined by the other arguments:
22747      *  'bitmap' points to the bitmap, or NULL if to ignore that.
22748      *  'nonbitmap_invlist' is an inversion list of the code points that are in
22749      *      the bitmap range, but for some reason aren't in the bitmap; NULL if
22750      *      none.  The reasons for this could be that they require some
22751      *      condition such as the target string being or not being in UTF-8
22752      *      (under /d), or because they came from a user-defined property that
22753      *      was not resolved at the time of the regex compilation (under /u)
22754      *  'only_utf8_locale_invlist' is an inversion list of the code points that
22755      *      are valid only if the runtime locale is a UTF-8 one; NULL if none
22756      *  'node' is the regex pattern ANYOF node.  It is needed only when the
22757      *      above two parameters are not null, and is passed so that this
22758      *      routine can tease apart the various reasons for them.
22759      *  'flags' is the flags field of 'node'
22760      *  'force_as_is_display' is TRUE if this routine should definitely NOT try
22761      *      to invert things to see if that leads to a cleaner display.  If
22762      *      FALSE, this routine is free to use its judgment about doing this.
22763      *
22764      * It returns TRUE if there was actually something output.  (It may be that
22765      * the bitmap, etc is empty.)
22766      *
22767      * When called for outputting the bitmap of a non-ANYOF node, just pass the
22768      * bitmap, with the succeeding parameters set to NULL, and the final one to
22769      * FALSE.
22770      */
22771
22772     /* In general, it tries to display the 'cleanest' representation of the
22773      * innards, choosing whether to display them inverted or not, regardless of
22774      * whether the class itself is to be inverted.  However,  there are some
22775      * cases where it can't try inverting, as what actually matches isn't known
22776      * until runtime, and hence the inversion isn't either. */
22777
22778     bool inverting_allowed = ! force_as_is_display;
22779
22780     int i;
22781     STRLEN orig_sv_cur = SvCUR(sv);
22782
22783     SV* invlist;            /* Inversion list we accumulate of code points that
22784                                are unconditionally matched */
22785     SV* only_utf8 = NULL;   /* Under /d, list of matches iff the target is
22786                                UTF-8 */
22787     SV* not_utf8 =  NULL;   /* /d, list of matches iff the target isn't UTF-8
22788                              */
22789     SV* posixes = NULL;     /* Under /l, string of things like [:word:], \D */
22790     SV* only_utf8_locale = NULL;    /* Under /l, list of matches if the locale
22791                                        is UTF-8 */
22792
22793     SV* as_is_display;      /* The output string when we take the inputs
22794                                literally */
22795     SV* inverted_display;   /* The output string when we invert the inputs */
22796
22797     bool invert = cBOOL(flags & ANYOF_INVERT);  /* Is the input to be inverted
22798                                                    to match? */
22799     /* We are biased in favor of displaying things without them being inverted,
22800      * as that is generally easier to understand */
22801     const int bias = 5;
22802
22803     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
22804
22805     /* Start off with whatever code points are passed in.  (We clone, so we
22806      * don't change the caller's list) */
22807     if (nonbitmap_invlist) {
22808         assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
22809         invlist = invlist_clone(nonbitmap_invlist, NULL);
22810     }
22811     else {  /* Worst case size is every other code point is matched */
22812         invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
22813     }
22814
22815     if (flags) {
22816         if (OP(node) == ANYOFD) {
22817
22818             /* This flag indicates that the code points below 0x100 in the
22819              * nonbitmap list are precisely the ones that match only when the
22820              * target is UTF-8 (they should all be non-ASCII). */
22821             if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
22822             {
22823                 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
22824                 _invlist_subtract(invlist, only_utf8, &invlist);
22825             }
22826
22827             /* And this flag for matching all non-ASCII 0xFF and below */
22828             if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
22829             {
22830                 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
22831             }
22832         }
22833         else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
22834
22835             /* If either of these flags are set, what matches isn't
22836              * determinable except during execution, so don't know enough here
22837              * to invert */
22838             if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
22839                 inverting_allowed = FALSE;
22840             }
22841
22842             /* What the posix classes match also varies at runtime, so these
22843              * will be output symbolically. */
22844             if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
22845                 int i;
22846
22847                 posixes = newSVpvs("");
22848                 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
22849                     if (ANYOF_POSIXL_TEST(node, i)) {
22850                         sv_catpv(posixes, anyofs[i]);
22851                     }
22852                 }
22853             }
22854         }
22855     }
22856
22857     /* Accumulate the bit map into the unconditional match list */
22858     if (bitmap) {
22859         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
22860             if (BITMAP_TEST(bitmap, i)) {
22861                 int start = i++;
22862                 for (;
22863                      i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
22864                      i++)
22865                 { /* empty */ }
22866                 invlist = _add_range_to_invlist(invlist, start, i-1);
22867             }
22868         }
22869     }
22870
22871     /* Make sure that the conditional match lists don't have anything in them
22872      * that match unconditionally; otherwise the output is quite confusing.
22873      * This could happen if the code that populates these misses some
22874      * duplication. */
22875     if (only_utf8) {
22876         _invlist_subtract(only_utf8, invlist, &only_utf8);
22877     }
22878     if (not_utf8) {
22879         _invlist_subtract(not_utf8, invlist, &not_utf8);
22880     }
22881
22882     if (only_utf8_locale_invlist) {
22883
22884         /* Since this list is passed in, we have to make a copy before
22885          * modifying it */
22886         only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
22887
22888         _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
22889
22890         /* And, it can get really weird for us to try outputting an inverted
22891          * form of this list when it has things above the bitmap, so don't even
22892          * try */
22893         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22894             inverting_allowed = FALSE;
22895         }
22896     }
22897
22898     /* Calculate what the output would be if we take the input as-is */
22899     as_is_display = put_charclass_bitmap_innards_common(invlist,
22900                                                     posixes,
22901                                                     only_utf8,
22902                                                     not_utf8,
22903                                                     only_utf8_locale,
22904                                                     invert);
22905
22906     /* If have to take the output as-is, just do that */
22907     if (! inverting_allowed) {
22908         if (as_is_display) {
22909             sv_catsv(sv, as_is_display);
22910             SvREFCNT_dec_NN(as_is_display);
22911         }
22912     }
22913     else { /* But otherwise, create the output again on the inverted input, and
22914               use whichever version is shorter */
22915
22916         int inverted_bias, as_is_bias;
22917
22918         /* We will apply our bias to whichever of the results doesn't have
22919          * the '^' */
22920         if (invert) {
22921             invert = FALSE;
22922             as_is_bias = bias;
22923             inverted_bias = 0;
22924         }
22925         else {
22926             invert = TRUE;
22927             as_is_bias = 0;
22928             inverted_bias = bias;
22929         }
22930
22931         /* Now invert each of the lists that contribute to the output,
22932          * excluding from the result things outside the possible range */
22933
22934         /* For the unconditional inversion list, we have to add in all the
22935          * conditional code points, so that when inverted, they will be gone
22936          * from it */
22937         _invlist_union(only_utf8, invlist, &invlist);
22938         _invlist_union(not_utf8, invlist, &invlist);
22939         _invlist_union(only_utf8_locale, invlist, &invlist);
22940         _invlist_invert(invlist);
22941         _invlist_intersection(invlist, PL_InBitmap, &invlist);
22942
22943         if (only_utf8) {
22944             _invlist_invert(only_utf8);
22945             _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
22946         }
22947         else if (not_utf8) {
22948
22949             /* If a code point matches iff the target string is not in UTF-8,
22950              * then complementing the result has it not match iff not in UTF-8,
22951              * which is the same thing as matching iff it is UTF-8. */
22952             only_utf8 = not_utf8;
22953             not_utf8 = NULL;
22954         }
22955
22956         if (only_utf8_locale) {
22957             _invlist_invert(only_utf8_locale);
22958             _invlist_intersection(only_utf8_locale,
22959                                   PL_InBitmap,
22960                                   &only_utf8_locale);
22961         }
22962
22963         inverted_display = put_charclass_bitmap_innards_common(
22964                                             invlist,
22965                                             posixes,
22966                                             only_utf8,
22967                                             not_utf8,
22968                                             only_utf8_locale, invert);
22969
22970         /* Use the shortest representation, taking into account our bias
22971          * against showing it inverted */
22972         if (   inverted_display
22973             && (   ! as_is_display
22974                 || (  SvCUR(inverted_display) + inverted_bias
22975                     < SvCUR(as_is_display)    + as_is_bias)))
22976         {
22977             sv_catsv(sv, inverted_display);
22978         }
22979         else if (as_is_display) {
22980             sv_catsv(sv, as_is_display);
22981         }
22982
22983         SvREFCNT_dec(as_is_display);
22984         SvREFCNT_dec(inverted_display);
22985     }
22986
22987     SvREFCNT_dec_NN(invlist);
22988     SvREFCNT_dec(only_utf8);
22989     SvREFCNT_dec(not_utf8);
22990     SvREFCNT_dec(posixes);
22991     SvREFCNT_dec(only_utf8_locale);
22992
22993     return SvCUR(sv) > orig_sv_cur;
22994 }
22995
22996 #define CLEAR_OPTSTART                                                       \
22997     if (optstart) STMT_START {                                               \
22998         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_                                           \
22999                               " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
23000         optstart=NULL;                                                       \
23001     } STMT_END
23002
23003 #define DUMPUNTIL(b,e)                                                       \
23004                     CLEAR_OPTSTART;                                          \
23005                     node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
23006
23007 STATIC const regnode *
23008 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
23009             const regnode *last, const regnode *plast,
23010             SV* sv, I32 indent, U32 depth)
23011 {
23012     U8 op = PSEUDO;     /* Arbitrary non-END op. */
23013     const regnode *next;
23014     const regnode *optstart= NULL;
23015
23016     RXi_GET_DECL(r, ri);
23017     DECLARE_AND_GET_RE_DEBUG_FLAGS;
23018
23019     PERL_ARGS_ASSERT_DUMPUNTIL;
23020
23021 #ifdef DEBUG_DUMPUNTIL
23022     Perl_re_printf( aTHX_  "--- %d : %d - %d - %d\n", indent, node-start,
23023         last ? last-start : 0, plast ? plast-start : 0);
23024 #endif
23025
23026     if (plast && plast < last)
23027         last= plast;
23028
23029     while (PL_regkind[op] != END && (!last || node < last)) {
23030         assert(node);
23031         /* While that wasn't END last time... */
23032         NODE_ALIGN(node);
23033         op = OP(node);
23034         if (op == CLOSE || op == SRCLOSE || op == WHILEM)
23035             indent--;
23036         next = regnext((regnode *)node);
23037
23038         /* Where, what. */
23039         if (OP(node) == OPTIMIZED) {
23040             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
23041                 optstart = node;
23042             else
23043                 goto after_print;
23044         } else
23045             CLEAR_OPTSTART;
23046
23047         regprop(r, sv, node, NULL, NULL);
23048         Perl_re_printf( aTHX_  "%4" IVdf ":%*s%s", (IV)(node - start),
23049                       (int)(2*indent + 1), "", SvPVX_const(sv));
23050
23051         if (OP(node) != OPTIMIZED) {
23052             if (next == NULL)           /* Next ptr. */
23053                 Perl_re_printf( aTHX_  " (0)");
23054             else if (PL_regkind[(U8)op] == BRANCH
23055                      && PL_regkind[OP(next)] != BRANCH )
23056                 Perl_re_printf( aTHX_  " (FAIL)");
23057             else
23058                 Perl_re_printf( aTHX_  " (%" IVdf ")", (IV)(next - start));
23059             Perl_re_printf( aTHX_ "\n");
23060         }
23061
23062       after_print:
23063         if (PL_regkind[(U8)op] == BRANCHJ) {
23064             assert(next);
23065             {
23066                 const regnode *nnode = (OP(next) == LONGJMP
23067                                        ? regnext((regnode *)next)
23068                                        : next);
23069                 if (last && nnode > last)
23070                     nnode = last;
23071                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
23072             }
23073         }
23074         else if (PL_regkind[(U8)op] == BRANCH) {
23075             assert(next);
23076             DUMPUNTIL(NEXTOPER(node), next);
23077         }
23078         else if ( PL_regkind[(U8)op]  == TRIE ) {
23079             const regnode *this_trie = node;
23080             const char op = OP(node);
23081             const U32 n = ARG(node);
23082             const reg_ac_data * const ac = op>=AHOCORASICK ?
23083                (reg_ac_data *)ri->data->data[n] :
23084                NULL;
23085             const reg_trie_data * const trie =
23086                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
23087 #ifdef DEBUGGING
23088             AV *const trie_words
23089                            = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
23090 #endif
23091             const regnode *nextbranch= NULL;
23092             I32 word_idx;
23093             SvPVCLEAR(sv);
23094             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
23095                 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
23096
23097                 Perl_re_indentf( aTHX_  "%s ",
23098                     indent+3,
23099                     elem_ptr
23100                     ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
23101                                 SvCUR(*elem_ptr), PL_dump_re_max_len,
23102                                 PL_colors[0], PL_colors[1],
23103                                 (SvUTF8(*elem_ptr)
23104                                  ? PERL_PV_ESCAPE_UNI
23105                                  : 0)
23106                                 | PERL_PV_PRETTY_ELLIPSES
23107                                 | PERL_PV_PRETTY_LTGT
23108                             )
23109                     : "???"
23110                 );
23111                 if (trie->jump) {
23112                     U16 dist= trie->jump[word_idx+1];
23113                     Perl_re_printf( aTHX_  "(%" UVuf ")\n",
23114                                (UV)((dist ? this_trie + dist : next) - start));
23115                     if (dist) {
23116                         if (!nextbranch)
23117                             nextbranch= this_trie + trie->jump[0];
23118                         DUMPUNTIL(this_trie + dist, nextbranch);
23119                     }
23120                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
23121                         nextbranch= regnext((regnode *)nextbranch);
23122                 } else {
23123                     Perl_re_printf( aTHX_  "\n");
23124                 }
23125             }
23126             if (last && next > last)
23127                 node= last;
23128             else
23129                 node= next;
23130         }
23131         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
23132             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
23133                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
23134         }
23135         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
23136             assert(next);
23137             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
23138         }
23139         else if ( op == PLUS || op == STAR) {
23140             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
23141         }
23142         else if (PL_regkind[(U8)op] == EXACT || op == ANYOFHs) {
23143             /* Literal string, where present. */
23144             node += NODE_SZ_STR(node) - 1;
23145             node = NEXTOPER(node);
23146         }
23147         else {
23148             node = NEXTOPER(node);
23149             node += regarglen[(U8)op];
23150         }
23151         if (op == CURLYX || op == OPEN || op == SROPEN)
23152             indent++;
23153     }
23154     CLEAR_OPTSTART;
23155 #ifdef DEBUG_DUMPUNTIL
23156     Perl_re_printf( aTHX_  "--- %d\n", (int)indent);
23157 #endif
23158     return node;
23159 }
23160
23161 #endif  /* DEBUGGING */
23162
23163 #ifndef PERL_IN_XSUB_RE
23164
23165 #  include "uni_keywords.h"
23166
23167 void
23168 Perl_init_uniprops(pTHX)
23169 {
23170
23171 #  ifdef DEBUGGING
23172     char * dump_len_string;
23173
23174     dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
23175     if (   ! dump_len_string
23176         || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
23177     {
23178         PL_dump_re_max_len = 60;    /* A reasonable default */
23179     }
23180 #  endif
23181
23182     PL_user_def_props = newHV();
23183
23184 #  ifdef USE_ITHREADS
23185
23186     HvSHAREKEYS_off(PL_user_def_props);
23187     PL_user_def_props_aTHX = aTHX;
23188
23189 #  endif
23190
23191     /* Set up the inversion list interpreter-level variables */
23192
23193     PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
23194     PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
23195     PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
23196     PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
23197     PL_XPosix_ptrs[_CC_CASED] =  _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
23198     PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
23199     PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
23200     PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
23201     PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
23202     PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
23203     PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
23204     PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
23205     PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
23206     PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
23207     PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
23208     PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
23209
23210     PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
23211     PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
23212     PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
23213     PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
23214     PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
23215     PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
23216     PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
23217     PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
23218     PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
23219     PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
23220     PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
23221     PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
23222     PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
23223     PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
23224     PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
23225     PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
23226
23227     PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
23228     PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
23229     PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
23230     PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
23231     PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
23232
23233     PL_InBitmap = _new_invlist_C_array(InBitmap_invlist);
23234     PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
23235     PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
23236     PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
23237
23238     PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
23239
23240     PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
23241     PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
23242
23243     PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
23244     PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
23245
23246     PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
23247     PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
23248                                             UNI__PERL_FOLDS_TO_MULTI_CHAR]);
23249     PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
23250                                             UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
23251     PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
23252     PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
23253     PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
23254     PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
23255     PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
23256     PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
23257     PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
23258     PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
23259     PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]);
23260
23261 #  ifdef UNI_XIDC
23262     /* The below are used only by deprecated functions.  They could be removed */
23263     PL_utf8_xidcont  = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
23264     PL_utf8_idcont   = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
23265     PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
23266 #  endif
23267 }
23268
23269 /* These four functions are compiled only in regcomp.c, where they have access
23270  * to the data they return.  They are a way for re_comp.c to get access to that
23271  * data without having to compile the whole data structures. */
23272
23273 I16
23274 Perl_do_uniprop_match(const char * const key, const U16 key_len)
23275 {
23276     PERL_ARGS_ASSERT_DO_UNIPROP_MATCH;
23277
23278     return match_uniprop((U8 *) key, key_len);
23279 }
23280
23281 SV *
23282 Perl_get_prop_definition(pTHX_ const int table_index)
23283 {
23284     PERL_ARGS_ASSERT_GET_PROP_DEFINITION;
23285
23286     /* Create and return the inversion list */
23287     return _new_invlist_C_array(uni_prop_ptrs[table_index]);
23288 }
23289
23290 const char * const *
23291 Perl_get_prop_values(const int table_index)
23292 {
23293     PERL_ARGS_ASSERT_GET_PROP_VALUES;
23294
23295     return UNI_prop_value_ptrs[table_index];
23296 }
23297
23298 const char *
23299 Perl_get_deprecated_property_msg(const Size_t warning_offset)
23300 {
23301     PERL_ARGS_ASSERT_GET_DEPRECATED_PROPERTY_MSG;
23302
23303     return deprecated_property_msgs[warning_offset];
23304 }
23305
23306 #  if 0
23307
23308 This code was mainly added for backcompat to give a warning for non-portable
23309 code points in user-defined properties.  But experiments showed that the
23310 warning in earlier perls were only omitted on overflow, which should be an
23311 error, so there really isnt a backcompat issue, and actually adding the
23312 warning when none was present before might cause breakage, for little gain.  So
23313 khw left this code in, but not enabled.  Tests were never added.
23314
23315 embed.fnc entry:
23316 Ei      |const char *|get_extended_utf8_msg|const UV cp
23317
23318 PERL_STATIC_INLINE const char *
23319 S_get_extended_utf8_msg(pTHX_ const UV cp)
23320 {
23321     U8 dummy[UTF8_MAXBYTES + 1];
23322     HV *msgs;
23323     SV **msg;
23324
23325     uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
23326                              &msgs);
23327
23328     msg = hv_fetchs(msgs, "text", 0);
23329     assert(msg);
23330
23331     (void) sv_2mortal((SV *) msgs);
23332
23333     return SvPVX(*msg);
23334 }
23335
23336 #  endif
23337 #endif /* end of ! PERL_IN_XSUB_RE */
23338
23339 STATIC REGEXP *
23340 S_compile_wildcard(pTHX_ const char * subpattern, const STRLEN len,
23341                          const bool ignore_case)
23342 {
23343     /* Pretends that the input subpattern is qr/subpattern/aam, compiling it
23344      * possibly with /i if the 'ignore_case' parameter is true.  Use /aa
23345      * because nothing outside of ASCII will match.  Use /m because the input
23346      * string may be a bunch of lines strung together.
23347      *
23348      * Also sets up the debugging info */
23349
23350     U32 flags = PMf_MULTILINE|PMf_WILDCARD;
23351     U32 rx_flags;
23352     SV * subpattern_sv = sv_2mortal(newSVpvn(subpattern, len));
23353     REGEXP * subpattern_re;
23354     DECLARE_AND_GET_RE_DEBUG_FLAGS;
23355
23356     PERL_ARGS_ASSERT_COMPILE_WILDCARD;
23357
23358     if (ignore_case) {
23359         flags |= PMf_FOLD;
23360     }
23361     set_regex_charset(&flags, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
23362
23363     /* Like in op.c, we copy the compile time pm flags to the rx ones */
23364     rx_flags = flags & RXf_PMf_COMPILETIME;
23365
23366 #ifndef PERL_IN_XSUB_RE
23367     /* Use the core engine if this file is regcomp.c.  That means no
23368      * 'use re "Debug ..." is in effect, so the core engine is sufficient */
23369     subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23370                                              &PL_core_reg_engine,
23371                                              NULL, NULL,
23372                                              rx_flags, flags);
23373 #else
23374     if (isDEBUG_WILDCARD) {
23375         /* Use the special debugging engine if this file is re_comp.c and wants
23376          * to output the wildcard matching.  This uses whatever
23377          * 'use re "Debug ..." is in effect */
23378         subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23379                                                  &my_reg_engine,
23380                                                  NULL, NULL,
23381                                                  rx_flags, flags);
23382     }
23383     else {
23384         /* Use the special wildcard engine if this file is re_comp.c and
23385          * doesn't want to output the wildcard matching.  This uses whatever
23386          * 'use re "Debug ..." is in effect for compilation, but this engine
23387          * structure has been set up so that it uses the core engine for
23388          * execution, so no execution debugging as a result of re.pm will be
23389          * displayed. */
23390         subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23391                                                  &wild_reg_engine,
23392                                                  NULL, NULL,
23393                                                  rx_flags, flags);
23394         /* XXX The above has the effect that any user-supplied regex engine
23395          * won't be called for matching wildcards.  That might be good, or bad.
23396          * It could be changed in several ways.  The reason it is done the
23397          * current way is to avoid having to save and restore
23398          * ^{^RE_DEBUG_FLAGS} around the execution.  save_scalar() perhaps
23399          * could be used.  Another suggestion is to keep the authoritative
23400          * value of the debug flags in a thread-local variable and add set/get
23401          * magic to ${^RE_DEBUG_FLAGS} to keep the C level variable up to date.
23402          * Still another is to pass a flag, say in the engine's intflags that
23403          * would be checked each time before doing the debug output */
23404     }
23405 #endif
23406
23407     assert(subpattern_re);  /* Should have died if didn't compile successfully */
23408     return subpattern_re;
23409 }
23410
23411 STATIC I32
23412 S_execute_wildcard(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
23413          char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
23414 {
23415     I32 result;
23416     DECLARE_AND_GET_RE_DEBUG_FLAGS;
23417
23418     PERL_ARGS_ASSERT_EXECUTE_WILDCARD;
23419
23420     ENTER;
23421
23422     /* The compilation has set things up so that if the program doesn't want to
23423      * see the wildcard matching procedure, it will get the core execution
23424      * engine, which is subject only to -Dr.  So we have to turn that off
23425      * around this procedure */
23426     if (! isDEBUG_WILDCARD) {
23427         /* Note! Casts away 'volatile' */
23428         SAVEI32(PL_debug);
23429         PL_debug &= ~ DEBUG_r_FLAG;
23430     }
23431
23432     result = CALLREGEXEC(prog, stringarg, strend, strbeg, minend, screamer,
23433                          NULL, nosave);
23434     LEAVE;
23435
23436     return result;
23437 }
23438
23439 SV *
23440 S_handle_user_defined_property(pTHX_
23441
23442     /* Parses the contents of a user-defined property definition; returning the
23443      * expanded definition if possible.  If so, the return is an inversion
23444      * list.
23445      *
23446      * If there are subroutines that are part of the expansion and which aren't
23447      * known at the time of the call to this function, this returns what
23448      * parse_uniprop_string() returned for the first one encountered.
23449      *
23450      * If an error was found, NULL is returned, and 'msg' gets a suitable
23451      * message appended to it.  (Appending allows the back trace of how we got
23452      * to the faulty definition to be displayed through nested calls of
23453      * user-defined subs.)
23454      *
23455      * The caller IS responsible for freeing any returned SV.
23456      *
23457      * The syntax of the contents is pretty much described in perlunicode.pod,
23458      * but we also allow comments on each line */
23459
23460     const char * name,          /* Name of property */
23461     const STRLEN name_len,      /* The name's length in bytes */
23462     const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
23463     const bool to_fold,         /* ? Is this under /i */
23464     const bool runtime,         /* ? Are we in compile- or run-time */
23465     const bool deferrable,      /* Is it ok for this property's full definition
23466                                    to be deferred until later? */
23467     SV* contents,               /* The property's definition */
23468     bool *user_defined_ptr,     /* This will be set TRUE as we wouldn't be
23469                                    getting called unless this is thought to be
23470                                    a user-defined property */
23471     SV * msg,                   /* Any error or warning msg(s) are appended to
23472                                    this */
23473     const STRLEN level)         /* Recursion level of this call */
23474 {
23475     STRLEN len;
23476     const char * string         = SvPV_const(contents, len);
23477     const char * const e        = string + len;
23478     const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
23479     const STRLEN msgs_length_on_entry = SvCUR(msg);
23480
23481     const char * s0 = string;   /* Points to first byte in the current line
23482                                    being parsed in 'string' */
23483     const char overflow_msg[] = "Code point too large in \"";
23484     SV* running_definition = NULL;
23485
23486     PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
23487
23488     *user_defined_ptr = TRUE;
23489
23490     /* Look at each line */
23491     while (s0 < e) {
23492         const char * s;     /* Current byte */
23493         char op = '+';      /* Default operation is 'union' */
23494         IV   min = 0;       /* range begin code point */
23495         IV   max = -1;      /* and range end */
23496         SV* this_definition;
23497
23498         /* Skip comment lines */
23499         if (*s0 == '#') {
23500             s0 = strchr(s0, '\n');
23501             if (s0 == NULL) {
23502                 break;
23503             }
23504             s0++;
23505             continue;
23506         }
23507
23508         /* For backcompat, allow an empty first line */
23509         if (*s0 == '\n') {
23510             s0++;
23511             continue;
23512         }
23513
23514         /* First character in the line may optionally be the operation */
23515         if (   *s0 == '+'
23516             || *s0 == '!'
23517             || *s0 == '-'
23518             || *s0 == '&')
23519         {
23520             op = *s0++;
23521         }
23522
23523         /* If the line is one or two hex digits separated by blank space, its
23524          * a range; otherwise it is either another user-defined property or an
23525          * error */
23526
23527         s = s0;
23528
23529         if (! isXDIGIT(*s)) {
23530             goto check_if_property;
23531         }
23532
23533         do { /* Each new hex digit will add 4 bits. */
23534             if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
23535                 s = strchr(s, '\n');
23536                 if (s == NULL) {
23537                     s = e;
23538                 }
23539                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23540                 sv_catpv(msg, overflow_msg);
23541                 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23542                                      UTF8fARG(is_contents_utf8, s - s0, s0));
23543                 sv_catpvs(msg, "\"");
23544                 goto return_failure;
23545             }
23546
23547             /* Accumulate this digit into the value */
23548             min = (min << 4) + READ_XDIGIT(s);
23549         } while (isXDIGIT(*s));
23550
23551         while (isBLANK(*s)) { s++; }
23552
23553         /* We allow comments at the end of the line */
23554         if (*s == '#') {
23555             s = strchr(s, '\n');
23556             if (s == NULL) {
23557                 s = e;
23558             }
23559             s++;
23560         }
23561         else if (s < e && *s != '\n') {
23562             if (! isXDIGIT(*s)) {
23563                 goto check_if_property;
23564             }
23565
23566             /* Look for the high point of the range */
23567             max = 0;
23568             do {
23569                 if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
23570                     s = strchr(s, '\n');
23571                     if (s == NULL) {
23572                         s = e;
23573                     }
23574                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23575                     sv_catpv(msg, overflow_msg);
23576                     Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23577                                       UTF8fARG(is_contents_utf8, s - s0, s0));
23578                     sv_catpvs(msg, "\"");
23579                     goto return_failure;
23580                 }
23581
23582                 max = (max << 4) + READ_XDIGIT(s);
23583             } while (isXDIGIT(*s));
23584
23585             while (isBLANK(*s)) { s++; }
23586
23587             if (*s == '#') {
23588                 s = strchr(s, '\n');
23589                 if (s == NULL) {
23590                     s = e;
23591                 }
23592             }
23593             else if (s < e && *s != '\n') {
23594                 goto check_if_property;
23595             }
23596         }
23597
23598         if (max == -1) {    /* The line only had one entry */
23599             max = min;
23600         }
23601         else if (max < min) {
23602             if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23603             sv_catpvs(msg, "Illegal range in \"");
23604             Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23605                                 UTF8fARG(is_contents_utf8, s - s0, s0));
23606             sv_catpvs(msg, "\"");
23607             goto return_failure;
23608         }
23609
23610 #  if 0   /* See explanation at definition above of get_extended_utf8_msg() */
23611
23612         if (   UNICODE_IS_PERL_EXTENDED(min)
23613             || UNICODE_IS_PERL_EXTENDED(max))
23614         {
23615             if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23616
23617             /* If both code points are non-portable, warn only on the lower
23618              * one. */
23619             sv_catpv(msg, get_extended_utf8_msg(
23620                                             (UNICODE_IS_PERL_EXTENDED(min))
23621                                             ? min : max));
23622             sv_catpvs(msg, " in \"");
23623             Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23624                                  UTF8fARG(is_contents_utf8, s - s0, s0));
23625             sv_catpvs(msg, "\"");
23626         }
23627
23628 #  endif
23629
23630         /* Here, this line contains a legal range */
23631         this_definition = sv_2mortal(_new_invlist(2));
23632         this_definition = _add_range_to_invlist(this_definition, min, max);
23633         goto calculate;
23634
23635       check_if_property:
23636
23637         /* Here it isn't a legal range line.  See if it is a legal property
23638          * line.  First find the end of the meat of the line */
23639         s = strpbrk(s, "#\n");
23640         if (s == NULL) {
23641             s = e;
23642         }
23643
23644         /* Ignore trailing blanks in keeping with the requirements of
23645          * parse_uniprop_string() */
23646         s--;
23647         while (s > s0 && isBLANK_A(*s)) {
23648             s--;
23649         }
23650         s++;
23651
23652         this_definition = parse_uniprop_string(s0, s - s0,
23653                                                is_utf8, to_fold, runtime,
23654                                                deferrable,
23655                                                NULL,
23656                                                user_defined_ptr, msg,
23657                                                (name_len == 0)
23658                                                 ? level /* Don't increase level
23659                                                            if input is empty */
23660                                                 : level + 1
23661                                               );
23662         if (this_definition == NULL) {
23663             goto return_failure;    /* 'msg' should have had the reason
23664                                        appended to it by the above call */
23665         }
23666
23667         if (! is_invlist(this_definition)) {    /* Unknown at this time */
23668             return newSVsv(this_definition);
23669         }
23670
23671         if (*s != '\n') {
23672             s = strchr(s, '\n');
23673             if (s == NULL) {
23674                 s = e;
23675             }
23676         }
23677
23678       calculate:
23679
23680         switch (op) {
23681             case '+':
23682                 _invlist_union(running_definition, this_definition,
23683                                                         &running_definition);
23684                 break;
23685             case '-':
23686                 _invlist_subtract(running_definition, this_definition,
23687                                                         &running_definition);
23688                 break;
23689             case '&':
23690                 _invlist_intersection(running_definition, this_definition,
23691                                                         &running_definition);
23692                 break;
23693             case '!':
23694                 _invlist_union_complement_2nd(running_definition,
23695                                         this_definition, &running_definition);
23696                 break;
23697             default:
23698                 Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
23699                                  __FILE__, __LINE__, op);
23700                 break;
23701         }
23702
23703         /* Position past the '\n' */
23704         s0 = s + 1;
23705     }   /* End of loop through the lines of 'contents' */
23706
23707     /* Here, we processed all the lines in 'contents' without error.  If we
23708      * didn't add any warnings, simply return success */
23709     if (msgs_length_on_entry == SvCUR(msg)) {
23710
23711         /* If the expansion was empty, the answer isn't nothing: its an empty
23712          * inversion list */
23713         if (running_definition == NULL) {
23714             running_definition = _new_invlist(1);
23715         }
23716
23717         return running_definition;
23718     }
23719
23720     /* Otherwise, add some explanatory text, but we will return success */
23721     goto return_msg;
23722
23723   return_failure:
23724     running_definition = NULL;
23725
23726   return_msg:
23727
23728     if (name_len > 0) {
23729         sv_catpvs(msg, " in expansion of ");
23730         Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
23731     }
23732
23733     return running_definition;
23734 }
23735
23736 /* As explained below, certain operations need to take place in the first
23737  * thread created.  These macros switch contexts */
23738 #  ifdef USE_ITHREADS
23739 #    define DECLARATION_FOR_GLOBAL_CONTEXT                                  \
23740                                         PerlInterpreter * save_aTHX = aTHX;
23741 #    define SWITCH_TO_GLOBAL_CONTEXT                                        \
23742                            PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
23743 #    define RESTORE_CONTEXT  PERL_SET_CONTEXT((aTHX = save_aTHX));
23744 #    define CUR_CONTEXT      aTHX
23745 #    define ORIGINAL_CONTEXT save_aTHX
23746 #  else
23747 #    define DECLARATION_FOR_GLOBAL_CONTEXT    dNOOP
23748 #    define SWITCH_TO_GLOBAL_CONTEXT          NOOP
23749 #    define RESTORE_CONTEXT                   NOOP
23750 #    define CUR_CONTEXT                       NULL
23751 #    define ORIGINAL_CONTEXT                  NULL
23752 #  endif
23753
23754 STATIC void
23755 S_delete_recursion_entry(pTHX_ void *key)
23756 {
23757     /* Deletes the entry used to detect recursion when expanding user-defined
23758      * properties.  This is a function so it can be set up to be called even if
23759      * the program unexpectedly quits */
23760
23761     SV ** current_entry;
23762     const STRLEN key_len = strlen((const char *) key);
23763     DECLARATION_FOR_GLOBAL_CONTEXT;
23764
23765     SWITCH_TO_GLOBAL_CONTEXT;
23766
23767     /* If the entry is one of these types, it is a permanent entry, and not the
23768      * one used to detect recursions.  This function should delete only the
23769      * recursion entry */
23770     current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
23771     if (     current_entry
23772         && ! is_invlist(*current_entry)
23773         && ! SvPOK(*current_entry))
23774     {
23775         (void) hv_delete(PL_user_def_props, (const char *) key, key_len,
23776                                                                     G_DISCARD);
23777     }
23778
23779     RESTORE_CONTEXT;
23780 }
23781
23782 STATIC SV *
23783 S_get_fq_name(pTHX_
23784               const char * const name,    /* The first non-blank in the \p{}, \P{} */
23785               const Size_t name_len,      /* Its length in bytes, not including any trailing space */
23786               const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
23787               const bool has_colon_colon
23788              )
23789 {
23790     /* Returns a mortal SV containing the fully qualified version of the input
23791      * name */
23792
23793     SV * fq_name;
23794
23795     fq_name = newSVpvs_flags("", SVs_TEMP);
23796
23797     /* Use the current package if it wasn't included in our input */
23798     if (! has_colon_colon) {
23799         const HV * pkg = (IN_PERL_COMPILETIME)
23800                          ? PL_curstash
23801                          : CopSTASH(PL_curcop);
23802         const char* pkgname = HvNAME(pkg);
23803
23804         Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23805                       UTF8fARG(is_utf8, strlen(pkgname), pkgname));
23806         sv_catpvs(fq_name, "::");
23807     }
23808
23809     Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23810                          UTF8fARG(is_utf8, name_len, name));
23811     return fq_name;
23812 }
23813
23814 STATIC SV *
23815 S_parse_uniprop_string(pTHX_
23816
23817     /* Parse the interior of a \p{}, \P{}.  Returns its definition if knowable
23818      * now.  If so, the return is an inversion list.
23819      *
23820      * If the property is user-defined, it is a subroutine, which in turn
23821      * may call other subroutines.  This function will call the whole nest of
23822      * them to get the definition they return; if some aren't known at the time
23823      * of the call to this function, the fully qualified name of the highest
23824      * level sub is returned.  It is an error to call this function at runtime
23825      * without every sub defined.
23826      *
23827      * If an error was found, NULL is returned, and 'msg' gets a suitable
23828      * message appended to it.  (Appending allows the back trace of how we got
23829      * to the faulty definition to be displayed through nested calls of
23830      * user-defined subs.)
23831      *
23832      * The caller should NOT try to free any returned inversion list.
23833      *
23834      * Other parameters will be set on return as described below */
23835
23836     const char * const name,    /* The first non-blank in the \p{}, \P{} */
23837     Size_t name_len,            /* Its length in bytes, not including any
23838                                    trailing space */
23839     const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
23840     const bool to_fold,         /* ? Is this under /i */
23841     const bool runtime,         /* TRUE if this is being called at run time */
23842     const bool deferrable,      /* TRUE if it's ok for the definition to not be
23843                                    known at this call */
23844     AV ** strings,              /* To return string property values, like named
23845                                    sequences */
23846     bool *user_defined_ptr,     /* Upon return from this function it will be
23847                                    set to TRUE if any component is a
23848                                    user-defined property */
23849     SV * msg,                   /* Any error or warning msg(s) are appended to
23850                                    this */
23851     const STRLEN level)         /* Recursion level of this call */
23852 {
23853     char* lookup_name;          /* normalized name for lookup in our tables */
23854     unsigned lookup_len;        /* Its length */
23855     enum { Not_Strict = 0,      /* Some properties have stricter name */
23856            Strict,              /* normalization rules, which we decide */
23857            As_Is                /* upon based on parsing */
23858          } stricter = Not_Strict;
23859
23860     /* nv= or numeric_value=, or possibly one of the cjk numeric properties
23861      * (though it requires extra effort to download them from Unicode and
23862      * compile perl to know about them) */
23863     bool is_nv_type = FALSE;
23864
23865     unsigned int i, j = 0;
23866     int equals_pos = -1;    /* Where the '=' is found, or negative if none */
23867     int slash_pos  = -1;    /* Where the '/' is found, or negative if none */
23868     int table_index = 0;    /* The entry number for this property in the table
23869                                of all Unicode property names */
23870     bool starts_with_Is = FALSE;  /* ? Does the name start with 'Is' */
23871     Size_t lookup_offset = 0;   /* Used to ignore the first few characters of
23872                                    the normalized name in certain situations */
23873     Size_t non_pkg_begin = 0;   /* Offset of first byte in 'name' that isn't
23874                                    part of a package name */
23875     Size_t lun_non_pkg_begin = 0;   /* Similarly for 'lookup_name' */
23876     bool could_be_user_defined = TRUE;  /* ? Could this be a user-defined
23877                                              property rather than a Unicode
23878                                              one. */
23879     SV * prop_definition = NULL;  /* The returned definition of 'name' or NULL
23880                                      if an error.  If it is an inversion list,
23881                                      it is the definition.  Otherwise it is a
23882                                      string containing the fully qualified sub
23883                                      name of 'name' */
23884     SV * fq_name = NULL;        /* For user-defined properties, the fully
23885                                    qualified name */
23886     bool invert_return = FALSE; /* ? Do we need to complement the result before
23887                                      returning it */
23888     bool stripped_utf8_pkg = FALSE; /* Set TRUE if the input includes an
23889                                        explicit utf8:: package that we strip
23890                                        off  */
23891     /* The expansion of properties that could be either user-defined or
23892      * official unicode ones is deferred until runtime, including a marker for
23893      * those that might be in the latter category.  This boolean indicates if
23894      * we've seen that marker.  If not, what we're parsing can't be such an
23895      * official Unicode property whose expansion was deferred */
23896     bool could_be_deferred_official = FALSE;
23897
23898     PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
23899
23900     /* The input will be normalized into 'lookup_name' */
23901     Newx(lookup_name, name_len, char);
23902     SAVEFREEPV(lookup_name);
23903
23904     /* Parse the input. */
23905     for (i = 0; i < name_len; i++) {
23906         char cur = name[i];
23907
23908         /* Most of the characters in the input will be of this ilk, being parts
23909          * of a name */
23910         if (isIDCONT_A(cur)) {
23911
23912             /* Case differences are ignored.  Our lookup routine assumes
23913              * everything is lowercase, so normalize to that */
23914             if (isUPPER_A(cur)) {
23915                 lookup_name[j++] = toLOWER_A(cur);
23916                 continue;
23917             }
23918
23919             if (cur == '_') { /* Don't include these in the normalized name */
23920                 continue;
23921             }
23922
23923             lookup_name[j++] = cur;
23924
23925             /* The first character in a user-defined name must be of this type.
23926              * */
23927             if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
23928                 could_be_user_defined = FALSE;
23929             }
23930
23931             continue;
23932         }
23933
23934         /* Here, the character is not something typically in a name,  But these
23935          * two types of characters (and the '_' above) can be freely ignored in
23936          * most situations.  Later it may turn out we shouldn't have ignored
23937          * them, and we have to reparse, but we don't have enough information
23938          * yet to make that decision */
23939         if (cur == '-' || isSPACE_A(cur)) {
23940             could_be_user_defined = FALSE;
23941             continue;
23942         }
23943
23944         /* An equals sign or single colon mark the end of the first part of
23945          * the property name */
23946         if (    cur == '='
23947             || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
23948         {
23949             lookup_name[j++] = '='; /* Treat the colon as an '=' */
23950             equals_pos = j; /* Note where it occurred in the input */
23951             could_be_user_defined = FALSE;
23952             break;
23953         }
23954
23955         /* If this looks like it is a marker we inserted at compile time,
23956          * set a flag and otherwise ignore it.  If it isn't in the final
23957          * position, keep it as it would have been user input. */
23958         if (     UNLIKELY(cur == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
23959             && ! deferrable
23960             &&   could_be_user_defined
23961             &&   i == name_len - 1)
23962         {
23963             name_len--;
23964             could_be_deferred_official = TRUE;
23965             continue;
23966         }
23967
23968         /* Otherwise, this character is part of the name. */
23969         lookup_name[j++] = cur;
23970
23971         /* Here it isn't a single colon, so if it is a colon, it must be a
23972          * double colon */
23973         if (cur == ':') {
23974
23975             /* A double colon should be a package qualifier.  We note its
23976              * position and continue.  Note that one could have
23977              *      pkg1::pkg2::...::foo
23978              * so that the position at the end of the loop will be just after
23979              * the final qualifier */
23980
23981             i++;
23982             non_pkg_begin = i + 1;
23983             lookup_name[j++] = ':';
23984             lun_non_pkg_begin = j;
23985         }
23986         else { /* Only word chars (and '::') can be in a user-defined name */
23987             could_be_user_defined = FALSE;
23988         }
23989     } /* End of parsing through the lhs of the property name (or all of it if
23990          no rhs) */
23991
23992 #  define STRLENs(s)  (sizeof("" s "") - 1)
23993
23994     /* If there is a single package name 'utf8::', it is ambiguous.  It could
23995      * be for a user-defined property, or it could be a Unicode property, as
23996      * all of them are considered to be for that package.  For the purposes of
23997      * parsing the rest of the property, strip it off */
23998     if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
23999         lookup_name +=  STRLENs("utf8::");
24000         j -=  STRLENs("utf8::");
24001         equals_pos -=  STRLENs("utf8::");
24002         stripped_utf8_pkg = TRUE;
24003     }
24004
24005     /* Here, we are either done with the whole property name, if it was simple;
24006      * or are positioned just after the '=' if it is compound. */
24007
24008     if (equals_pos >= 0) {
24009         assert(stricter == Not_Strict); /* We shouldn't have set this yet */
24010
24011         /* Space immediately after the '=' is ignored */
24012         i++;
24013         for (; i < name_len; i++) {
24014             if (! isSPACE_A(name[i])) {
24015                 break;
24016             }
24017         }
24018
24019         /* Most punctuation after the equals indicates a subpattern, like
24020          * \p{foo=/bar/} */
24021         if (   isPUNCT_A(name[i])
24022             &&  name[i] != '-'
24023             &&  name[i] != '+'
24024             &&  name[i] != '_'
24025             &&  name[i] != '{'
24026                 /* A backslash means the real delimitter is the next character,
24027                  * but it must be punctuation */
24028             && (name[i] != '\\' || (i < name_len && isPUNCT_A(name[i+1]))))
24029         {
24030             bool special_property = memEQs(lookup_name, j - 1, "name")
24031                                  || memEQs(lookup_name, j - 1, "na");
24032             if (! special_property) {
24033                 /* Find the property.  The table includes the equals sign, so
24034                  * we use 'j' as-is */
24035                 table_index = do_uniprop_match(lookup_name, j);
24036             }
24037             if (special_property || table_index) {
24038                 REGEXP * subpattern_re;
24039                 char open = name[i++];
24040                 char close;
24041                 const char * pos_in_brackets;
24042                 const char * const * prop_values;
24043                 bool escaped = 0;
24044
24045                 /* Backslash => delimitter is the character following.  We
24046                  * already checked that it is punctuation */
24047                 if (open == '\\') {
24048                     open = name[i++];
24049                     escaped = 1;
24050                 }
24051
24052                 /* This data structure is constructed so that the matching
24053                  * closing bracket is 3 past its matching opening.  The second
24054                  * set of closing is so that if the opening is something like
24055                  * ']', the closing will be that as well.  Something similar is
24056                  * done in toke.c */
24057                 pos_in_brackets = memCHRs("([<)]>)]>", open);
24058                 close = (pos_in_brackets) ? pos_in_brackets[3] : open;
24059
24060                 if (    i >= name_len
24061                     ||  name[name_len-1] != close
24062                     || (escaped && name[name_len-2] != '\\')
24063                         /* Also make sure that there are enough characters.
24064                          * e.g., '\\\' would show up incorrectly as legal even
24065                          * though it is too short */
24066                     || (SSize_t) (name_len - i - 1 - escaped) < 0)
24067                 {
24068                     sv_catpvs(msg, "Unicode property wildcard not terminated");
24069                     goto append_name_to_msg;
24070                 }
24071
24072                 Perl_ck_warner_d(aTHX_
24073                     packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS),
24074                     "The Unicode property wildcards feature is experimental");
24075
24076                 if (special_property) {
24077                     const char * error_msg;
24078                     const char * revised_name = name + i;
24079                     Size_t revised_name_len = name_len - (i + 1 + escaped);
24080
24081                     /* Currently, the only 'special_property' is name, which we
24082                      * lookup in _charnames.pm */
24083
24084                     if (! load_charnames(newSVpvs("placeholder"),
24085                                          revised_name, revised_name_len,
24086                                          &error_msg))
24087                     {
24088                         sv_catpv(msg, error_msg);
24089                         goto append_name_to_msg;
24090                     }
24091
24092                     /* Farm this out to a function just to make the current
24093                      * function less unwieldy */
24094                     if (handle_names_wildcard(revised_name, revised_name_len,
24095                                               &prop_definition,
24096                                               strings))
24097                     {
24098                         return prop_definition;
24099                     }
24100
24101                     goto failed;
24102                 }
24103
24104                 prop_values = get_prop_values(table_index);
24105
24106                 /* Now create and compile the wildcard subpattern.  Use /i
24107                  * because the property values are supposed to match with case
24108                  * ignored. */
24109                 subpattern_re = compile_wildcard(name + i,
24110                                                  name_len - i - 1 - escaped,
24111                                                  TRUE /* /i */
24112                                                 );
24113
24114                 /* For each legal property value, see if the supplied pattern
24115                  * matches it. */
24116                 while (*prop_values) {
24117                     const char * const entry = *prop_values;
24118                     const Size_t len = strlen(entry);
24119                     SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP);
24120
24121                     if (execute_wildcard(subpattern_re,
24122                                  (char *) entry,
24123                                  (char *) entry + len,
24124                                  (char *) entry, 0,
24125                                  entry_sv,
24126                                  0))
24127                     { /* Here, matched.  Add to the returned list */
24128                         Size_t total_len = j + len;
24129                         SV * sub_invlist = NULL;
24130                         char * this_string;
24131
24132                         /* We know this is a legal \p{property=value}.  Call
24133                          * the function to return the list of code points that
24134                          * match it */
24135                         Newxz(this_string, total_len + 1, char);
24136                         Copy(lookup_name, this_string, j, char);
24137                         my_strlcat(this_string, entry, total_len + 1);
24138                         SAVEFREEPV(this_string);
24139                         sub_invlist = parse_uniprop_string(this_string,
24140                                                            total_len,
24141                                                            is_utf8,
24142                                                            to_fold,
24143                                                            runtime,
24144                                                            deferrable,
24145                                                            NULL,
24146                                                            user_defined_ptr,
24147                                                            msg,
24148                                                            level + 1);
24149                         _invlist_union(prop_definition, sub_invlist,
24150                                        &prop_definition);
24151                     }
24152
24153                     prop_values++;  /* Next iteration, look at next propvalue */
24154                 } /* End of looking through property values; (the data
24155                      structure is terminated by a NULL ptr) */
24156
24157                 SvREFCNT_dec_NN(subpattern_re);
24158
24159                 if (prop_definition) {
24160                     return prop_definition;
24161                 }
24162
24163                 sv_catpvs(msg, "No Unicode property value wildcard matches:");
24164                 goto append_name_to_msg;
24165             }
24166
24167             /* Here's how khw thinks we should proceed to handle the properties
24168              * not yet done:    Bidi Mirroring Glyph        can map to ""
24169                                 Bidi Paired Bracket         can map to ""
24170                                 Case Folding  (both full and simple)
24171                                             Shouldn't /i be good enough for Full
24172                                 Decomposition Mapping
24173                                 Equivalent Unified Ideograph    can map to ""
24174                                 Lowercase Mapping  (both full and simple)
24175                                 NFKC Case Fold                  can map to ""
24176                                 Titlecase Mapping  (both full and simple)
24177                                 Uppercase Mapping  (both full and simple)
24178              * Handle these the same way Name is done, using say, _wild.pm, but
24179              * having both loose and full, like in charclass_invlists.h.
24180              * Perhaps move block and script to that as they are somewhat large
24181              * in charclass_invlists.h.
24182              * For properties where the default is the code point itself, such
24183              * as any of the case changing mappings, the string would otherwise
24184              * consist of all Unicode code points in UTF-8 strung together.
24185              * This would be impractical.  So instead, examine their compiled
24186              * pattern, looking at the ssc.  If none, reject the pattern as an
24187              * error.  Otherwise run the pattern against every code point in
24188              * the ssc.  The ssc is kind of like tr18's 3.9 Possible Match Sets
24189              * And it might be good to create an API to return the ssc.
24190              * Or handle them like the algorithmic names are done
24191              */
24192         } /* End of is a wildcard subppattern */
24193
24194         /* \p{name=...} is handled specially.  Instead of using the normal
24195          * mechanism involving charclass_invlists.h, it uses _charnames.pm
24196          * which has the necessary (huge) data accessible to it, and which
24197          * doesn't get loaded unless necessary.  The legal syntax for names is
24198          * somewhat different than other properties due both to the vagaries of
24199          * a few outlier official names, and the fact that only a few ASCII
24200          * characters are permitted in them */
24201         if (   memEQs(lookup_name, j - 1, "name")
24202             || memEQs(lookup_name, j - 1, "na"))
24203         {
24204             dSP;
24205             HV * table;
24206             SV * character;
24207             const char * error_msg;
24208             CV* lookup_loose;
24209             SV * character_name;
24210             STRLEN character_len;
24211             UV cp;
24212
24213             stricter = As_Is;
24214
24215             /* Since the RHS (after skipping initial space) is passed unchanged
24216              * to charnames, and there are different criteria for what are
24217              * legal characters in the name, just parse it here.  A character
24218              * name must begin with an ASCII alphabetic */
24219             if (! isALPHA(name[i])) {
24220                 goto failed;
24221             }
24222             lookup_name[j++] = name[i];
24223
24224             for (++i; i < name_len; i++) {
24225                 /* Official names can only be in the ASCII range, and only
24226                  * certain characters */
24227                 if (! isASCII(name[i]) || ! isCHARNAME_CONT(name[i])) {
24228                     goto failed;
24229                 }
24230                 lookup_name[j++] = name[i];
24231             }
24232
24233             /* Finished parsing, save the name into an SV */
24234             character_name = newSVpvn(lookup_name + equals_pos, j - equals_pos);
24235
24236             /* Make sure _charnames is loaded.  (The parameters give context
24237              * for any errors generated */
24238             table = load_charnames(character_name, name, name_len, &error_msg);
24239             if (table == NULL) {
24240                 sv_catpv(msg, error_msg);
24241                 goto append_name_to_msg;
24242             }
24243
24244             lookup_loose = get_cvs("_charnames::_loose_regcomp_lookup", 0);
24245             if (! lookup_loose) {
24246                 Perl_croak(aTHX_
24247                        "panic: Can't find '_charnames::_loose_regcomp_lookup");
24248             }
24249
24250             PUSHSTACKi(PERLSI_REGCOMP);
24251             ENTER ;
24252             SAVETMPS;
24253             save_re_context();
24254
24255             PUSHMARK(SP) ;
24256             XPUSHs(character_name);
24257             PUTBACK;
24258             call_sv(MUTABLE_SV(lookup_loose), G_SCALAR);
24259
24260             SPAGAIN ;
24261
24262             character = POPs;
24263             SvREFCNT_inc_simple_void_NN(character);
24264
24265             PUTBACK ;
24266             FREETMPS ;
24267             LEAVE ;
24268             POPSTACK;
24269
24270             if (! SvOK(character)) {
24271                 goto failed;
24272             }
24273
24274             cp = valid_utf8_to_uvchr((U8 *) SvPVX(character), &character_len);
24275             if (character_len == SvCUR(character)) {
24276                 prop_definition = add_cp_to_invlist(NULL, cp);
24277             }
24278             else {
24279                 AV * this_string;
24280
24281                 /* First of the remaining characters in the string. */
24282                 char * remaining = SvPVX(character) + character_len;
24283
24284                 if (strings == NULL) {
24285                     goto failed;    /* XXX Perhaps a specific msg instead, like
24286                                        'not available here' */
24287                 }
24288
24289                 if (*strings == NULL) {
24290                     *strings = newAV();
24291                 }
24292
24293                 this_string = newAV();
24294                 av_push(this_string, newSVuv(cp));
24295
24296                 do {
24297                     cp = valid_utf8_to_uvchr((U8 *) remaining, &character_len);
24298                     av_push(this_string, newSVuv(cp));
24299                     remaining += character_len;
24300                 } while (remaining < SvEND(character));
24301
24302                 av_push(*strings, (SV *) this_string);
24303             }
24304
24305             return prop_definition;
24306         }
24307
24308         /* Certain properties whose values are numeric need special handling.
24309          * They may optionally be prefixed by 'is'.  Ignore that prefix for the
24310          * purposes of checking if this is one of those properties */
24311         if (memBEGINPs(lookup_name, j, "is")) {
24312             lookup_offset = 2;
24313         }
24314
24315         /* Then check if it is one of these specially-handled properties.  The
24316          * possibilities are hard-coded because easier this way, and the list
24317          * is unlikely to change.
24318          *
24319          * All numeric value type properties are of this ilk, and are also
24320          * special in a different way later on.  So find those first.  There
24321          * are several numeric value type properties in the Unihan DB (which is
24322          * unlikely to be compiled with perl, but we handle it here in case it
24323          * does get compiled).  They all end with 'numeric'.  The interiors
24324          * aren't checked for the precise property.  This would stop working if
24325          * a cjk property were to be created that ended with 'numeric' and
24326          * wasn't a numeric type */
24327         is_nv_type = memEQs(lookup_name + lookup_offset,
24328                        j - 1 - lookup_offset, "numericvalue")
24329                   || memEQs(lookup_name + lookup_offset,
24330                       j - 1 - lookup_offset, "nv")
24331                   || (   memENDPs(lookup_name + lookup_offset,
24332                             j - 1 - lookup_offset, "numeric")
24333                       && (   memBEGINPs(lookup_name + lookup_offset,
24334                                       j - 1 - lookup_offset, "cjk")
24335                           || memBEGINPs(lookup_name + lookup_offset,
24336                                       j - 1 - lookup_offset, "k")));
24337         if (   is_nv_type
24338             || memEQs(lookup_name + lookup_offset,
24339                       j - 1 - lookup_offset, "canonicalcombiningclass")
24340             || memEQs(lookup_name + lookup_offset,
24341                       j - 1 - lookup_offset, "ccc")
24342             || memEQs(lookup_name + lookup_offset,
24343                       j - 1 - lookup_offset, "age")
24344             || memEQs(lookup_name + lookup_offset,
24345                       j - 1 - lookup_offset, "in")
24346             || memEQs(lookup_name + lookup_offset,
24347                       j - 1 - lookup_offset, "presentin"))
24348         {
24349             unsigned int k;
24350
24351             /* Since the stuff after the '=' is a number, we can't throw away
24352              * '-' willy-nilly, as those could be a minus sign.  Other stricter
24353              * rules also apply.  However, these properties all can have the
24354              * rhs not be a number, in which case they contain at least one
24355              * alphabetic.  In those cases, the stricter rules don't apply.
24356              * But the numeric type properties can have the alphas [Ee] to
24357              * signify an exponent, and it is still a number with stricter
24358              * rules.  So look for an alpha that signifies not-strict */
24359             stricter = Strict;
24360             for (k = i; k < name_len; k++) {
24361                 if (   isALPHA_A(name[k])
24362                     && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
24363                 {
24364                     stricter = Not_Strict;
24365                     break;
24366                 }
24367             }
24368         }
24369
24370         if (stricter) {
24371
24372             /* A number may have a leading '+' or '-'.  The latter is retained
24373              * */
24374             if (name[i] == '+') {
24375                 i++;
24376             }
24377             else if (name[i] == '-') {
24378                 lookup_name[j++] = '-';
24379                 i++;
24380             }
24381
24382             /* Skip leading zeros including single underscores separating the
24383              * zeros, or between the final leading zero and the first other
24384              * digit */
24385             for (; i < name_len - 1; i++) {
24386                 if (    name[i] != '0'
24387                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
24388                 {
24389                     break;
24390                 }
24391             }
24392         }
24393     }
24394     else {  /* No '=' */
24395
24396        /* Only a few properties without an '=' should be parsed with stricter
24397         * rules.  The list is unlikely to change. */
24398         if (   memBEGINPs(lookup_name, j, "perl")
24399             && memNEs(lookup_name + 4, j - 4, "space")
24400             && memNEs(lookup_name + 4, j - 4, "word"))
24401         {
24402             stricter = Strict;
24403
24404             /* We set the inputs back to 0 and the code below will reparse,
24405              * using strict */
24406             i = j = 0;
24407         }
24408     }
24409
24410     /* Here, we have either finished the property, or are positioned to parse
24411      * the remainder, and we know if stricter rules apply.  Finish out, if not
24412      * already done */
24413     for (; i < name_len; i++) {
24414         char cur = name[i];
24415
24416         /* In all instances, case differences are ignored, and we normalize to
24417          * lowercase */
24418         if (isUPPER_A(cur)) {
24419             lookup_name[j++] = toLOWER(cur);
24420             continue;
24421         }
24422
24423         /* An underscore is skipped, but not under strict rules unless it
24424          * separates two digits */
24425         if (cur == '_') {
24426             if (    stricter
24427                 && (     i == 0 || (int) i == equals_pos || i == name_len- 1
24428                     || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
24429             {
24430                 lookup_name[j++] = '_';
24431             }
24432             continue;
24433         }
24434
24435         /* Hyphens are skipped except under strict */
24436         if (cur == '-' && ! stricter) {
24437             continue;
24438         }
24439
24440         /* XXX Bug in documentation.  It says white space skipped adjacent to
24441          * non-word char.  Maybe we should, but shouldn't skip it next to a dot
24442          * in a number */
24443         if (isSPACE_A(cur) && ! stricter) {
24444             continue;
24445         }
24446
24447         lookup_name[j++] = cur;
24448
24449         /* Unless this is a non-trailing slash, we are done with it */
24450         if (i >= name_len - 1 || cur != '/') {
24451             continue;
24452         }
24453
24454         slash_pos = j;
24455
24456         /* A slash in the 'numeric value' property indicates that what follows
24457          * is a denominator.  It can have a leading '+' and '0's that should be
24458          * skipped.  But we have never allowed a negative denominator, so treat
24459          * a minus like every other character.  (No need to rule out a second
24460          * '/', as that won't match anything anyway */
24461         if (is_nv_type) {
24462             i++;
24463             if (i < name_len && name[i] == '+') {
24464                 i++;
24465             }
24466
24467             /* Skip leading zeros including underscores separating digits */
24468             for (; i < name_len - 1; i++) {
24469                 if (   name[i] != '0'
24470                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
24471                 {
24472                     break;
24473                 }
24474             }
24475
24476             /* Store the first real character in the denominator */
24477             if (i < name_len) {
24478                 lookup_name[j++] = name[i];
24479             }
24480         }
24481     }
24482
24483     /* Here are completely done parsing the input 'name', and 'lookup_name'
24484      * contains a copy, normalized.
24485      *
24486      * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
24487      * different from without the underscores.  */
24488     if (  (   UNLIKELY(memEQs(lookup_name, j, "l"))
24489            || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
24490         && UNLIKELY(name[name_len-1] == '_'))
24491     {
24492         lookup_name[j++] = '&';
24493     }
24494
24495     /* If the original input began with 'In' or 'Is', it could be a subroutine
24496      * call to a user-defined property instead of a Unicode property name. */
24497     if (    name_len - non_pkg_begin > 2
24498         &&  name[non_pkg_begin+0] == 'I'
24499         && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
24500     {
24501         /* Names that start with In have different characterstics than those
24502          * that start with Is */
24503         if (name[non_pkg_begin+1] == 's') {
24504             starts_with_Is = TRUE;
24505         }
24506     }
24507     else {
24508         could_be_user_defined = FALSE;
24509     }
24510
24511     if (could_be_user_defined) {
24512         CV* user_sub;
24513
24514         /* If the user defined property returns the empty string, it could
24515          * easily be because the pattern is being compiled before the data it
24516          * actually needs to compile is available.  This could be argued to be
24517          * a bug in the perl code, but this is a change of behavior for Perl,
24518          * so we handle it.  This means that intentionally returning nothing
24519          * will not be resolved until runtime */
24520         bool empty_return = FALSE;
24521
24522         /* Here, the name could be for a user defined property, which are
24523          * implemented as subs. */
24524         user_sub = get_cvn_flags(name, name_len, 0);
24525         if (! user_sub) {
24526
24527             /* Here, the property name could be a user-defined one, but there
24528              * is no subroutine to handle it (as of now).   Defer handling it
24529              * until runtime.  Otherwise, a block defined by Unicode in a later
24530              * release would get the synonym InFoo added for it, and existing
24531              * code that used that name would suddenly break if it referred to
24532              * the property before the sub was declared.  See [perl #134146] */
24533             if (deferrable) {
24534                 goto definition_deferred;
24535             }
24536
24537             /* Here, we are at runtime, and didn't find the user property.  It
24538              * could be an official property, but only if no package was
24539              * specified, or just the utf8:: package. */
24540             if (could_be_deferred_official) {
24541                 lookup_name += lun_non_pkg_begin;
24542                 j -= lun_non_pkg_begin;
24543             }
24544             else if (! stripped_utf8_pkg) {
24545                 goto unknown_user_defined;
24546             }
24547
24548             /* Drop down to look up in the official properties */
24549         }
24550         else {
24551             const char insecure[] = "Insecure user-defined property";
24552
24553             /* Here, there is a sub by the correct name.  Normally we call it
24554              * to get the property definition */
24555             dSP;
24556             SV * user_sub_sv = MUTABLE_SV(user_sub);
24557             SV * error;     /* Any error returned by calling 'user_sub' */
24558             SV * key;       /* The key into the hash of user defined sub names
24559                              */
24560             SV * placeholder;
24561             SV ** saved_user_prop_ptr;      /* Hash entry for this property */
24562
24563             /* How many times to retry when another thread is in the middle of
24564              * expanding the same definition we want */
24565             PERL_INT_FAST8_T retry_countdown = 10;
24566
24567             DECLARATION_FOR_GLOBAL_CONTEXT;
24568
24569             /* If we get here, we know this property is user-defined */
24570             *user_defined_ptr = TRUE;
24571
24572             /* We refuse to call a potentially tainted subroutine; returning an
24573              * error instead */
24574             if (TAINT_get) {
24575                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24576                 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
24577                 goto append_name_to_msg;
24578             }
24579
24580             /* In principal, we only call each subroutine property definition
24581              * once during the life of the program.  This guarantees that the
24582              * property definition never changes.  The results of the single
24583              * sub call are stored in a hash, which is used instead for future
24584              * references to this property.  The property definition is thus
24585              * immutable.  But, to allow the user to have a /i-dependent
24586              * definition, we call the sub once for non-/i, and once for /i,
24587              * should the need arise, passing the /i status as a parameter.
24588              *
24589              * We start by constructing the hash key name, consisting of the
24590              * fully qualified subroutine name, preceded by the /i status, so
24591              * that there is a key for /i and a different key for non-/i */
24592             key = newSVpvn(((to_fold) ? "1" : "0"), 1);
24593             fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
24594                                           non_pkg_begin != 0);
24595             sv_catsv(key, fq_name);
24596             sv_2mortal(key);
24597
24598             /* We only call the sub once throughout the life of the program
24599              * (with the /i, non-/i exception noted above).  That means the
24600              * hash must be global and accessible to all threads.  It is
24601              * created at program start-up, before any threads are created, so
24602              * is accessible to all children.  But this creates some
24603              * complications.
24604              *
24605              * 1) The keys can't be shared, or else problems arise; sharing is
24606              *    turned off at hash creation time
24607              * 2) All SVs in it are there for the remainder of the life of the
24608              *    program, and must be created in the same interpreter context
24609              *    as the hash, or else they will be freed from the wrong pool
24610              *    at global destruction time.  This is handled by switching to
24611              *    the hash's context to create each SV going into it, and then
24612              *    immediately switching back
24613              * 3) All accesses to the hash must be controlled by a mutex, to
24614              *    prevent two threads from getting an unstable state should
24615              *    they simultaneously be accessing it.  The code below is
24616              *    crafted so that the mutex is locked whenever there is an
24617              *    access and unlocked only when the next stable state is
24618              *    achieved.
24619              *
24620              * The hash stores either the definition of the property if it was
24621              * valid, or, if invalid, the error message that was raised.  We
24622              * use the type of SV to distinguish.
24623              *
24624              * There's also the need to guard against the definition expansion
24625              * from infinitely recursing.  This is handled by storing the aTHX
24626              * of the expanding thread during the expansion.  Again the SV type
24627              * is used to distinguish this from the other two cases.  If we
24628              * come to here and the hash entry for this property is our aTHX,
24629              * it means we have recursed, and the code assumes that we would
24630              * infinitely recurse, so instead stops and raises an error.
24631              * (Any recursion has always been treated as infinite recursion in
24632              * this feature.)
24633              *
24634              * If instead, the entry is for a different aTHX, it means that
24635              * that thread has gotten here first, and hasn't finished expanding
24636              * the definition yet.  We just have to wait until it is done.  We
24637              * sleep and retry a few times, returning an error if the other
24638              * thread doesn't complete. */
24639
24640           re_fetch:
24641             USER_PROP_MUTEX_LOCK;
24642
24643             /* If we have an entry for this key, the subroutine has already
24644              * been called once with this /i status. */
24645             saved_user_prop_ptr = hv_fetch(PL_user_def_props,
24646                                                    SvPVX(key), SvCUR(key), 0);
24647             if (saved_user_prop_ptr) {
24648
24649                 /* If the saved result is an inversion list, it is the valid
24650                  * definition of this property */
24651                 if (is_invlist(*saved_user_prop_ptr)) {
24652                     prop_definition = *saved_user_prop_ptr;
24653
24654                     /* The SV in the hash won't be removed until global
24655                      * destruction, so it is stable and we can unlock */
24656                     USER_PROP_MUTEX_UNLOCK;
24657
24658                     /* The caller shouldn't try to free this SV */
24659                     return prop_definition;
24660                 }
24661
24662                 /* Otherwise, if it is a string, it is the error message
24663                  * that was returned when we first tried to evaluate this
24664                  * property.  Fail, and append the message */
24665                 if (SvPOK(*saved_user_prop_ptr)) {
24666                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24667                     sv_catsv(msg, *saved_user_prop_ptr);
24668
24669                     /* The SV in the hash won't be removed until global
24670                      * destruction, so it is stable and we can unlock */
24671                     USER_PROP_MUTEX_UNLOCK;
24672
24673                     return NULL;
24674                 }
24675
24676                 assert(SvIOK(*saved_user_prop_ptr));
24677
24678                 /* Here, we have an unstable entry in the hash.  Either another
24679                  * thread is in the middle of expanding the property's
24680                  * definition, or we are ourselves recursing.  We use the aTHX
24681                  * in it to distinguish */
24682                 if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
24683
24684                     /* Here, it's another thread doing the expanding.  We've
24685                      * looked as much as we are going to at the contents of the
24686                      * hash entry.  It's safe to unlock. */
24687                     USER_PROP_MUTEX_UNLOCK;
24688
24689                     /* Retry a few times */
24690                     if (retry_countdown-- > 0) {
24691                         PerlProc_sleep(1);
24692                         goto re_fetch;
24693                     }
24694
24695                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24696                     sv_catpvs(msg, "Timeout waiting for another thread to "
24697                                    "define");
24698                     goto append_name_to_msg;
24699                 }
24700
24701                 /* Here, we are recursing; don't dig any deeper */
24702                 USER_PROP_MUTEX_UNLOCK;
24703
24704                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24705                 sv_catpvs(msg,
24706                           "Infinite recursion in user-defined property");
24707                 goto append_name_to_msg;
24708             }
24709
24710             /* Here, this thread has exclusive control, and there is no entry
24711              * for this property in the hash.  So we have the go ahead to
24712              * expand the definition ourselves. */
24713
24714             PUSHSTACKi(PERLSI_REGCOMP);
24715             ENTER;
24716
24717             /* Create a temporary placeholder in the hash to detect recursion
24718              * */
24719             SWITCH_TO_GLOBAL_CONTEXT;
24720             placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
24721             (void) hv_store_ent(PL_user_def_props, key, placeholder, 0);
24722             RESTORE_CONTEXT;
24723
24724             /* Now that we have a placeholder, we can let other threads
24725              * continue */
24726             USER_PROP_MUTEX_UNLOCK;
24727
24728             /* Make sure the placeholder always gets destroyed */
24729             SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key));
24730
24731             PUSHMARK(SP);
24732             SAVETMPS;
24733
24734             /* Call the user's function, with the /i status as a parameter.
24735              * Note that we have gone to a lot of trouble to keep this call
24736              * from being within the locked mutex region. */
24737             XPUSHs(boolSV(to_fold));
24738             PUTBACK;
24739
24740             /* The following block was taken from swash_init().  Presumably
24741              * they apply to here as well, though we no longer use a swash --
24742              * khw */
24743             SAVEHINTS();
24744             save_re_context();
24745             /* We might get here via a subroutine signature which uses a utf8
24746              * parameter name, at which point PL_subname will have been set
24747              * but not yet used. */
24748             save_item(PL_subname);
24749
24750             /* G_SCALAR guarantees a single return value */
24751             (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
24752
24753             SPAGAIN;
24754
24755             error = ERRSV;
24756             if (TAINT_get || SvTRUE(error)) {
24757                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24758                 if (SvTRUE(error)) {
24759                     sv_catpvs(msg, "Error \"");
24760                     sv_catsv(msg, error);
24761                     sv_catpvs(msg, "\"");
24762                 }
24763                 if (TAINT_get) {
24764                     if (SvTRUE(error)) sv_catpvs(msg, "; ");
24765                     sv_catpvn(msg, insecure, sizeof(insecure) - 1);
24766                 }
24767
24768                 if (name_len > 0) {
24769                     sv_catpvs(msg, " in expansion of ");
24770                     Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
24771                                                                   name_len,
24772                                                                   name));
24773                 }
24774
24775                 (void) POPs;
24776                 prop_definition = NULL;
24777             }
24778             else {
24779                 SV * contents = POPs;
24780
24781                 /* The contents is supposed to be the expansion of the property
24782                  * definition.  If the definition is deferrable, and we got an
24783                  * empty string back, set a flag to later defer it (after clean
24784                  * up below). */
24785                 if (      deferrable
24786                     && (! SvPOK(contents) || SvCUR(contents) == 0))
24787                 {
24788                         empty_return = TRUE;
24789                 }
24790                 else { /* Otherwise, call a function to check for valid syntax,
24791                           and handle it */
24792
24793                     prop_definition = handle_user_defined_property(
24794                                                     name, name_len,
24795                                                     is_utf8, to_fold, runtime,
24796                                                     deferrable,
24797                                                     contents, user_defined_ptr,
24798                                                     msg,
24799                                                     level);
24800                 }
24801             }
24802
24803             /* Here, we have the results of the expansion.  Delete the
24804              * placeholder, and if the definition is now known, replace it with
24805              * that definition.  We need exclusive access to the hash, and we
24806              * can't let anyone else in, between when we delete the placeholder
24807              * and add the permanent entry */
24808             USER_PROP_MUTEX_LOCK;
24809
24810             S_delete_recursion_entry(aTHX_ SvPVX(key));
24811
24812             if (    ! empty_return
24813                 && (! prop_definition || is_invlist(prop_definition)))
24814             {
24815                 /* If we got success we use the inversion list defining the
24816                  * property; otherwise use the error message */
24817                 SWITCH_TO_GLOBAL_CONTEXT;
24818                 (void) hv_store_ent(PL_user_def_props,
24819                                     key,
24820                                     ((prop_definition)
24821                                      ? newSVsv(prop_definition)
24822                                      : newSVsv(msg)),
24823                                     0);
24824                 RESTORE_CONTEXT;
24825             }
24826
24827             /* All done, and the hash now has a permanent entry for this
24828              * property.  Give up exclusive control */
24829             USER_PROP_MUTEX_UNLOCK;
24830
24831             FREETMPS;
24832             LEAVE;
24833             POPSTACK;
24834
24835             if (empty_return) {
24836                 goto definition_deferred;
24837             }
24838
24839             if (prop_definition) {
24840
24841                 /* If the definition is for something not known at this time,
24842                  * we toss it, and go return the main property name, as that's
24843                  * the one the user will be aware of */
24844                 if (! is_invlist(prop_definition)) {
24845                     SvREFCNT_dec_NN(prop_definition);
24846                     goto definition_deferred;
24847                 }
24848
24849                 sv_2mortal(prop_definition);
24850             }
24851
24852             /* And return */
24853             return prop_definition;
24854
24855         }   /* End of calling the subroutine for the user-defined property */
24856     }       /* End of it could be a user-defined property */
24857
24858     /* Here it wasn't a user-defined property that is known at this time.  See
24859      * if it is a Unicode property */
24860
24861     lookup_len = j;     /* This is a more mnemonic name than 'j' */
24862
24863     /* Get the index into our pointer table of the inversion list corresponding
24864      * to the property */
24865     table_index = do_uniprop_match(lookup_name, lookup_len);
24866
24867     /* If it didn't find the property ... */
24868     if (table_index == 0) {
24869
24870         /* Try again stripping off any initial 'Is'.  This is because we
24871          * promise that an initial Is is optional.  The same isn't true of
24872          * names that start with 'In'.  Those can match only blocks, and the
24873          * lookup table already has those accounted for.  The lookup table also
24874          * has already accounted for Perl extensions (without and = sign)
24875          * starting with 'i's'. */
24876         if (starts_with_Is && equals_pos >= 0) {
24877             lookup_name += 2;
24878             lookup_len -= 2;
24879             equals_pos -= 2;
24880             slash_pos -= 2;
24881
24882             table_index = do_uniprop_match(lookup_name, lookup_len);
24883         }
24884
24885         if (table_index == 0) {
24886             char * canonical;
24887
24888             /* Here, we didn't find it.  If not a numeric type property, and
24889              * can't be a user-defined one, it isn't a legal property */
24890             if (! is_nv_type) {
24891                 if (! could_be_user_defined) {
24892                     goto failed;
24893                 }
24894
24895                 /* Here, the property name is legal as a user-defined one.   At
24896                  * compile time, it might just be that the subroutine for that
24897                  * property hasn't been encountered yet, but at runtime, it's
24898                  * an error to try to use an undefined one */
24899                 if (! deferrable) {
24900                     goto unknown_user_defined;;
24901                 }
24902
24903                 goto definition_deferred;
24904             } /* End of isn't a numeric type property */
24905
24906             /* The numeric type properties need more work to decide.  What we
24907              * do is make sure we have the number in canonical form and look
24908              * that up. */
24909
24910             if (slash_pos < 0) {    /* No slash */
24911
24912                 /* When it isn't a rational, take the input, convert it to a
24913                  * NV, then create a canonical string representation of that
24914                  * NV. */
24915
24916                 NV value;
24917                 SSize_t value_len = lookup_len - equals_pos;
24918
24919                 /* Get the value */
24920                 if (   value_len <= 0
24921                     || my_atof3(lookup_name + equals_pos, &value,
24922                                 value_len)
24923                           != lookup_name + lookup_len)
24924                 {
24925                     goto failed;
24926                 }
24927
24928                 /* If the value is an integer, the canonical value is integral
24929                  * */
24930                 if (Perl_ceil(value) == value) {
24931                     canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
24932                                             equals_pos, lookup_name, value);
24933                 }
24934                 else {  /* Otherwise, it is %e with a known precision */
24935                     char * exp_ptr;
24936
24937                     canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
24938                                                 equals_pos, lookup_name,
24939                                                 PL_E_FORMAT_PRECISION, value);
24940
24941                     /* The exponent generated is expecting two digits, whereas
24942                      * %e on some systems will generate three.  Remove leading
24943                      * zeros in excess of 2 from the exponent.  We start
24944                      * looking for them after the '=' */
24945                     exp_ptr = strchr(canonical + equals_pos, 'e');
24946                     if (exp_ptr) {
24947                         char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
24948                         SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
24949
24950                         assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
24951
24952                         if (excess_exponent_len > 0) {
24953                             SSize_t leading_zeros = strspn(cur_ptr, "0");
24954                             SSize_t excess_leading_zeros
24955                                     = MIN(leading_zeros, excess_exponent_len);
24956                             if (excess_leading_zeros > 0) {
24957                                 Move(cur_ptr + excess_leading_zeros,
24958                                      cur_ptr,
24959                                      strlen(cur_ptr) - excess_leading_zeros
24960                                        + 1,  /* Copy the NUL as well */
24961                                      char);
24962                             }
24963                         }
24964                     }
24965                 }
24966             }
24967             else {  /* Has a slash.  Create a rational in canonical form  */
24968                 UV numerator, denominator, gcd, trial;
24969                 const char * end_ptr;
24970                 const char * sign = "";
24971
24972                 /* We can't just find the numerator, denominator, and do the
24973                  * division, then use the method above, because that is
24974                  * inexact.  And the input could be a rational that is within
24975                  * epsilon (given our precision) of a valid rational, and would
24976                  * then incorrectly compare valid.
24977                  *
24978                  * We're only interested in the part after the '=' */
24979                 const char * this_lookup_name = lookup_name + equals_pos;
24980                 lookup_len -= equals_pos;
24981                 slash_pos -= equals_pos;
24982
24983                 /* Handle any leading minus */
24984                 if (this_lookup_name[0] == '-') {
24985                     sign = "-";
24986                     this_lookup_name++;
24987                     lookup_len--;
24988                     slash_pos--;
24989                 }
24990
24991                 /* Convert the numerator to numeric */
24992                 end_ptr = this_lookup_name + slash_pos;
24993                 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
24994                     goto failed;
24995                 }
24996
24997                 /* It better have included all characters before the slash */
24998                 if (*end_ptr != '/') {
24999                     goto failed;
25000                 }
25001
25002                 /* Set to look at just the denominator */
25003                 this_lookup_name += slash_pos;
25004                 lookup_len -= slash_pos;
25005                 end_ptr = this_lookup_name + lookup_len;
25006
25007                 /* Convert the denominator to numeric */
25008                 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
25009                     goto failed;
25010                 }
25011
25012                 /* It better be the rest of the characters, and don't divide by
25013                  * 0 */
25014                 if (   end_ptr != this_lookup_name + lookup_len
25015                     || denominator == 0)
25016                 {
25017                     goto failed;
25018                 }
25019
25020                 /* Get the greatest common denominator using
25021                    http://en.wikipedia.org/wiki/Euclidean_algorithm */
25022                 gcd = numerator;
25023                 trial = denominator;
25024                 while (trial != 0) {
25025                     UV temp = trial;
25026                     trial = gcd % trial;
25027                     gcd = temp;
25028                 }
25029
25030                 /* If already in lowest possible terms, we have already tried
25031                  * looking this up */
25032                 if (gcd == 1) {
25033                     goto failed;
25034                 }
25035
25036                 /* Reduce the rational, which should put it in canonical form
25037                  * */
25038                 numerator /= gcd;
25039                 denominator /= gcd;
25040
25041                 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
25042                         equals_pos, lookup_name, sign, numerator, denominator);
25043             }
25044
25045             /* Here, we have the number in canonical form.  Try that */
25046             table_index = do_uniprop_match(canonical, strlen(canonical));
25047             if (table_index == 0) {
25048                 goto failed;
25049             }
25050         }   /* End of still didn't find the property in our table */
25051     }       /* End of       didn't find the property in our table */
25052
25053     /* Here, we have a non-zero return, which is an index into a table of ptrs.
25054      * A negative return signifies that the real index is the absolute value,
25055      * but the result needs to be inverted */
25056     if (table_index < 0) {
25057         invert_return = TRUE;
25058         table_index = -table_index;
25059     }
25060
25061     /* Out-of band indices indicate a deprecated property.  The proper index is
25062      * modulo it with the table size.  And dividing by the table size yields
25063      * an offset into a table constructed by regen/mk_invlists.pl to contain
25064      * the corresponding warning message */
25065     if (table_index > MAX_UNI_KEYWORD_INDEX) {
25066         Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
25067         table_index %= MAX_UNI_KEYWORD_INDEX;
25068         Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
25069                 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
25070                 (int) name_len, name,
25071                 get_deprecated_property_msg(warning_offset));
25072     }
25073
25074     /* In a few properties, a different property is used under /i.  These are
25075      * unlikely to change, so are hard-coded here. */
25076     if (to_fold) {
25077         if (   table_index == UNI_XPOSIXUPPER
25078             || table_index == UNI_XPOSIXLOWER
25079             || table_index == UNI_TITLE)
25080         {
25081             table_index = UNI_CASED;
25082         }
25083         else if (   table_index == UNI_UPPERCASELETTER
25084                  || table_index == UNI_LOWERCASELETTER
25085 #  ifdef UNI_TITLECASELETTER   /* Missing from early Unicodes */
25086                  || table_index == UNI_TITLECASELETTER
25087 #  endif
25088         ) {
25089             table_index = UNI_CASEDLETTER;
25090         }
25091         else if (  table_index == UNI_POSIXUPPER
25092                 || table_index == UNI_POSIXLOWER)
25093         {
25094             table_index = UNI_POSIXALPHA;
25095         }
25096     }
25097
25098     /* Create and return the inversion list */
25099     prop_definition = get_prop_definition(table_index);
25100     sv_2mortal(prop_definition);
25101
25102     /* See if there is a private use override to add to this definition */
25103     {
25104         COPHH * hinthash = (IN_PERL_COMPILETIME)
25105                            ? CopHINTHASH_get(&PL_compiling)
25106                            : CopHINTHASH_get(PL_curcop);
25107         SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0);
25108
25109         if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) {
25110
25111             /* See if there is an element in the hints hash for this table */
25112             SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index);
25113             const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup));
25114
25115             if (pos) {
25116                 bool dummy;
25117                 SV * pu_definition;
25118                 SV * pu_invlist;
25119                 SV * expanded_prop_definition =
25120                             sv_2mortal(invlist_clone(prop_definition, NULL));
25121
25122                 /* If so, it's definition is the string from here to the next
25123                  * \a character.  And its format is the same as a user-defined
25124                  * property */
25125                 pos += SvCUR(pu_lookup);
25126                 pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos);
25127                 pu_invlist = handle_user_defined_property(lookup_name,
25128                                                           lookup_len,
25129                                                           0, /* Not UTF-8 */
25130                                                           0, /* Not folded */
25131                                                           runtime,
25132                                                           deferrable,
25133                                                           pu_definition,
25134                                                           &dummy,
25135                                                           msg,
25136                                                           level);
25137                 if (TAINT_get) {
25138                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
25139                     sv_catpvs(msg, "Insecure private-use override");
25140                     goto append_name_to_msg;
25141                 }
25142
25143                 /* For now, as a safety measure, make sure that it doesn't
25144                  * override non-private use code points */
25145                 _invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist);
25146
25147                 /* Add it to the list to be returned */
25148                 _invlist_union(prop_definition, pu_invlist,
25149                                &expanded_prop_definition);
25150                 prop_definition = expanded_prop_definition;
25151                 Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental");
25152             }
25153         }
25154     }
25155
25156     if (invert_return) {
25157         _invlist_invert(prop_definition);
25158     }
25159     return prop_definition;
25160
25161   unknown_user_defined:
25162     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
25163     sv_catpvs(msg, "Unknown user-defined property name");
25164     goto append_name_to_msg;
25165
25166   failed:
25167     if (non_pkg_begin != 0) {
25168         if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
25169         sv_catpvs(msg, "Illegal user-defined property name");
25170     }
25171     else {
25172         if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
25173         sv_catpvs(msg, "Can't find Unicode property definition");
25174     }
25175     /* FALLTHROUGH */
25176
25177   append_name_to_msg:
25178     {
25179         const char * prefix = (runtime && level == 0) ?  " \\p{" : " \"";
25180         const char * suffix = (runtime && level == 0) ?  "}" : "\"";
25181
25182         sv_catpv(msg, prefix);
25183         Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
25184         sv_catpv(msg, suffix);
25185     }
25186
25187     return NULL;
25188
25189   definition_deferred:
25190
25191     {
25192         bool is_qualified = non_pkg_begin != 0;  /* If has "::" */
25193
25194         /* Here it could yet to be defined, so defer evaluation of this until
25195          * its needed at runtime.  We need the fully qualified property name to
25196          * avoid ambiguity */
25197         if (! fq_name) {
25198             fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
25199                                                                 is_qualified);
25200         }
25201
25202         /* If it didn't come with a package, or the package is utf8::, this
25203          * actually could be an official Unicode property whose inclusion we
25204          * are deferring until runtime to make sure that it isn't overridden by
25205          * a user-defined property of the same name (which we haven't
25206          * encountered yet).  Add a marker to indicate this possibility, for
25207          * use at such time when we first need the definition during pattern
25208          * matching execution */
25209         if (! is_qualified || memBEGINPs(name, non_pkg_begin, "utf8::")) {
25210             sv_catpvs(fq_name, DEFERRED_COULD_BE_OFFICIAL_MARKERs);
25211         }
25212
25213         /* We also need a trailing newline */
25214         sv_catpvs(fq_name, "\n");
25215
25216         *user_defined_ptr = TRUE;
25217         return fq_name;
25218     }
25219 }
25220
25221 STATIC bool
25222 S_handle_names_wildcard(pTHX_ const char * wname, /* wildcard name to match */
25223                               const STRLEN wname_len, /* Its length */
25224                               SV ** prop_definition,
25225                               AV ** strings)
25226 {
25227     /* Deal with Name property wildcard subpatterns; returns TRUE if there were
25228      * any matches, adding them to prop_definition */
25229
25230     dSP;
25231
25232     CV * get_names_info;        /* entry to charnames.pm to get info we need */
25233     SV * names_string;          /* Contains all character names, except algo */
25234     SV * algorithmic_names;     /* Contains info about algorithmically
25235                                    generated character names */
25236     REGEXP * subpattern_re;     /* The user's pattern to match with */
25237     struct regexp * prog;       /* The compiled pattern */
25238     char * all_names_start;     /* lib/unicore/Name.pl string of every
25239                                    (non-algorithmic) character name */
25240     char * cur_pos;             /* We match, effectively using /gc; this is
25241                                    where we are now */
25242     bool found_matches = FALSE; /* Did any name match so far? */
25243     SV * empty;                 /* For matching zero length names */
25244     SV * must_sv;               /* Contains the substring, if any, that must be
25245                                    in a name for the subpattern to match */
25246     const char * must;          /* The PV of 'must' */
25247     STRLEN must_len;            /* And its length */
25248     SV * syllable_name = NULL;  /* For Hangul syllables */
25249     const char hangul_prefix[] = "HANGUL SYLLABLE ";
25250     const STRLEN hangul_prefix_len = sizeof(hangul_prefix) - 1;
25251
25252     /* By inspection, there are a maximum of 7 bytes in the suffix of a hangul
25253      * syllable name, and these are immutable and guaranteed by the Unicode
25254      * standard to never be extended */
25255     const STRLEN syl_max_len = hangul_prefix_len + 7;
25256
25257     IV i;
25258
25259     PERL_ARGS_ASSERT_HANDLE_NAMES_WILDCARD;
25260
25261     /* Make sure _charnames is loaded.  (The parameters give context
25262      * for any errors generated */
25263     get_names_info = get_cv("_charnames::_get_names_info", 0);
25264     if (! get_names_info) {
25265         Perl_croak(aTHX_ "panic: Can't find '_charnames::_get_names_info");
25266     }
25267
25268     /* Get the charnames data */
25269     PUSHSTACKi(PERLSI_REGCOMP);
25270     ENTER ;
25271     SAVETMPS;
25272     save_re_context();
25273
25274     PUSHMARK(SP) ;
25275     PUTBACK;
25276
25277     /* Special _charnames entry point that returns the info this routine
25278      * requires */
25279     call_sv(MUTABLE_SV(get_names_info), G_LIST);
25280
25281     SPAGAIN ;
25282
25283     /* Data structure for names which end in their very own code points */
25284     algorithmic_names = POPs;
25285     SvREFCNT_inc_simple_void_NN(algorithmic_names);
25286
25287     /* The lib/unicore/Name.pl string */
25288     names_string = POPs;
25289     SvREFCNT_inc_simple_void_NN(names_string);
25290
25291     PUTBACK ;
25292     FREETMPS ;
25293     LEAVE ;
25294     POPSTACK;
25295
25296     if (   ! SvROK(names_string)
25297         || ! SvROK(algorithmic_names))
25298     {   /* Perhaps should panic instead XXX */
25299         SvREFCNT_dec(names_string);
25300         SvREFCNT_dec(algorithmic_names);
25301         return FALSE;
25302     }
25303
25304     names_string = sv_2mortal(SvRV(names_string));
25305     all_names_start = SvPVX(names_string);
25306     cur_pos = all_names_start;
25307
25308     algorithmic_names= sv_2mortal(SvRV(algorithmic_names));
25309
25310     /* Compile the subpattern consisting of the name being looked for */
25311     subpattern_re = compile_wildcard(wname, wname_len, FALSE /* /-i */ );
25312
25313     must_sv = re_intuit_string(subpattern_re);
25314     if (must_sv) {
25315         /* regexec.c can free the re_intuit_string() return. GH #17734 */
25316         must_sv = sv_2mortal(newSVsv(must_sv));
25317         must = SvPV(must_sv, must_len);
25318     }
25319     else {
25320         must = "";
25321         must_len = 0;
25322     }
25323
25324     /* (Note: 'must' could contain a NUL.  And yet we use strspn() below on it.
25325      * This works because the NUL causes the function to return early, thus
25326      * showing that there are characters in it other than the acceptable ones,
25327      * which is our desired result.) */
25328
25329     prog = ReANY(subpattern_re);
25330
25331     /* If only nothing is matched, skip to where empty names are looked for */
25332     if (prog->maxlen == 0) {
25333         goto check_empty;
25334     }
25335
25336     /* And match against the string of all names /gc.  Don't even try if it
25337      * must match a character not found in any name. */
25338     if (strspn(must, "\n -0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ()") == must_len)
25339     {
25340         while (execute_wildcard(subpattern_re,
25341                                 cur_pos,
25342                                 SvEND(names_string),
25343                                 all_names_start, 0,
25344                                 names_string,
25345                                 0))
25346         { /* Here, matched. */
25347
25348             /* Note the string entries look like
25349              *      00001\nSTART OF HEADING\n\n
25350              * so we could match anywhere in that string.  We have to rule out
25351              * matching a code point line */
25352             char * this_name_start = all_names_start
25353                                                 + RX_OFFS(subpattern_re)->start;
25354             char * this_name_end   = all_names_start
25355                                                 + RX_OFFS(subpattern_re)->end;
25356             char * cp_start;
25357             char * cp_end;
25358             UV cp = 0;      /* Silences some compilers */
25359             AV * this_string = NULL;
25360             bool is_multi = FALSE;
25361
25362             /* If matched nothing, advance to next possible match */
25363             if (this_name_start == this_name_end) {
25364                 cur_pos = (char *) memchr(this_name_end + 1, '\n',
25365                                           SvEND(names_string) - this_name_end);
25366                 if (cur_pos == NULL) {
25367                     break;
25368                 }
25369             }
25370             else {
25371                 /* Position the next match to start beyond the current returned
25372                  * entry */
25373                 cur_pos = (char *) memchr(this_name_end, '\n',
25374                                           SvEND(names_string) - this_name_end);
25375             }
25376
25377             /* Back up to the \n just before the beginning of the character. */
25378             cp_end = (char *) my_memrchr(all_names_start,
25379                                          '\n',
25380                                          this_name_start - all_names_start);
25381
25382             /* If we didn't find a \n, it means it matched somewhere in the
25383              * initial '00000' in the string, so isn't a real match */
25384             if (cp_end == NULL) {
25385                 continue;
25386             }
25387
25388             this_name_start = cp_end + 1;   /* The name starts just after */
25389             cp_end--;                       /* the \n, and the code point */
25390                                             /* ends just before it */
25391
25392             /* All code points are 5 digits long */
25393             cp_start = cp_end - 4;
25394
25395             /* This shouldn't happen, as we found a \n, and the first \n is
25396              * further along than what we subtracted */
25397             assert(cp_start >= all_names_start);
25398
25399             if (cp_start == all_names_start) {
25400                 *prop_definition = add_cp_to_invlist(*prop_definition, 0);
25401                 continue;
25402             }
25403
25404             /* If the character is a blank, we either have a named sequence, or
25405              * something is wrong */
25406             if (*(cp_start - 1) == ' ') {
25407                 cp_start = (char *) my_memrchr(all_names_start,
25408                                                '\n',
25409                                                cp_start - all_names_start);
25410                 cp_start++;
25411             }
25412
25413             assert(cp_start != NULL && cp_start >= all_names_start + 2);
25414
25415             /* Except for the first line in the string, the sequence before the
25416              * code point is \n\n.  If that isn't the case here, we didn't
25417              * match the name of a character.  (We could have matched a named
25418              * sequence, not currently handled */
25419             if (*(cp_start - 1) != '\n' || *(cp_start - 2) != '\n') {
25420                 continue;
25421             }
25422
25423             /* We matched!  Add this to the list */
25424             found_matches = TRUE;
25425
25426             /* Loop through all the code points in the sequence */
25427             while (cp_start < cp_end) {
25428
25429                 /* Calculate this code point from its 5 digits */
25430                 cp = (XDIGIT_VALUE(cp_start[0]) << 16)
25431                    + (XDIGIT_VALUE(cp_start[1]) << 12)
25432                    + (XDIGIT_VALUE(cp_start[2]) << 8)
25433                    + (XDIGIT_VALUE(cp_start[3]) << 4)
25434                    +  XDIGIT_VALUE(cp_start[4]);
25435
25436                 cp_start += 6;  /* Go past any blank */
25437
25438                 if (cp_start < cp_end || is_multi) {
25439                     if (this_string == NULL) {
25440                         this_string = newAV();
25441                     }
25442
25443                     is_multi = TRUE;
25444                     av_push(this_string, newSVuv(cp));
25445                 }
25446             }
25447
25448             if (is_multi) { /* Was more than one code point */
25449                 if (*strings == NULL) {
25450                     *strings = newAV();
25451                 }
25452
25453                 av_push(*strings, (SV *) this_string);
25454             }
25455             else {  /* Only a single code point */
25456                 *prop_definition = add_cp_to_invlist(*prop_definition, cp);
25457             }
25458         } /* End of loop through the non-algorithmic names string */
25459     }
25460
25461     /* There are also character names not in 'names_string'.  These are
25462      * algorithmically generatable.  Try this pattern on each possible one.
25463      * (khw originally planned to leave this out given the large number of
25464      * matches attempted; but the speed turned out to be quite acceptable
25465      *
25466      * There are plenty of opportunities to optimize to skip many of the tests.
25467      * beyond the rudimentary ones already here */
25468
25469     /* First see if the subpattern matches any of the algorithmic generatable
25470      * Hangul syllable names.
25471      *
25472      * We know none of these syllable names will match if the input pattern
25473      * requires more bytes than any syllable has, or if the input pattern only
25474      * matches an empty name, or if the pattern has something it must match and
25475      * one of the characters in that isn't in any Hangul syllable. */
25476     if (    prog->minlen <= (SSize_t) syl_max_len
25477         &&  prog->maxlen > 0
25478         && (strspn(must, "\n ABCDEGHIJKLMNOPRSTUWY") == must_len))
25479     {
25480         /* These constants, names, values, and algorithm are adapted from the
25481          * Unicode standard, version 5.1, section 3.12, and should never
25482          * change. */
25483         const char * JamoL[] = {
25484             "G", "GG", "N", "D", "DD", "R", "M", "B", "BB",
25485             "S", "SS", "", "J", "JJ", "C", "K", "T", "P", "H"
25486         };
25487         const int LCount = C_ARRAY_LENGTH(JamoL);
25488
25489         const char * JamoV[] = {
25490             "A", "AE", "YA", "YAE", "EO", "E", "YEO", "YE", "O", "WA",
25491             "WAE", "OE", "YO", "U", "WEO", "WE", "WI", "YU", "EU", "YI",
25492             "I"
25493         };
25494         const int VCount = C_ARRAY_LENGTH(JamoV);
25495
25496         const char * JamoT[] = {
25497             "", "G", "GG", "GS", "N", "NJ", "NH", "D", "L",
25498             "LG", "LM", "LB", "LS", "LT", "LP", "LH", "M", "B",
25499             "BS", "S", "SS", "NG", "J", "C", "K", "T", "P", "H"
25500         };
25501         const int TCount = C_ARRAY_LENGTH(JamoT);
25502
25503         int L, V, T;
25504
25505         /* This is the initial Hangul syllable code point; each time through the
25506          * inner loop, it maps to the next higher code point.  For more info,
25507          * see the Hangul syllable section of the Unicode standard. */
25508         int cp = 0xAC00;
25509
25510         syllable_name = sv_2mortal(newSV(syl_max_len));
25511         sv_setpvn(syllable_name, hangul_prefix, hangul_prefix_len);
25512
25513         for (L = 0; L < LCount; L++) {
25514             for (V = 0; V < VCount; V++) {
25515                 for (T = 0; T < TCount; T++) {
25516
25517                     /* Truncate back to the prefix, which is unvarying */
25518                     SvCUR_set(syllable_name, hangul_prefix_len);
25519
25520                     sv_catpv(syllable_name, JamoL[L]);
25521                     sv_catpv(syllable_name, JamoV[V]);
25522                     sv_catpv(syllable_name, JamoT[T]);
25523
25524                     if (execute_wildcard(subpattern_re,
25525                                 SvPVX(syllable_name),
25526                                 SvEND(syllable_name),
25527                                 SvPVX(syllable_name), 0,
25528                                 syllable_name,
25529                                 0))
25530                     {
25531                         *prop_definition = add_cp_to_invlist(*prop_definition,
25532                                                              cp);
25533                         found_matches = TRUE;
25534                     }
25535
25536                     cp++;
25537                 }
25538             }
25539         }
25540     }
25541
25542     /* The rest of the algorithmically generatable names are of the form
25543      * "PREFIX-code_point".  The prefixes and the code point limits of each
25544      * were returned to us in the array 'algorithmic_names' from data in
25545      * lib/unicore/Name.pm.  'code_point' in the name is expressed in hex. */
25546     for (i = 0; i <= av_top_index((AV *) algorithmic_names); i++) {
25547         IV j;
25548
25549         /* Each element of the array is a hash, giving the details for the
25550          * series of names it covers.  There is the base name of the characters
25551          * in the series, and the low and high code points in the series.  And,
25552          * for optimization purposes a string containing all the legal
25553          * characters that could possibly be in a name in this series. */
25554         HV * this_series = (HV *) SvRV(* av_fetch((AV *) algorithmic_names, i, 0));
25555         SV * prefix = * hv_fetchs(this_series, "name", 0);
25556         IV low = SvIV(* hv_fetchs(this_series, "low", 0));
25557         IV high = SvIV(* hv_fetchs(this_series, "high", 0));
25558         char * legal = SvPVX(* hv_fetchs(this_series, "legal", 0));
25559
25560         /* Pre-allocate an SV with enough space */
25561         SV * algo_name = sv_2mortal(Perl_newSVpvf(aTHX_ "%s-0000",
25562                                                         SvPVX(prefix)));
25563         if (high >= 0x10000) {
25564             sv_catpvs(algo_name, "0");
25565         }
25566
25567         /* This series can be skipped entirely if the pattern requires
25568          * something longer than any name in the series, or can only match an
25569          * empty name, or contains a character not found in any name in the
25570          * series */
25571         if (    prog->minlen <= (SSize_t) SvCUR(algo_name)
25572             &&  prog->maxlen > 0
25573             && (strspn(must, legal) == must_len))
25574         {
25575             for (j = low; j <= high; j++) { /* For each code point in the series */
25576
25577                 /* Get its name, and see if it matches the subpattern */
25578                 Perl_sv_setpvf(aTHX_ algo_name, "%s-%X", SvPVX(prefix),
25579                                      (unsigned) j);
25580
25581                 if (execute_wildcard(subpattern_re,
25582                                     SvPVX(algo_name),
25583                                     SvEND(algo_name),
25584                                     SvPVX(algo_name), 0,
25585                                     algo_name,
25586                                     0))
25587                 {
25588                     *prop_definition = add_cp_to_invlist(*prop_definition, j);
25589                     found_matches = TRUE;
25590                 }
25591             }
25592         }
25593     }
25594
25595   check_empty:
25596     /* Finally, see if the subpattern matches an empty string */
25597     empty = newSVpvs("");
25598     if (execute_wildcard(subpattern_re,
25599                          SvPVX(empty),
25600                          SvEND(empty),
25601                          SvPVX(empty), 0,
25602                          empty,
25603                          0))
25604     {
25605         /* Many code points have empty names.  Currently these are the \p{GC=C}
25606          * ones, minus CC and CF */
25607
25608         SV * empty_names_ref = get_prop_definition(UNI_C);
25609         SV * empty_names = invlist_clone(empty_names_ref, NULL);
25610
25611         SV * subtract = get_prop_definition(UNI_CC);
25612
25613         _invlist_subtract(empty_names, subtract, &empty_names);
25614         SvREFCNT_dec_NN(empty_names_ref);
25615         SvREFCNT_dec_NN(subtract);
25616
25617         subtract = get_prop_definition(UNI_CF);
25618         _invlist_subtract(empty_names, subtract, &empty_names);
25619         SvREFCNT_dec_NN(subtract);
25620
25621         _invlist_union(*prop_definition, empty_names, prop_definition);
25622         found_matches = TRUE;
25623         SvREFCNT_dec_NN(empty_names);
25624     }
25625     SvREFCNT_dec_NN(empty);
25626
25627 #if 0
25628     /* If we ever were to accept aliases for, say private use names, we would
25629      * need to do something fancier to find empty names.  The code below works
25630      * (at the time it was written), and is slower than the above */
25631     const char empties_pat[] = "^.";
25632     if (strNE(name, empties_pat)) {
25633         SV * empty = newSVpvs("");
25634         if (execute_wildcard(subpattern_re,
25635                     SvPVX(empty),
25636                     SvEND(empty),
25637                     SvPVX(empty), 0,
25638                     empty,
25639                     0))
25640         {
25641             SV * empties = NULL;
25642
25643             (void) handle_names_wildcard(empties_pat, strlen(empties_pat), &empties);
25644
25645             _invlist_union_complement_2nd(*prop_definition, empties, prop_definition);
25646             SvREFCNT_dec_NN(empties);
25647
25648             found_matches = TRUE;
25649         }
25650         SvREFCNT_dec_NN(empty);
25651     }
25652 #endif
25653
25654     SvREFCNT_dec_NN(subpattern_re);
25655     return found_matches;
25656 }
25657
25658 /*
25659  * ex: set ts=8 sts=4 sw=4 et:
25660  */