This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Use static asserts when comparing sizeof() to a constant
[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 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
147  _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
148 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
149  _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
150 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
151 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
152
153 #ifndef STATIC
154 #define STATIC  static
155 #endif
156
157 /* this is a chain of data about sub patterns we are processing that
158    need to be handled separately/specially in study_chunk. Its so
159    we can simulate recursion without losing state.  */
160 struct scan_frame;
161 typedef struct scan_frame {
162     regnode *last_regnode;      /* last node to process in this frame */
163     regnode *next_regnode;      /* next node to process when last is reached */
164     U32 prev_recursed_depth;
165     I32 stopparen;              /* what stopparen do we use */
166     bool in_gosub;              /* this or an outer frame is for GOSUB */
167
168     struct scan_frame *this_prev_frame; /* this previous frame */
169     struct scan_frame *prev_frame;      /* previous frame */
170     struct scan_frame *next_frame;      /* next frame */
171 } scan_frame;
172
173 /* Certain characters are output as a sequence with the first being a
174  * backslash. */
175 #define isBACKSLASHED_PUNCT(c)  memCHRs("-[]\\^", c)
176
177
178 struct RExC_state_t {
179     U32         flags;                  /* RXf_* are we folding, multilining? */
180     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
181     char        *precomp;               /* uncompiled string. */
182     char        *precomp_end;           /* pointer to end of uncompiled string. */
183     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
184     regexp      *rx;                    /* perl core regexp structure */
185     regexp_internal     *rxi;           /* internal data for regexp object
186                                            pprivate field */
187     char        *start;                 /* Start of input for compile */
188     char        *end;                   /* End of input for compile */
189     char        *parse;                 /* Input-scan pointer. */
190     char        *copy_start;            /* start of copy of input within
191                                            constructed parse string */
192     char        *save_copy_start;       /* Provides one level of saving
193                                            and restoring 'copy_start' */
194     char        *copy_start_in_input;   /* Position in input string
195                                            corresponding to copy_start */
196     SSize_t     whilem_seen;            /* number of WHILEM in this expr */
197     regnode     *emit_start;            /* Start of emitted-code area */
198     regnode_offset emit;                /* Code-emit pointer */
199     I32         naughty;                /* How bad is this pattern? */
200     I32         sawback;                /* Did we see \1, ...? */
201     SSize_t     size;                   /* Number of regnode equivalents in
202                                            pattern */
203     Size_t      sets_depth;              /* Counts recursion depth of already-
204                                            compiled regex set patterns */
205     U32         seen;
206
207     I32      parens_buf_size;           /* #slots malloced open/close_parens */
208     regnode_offset *open_parens;        /* offsets to open parens */
209     regnode_offset *close_parens;       /* offsets to close parens */
210     HV          *paren_names;           /* Paren names */
211
212     /* position beyond 'precomp' of the warning message furthest away from
213      * 'precomp'.  During the parse, no warnings are raised for any problems
214      * earlier in the parse than this position.  This works if warnings are
215      * raised the first time a given spot is parsed, and if only one
216      * independent warning is raised for any given spot */
217     Size_t      latest_warn_offset;
218
219     I32         npar;                   /* Capture buffer count so far in the
220                                            parse, (OPEN) plus one. ("par" 0 is
221                                            the whole pattern)*/
222     I32         total_par;              /* During initial parse, is either 0,
223                                            or -1; the latter indicating a
224                                            reparse is needed.  After that pass,
225                                            it is what 'npar' became after the
226                                            pass.  Hence, it being > 0 indicates
227                                            we are in a reparse situation */
228     I32         nestroot;               /* root parens we are in - used by
229                                            accept */
230     I32         seen_zerolen;
231     regnode     *end_op;                /* END node in program */
232     I32         utf8;           /* whether the pattern is utf8 or not */
233     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
234                                 /* XXX use this for future optimisation of case
235                                  * where pattern must be upgraded to utf8. */
236     I32         uni_semantics;  /* If a d charset modifier should use unicode
237                                    rules, even if the pattern is not in
238                                    utf8 */
239
240     I32         recurse_count;          /* Number of recurse regops we have generated */
241     regnode     **recurse;              /* Recurse regops */
242     U8          *study_chunk_recursed;  /* bitmap of which subs we have moved
243                                            through */
244     U32         study_chunk_recursed_bytes;  /* bytes in bitmap */
245     I32         in_lookbehind;
246     I32         in_lookahead;
247     I32         contains_locale;
248     I32         override_recoding;
249     I32         recode_x_to_native;
250     I32         in_multi_char_class;
251     int         code_index;             /* next code_blocks[] slot */
252     struct reg_code_blocks *code_blocks;/* positions of literal (?{})
253                                             within pattern */
254     SSize_t     maxlen;                        /* mininum possible number of chars in string to match */
255     scan_frame *frame_head;
256     scan_frame *frame_last;
257     U32         frame_count;
258     AV         *warn_text;
259     HV         *unlexed_names;
260     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
261 #ifdef DEBUGGING
262     const char  *lastparse;
263     I32         lastnum;
264     U32         study_chunk_recursed_count;
265     AV          *paren_name_list;       /* idx -> name */
266     SV          *mysv1;
267     SV          *mysv2;
268
269 #define RExC_lastparse  (pRExC_state->lastparse)
270 #define RExC_lastnum    (pRExC_state->lastnum)
271 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
272 #define RExC_study_chunk_recursed_count    (pRExC_state->study_chunk_recursed_count)
273 #define RExC_mysv       (pRExC_state->mysv1)
274 #define RExC_mysv1      (pRExC_state->mysv1)
275 #define RExC_mysv2      (pRExC_state->mysv2)
276
277 #endif
278     bool        seen_d_op;
279     bool        strict;
280     bool        study_started;
281     bool        in_script_run;
282     bool        use_BRANCHJ;
283     bool        sWARN_EXPERIMENTAL__VLB;
284     bool        sWARN_EXPERIMENTAL__REGEX_SETS;
285 };
286
287 #define RExC_flags      (pRExC_state->flags)
288 #define RExC_pm_flags   (pRExC_state->pm_flags)
289 #define RExC_precomp    (pRExC_state->precomp)
290 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
291 #define RExC_copy_start_in_constructed  (pRExC_state->copy_start)
292 #define RExC_save_copy_start_in_constructed  (pRExC_state->save_copy_start)
293 #define RExC_precomp_end (pRExC_state->precomp_end)
294 #define RExC_rx_sv      (pRExC_state->rx_sv)
295 #define RExC_rx         (pRExC_state->rx)
296 #define RExC_rxi        (pRExC_state->rxi)
297 #define RExC_start      (pRExC_state->start)
298 #define RExC_end        (pRExC_state->end)
299 #define RExC_parse      (pRExC_state->parse)
300 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
301 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
302 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
303                                                    under /d from /u ? */
304
305 #ifdef RE_TRACK_PATTERN_OFFSETS
306 #  define RExC_offsets  (RExC_rxi->u.offsets) /* I am not like the
307                                                          others */
308 #endif
309 #define RExC_emit       (pRExC_state->emit)
310 #define RExC_emit_start (pRExC_state->emit_start)
311 #define RExC_sawback    (pRExC_state->sawback)
312 #define RExC_seen       (pRExC_state->seen)
313 #define RExC_size       (pRExC_state->size)
314 #define RExC_maxlen        (pRExC_state->maxlen)
315 #define RExC_npar       (pRExC_state->npar)
316 #define RExC_total_parens       (pRExC_state->total_par)
317 #define RExC_parens_buf_size    (pRExC_state->parens_buf_size)
318 #define RExC_nestroot   (pRExC_state->nestroot)
319 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
320 #define RExC_utf8       (pRExC_state->utf8)
321 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
322 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
323 #define RExC_open_parens        (pRExC_state->open_parens)
324 #define RExC_close_parens       (pRExC_state->close_parens)
325 #define RExC_end_op     (pRExC_state->end_op)
326 #define RExC_paren_names        (pRExC_state->paren_names)
327 #define RExC_recurse    (pRExC_state->recurse)
328 #define RExC_recurse_count      (pRExC_state->recurse_count)
329 #define RExC_sets_depth         (pRExC_state->sets_depth)
330 #define RExC_study_chunk_recursed        (pRExC_state->study_chunk_recursed)
331 #define RExC_study_chunk_recursed_bytes  \
332                                    (pRExC_state->study_chunk_recursed_bytes)
333 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
334 #define RExC_in_lookahead       (pRExC_state->in_lookahead)
335 #define RExC_contains_locale    (pRExC_state->contains_locale)
336 #define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
337
338 #ifdef EBCDIC
339 #  define SET_recode_x_to_native(x)                                         \
340                     STMT_START { RExC_recode_x_to_native = (x); } STMT_END
341 #else
342 #  define SET_recode_x_to_native(x) NOOP
343 #endif
344
345 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
346 #define RExC_frame_head (pRExC_state->frame_head)
347 #define RExC_frame_last (pRExC_state->frame_last)
348 #define RExC_frame_count (pRExC_state->frame_count)
349 #define RExC_strict (pRExC_state->strict)
350 #define RExC_study_started      (pRExC_state->study_started)
351 #define RExC_warn_text (pRExC_state->warn_text)
352 #define RExC_in_script_run      (pRExC_state->in_script_run)
353 #define RExC_use_BRANCHJ        (pRExC_state->use_BRANCHJ)
354 #define RExC_warned_WARN_EXPERIMENTAL__VLB (pRExC_state->sWARN_EXPERIMENTAL__VLB)
355 #define RExC_warned_WARN_EXPERIMENTAL__REGEX_SETS (pRExC_state->sWARN_EXPERIMENTAL__REGEX_SETS)
356 #define RExC_unlexed_names (pRExC_state->unlexed_names)
357
358 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
359  * a flag to disable back-off on the fixed/floating substrings - if it's
360  * a high complexity pattern we assume the benefit of avoiding a full match
361  * is worth the cost of checking for the substrings even if they rarely help.
362  */
363 #define RExC_naughty    (pRExC_state->naughty)
364 #define TOO_NAUGHTY (10)
365 #define MARK_NAUGHTY(add) \
366     if (RExC_naughty < TOO_NAUGHTY) \
367         RExC_naughty += (add)
368 #define MARK_NAUGHTY_EXP(exp, add) \
369     if (RExC_naughty < TOO_NAUGHTY) \
370         RExC_naughty += RExC_naughty / (exp) + (add)
371
372 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
373 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
374         ((*s) == '{' && regcurly(s)))
375
376 /*
377  * Flags to be passed up and down.
378  */
379 #define WORST           0       /* Worst case. */
380 #define HASWIDTH        0x01    /* Known to not match null strings, could match
381                                    non-null ones. */
382
383 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
384  * character.  (There needs to be a case: in the switch statement in regexec.c
385  * for any node marked SIMPLE.)  Note that this is not the same thing as
386  * REGNODE_SIMPLE */
387 #define SIMPLE          0x02
388 #define SPSTART         0x04    /* Starts with * or + */
389 #define POSTPONED       0x08    /* (?1),(?&name), (??{...}) or similar */
390 #define TRYAGAIN        0x10    /* Weeded out a declaration. */
391 #define RESTART_PARSE   0x20    /* Need to redo the parse */
392 #define NEED_UTF8       0x40    /* In conjunction with RESTART_PARSE, need to
393                                    calcuate sizes as UTF-8 */
394
395 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
396
397 /* whether trie related optimizations are enabled */
398 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
399 #define TRIE_STUDY_OPT
400 #define FULL_TRIE_STUDY
401 #define TRIE_STCLASS
402 #endif
403
404
405
406 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
407 #define PBITVAL(paren) (1 << ((paren) & 7))
408 #define PAREN_OFFSET(depth) \
409     (RExC_study_chunk_recursed + (depth) * RExC_study_chunk_recursed_bytes)
410 #define PAREN_TEST(depth, paren) \
411     (PBYTE(PAREN_OFFSET(depth), paren) & PBITVAL(paren))
412 #define PAREN_SET(depth, paren) \
413     (PBYTE(PAREN_OFFSET(depth), paren) |= PBITVAL(paren))
414 #define PAREN_UNSET(depth, paren) \
415     (PBYTE(PAREN_OFFSET(depth), paren) &= ~PBITVAL(paren))
416
417 #define REQUIRE_UTF8(flagp) STMT_START {                                   \
418                                      if (!UTF) {                           \
419                                          *flagp = RESTART_PARSE|NEED_UTF8; \
420                                          return 0;                         \
421                                      }                                     \
422                              } STMT_END
423
424 /* Change from /d into /u rules, and restart the parse.  RExC_uni_semantics is
425  * a flag that indicates we need to override /d with /u as a result of
426  * something in the pattern.  It should only be used in regards to calling
427  * set_regex_charset() or get_regex_charset() */
428 #define REQUIRE_UNI_RULES(flagp, restart_retval)                            \
429     STMT_START {                                                            \
430             if (DEPENDS_SEMANTICS) {                                        \
431                 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);      \
432                 RExC_uni_semantics = 1;                                     \
433                 if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) {           \
434                     /* No need to restart the parse if we haven't seen      \
435                      * anything that differs between /u and /d, and no need \
436                      * to restart immediately if we're going to reparse     \
437                      * anyway to count parens */                            \
438                     *flagp |= RESTART_PARSE;                                \
439                     return restart_retval;                                  \
440                 }                                                           \
441             }                                                               \
442     } STMT_END
443
444 #define REQUIRE_BRANCHJ(flagp, restart_retval)                              \
445     STMT_START {                                                            \
446                 RExC_use_BRANCHJ = 1;                                       \
447                 *flagp |= RESTART_PARSE;                                    \
448                 return restart_retval;                                      \
449     } STMT_END
450
451 /* Until we have completed the parse, we leave RExC_total_parens at 0 or
452  * less.  After that, it must always be positive, because the whole re is
453  * considered to be surrounded by virtual parens.  Setting it to negative
454  * indicates there is some construct that needs to know the actual number of
455  * parens to be properly handled.  And that means an extra pass will be
456  * required after we've counted them all */
457 #define ALL_PARENS_COUNTED (RExC_total_parens > 0)
458 #define REQUIRE_PARENS_PASS                                                 \
459     STMT_START {  /* No-op if have completed a pass */                      \
460                     if (! ALL_PARENS_COUNTED) RExC_total_parens = -1;       \
461     } STMT_END
462 #define IN_PARENS_PASS (RExC_total_parens < 0)
463
464
465 /* This is used to return failure (zero) early from the calling function if
466  * various flags in 'flags' are set.  Two flags always cause a return:
467  * 'RESTART_PARSE' and 'NEED_UTF8'.   'extra' can be used to specify any
468  * additional flags that should cause a return; 0 if none.  If the return will
469  * be done, '*flagp' is first set to be all of the flags that caused the
470  * return. */
471 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra)                  \
472     STMT_START {                                                            \
473             if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) {              \
474                 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra));     \
475                 return 0;                                                   \
476             }                                                               \
477     } STMT_END
478
479 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
480
481 #define RETURN_FAIL_ON_RESTART(flags,flagp)                                 \
482                         RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
483 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp)                                 \
484                                     if (MUST_RESTART(*(flagp))) return 0
485
486 /* This converts the named class defined in regcomp.h to its equivalent class
487  * number defined in handy.h. */
488 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
489 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
490
491 #define _invlist_union_complement_2nd(a, b, output) \
492                         _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
493 #define _invlist_intersection_complement_2nd(a, b, output) \
494                  _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
495
496 /* We add a marker if we are deferring expansion of a property that is both
497  * 1) potentiallly user-defined; and
498  * 2) could also be an official Unicode property.
499  *
500  * Without this marker, any deferred expansion can only be for a user-defined
501  * one.  This marker shouldn't conflict with any that could be in a legal name,
502  * and is appended to its name to indicate this.  There is a string and
503  * character form */
504 #define DEFERRED_COULD_BE_OFFICIAL_MARKERs  "~"
505 #define DEFERRED_COULD_BE_OFFICIAL_MARKERc  '~'
506
507 /* What is infinity for optimization purposes */
508 #define OPTIMIZE_INFTY  SSize_t_MAX
509
510 /* About scan_data_t.
511
512   During optimisation we recurse through the regexp program performing
513   various inplace (keyhole style) optimisations. In addition study_chunk
514   and scan_commit populate this data structure with information about
515   what strings MUST appear in the pattern. We look for the longest
516   string that must appear at a fixed location, and we look for the
517   longest string that may appear at a floating location. So for instance
518   in the pattern:
519
520     /FOO[xX]A.*B[xX]BAR/
521
522   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
523   strings (because they follow a .* construct). study_chunk will identify
524   both FOO and BAR as being the longest fixed and floating strings respectively.
525
526   The strings can be composites, for instance
527
528      /(f)(o)(o)/
529
530   will result in a composite fixed substring 'foo'.
531
532   For each string some basic information is maintained:
533
534   - min_offset
535     This is the position the string must appear at, or not before.
536     It also implicitly (when combined with minlenp) tells us how many
537     characters must match before the string we are searching for.
538     Likewise when combined with minlenp and the length of the string it
539     tells us how many characters must appear after the string we have
540     found.
541
542   - max_offset
543     Only used for floating strings. This is the rightmost point that
544     the string can appear at. If set to OPTIMIZE_INFTY it indicates that the
545     string can occur infinitely far to the right.
546     For fixed strings, it is equal to min_offset.
547
548   - minlenp
549     A pointer to the minimum number of characters of the pattern that the
550     string was found inside. This is important as in the case of positive
551     lookahead or positive lookbehind we can have multiple patterns
552     involved. Consider
553
554     /(?=FOO).*F/
555
556     The minimum length of the pattern overall is 3, the minimum length
557     of the lookahead part is 3, but the minimum length of the part that
558     will actually match is 1. So 'FOO's minimum length is 3, but the
559     minimum length for the F is 1. This is important as the minimum length
560     is used to determine offsets in front of and behind the string being
561     looked for.  Since strings can be composites this is the length of the
562     pattern at the time it was committed with a scan_commit. Note that
563     the length is calculated by study_chunk, so that the minimum lengths
564     are not known until the full pattern has been compiled, thus the
565     pointer to the value.
566
567   - lookbehind
568
569     In the case of lookbehind the string being searched for can be
570     offset past the start point of the final matching string.
571     If this value was just blithely removed from the min_offset it would
572     invalidate some of the calculations for how many chars must match
573     before or after (as they are derived from min_offset and minlen and
574     the length of the string being searched for).
575     When the final pattern is compiled and the data is moved from the
576     scan_data_t structure into the regexp structure the information
577     about lookbehind is factored in, with the information that would
578     have been lost precalculated in the end_shift field for the
579     associated string.
580
581   The fields pos_min and pos_delta are used to store the minimum offset
582   and the delta to the maximum offset at the current point in the pattern.
583
584 */
585
586 struct scan_data_substrs {
587     SV      *str;       /* longest substring found in pattern */
588     SSize_t min_offset; /* earliest point in string it can appear */
589     SSize_t max_offset; /* latest point in string it can appear */
590     SSize_t *minlenp;   /* pointer to the minlen relevant to the string */
591     SSize_t lookbehind; /* is the pos of the string modified by LB */
592     I32 flags;          /* per substring SF_* and SCF_* flags */
593 };
594
595 typedef struct scan_data_t {
596     /*I32 len_min;      unused */
597     /*I32 len_delta;    unused */
598     SSize_t pos_min;
599     SSize_t pos_delta;
600     SV *last_found;
601     SSize_t last_end;       /* min value, <0 unless valid. */
602     SSize_t last_start_min;
603     SSize_t last_start_max;
604     U8      cur_is_floating; /* whether the last_* values should be set as
605                               * the next fixed (0) or floating (1)
606                               * substring */
607
608     /* [0] is longest fixed substring so far, [1] is longest float so far */
609     struct scan_data_substrs  substrs[2];
610
611     I32 flags;             /* common SF_* and SCF_* flags */
612     I32 whilem_c;
613     SSize_t *last_closep;
614     regnode_ssc *start_class;
615 } scan_data_t;
616
617 /*
618  * Forward declarations for pregcomp()'s friends.
619  */
620
621 static const scan_data_t zero_scan_data = {
622     0, 0, NULL, 0, 0, 0, 0,
623     {
624         { NULL, 0, 0, 0, 0, 0 },
625         { NULL, 0, 0, 0, 0, 0 },
626     },
627     0, 0, NULL, NULL
628 };
629
630 /* study flags */
631
632 #define SF_BEFORE_SEOL          0x0001
633 #define SF_BEFORE_MEOL          0x0002
634 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
635
636 #define SF_IS_INF               0x0040
637 #define SF_HAS_PAR              0x0080
638 #define SF_IN_PAR               0x0100
639 #define SF_HAS_EVAL             0x0200
640
641
642 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
643  * longest substring in the pattern. When it is not set the optimiser keeps
644  * track of position, but does not keep track of the actual strings seen,
645  *
646  * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
647  * /foo/i will not.
648  *
649  * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
650  * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
651  * turned off because of the alternation (BRANCH). */
652 #define SCF_DO_SUBSTR           0x0400
653
654 #define SCF_DO_STCLASS_AND      0x0800
655 #define SCF_DO_STCLASS_OR       0x1000
656 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
657 #define SCF_WHILEM_VISITED_POS  0x2000
658
659 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
660 #define SCF_SEEN_ACCEPT         0x8000
661 #define SCF_TRIE_DOING_RESTUDY 0x10000
662 #define SCF_IN_DEFINE          0x20000
663
664
665
666
667 #define UTF cBOOL(RExC_utf8)
668
669 /* The enums for all these are ordered so things work out correctly */
670 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
671 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags)                    \
672                                                      == REGEX_DEPENDS_CHARSET)
673 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
674 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags)                \
675                                                      >= REGEX_UNICODE_CHARSET)
676 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags)                      \
677                                             == REGEX_ASCII_RESTRICTED_CHARSET)
678 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags)             \
679                                             >= REGEX_ASCII_RESTRICTED_CHARSET)
680 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags)                 \
681                                         == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
682
683 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
684
685 /* For programs that want to be strictly Unicode compatible by dying if any
686  * attempt is made to match a non-Unicode code point against a Unicode
687  * property.  */
688 #define ALWAYS_WARN_SUPER  ckDEAD(packWARN(WARN_NON_UNICODE))
689
690 #define OOB_NAMEDCLASS          -1
691
692 /* There is no code point that is out-of-bounds, so this is problematic.  But
693  * its only current use is to initialize a variable that is always set before
694  * looked at. */
695 #define OOB_UNICODE             0xDEADBEEF
696
697 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
698
699
700 /* length of regex to show in messages that don't mark a position within */
701 #define RegexLengthToShowInErrorMessages 127
702
703 /*
704  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
705  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
706  * op/pragma/warn/regcomp.
707  */
708 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
709 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
710
711 #define REPORT_LOCATION " in regex; marked by " MARKER1    \
712                         " in m/%" UTF8f MARKER2 "%" UTF8f "/"
713
714 /* The code in this file in places uses one level of recursion with parsing
715  * rebased to an alternate string constructed by us in memory.  This can take
716  * the form of something that is completely different from the input, or
717  * something that uses the input as part of the alternate.  In the first case,
718  * there should be no possibility of an error, as we are in complete control of
719  * the alternate string.  But in the second case we don't completely control
720  * the input portion, so there may be errors in that.  Here's an example:
721  *      /[abc\x{DF}def]/ui
722  * is handled specially because \x{df} folds to a sequence of more than one
723  * character: 'ss'.  What is done is to create and parse an alternate string,
724  * which looks like this:
725  *      /(?:\x{DF}|[abc\x{DF}def])/ui
726  * where it uses the input unchanged in the middle of something it constructs,
727  * which is a branch for the DF outside the character class, and clustering
728  * parens around the whole thing. (It knows enough to skip the DF inside the
729  * class while in this substitute parse.) 'abc' and 'def' may have errors that
730  * need to be reported.  The general situation looks like this:
731  *
732  *                                       |<------- identical ------>|
733  *              sI                       tI               xI       eI
734  * Input:       ---------------------------------------------------------------
735  * Constructed:         ---------------------------------------------------
736  *                      sC               tC               xC       eC     EC
737  *                                       |<------- identical ------>|
738  *
739  * sI..eI   is the portion of the input pattern we are concerned with here.
740  * sC..EC   is the constructed substitute parse string.
741  *  sC..tC  is constructed by us
742  *  tC..eC  is an exact duplicate of the portion of the input pattern tI..eI.
743  *          In the diagram, these are vertically aligned.
744  *  eC..EC  is also constructed by us.
745  * xC       is the position in the substitute parse string where we found a
746  *          problem.
747  * xI       is the position in the original pattern corresponding to xC.
748  *
749  * We want to display a message showing the real input string.  Thus we need to
750  * translate from xC to xI.  We know that xC >= tC, since the portion of the
751  * string sC..tC has been constructed by us, and so shouldn't have errors.  We
752  * get:
753  *      xI = tI + (xC - tC)
754  *
755  * When the substitute parse is constructed, the code needs to set:
756  *      RExC_start (sC)
757  *      RExC_end (eC)
758  *      RExC_copy_start_in_input  (tI)
759  *      RExC_copy_start_in_constructed (tC)
760  * and restore them when done.
761  *
762  * During normal processing of the input pattern, both
763  * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
764  * sI, so that xC equals xI.
765  */
766
767 #define sI              RExC_precomp
768 #define eI              RExC_precomp_end
769 #define sC              RExC_start
770 #define eC              RExC_end
771 #define tI              RExC_copy_start_in_input
772 #define tC              RExC_copy_start_in_constructed
773 #define xI(xC)          (tI + (xC - tC))
774 #define xI_offset(xC)   (xI(xC) - sI)
775
776 #define REPORT_LOCATION_ARGS(xC)                                            \
777     UTF8fARG(UTF,                                                           \
778              (xI(xC) > eI) /* Don't run off end */                          \
779               ? eI - sI   /* Length before the <--HERE */                   \
780               : ((xI_offset(xC) >= 0)                                       \
781                  ? xI_offset(xC)                                            \
782                  : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %"    \
783                                     IVdf " trying to output message for "   \
784                                     " pattern %.*s",                        \
785                                     __FILE__, __LINE__, (IV) xI_offset(xC), \
786                                     ((int) (eC - sC)), sC), 0)),            \
787              sI),         /* The input pattern printed up to the <--HERE */ \
788     UTF8fARG(UTF,                                                           \
789              (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */    \
790              (xI(xC) > eI) ? eI : xI(xC))     /* pattern after <--HERE */
791
792 /* Used to point after bad bytes for an error message, but avoid skipping
793  * past a nul byte. */
794 #define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1)
795
796 /* Set up to clean up after our imminent demise */
797 #define PREPARE_TO_DIE                                                      \
798     STMT_START {                                                            \
799         if (RExC_rx_sv)                                                     \
800             SAVEFREESV(RExC_rx_sv);                                         \
801         if (RExC_open_parens)                                               \
802             SAVEFREEPV(RExC_open_parens);                                   \
803         if (RExC_close_parens)                                              \
804             SAVEFREEPV(RExC_close_parens);                                  \
805     } STMT_END
806
807 /*
808  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
809  * arg. Show regex, up to a maximum length. If it's too long, chop and add
810  * "...".
811  */
812 #define _FAIL(code) STMT_START {                                        \
813     const char *ellipses = "";                                          \
814     IV len = RExC_precomp_end - RExC_precomp;                           \
815                                                                         \
816     PREPARE_TO_DIE;                                                     \
817     if (len > RegexLengthToShowInErrorMessages) {                       \
818         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
819         len = RegexLengthToShowInErrorMessages - 10;                    \
820         ellipses = "...";                                               \
821     }                                                                   \
822     code;                                                               \
823 } STMT_END
824
825 #define FAIL(msg) _FAIL(                            \
826     Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/",         \
827             msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
828
829 #define FAIL2(msg,arg) _FAIL(                       \
830     Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/",       \
831             arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
832
833 #define FAIL3(msg,arg1,arg2) _FAIL(                         \
834     Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/",       \
835      arg1, arg2, UTF8fARG(UTF, len, RExC_precomp), ellipses))
836
837 /*
838  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
839  */
840 #define Simple_vFAIL(m) STMT_START {                                    \
841     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
842             m, REPORT_LOCATION_ARGS(RExC_parse));                       \
843 } STMT_END
844
845 /*
846  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
847  */
848 #define vFAIL(m) STMT_START {                           \
849     PREPARE_TO_DIE;                                     \
850     Simple_vFAIL(m);                                    \
851 } STMT_END
852
853 /*
854  * Like Simple_vFAIL(), but accepts two arguments.
855  */
856 #define Simple_vFAIL2(m,a1) STMT_START {                        \
857     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1,                \
858                       REPORT_LOCATION_ARGS(RExC_parse));        \
859 } STMT_END
860
861 /*
862  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
863  */
864 #define vFAIL2(m,a1) STMT_START {                       \
865     PREPARE_TO_DIE;                                     \
866     Simple_vFAIL2(m, a1);                               \
867 } STMT_END
868
869
870 /*
871  * Like Simple_vFAIL(), but accepts three arguments.
872  */
873 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
874     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2,            \
875             REPORT_LOCATION_ARGS(RExC_parse));                  \
876 } STMT_END
877
878 /*
879  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
880  */
881 #define vFAIL3(m,a1,a2) STMT_START {                    \
882     PREPARE_TO_DIE;                                     \
883     Simple_vFAIL3(m, a1, a2);                           \
884 } STMT_END
885
886 /*
887  * Like Simple_vFAIL(), but accepts four arguments.
888  */
889 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
890     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2, a3,        \
891             REPORT_LOCATION_ARGS(RExC_parse));                  \
892 } STMT_END
893
894 #define vFAIL4(m,a1,a2,a3) STMT_START {                 \
895     PREPARE_TO_DIE;                                     \
896     Simple_vFAIL4(m, a1, a2, a3);                       \
897 } STMT_END
898
899 /* A specialized version of vFAIL2 that works with UTF8f */
900 #define vFAIL2utf8f(m, a1) STMT_START {             \
901     PREPARE_TO_DIE;                                 \
902     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1,  \
903             REPORT_LOCATION_ARGS(RExC_parse));      \
904 } STMT_END
905
906 #define vFAIL3utf8f(m, a1, a2) STMT_START {             \
907     PREPARE_TO_DIE;                                     \
908     S_re_croak(aTHX_ UTF, m REPORT_LOCATION, a1, a2,  \
909             REPORT_LOCATION_ARGS(RExC_parse));          \
910 } STMT_END
911
912 /* Setting this to NULL is a signal to not output warnings */
913 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE                               \
914     STMT_START {                                                            \
915       RExC_save_copy_start_in_constructed  = RExC_copy_start_in_constructed;\
916       RExC_copy_start_in_constructed = NULL;                                \
917     } STMT_END
918 #define RESTORE_WARNINGS                                                    \
919     RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed
920
921 /* Since a warning can be generated multiple times as the input is reparsed, we
922  * output it the first time we come to that point in the parse, but suppress it
923  * otherwise.  'RExC_copy_start_in_constructed' being NULL is a flag to not
924  * generate any warnings */
925 #define TO_OUTPUT_WARNINGS(loc)                                         \
926   (   RExC_copy_start_in_constructed                                    \
927    && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
928
929 /* After we've emitted a warning, we save the position in the input so we don't
930  * output it again */
931 #define UPDATE_WARNINGS_LOC(loc)                                        \
932     STMT_START {                                                        \
933         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
934             RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc)))         \
935                                                        - RExC_precomp;  \
936         }                                                               \
937     } STMT_END
938
939 /* 'warns' is the output of the packWARNx macro used in 'code' */
940 #define _WARN_HELPER(loc, warns, code)                                  \
941     STMT_START {                                                        \
942         if (! RExC_copy_start_in_constructed) {                         \
943             Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none"  \
944                               " expected at '%s'",                      \
945                               __FILE__, __LINE__, loc);                 \
946         }                                                               \
947         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
948             if (ckDEAD(warns))                                          \
949                 PREPARE_TO_DIE;                                         \
950             code;                                                       \
951             UPDATE_WARNINGS_LOC(loc);                                   \
952         }                                                               \
953     } STMT_END
954
955 /* m is not necessarily a "literal string", in this macro */
956 #define warn_non_literal_string(loc, packed_warn, m)                    \
957     _WARN_HELPER(loc, packed_warn,                                      \
958                       Perl_warner(aTHX_ packed_warn,                    \
959                                        "%s" REPORT_LOCATION,            \
960                                   m, REPORT_LOCATION_ARGS(loc)))
961 #define reg_warn_non_literal_string(loc, m)                             \
962                 warn_non_literal_string(loc, packWARN(WARN_REGEXP), m)
963
964 #define ckWARN2_non_literal_string(loc, packwarn, m, a1)                    \
965     STMT_START {                                                            \
966                 char * format;                                              \
967                 Size_t format_size = strlen(m) + strlen(REPORT_LOCATION)+ 1;\
968                 Newx(format, format_size, char);                            \
969                 my_strlcpy(format, m, format_size);                         \
970                 my_strlcat(format, REPORT_LOCATION, format_size);           \
971                 SAVEFREEPV(format);                                         \
972                 _WARN_HELPER(loc, packwarn,                                 \
973                       Perl_ck_warner(aTHX_ packwarn,                        \
974                                         format,                             \
975                                         a1, REPORT_LOCATION_ARGS(loc)));    \
976     } STMT_END
977
978 #define ckWARNreg(loc,m)                                                \
979     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
980                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
981                                           m REPORT_LOCATION,            \
982                                           REPORT_LOCATION_ARGS(loc)))
983
984 #define vWARN(loc, m)                                                   \
985     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
986                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
987                                        m REPORT_LOCATION,               \
988                                        REPORT_LOCATION_ARGS(loc)))      \
989
990 #define vWARN_dep(loc, m)                                               \
991     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
992                       Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),      \
993                                        m REPORT_LOCATION,               \
994                                        REPORT_LOCATION_ARGS(loc)))
995
996 #define ckWARNdep(loc,m)                                                \
997     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
998                       Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
999                                             m REPORT_LOCATION,          \
1000                                             REPORT_LOCATION_ARGS(loc)))
1001
1002 #define ckWARNregdep(loc,m)                                                 \
1003     _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP),              \
1004                       Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED,     \
1005                                                       WARN_REGEXP),         \
1006                                              m REPORT_LOCATION,             \
1007                                              REPORT_LOCATION_ARGS(loc)))
1008
1009 #define ckWARN2reg_d(loc,m, a1)                                             \
1010     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
1011                       Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP),         \
1012                                             m REPORT_LOCATION,              \
1013                                             a1, REPORT_LOCATION_ARGS(loc)))
1014
1015 #define ckWARN2reg(loc, m, a1)                                              \
1016     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
1017                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
1018                                           m REPORT_LOCATION,                \
1019                                           a1, REPORT_LOCATION_ARGS(loc)))
1020
1021 #define vWARN3(loc, m, a1, a2)                                              \
1022     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
1023                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),              \
1024                                        m REPORT_LOCATION,                   \
1025                                        a1, a2, REPORT_LOCATION_ARGS(loc)))
1026
1027 #define ckWARN3reg(loc, m, a1, a2)                                          \
1028     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
1029                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
1030                                           m REPORT_LOCATION,                \
1031                                           a1, a2,                           \
1032                                           REPORT_LOCATION_ARGS(loc)))
1033
1034 #define vWARN4(loc, m, a1, a2, a3)                                      \
1035     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
1036                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
1037                                        m REPORT_LOCATION,               \
1038                                        a1, a2, a3,                      \
1039                                        REPORT_LOCATION_ARGS(loc)))
1040
1041 #define ckWARN4reg(loc, m, a1, a2, a3)                                  \
1042     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
1043                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
1044                                           m REPORT_LOCATION,            \
1045                                           a1, a2, a3,                   \
1046                                           REPORT_LOCATION_ARGS(loc)))
1047
1048 #define vWARN5(loc, m, a1, a2, a3, a4)                                  \
1049     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
1050                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
1051                                        m REPORT_LOCATION,               \
1052                                        a1, a2, a3, a4,                  \
1053                                        REPORT_LOCATION_ARGS(loc)))
1054
1055 #define ckWARNexperimental(loc, class, m)                               \
1056     STMT_START {                                                        \
1057         if (! RExC_warned_ ## class) { /* warn once per compilation */  \
1058             RExC_warned_ ## class = 1;                                  \
1059             _WARN_HELPER(loc, packWARN(class),                          \
1060                       Perl_ck_warner_d(aTHX_ packWARN(class),           \
1061                                             m REPORT_LOCATION,          \
1062                                             REPORT_LOCATION_ARGS(loc)));\
1063         }                                                               \
1064     } STMT_END
1065
1066 /* Convert between a pointer to a node and its offset from the beginning of the
1067  * program */
1068 #define REGNODE_p(offset)    (RExC_emit_start + (offset))
1069 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
1070
1071 /* Macros for recording node offsets.   20001227 mjd@plover.com
1072  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
1073  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
1074  * Element 0 holds the number n.
1075  * Position is 1 indexed.
1076  */
1077 #ifndef RE_TRACK_PATTERN_OFFSETS
1078 #define Set_Node_Offset_To_R(offset,byte)
1079 #define Set_Node_Offset(node,byte)
1080 #define Set_Cur_Node_Offset
1081 #define Set_Node_Length_To_R(node,len)
1082 #define Set_Node_Length(node,len)
1083 #define Set_Node_Cur_Length(node,start)
1084 #define Node_Offset(n)
1085 #define Node_Length(n)
1086 #define Set_Node_Offset_Length(node,offset,len)
1087 #define ProgLen(ri) ri->u.proglen
1088 #define SetProgLen(ri,x) ri->u.proglen = x
1089 #define Track_Code(code)
1090 #else
1091 #define ProgLen(ri) ri->u.offsets[0]
1092 #define SetProgLen(ri,x) ri->u.offsets[0] = x
1093 #define Set_Node_Offset_To_R(offset,byte) STMT_START {                  \
1094         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
1095                     __LINE__, (int)(offset), (int)(byte)));             \
1096         if((offset) < 0) {                                              \
1097             Perl_croak(aTHX_ "value of node is %d in Offset macro",     \
1098                                          (int)(offset));                \
1099         } else {                                                        \
1100             RExC_offsets[2*(offset)-1] = (byte);                        \
1101         }                                                               \
1102 } STMT_END
1103
1104 #define Set_Node_Offset(node,byte)                                      \
1105     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
1106 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
1107
1108 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
1109         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
1110                 __LINE__, (int)(node), (int)(len)));                    \
1111         if((node) < 0) {                                                \
1112             Perl_croak(aTHX_ "value of node is %d in Length macro",     \
1113                                          (int)(node));                  \
1114         } else {                                                        \
1115             RExC_offsets[2*(node)] = (len);                             \
1116         }                                                               \
1117 } STMT_END
1118
1119 #define Set_Node_Length(node,len) \
1120     Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1121 #define Set_Node_Cur_Length(node, start)                \
1122     Set_Node_Length(node, RExC_parse - start)
1123
1124 /* Get offsets and lengths */
1125 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1126 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1127
1128 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
1129     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset));       \
1130     Set_Node_Length_To_R(REGNODE_OFFSET(node), (len));  \
1131 } STMT_END
1132
1133 #define Track_Code(code) STMT_START { code } STMT_END
1134 #endif
1135
1136 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1137 #define EXPERIMENTAL_INPLACESCAN
1138 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1139
1140 #ifdef DEBUGGING
1141 int
1142 Perl_re_printf(pTHX_ const char *fmt, ...)
1143 {
1144     va_list ap;
1145     int result;
1146     PerlIO *f= Perl_debug_log;
1147     PERL_ARGS_ASSERT_RE_PRINTF;
1148     va_start(ap, fmt);
1149     result = PerlIO_vprintf(f, fmt, ap);
1150     va_end(ap);
1151     return result;
1152 }
1153
1154 int
1155 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1156 {
1157     va_list ap;
1158     int result;
1159     PerlIO *f= Perl_debug_log;
1160     PERL_ARGS_ASSERT_RE_INDENTF;
1161     va_start(ap, depth);
1162     PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1163     result = PerlIO_vprintf(f, fmt, ap);
1164     va_end(ap);
1165     return result;
1166 }
1167 #endif /* DEBUGGING */
1168
1169 #define DEBUG_RExC_seen()                                                   \
1170         DEBUG_OPTIMISE_MORE_r({                                             \
1171             Perl_re_printf( aTHX_ "RExC_seen: ");                           \
1172                                                                             \
1173             if (RExC_seen & REG_ZERO_LEN_SEEN)                              \
1174                 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN ");                \
1175                                                                             \
1176             if (RExC_seen & REG_LOOKBEHIND_SEEN)                            \
1177                 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN ");              \
1178                                                                             \
1179             if (RExC_seen & REG_GPOS_SEEN)                                  \
1180                 Perl_re_printf( aTHX_ "REG_GPOS_SEEN ");                    \
1181                                                                             \
1182             if (RExC_seen & REG_RECURSE_SEEN)                               \
1183                 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN ");                 \
1184                                                                             \
1185             if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)                    \
1186                 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN ");      \
1187                                                                             \
1188             if (RExC_seen & REG_VERBARG_SEEN)                               \
1189                 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN ");                 \
1190                                                                             \
1191             if (RExC_seen & REG_CUTGROUP_SEEN)                              \
1192                 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN ");                \
1193                                                                             \
1194             if (RExC_seen & REG_RUN_ON_COMMENT_SEEN)                        \
1195                 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN ");          \
1196                                                                             \
1197             if (RExC_seen & REG_UNFOLDED_MULTI_SEEN)                        \
1198                 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN ");          \
1199                                                                             \
1200             if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)                  \
1201                 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN ");    \
1202                                                                             \
1203             Perl_re_printf( aTHX_ "\n");                                    \
1204         });
1205
1206 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1207   if ((flags) & flag) Perl_re_printf( aTHX_  "%s ", #flag)
1208
1209
1210 #ifdef DEBUGGING
1211 static void
1212 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1213                                     const char *close_str)
1214 {
1215     if (!flags)
1216         return;
1217
1218     Perl_re_printf( aTHX_  "%s", open_str);
1219     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1220     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1221     DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1222     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1223     DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1224     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1225     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1226     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1227     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1228     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1229     DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1230     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1231     DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1232     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1233     DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1234     Perl_re_printf( aTHX_  "%s", close_str);
1235 }
1236
1237
1238 static void
1239 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1240                     U32 depth, int is_inf)
1241 {
1242     DECLARE_AND_GET_RE_DEBUG_FLAGS;
1243
1244     DEBUG_OPTIMISE_MORE_r({
1245         if (!data)
1246             return;
1247         Perl_re_indentf(aTHX_  "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1248             depth,
1249             where,
1250             (IV)data->pos_min,
1251             (IV)data->pos_delta,
1252             (UV)data->flags
1253         );
1254
1255         S_debug_show_study_flags(aTHX_ data->flags," [","]");
1256
1257         Perl_re_printf( aTHX_
1258             " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1259             (IV)data->whilem_c,
1260             (IV)(data->last_closep ? *((data)->last_closep) : -1),
1261             is_inf ? "INF " : ""
1262         );
1263
1264         if (data->last_found) {
1265             int i;
1266             Perl_re_printf(aTHX_
1267                 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1268                     SvPVX_const(data->last_found),
1269                     (IV)data->last_end,
1270                     (IV)data->last_start_min,
1271                     (IV)data->last_start_max
1272             );
1273
1274             for (i = 0; i < 2; i++) {
1275                 Perl_re_printf(aTHX_
1276                     " %s%s: '%s' @ %" IVdf "/%" IVdf,
1277                     data->cur_is_floating == i ? "*" : "",
1278                     i ? "Float" : "Fixed",
1279                     SvPVX_const(data->substrs[i].str),
1280                     (IV)data->substrs[i].min_offset,
1281                     (IV)data->substrs[i].max_offset
1282                 );
1283                 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1284             }
1285         }
1286
1287         Perl_re_printf( aTHX_ "\n");
1288     });
1289 }
1290
1291
1292 static void
1293 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1294                 regnode *scan, U32 depth, U32 flags)
1295 {
1296     DECLARE_AND_GET_RE_DEBUG_FLAGS;
1297
1298     DEBUG_OPTIMISE_r({
1299         regnode *Next;
1300
1301         if (!scan)
1302             return;
1303         Next = regnext(scan);
1304         regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1305         Perl_re_indentf( aTHX_   "%s>%3d: %s (%d)",
1306             depth,
1307             str,
1308             REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1309             Next ? (REG_NODE_NUM(Next)) : 0 );
1310         S_debug_show_study_flags(aTHX_ flags," [ ","]");
1311         Perl_re_printf( aTHX_  "\n");
1312    });
1313 }
1314
1315
1316 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1317                     S_debug_studydata(aTHX_ where, data, depth, is_inf)
1318
1319 #  define DEBUG_PEEP(str, scan, depth, flags)   \
1320                     S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1321
1322 #else
1323 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1324 #  define DEBUG_PEEP(str, scan, depth, flags)         NOOP
1325 #endif
1326
1327
1328 /* =========================================================
1329  * BEGIN edit_distance stuff.
1330  *
1331  * This calculates how many single character changes of any type are needed to
1332  * transform a string into another one.  It is taken from version 3.1 of
1333  *
1334  * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1335  */
1336
1337 /* Our unsorted dictionary linked list.   */
1338 /* Note we use UVs, not chars. */
1339
1340 struct dictionary{
1341   UV key;
1342   UV value;
1343   struct dictionary* next;
1344 };
1345 typedef struct dictionary item;
1346
1347
1348 PERL_STATIC_INLINE item*
1349 push(UV key, item* curr)
1350 {
1351     item* head;
1352     Newx(head, 1, item);
1353     head->key = key;
1354     head->value = 0;
1355     head->next = curr;
1356     return head;
1357 }
1358
1359
1360 PERL_STATIC_INLINE item*
1361 find(item* head, UV key)
1362 {
1363     item* iterator = head;
1364     while (iterator){
1365         if (iterator->key == key){
1366             return iterator;
1367         }
1368         iterator = iterator->next;
1369     }
1370
1371     return NULL;
1372 }
1373
1374 PERL_STATIC_INLINE item*
1375 uniquePush(item* head, UV key)
1376 {
1377     item* iterator = head;
1378
1379     while (iterator){
1380         if (iterator->key == key) {
1381             return head;
1382         }
1383         iterator = iterator->next;
1384     }
1385
1386     return push(key, head);
1387 }
1388
1389 PERL_STATIC_INLINE void
1390 dict_free(item* head)
1391 {
1392     item* iterator = head;
1393
1394     while (iterator) {
1395         item* temp = iterator;
1396         iterator = iterator->next;
1397         Safefree(temp);
1398     }
1399
1400     head = NULL;
1401 }
1402
1403 /* End of Dictionary Stuff */
1404
1405 /* All calculations/work are done here */
1406 STATIC int
1407 S_edit_distance(const UV* src,
1408                 const UV* tgt,
1409                 const STRLEN x,             /* length of src[] */
1410                 const STRLEN y,             /* length of tgt[] */
1411                 const SSize_t maxDistance
1412 )
1413 {
1414     item *head = NULL;
1415     UV swapCount, swapScore, targetCharCount, i, j;
1416     UV *scores;
1417     UV score_ceil = x + y;
1418
1419     PERL_ARGS_ASSERT_EDIT_DISTANCE;
1420
1421     /* intialize matrix start values */
1422     Newx(scores, ( (x + 2) * (y + 2)), UV);
1423     scores[0] = score_ceil;
1424     scores[1 * (y + 2) + 0] = score_ceil;
1425     scores[0 * (y + 2) + 1] = score_ceil;
1426     scores[1 * (y + 2) + 1] = 0;
1427     head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1428
1429     /* work loops    */
1430     /* i = src index */
1431     /* j = tgt index */
1432     for (i=1;i<=x;i++) {
1433         if (i < x)
1434             head = uniquePush(head, src[i]);
1435         scores[(i+1) * (y + 2) + 1] = i;
1436         scores[(i+1) * (y + 2) + 0] = score_ceil;
1437         swapCount = 0;
1438
1439         for (j=1;j<=y;j++) {
1440             if (i == 1) {
1441                 if(j < y)
1442                 head = uniquePush(head, tgt[j]);
1443                 scores[1 * (y + 2) + (j + 1)] = j;
1444                 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1445             }
1446
1447             targetCharCount = find(head, tgt[j-1])->value;
1448             swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1449
1450             if (src[i-1] != tgt[j-1]){
1451                 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));
1452             }
1453             else {
1454                 swapCount = j;
1455                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1456             }
1457         }
1458
1459         find(head, src[i-1])->value = i;
1460     }
1461
1462     {
1463         IV score = scores[(x+1) * (y + 2) + (y + 1)];
1464         dict_free(head);
1465         Safefree(scores);
1466         return (maxDistance != 0 && maxDistance < score)?(-1):score;
1467     }
1468 }
1469
1470 /* END of edit_distance() stuff
1471  * ========================================================= */
1472
1473 /* Mark that we cannot extend a found fixed substring at this point.
1474    Update the longest found anchored substring or the longest found
1475    floating substrings if needed. */
1476
1477 STATIC void
1478 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1479                     SSize_t *minlenp, int is_inf)
1480 {
1481     const STRLEN l = CHR_SVLEN(data->last_found);
1482     SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1483     const STRLEN old_l = CHR_SVLEN(longest_sv);
1484     DECLARE_AND_GET_RE_DEBUG_FLAGS;
1485
1486     PERL_ARGS_ASSERT_SCAN_COMMIT;
1487
1488     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1489         const U8 i = data->cur_is_floating;
1490         SvSetMagicSV(longest_sv, data->last_found);
1491         data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1492
1493         if (!i) /* fixed */
1494             data->substrs[0].max_offset = data->substrs[0].min_offset;
1495         else { /* float */
1496             data->substrs[1].max_offset =
1497                       (is_inf)
1498                        ? OPTIMIZE_INFTY
1499                        : (l
1500                           ? data->last_start_max
1501                           /* temporary underflow guard for 5.32 */
1502                           : data->pos_delta < 0 ? OPTIMIZE_INFTY
1503                           : (data->pos_delta > OPTIMIZE_INFTY - data->pos_min
1504                                          ? OPTIMIZE_INFTY
1505                                          : data->pos_min + data->pos_delta));
1506         }
1507
1508         data->substrs[i].flags &= ~SF_BEFORE_EOL;
1509         data->substrs[i].flags |= data->flags & SF_BEFORE_EOL;
1510         data->substrs[i].minlenp = minlenp;
1511         data->substrs[i].lookbehind = 0;
1512     }
1513
1514     SvCUR_set(data->last_found, 0);
1515     {
1516         SV * const sv = data->last_found;
1517         if (SvUTF8(sv) && SvMAGICAL(sv)) {
1518             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1519             if (mg)
1520                 mg->mg_len = 0;
1521         }
1522     }
1523     data->last_end = -1;
1524     data->flags &= ~SF_BEFORE_EOL;
1525     DEBUG_STUDYDATA("commit", data, 0, is_inf);
1526 }
1527
1528 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1529  * list that describes which code points it matches */
1530
1531 STATIC void
1532 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1533 {
1534     /* Set the SSC 'ssc' to match an empty string or any code point */
1535
1536     PERL_ARGS_ASSERT_SSC_ANYTHING;
1537
1538     assert(is_ANYOF_SYNTHETIC(ssc));
1539
1540     /* mortalize so won't leak */
1541     ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1542     ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING;  /* Plus matches empty */
1543 }
1544
1545 STATIC int
1546 S_ssc_is_anything(const regnode_ssc *ssc)
1547 {
1548     /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1549      * point; FALSE otherwise.  Thus, this is used to see if using 'ssc' buys
1550      * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1551      * in any way, so there's no point in using it */
1552
1553     UV start, end;
1554     bool ret;
1555
1556     PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1557
1558     assert(is_ANYOF_SYNTHETIC(ssc));
1559
1560     if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1561         return FALSE;
1562     }
1563
1564     /* See if the list consists solely of the range 0 - Infinity */
1565     invlist_iterinit(ssc->invlist);
1566     ret = invlist_iternext(ssc->invlist, &start, &end)
1567           && start == 0
1568           && end == UV_MAX;
1569
1570     invlist_iterfinish(ssc->invlist);
1571
1572     if (ret) {
1573         return TRUE;
1574     }
1575
1576     /* If e.g., both \w and \W are set, matches everything */
1577     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1578         int i;
1579         for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1580             if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1581                 return TRUE;
1582             }
1583         }
1584     }
1585
1586     return FALSE;
1587 }
1588
1589 STATIC void
1590 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1591 {
1592     /* Initializes the SSC 'ssc'.  This includes setting it to match an empty
1593      * string, any code point, or any posix class under locale */
1594
1595     PERL_ARGS_ASSERT_SSC_INIT;
1596
1597     Zero(ssc, 1, regnode_ssc);
1598     set_ANYOF_SYNTHETIC(ssc);
1599     ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1600     ssc_anything(ssc);
1601
1602     /* If any portion of the regex is to operate under locale rules that aren't
1603      * fully known at compile time, initialization includes it.  The reason
1604      * this isn't done for all regexes is that the optimizer was written under
1605      * the assumption that locale was all-or-nothing.  Given the complexity and
1606      * lack of documentation in the optimizer, and that there are inadequate
1607      * test cases for locale, many parts of it may not work properly, it is
1608      * safest to avoid locale unless necessary. */
1609     if (RExC_contains_locale) {
1610         ANYOF_POSIXL_SETALL(ssc);
1611     }
1612     else {
1613         ANYOF_POSIXL_ZERO(ssc);
1614     }
1615 }
1616
1617 STATIC int
1618 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1619                         const regnode_ssc *ssc)
1620 {
1621     /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1622      * to the list of code points matched, and locale posix classes; hence does
1623      * not check its flags) */
1624
1625     UV start, end;
1626     bool ret;
1627
1628     PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1629
1630     assert(is_ANYOF_SYNTHETIC(ssc));
1631
1632     invlist_iterinit(ssc->invlist);
1633     ret = invlist_iternext(ssc->invlist, &start, &end)
1634           && start == 0
1635           && end == UV_MAX;
1636
1637     invlist_iterfinish(ssc->invlist);
1638
1639     if (! ret) {
1640         return FALSE;
1641     }
1642
1643     if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1644         return FALSE;
1645     }
1646
1647     return TRUE;
1648 }
1649
1650 #define INVLIST_INDEX 0
1651 #define ONLY_LOCALE_MATCHES_INDEX 1
1652 #define DEFERRED_USER_DEFINED_INDEX 2
1653
1654 STATIC SV*
1655 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1656                                const regnode_charclass* const node)
1657 {
1658     /* Returns a mortal inversion list defining which code points are matched
1659      * by 'node', which is of type ANYOF.  Handles complementing the result if
1660      * appropriate.  If some code points aren't knowable at this time, the
1661      * returned list must, and will, contain every code point that is a
1662      * possibility. */
1663
1664     dVAR;
1665     SV* invlist = NULL;
1666     SV* only_utf8_locale_invlist = NULL;
1667     unsigned int i;
1668     const U32 n = ARG(node);
1669     bool new_node_has_latin1 = FALSE;
1670     const U8 flags = (inRANGE(OP(node), ANYOFH, ANYOFRb))
1671                       ? 0
1672                       : ANYOF_FLAGS(node);
1673
1674     PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1675
1676     /* Look at the data structure created by S_set_ANYOF_arg() */
1677     if (n != ANYOF_ONLY_HAS_BITMAP) {
1678         SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1679         AV * const av = MUTABLE_AV(SvRV(rv));
1680         SV **const ary = AvARRAY(av);
1681         assert(RExC_rxi->data->what[n] == 's');
1682
1683         if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1684
1685             /* Here there are things that won't be known until runtime -- we
1686              * have to assume it could be anything */
1687             invlist = sv_2mortal(_new_invlist(1));
1688             return _add_range_to_invlist(invlist, 0, UV_MAX);
1689         }
1690         else if (ary[INVLIST_INDEX]) {
1691
1692             /* Use the node's inversion list */
1693             invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1694         }
1695
1696         /* Get the code points valid only under UTF-8 locales */
1697         if (   (flags & ANYOFL_FOLD)
1698             &&  av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1699         {
1700             only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1701         }
1702     }
1703
1704     if (! invlist) {
1705         invlist = sv_2mortal(_new_invlist(0));
1706     }
1707
1708     /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1709      * code points, and an inversion list for the others, but if there are code
1710      * points that should match only conditionally on the target string being
1711      * UTF-8, those are placed in the inversion list, and not the bitmap.
1712      * Since there are circumstances under which they could match, they are
1713      * included in the SSC.  But if the ANYOF node is to be inverted, we have
1714      * to exclude them here, so that when we invert below, the end result
1715      * actually does include them.  (Think about "\xe0" =~ /[^\xc0]/di;).  We
1716      * have to do this here before we add the unconditionally matched code
1717      * points */
1718     if (flags & ANYOF_INVERT) {
1719         _invlist_intersection_complement_2nd(invlist,
1720                                              PL_UpperLatin1,
1721                                              &invlist);
1722     }
1723
1724     /* Add in the points from the bit map */
1725     if (! inRANGE(OP(node), ANYOFH, ANYOFRb)) {
1726         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1727             if (ANYOF_BITMAP_TEST(node, i)) {
1728                 unsigned int start = i++;
1729
1730                 for (;    i < NUM_ANYOF_CODE_POINTS
1731                        && ANYOF_BITMAP_TEST(node, i); ++i)
1732                 {
1733                     /* empty */
1734                 }
1735                 invlist = _add_range_to_invlist(invlist, start, i-1);
1736                 new_node_has_latin1 = TRUE;
1737             }
1738         }
1739     }
1740
1741     /* If this can match all upper Latin1 code points, have to add them
1742      * as well.  But don't add them if inverting, as when that gets done below,
1743      * it would exclude all these characters, including the ones it shouldn't
1744      * that were added just above */
1745     if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD
1746         && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1747     {
1748         _invlist_union(invlist, PL_UpperLatin1, &invlist);
1749     }
1750
1751     /* Similarly for these */
1752     if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1753         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1754     }
1755
1756     if (flags & ANYOF_INVERT) {
1757         _invlist_invert(invlist);
1758     }
1759     else if (flags & ANYOFL_FOLD) {
1760         if (new_node_has_latin1) {
1761
1762             /* Under /li, any 0-255 could fold to any other 0-255, depending on
1763              * the locale.  We can skip this if there are no 0-255 at all. */
1764             _invlist_union(invlist, PL_Latin1, &invlist);
1765
1766             invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1767             invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1768         }
1769         else {
1770             if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1771                 invlist = add_cp_to_invlist(invlist, 'I');
1772             }
1773             if (_invlist_contains_cp(invlist,
1774                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1775             {
1776                 invlist = add_cp_to_invlist(invlist, 'i');
1777             }
1778         }
1779     }
1780
1781     /* Similarly add the UTF-8 locale possible matches.  These have to be
1782      * deferred until after the non-UTF-8 locale ones are taken care of just
1783      * above, or it leads to wrong results under ANYOF_INVERT */
1784     if (only_utf8_locale_invlist) {
1785         _invlist_union_maybe_complement_2nd(invlist,
1786                                             only_utf8_locale_invlist,
1787                                             flags & ANYOF_INVERT,
1788                                             &invlist);
1789     }
1790
1791     return invlist;
1792 }
1793
1794 /* These two functions currently do the exact same thing */
1795 #define ssc_init_zero           ssc_init
1796
1797 #define ssc_add_cp(ssc, cp)   ssc_add_range((ssc), (cp), (cp))
1798 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1799
1800 /* 'AND' a given class with another one.  Can create false positives.  'ssc'
1801  * should not be inverted.  'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1802  * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1803
1804 STATIC void
1805 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1806                 const regnode_charclass *and_with)
1807 {
1808     /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1809      * another SSC or a regular ANYOF class.  Can create false positives. */
1810
1811     SV* anded_cp_list;
1812     U8  and_with_flags = inRANGE(OP(and_with), ANYOFH, ANYOFRb)
1813                           ? 0
1814                           : ANYOF_FLAGS(and_with);
1815     U8  anded_flags;
1816
1817     PERL_ARGS_ASSERT_SSC_AND;
1818
1819     assert(is_ANYOF_SYNTHETIC(ssc));
1820
1821     /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1822      * the code point inversion list and just the relevant flags */
1823     if (is_ANYOF_SYNTHETIC(and_with)) {
1824         anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1825         anded_flags = and_with_flags;
1826
1827         /* XXX This is a kludge around what appears to be deficiencies in the
1828          * optimizer.  If we make S_ssc_anything() add in the WARN_SUPER flag,
1829          * there are paths through the optimizer where it doesn't get weeded
1830          * out when it should.  And if we don't make some extra provision for
1831          * it like the code just below, it doesn't get added when it should.
1832          * This solution is to add it only when AND'ing, which is here, and
1833          * only when what is being AND'ed is the pristine, original node
1834          * matching anything.  Thus it is like adding it to ssc_anything() but
1835          * only when the result is to be AND'ed.  Probably the same solution
1836          * could be adopted for the same problem we have with /l matching,
1837          * which is solved differently in S_ssc_init(), and that would lead to
1838          * fewer false positives than that solution has.  But if this solution
1839          * creates bugs, the consequences are only that a warning isn't raised
1840          * that should be; while the consequences for having /l bugs is
1841          * incorrect matches */
1842         if (ssc_is_anything((regnode_ssc *)and_with)) {
1843             anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1844         }
1845     }
1846     else {
1847         anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1848         if (OP(and_with) == ANYOFD) {
1849             anded_flags = and_with_flags & ANYOF_COMMON_FLAGS;
1850         }
1851         else {
1852             anded_flags = and_with_flags
1853             &( ANYOF_COMMON_FLAGS
1854               |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1855               |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1856             if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) {
1857                 anded_flags &=
1858                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1859             }
1860         }
1861     }
1862
1863     ANYOF_FLAGS(ssc) &= anded_flags;
1864
1865     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1866      * C2 is the list of code points in 'and-with'; P2, its posix classes.
1867      * 'and_with' may be inverted.  When not inverted, we have the situation of
1868      * computing:
1869      *  (C1 | P1) & (C2 | P2)
1870      *                     =  (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1871      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1872      *                    <=  ((C1 & C2) |       P2)) | ( P1       | (P1 & P2))
1873      *                    <=  ((C1 & C2) | P1 | P2)
1874      * Alternatively, the last few steps could be:
1875      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1876      *                    <=  ((C1 & C2) |  C1      ) | (      C2  | (P1 & P2))
1877      *                    <=  (C1 | C2 | (P1 & P2))
1878      * We favor the second approach if either P1 or P2 is non-empty.  This is
1879      * because these components are a barrier to doing optimizations, as what
1880      * they match cannot be known until the moment of matching as they are
1881      * dependent on the current locale, 'AND"ing them likely will reduce or
1882      * eliminate them.
1883      * But we can do better if we know that C1,P1 are in their initial state (a
1884      * frequent occurrence), each matching everything:
1885      *  (<everything>) & (C2 | P2) =  C2 | P2
1886      * Similarly, if C2,P2 are in their initial state (again a frequent
1887      * occurrence), the result is a no-op
1888      *  (C1 | P1) & (<everything>) =  C1 | P1
1889      *
1890      * Inverted, we have
1891      *  (C1 | P1) & ~(C2 | P2)  =  (C1 | P1) & (~C2 & ~P2)
1892      *                          =  (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1893      *                         <=  (C1 & ~C2) | (P1 & ~P2)
1894      * */
1895
1896     if ((and_with_flags & ANYOF_INVERT)
1897         && ! is_ANYOF_SYNTHETIC(and_with))
1898     {
1899         unsigned int i;
1900
1901         ssc_intersection(ssc,
1902                          anded_cp_list,
1903                          FALSE /* Has already been inverted */
1904                          );
1905
1906         /* If either P1 or P2 is empty, the intersection will be also; can skip
1907          * the loop */
1908         if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) {
1909             ANYOF_POSIXL_ZERO(ssc);
1910         }
1911         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1912
1913             /* Note that the Posix class component P from 'and_with' actually
1914              * looks like:
1915              *      P = Pa | Pb | ... | Pn
1916              * where each component is one posix class, such as in [\w\s].
1917              * Thus
1918              *      ~P = ~(Pa | Pb | ... | Pn)
1919              *         = ~Pa & ~Pb & ... & ~Pn
1920              *        <= ~Pa | ~Pb | ... | ~Pn
1921              * The last is something we can easily calculate, but unfortunately
1922              * is likely to have many false positives.  We could do better
1923              * in some (but certainly not all) instances if two classes in
1924              * P have known relationships.  For example
1925              *      :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1926              * So
1927              *      :lower: & :print: = :lower:
1928              * And similarly for classes that must be disjoint.  For example,
1929              * since \s and \w can have no elements in common based on rules in
1930              * the POSIX standard,
1931              *      \w & ^\S = nothing
1932              * Unfortunately, some vendor locales do not meet the Posix
1933              * standard, in particular almost everything by Microsoft.
1934              * The loop below just changes e.g., \w into \W and vice versa */
1935
1936             regnode_charclass_posixl temp;
1937             int add = 1;    /* To calculate the index of the complement */
1938
1939             Zero(&temp, 1, regnode_charclass_posixl);
1940             ANYOF_POSIXL_ZERO(&temp);
1941             for (i = 0; i < ANYOF_MAX; i++) {
1942                 assert(i % 2 != 0
1943                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1944                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1945
1946                 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1947                     ANYOF_POSIXL_SET(&temp, i + add);
1948                 }
1949                 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1950             }
1951             ANYOF_POSIXL_AND(&temp, ssc);
1952
1953         } /* else ssc already has no posixes */
1954     } /* else: Not inverted.  This routine is a no-op if 'and_with' is an SSC
1955          in its initial state */
1956     else if (! is_ANYOF_SYNTHETIC(and_with)
1957              || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1958     {
1959         /* But if 'ssc' is in its initial state, the result is just 'and_with';
1960          * copy it over 'ssc' */
1961         if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1962             if (is_ANYOF_SYNTHETIC(and_with)) {
1963                 StructCopy(and_with, ssc, regnode_ssc);
1964             }
1965             else {
1966                 ssc->invlist = anded_cp_list;
1967                 ANYOF_POSIXL_ZERO(ssc);
1968                 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1969                     ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1970                 }
1971             }
1972         }
1973         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1974                  || (and_with_flags & ANYOF_MATCHES_POSIXL))
1975         {
1976             /* One or the other of P1, P2 is non-empty. */
1977             if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1978                 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1979             }
1980             ssc_union(ssc, anded_cp_list, FALSE);
1981         }
1982         else { /* P1 = P2 = empty */
1983             ssc_intersection(ssc, anded_cp_list, FALSE);
1984         }
1985     }
1986 }
1987
1988 STATIC void
1989 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1990                const regnode_charclass *or_with)
1991 {
1992     /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1993      * another SSC or a regular ANYOF class.  Can create false positives if
1994      * 'or_with' is to be inverted. */
1995
1996     SV* ored_cp_list;
1997     U8 ored_flags;
1998     U8  or_with_flags = inRANGE(OP(or_with), ANYOFH, ANYOFRb)
1999                          ? 0
2000                          : ANYOF_FLAGS(or_with);
2001
2002     PERL_ARGS_ASSERT_SSC_OR;
2003
2004     assert(is_ANYOF_SYNTHETIC(ssc));
2005
2006     /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
2007      * the code point inversion list and just the relevant flags */
2008     if (is_ANYOF_SYNTHETIC(or_with)) {
2009         ored_cp_list = ((regnode_ssc*) or_with)->invlist;
2010         ored_flags = or_with_flags;
2011     }
2012     else {
2013         ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
2014         ored_flags = or_with_flags & ANYOF_COMMON_FLAGS;
2015         if (OP(or_with) != ANYOFD) {
2016             ored_flags
2017             |= or_with_flags
2018              & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2019                 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
2020             if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) {
2021                 ored_flags |=
2022                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
2023             }
2024         }
2025     }
2026
2027     ANYOF_FLAGS(ssc) |= ored_flags;
2028
2029     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
2030      * C2 is the list of code points in 'or-with'; P2, its posix classes.
2031      * 'or_with' may be inverted.  When not inverted, we have the simple
2032      * situation of computing:
2033      *  (C1 | P1) | (C2 | P2)  =  (C1 | C2) | (P1 | P2)
2034      * If P1|P2 yields a situation with both a class and its complement are
2035      * set, like having both \w and \W, this matches all code points, and we
2036      * can delete these from the P component of the ssc going forward.  XXX We
2037      * might be able to delete all the P components, but I (khw) am not certain
2038      * about this, and it is better to be safe.
2039      *
2040      * Inverted, we have
2041      *  (C1 | P1) | ~(C2 | P2)  =  (C1 | P1) | (~C2 & ~P2)
2042      *                         <=  (C1 | P1) | ~C2
2043      *                         <=  (C1 | ~C2) | P1
2044      * (which results in actually simpler code than the non-inverted case)
2045      * */
2046
2047     if ((or_with_flags & ANYOF_INVERT)
2048         && ! is_ANYOF_SYNTHETIC(or_with))
2049     {
2050         /* We ignore P2, leaving P1 going forward */
2051     }   /* else  Not inverted */
2052     else if (or_with_flags & ANYOF_MATCHES_POSIXL) {
2053         ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
2054         if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2055             unsigned int i;
2056             for (i = 0; i < ANYOF_MAX; i += 2) {
2057                 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
2058                 {
2059                     ssc_match_all_cp(ssc);
2060                     ANYOF_POSIXL_CLEAR(ssc, i);
2061                     ANYOF_POSIXL_CLEAR(ssc, i+1);
2062                 }
2063             }
2064         }
2065     }
2066
2067     ssc_union(ssc,
2068               ored_cp_list,
2069               FALSE /* Already has been inverted */
2070               );
2071 }
2072
2073 STATIC void
2074 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
2075 {
2076     PERL_ARGS_ASSERT_SSC_UNION;
2077
2078     assert(is_ANYOF_SYNTHETIC(ssc));
2079
2080     _invlist_union_maybe_complement_2nd(ssc->invlist,
2081                                         invlist,
2082                                         invert2nd,
2083                                         &ssc->invlist);
2084 }
2085
2086 STATIC void
2087 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
2088                          SV* const invlist,
2089                          const bool invert2nd)
2090 {
2091     PERL_ARGS_ASSERT_SSC_INTERSECTION;
2092
2093     assert(is_ANYOF_SYNTHETIC(ssc));
2094
2095     _invlist_intersection_maybe_complement_2nd(ssc->invlist,
2096                                                invlist,
2097                                                invert2nd,
2098                                                &ssc->invlist);
2099 }
2100
2101 STATIC void
2102 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
2103 {
2104     PERL_ARGS_ASSERT_SSC_ADD_RANGE;
2105
2106     assert(is_ANYOF_SYNTHETIC(ssc));
2107
2108     ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
2109 }
2110
2111 STATIC void
2112 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2113 {
2114     /* AND just the single code point 'cp' into the SSC 'ssc' */
2115
2116     SV* cp_list = _new_invlist(2);
2117
2118     PERL_ARGS_ASSERT_SSC_CP_AND;
2119
2120     assert(is_ANYOF_SYNTHETIC(ssc));
2121
2122     cp_list = add_cp_to_invlist(cp_list, cp);
2123     ssc_intersection(ssc, cp_list,
2124                      FALSE /* Not inverted */
2125                      );
2126     SvREFCNT_dec_NN(cp_list);
2127 }
2128
2129 STATIC void
2130 S_ssc_clear_locale(regnode_ssc *ssc)
2131 {
2132     /* Set the SSC 'ssc' to not match any locale things */
2133     PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2134
2135     assert(is_ANYOF_SYNTHETIC(ssc));
2136
2137     ANYOF_POSIXL_ZERO(ssc);
2138     ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2139 }
2140
2141 #define NON_OTHER_COUNT   NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2142
2143 STATIC bool
2144 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2145 {
2146     /* The synthetic start class is used to hopefully quickly winnow down
2147      * places where a pattern could start a match in the target string.  If it
2148      * doesn't really narrow things down that much, there isn't much point to
2149      * having the overhead of using it.  This function uses some very crude
2150      * heuristics to decide if to use the ssc or not.
2151      *
2152      * It returns TRUE if 'ssc' rules out more than half what it considers to
2153      * be the "likely" possible matches, but of course it doesn't know what the
2154      * actual things being matched are going to be; these are only guesses
2155      *
2156      * For /l matches, it assumes that the only likely matches are going to be
2157      *      in the 0-255 range, uniformly distributed, so half of that is 127
2158      * For /a and /d matches, it assumes that the likely matches will be just
2159      *      the ASCII range, so half of that is 63
2160      * For /u and there isn't anything matching above the Latin1 range, it
2161      *      assumes that that is the only range likely to be matched, and uses
2162      *      half that as the cut-off: 127.  If anything matches above Latin1,
2163      *      it assumes that all of Unicode could match (uniformly), except for
2164      *      non-Unicode code points and things in the General Category "Other"
2165      *      (unassigned, private use, surrogates, controls and formats).  This
2166      *      is a much large number. */
2167
2168     U32 count = 0;      /* Running total of number of code points matched by
2169                            'ssc' */
2170     UV start, end;      /* Start and end points of current range in inversion
2171                            XXX outdated.  UTF-8 locales are common, what about invert? list */
2172     const U32 max_code_points = (LOC)
2173                                 ?  256
2174                                 : ((  ! UNI_SEMANTICS
2175                                     ||  invlist_highest(ssc->invlist) < 256)
2176                                   ? 128
2177                                   : NON_OTHER_COUNT);
2178     const U32 max_match = max_code_points / 2;
2179
2180     PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2181
2182     invlist_iterinit(ssc->invlist);
2183     while (invlist_iternext(ssc->invlist, &start, &end)) {
2184         if (start >= max_code_points) {
2185             break;
2186         }
2187         end = MIN(end, max_code_points - 1);
2188         count += end - start + 1;
2189         if (count >= max_match) {
2190             invlist_iterfinish(ssc->invlist);
2191             return FALSE;
2192         }
2193     }
2194
2195     return TRUE;
2196 }
2197
2198
2199 STATIC void
2200 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2201 {
2202     /* The inversion list in the SSC is marked mortal; now we need a more
2203      * permanent copy, which is stored the same way that is done in a regular
2204      * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2205      * map */
2206
2207     SV* invlist = invlist_clone(ssc->invlist, NULL);
2208
2209     PERL_ARGS_ASSERT_SSC_FINALIZE;
2210
2211     assert(is_ANYOF_SYNTHETIC(ssc));
2212
2213     /* The code in this file assumes that all but these flags aren't relevant
2214      * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2215      * by the time we reach here */
2216     assert(! (ANYOF_FLAGS(ssc)
2217         & ~( ANYOF_COMMON_FLAGS
2218             |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2219             |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2220
2221     populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2222
2223     set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2224     SvREFCNT_dec(invlist);
2225
2226     /* Make sure is clone-safe */
2227     ssc->invlist = NULL;
2228
2229     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2230         ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2231         OP(ssc) = ANYOFPOSIXL;
2232     }
2233     else if (RExC_contains_locale) {
2234         OP(ssc) = ANYOFL;
2235     }
2236
2237     assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2238 }
2239
2240 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2241 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
2242 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2243 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list         \
2244                                ? (TRIE_LIST_CUR( idx ) - 1)           \
2245                                : 0 )
2246
2247
2248 #ifdef DEBUGGING
2249 /*
2250    dump_trie(trie,widecharmap,revcharmap)
2251    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2252    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2253
2254    These routines dump out a trie in a somewhat readable format.
2255    The _interim_ variants are used for debugging the interim
2256    tables that are used to generate the final compressed
2257    representation which is what dump_trie expects.
2258
2259    Part of the reason for their existence is to provide a form
2260    of documentation as to how the different representations function.
2261
2262 */
2263
2264 /*
2265   Dumps the final compressed table form of the trie to Perl_debug_log.
2266   Used for debugging make_trie().
2267 */
2268
2269 STATIC void
2270 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2271             AV *revcharmap, U32 depth)
2272 {
2273     U32 state;
2274     SV *sv=sv_newmortal();
2275     int colwidth= widecharmap ? 6 : 4;
2276     U16 word;
2277     DECLARE_AND_GET_RE_DEBUG_FLAGS;
2278
2279     PERL_ARGS_ASSERT_DUMP_TRIE;
2280
2281     Perl_re_indentf( aTHX_  "Char : %-6s%-6s%-4s ",
2282         depth+1, "Match","Base","Ofs" );
2283
2284     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2285         SV ** const tmp = av_fetch( revcharmap, state, 0);
2286         if ( tmp ) {
2287             Perl_re_printf( aTHX_  "%*s",
2288                 colwidth,
2289                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2290                             PL_colors[0], PL_colors[1],
2291                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2292                             PERL_PV_ESCAPE_FIRSTCHAR
2293                 )
2294             );
2295         }
2296     }
2297     Perl_re_printf( aTHX_  "\n");
2298     Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2299
2300     for( state = 0 ; state < trie->uniquecharcount ; state++ )
2301         Perl_re_printf( aTHX_  "%.*s", colwidth, "--------");
2302     Perl_re_printf( aTHX_  "\n");
2303
2304     for( state = 1 ; state < trie->statecount ; state++ ) {
2305         const U32 base = trie->states[ state ].trans.base;
2306
2307         Perl_re_indentf( aTHX_  "#%4" UVXf "|", depth+1, (UV)state);
2308
2309         if ( trie->states[ state ].wordnum ) {
2310             Perl_re_printf( aTHX_  " W%4X", trie->states[ state ].wordnum );
2311         } else {
2312             Perl_re_printf( aTHX_  "%6s", "" );
2313         }
2314
2315         Perl_re_printf( aTHX_  " @%4" UVXf " ", (UV)base );
2316
2317         if ( base ) {
2318             U32 ofs = 0;
2319
2320             while( ( base + ofs  < trie->uniquecharcount ) ||
2321                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
2322                      && trie->trans[ base + ofs - trie->uniquecharcount ].check
2323                                                                     != state))
2324                     ofs++;
2325
2326             Perl_re_printf( aTHX_  "+%2" UVXf "[ ", (UV)ofs);
2327
2328             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2329                 if ( ( base + ofs >= trie->uniquecharcount )
2330                         && ( base + ofs - trie->uniquecharcount
2331                                                         < trie->lasttrans )
2332                         && trie->trans[ base + ofs
2333                                     - trie->uniquecharcount ].check == state )
2334                 {
2335                    Perl_re_printf( aTHX_  "%*" UVXf, colwidth,
2336                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2337                    );
2338                 } else {
2339                     Perl_re_printf( aTHX_  "%*s", colwidth,"   ." );
2340                 }
2341             }
2342
2343             Perl_re_printf( aTHX_  "]");
2344
2345         }
2346         Perl_re_printf( aTHX_  "\n" );
2347     }
2348     Perl_re_indentf( aTHX_  "word_info N:(prev,len)=",
2349                                 depth);
2350     for (word=1; word <= trie->wordcount; word++) {
2351         Perl_re_printf( aTHX_  " %d:(%d,%d)",
2352             (int)word, (int)(trie->wordinfo[word].prev),
2353             (int)(trie->wordinfo[word].len));
2354     }
2355     Perl_re_printf( aTHX_  "\n" );
2356 }
2357 /*
2358   Dumps a fully constructed but uncompressed trie in list form.
2359   List tries normally only are used for construction when the number of
2360   possible chars (trie->uniquecharcount) is very high.
2361   Used for debugging make_trie().
2362 */
2363 STATIC void
2364 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2365                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
2366                          U32 depth)
2367 {
2368     U32 state;
2369     SV *sv=sv_newmortal();
2370     int colwidth= widecharmap ? 6 : 4;
2371     DECLARE_AND_GET_RE_DEBUG_FLAGS;
2372
2373     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2374
2375     /* print out the table precompression.  */
2376     Perl_re_indentf( aTHX_  "State :Word | Transition Data\n",
2377             depth+1 );
2378     Perl_re_indentf( aTHX_  "%s",
2379             depth+1, "------:-----+-----------------\n" );
2380
2381     for( state=1 ; state < next_alloc ; state ++ ) {
2382         U16 charid;
2383
2384         Perl_re_indentf( aTHX_  " %4" UVXf " :",
2385             depth+1, (UV)state  );
2386         if ( ! trie->states[ state ].wordnum ) {
2387             Perl_re_printf( aTHX_  "%5s| ","");
2388         } else {
2389             Perl_re_printf( aTHX_  "W%4x| ",
2390                 trie->states[ state ].wordnum
2391             );
2392         }
2393         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2394             SV ** const tmp = av_fetch( revcharmap,
2395                                         TRIE_LIST_ITEM(state, charid).forid, 0);
2396             if ( tmp ) {
2397                 Perl_re_printf( aTHX_  "%*s:%3X=%4" UVXf " | ",
2398                     colwidth,
2399                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2400                               colwidth,
2401                               PL_colors[0], PL_colors[1],
2402                               (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2403                               | PERL_PV_ESCAPE_FIRSTCHAR
2404                     ) ,
2405                     TRIE_LIST_ITEM(state, charid).forid,
2406                     (UV)TRIE_LIST_ITEM(state, charid).newstate
2407                 );
2408                 if (!(charid % 10))
2409                     Perl_re_printf( aTHX_  "\n%*s| ",
2410                         (int)((depth * 2) + 14), "");
2411             }
2412         }
2413         Perl_re_printf( aTHX_  "\n");
2414     }
2415 }
2416
2417 /*
2418   Dumps a fully constructed but uncompressed trie in table form.
2419   This is the normal DFA style state transition table, with a few
2420   twists to facilitate compression later.
2421   Used for debugging make_trie().
2422 */
2423 STATIC void
2424 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2425                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
2426                           U32 depth)
2427 {
2428     U32 state;
2429     U16 charid;
2430     SV *sv=sv_newmortal();
2431     int colwidth= widecharmap ? 6 : 4;
2432     DECLARE_AND_GET_RE_DEBUG_FLAGS;
2433
2434     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2435
2436     /*
2437        print out the table precompression so that we can do a visual check
2438        that they are identical.
2439      */
2440
2441     Perl_re_indentf( aTHX_  "Char : ", depth+1 );
2442
2443     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2444         SV ** const tmp = av_fetch( revcharmap, charid, 0);
2445         if ( tmp ) {
2446             Perl_re_printf( aTHX_  "%*s",
2447                 colwidth,
2448                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2449                             PL_colors[0], PL_colors[1],
2450                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2451                             PERL_PV_ESCAPE_FIRSTCHAR
2452                 )
2453             );
2454         }
2455     }
2456
2457     Perl_re_printf( aTHX_ "\n");
2458     Perl_re_indentf( aTHX_  "State+-", depth+1 );
2459
2460     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2461         Perl_re_printf( aTHX_  "%.*s", colwidth,"--------");
2462     }
2463
2464     Perl_re_printf( aTHX_  "\n" );
2465
2466     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2467
2468         Perl_re_indentf( aTHX_  "%4" UVXf " : ",
2469             depth+1,
2470             (UV)TRIE_NODENUM( state ) );
2471
2472         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2473             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2474             if (v)
2475                 Perl_re_printf( aTHX_  "%*" UVXf, colwidth, v );
2476             else
2477                 Perl_re_printf( aTHX_  "%*s", colwidth, "." );
2478         }
2479         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2480             Perl_re_printf( aTHX_  " (%4" UVXf ")\n",
2481                                             (UV)trie->trans[ state ].check );
2482         } else {
2483             Perl_re_printf( aTHX_  " (%4" UVXf ") W%4X\n",
2484                                             (UV)trie->trans[ state ].check,
2485             trie->states[ TRIE_NODENUM( state ) ].wordnum );
2486         }
2487     }
2488 }
2489
2490 #endif
2491
2492
2493 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2494   startbranch: the first branch in the whole branch sequence
2495   first      : start branch of sequence of branch-exact nodes.
2496                May be the same as startbranch
2497   last       : Thing following the last branch.
2498                May be the same as tail.
2499   tail       : item following the branch sequence
2500   count      : words in the sequence
2501   flags      : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2502   depth      : indent depth
2503
2504 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2505
2506 A trie is an N'ary tree where the branches are determined by digital
2507 decomposition of the key. IE, at the root node you look up the 1st character and
2508 follow that branch repeat until you find the end of the branches. Nodes can be
2509 marked as "accepting" meaning they represent a complete word. Eg:
2510
2511   /he|she|his|hers/
2512
2513 would convert into the following structure. Numbers represent states, letters
2514 following numbers represent valid transitions on the letter from that state, if
2515 the number is in square brackets it represents an accepting state, otherwise it
2516 will be in parenthesis.
2517
2518       +-h->+-e->[3]-+-r->(8)-+-s->[9]
2519       |    |
2520       |   (2)
2521       |    |
2522      (1)   +-i->(6)-+-s->[7]
2523       |
2524       +-s->(3)-+-h->(4)-+-e->[5]
2525
2526       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2527
2528 This shows that when matching against the string 'hers' we will begin at state 1
2529 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2530 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2531 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2532 single traverse. We store a mapping from accepting to state to which word was
2533 matched, and then when we have multiple possibilities we try to complete the
2534 rest of the regex in the order in which they occurred in the alternation.
2535
2536 The only prior NFA like behaviour that would be changed by the TRIE support is
2537 the silent ignoring of duplicate alternations which are of the form:
2538
2539  / (DUPE|DUPE) X? (?{ ... }) Y /x
2540
2541 Thus EVAL blocks following a trie may be called a different number of times with
2542 and without the optimisation. With the optimisations dupes will be silently
2543 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2544 the following demonstrates:
2545
2546  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2547
2548 which prints out 'word' three times, but
2549
2550  'words'=~/(word|word|word)(?{ print $1 })S/
2551
2552 which doesnt print it out at all. This is due to other optimisations kicking in.
2553
2554 Example of what happens on a structural level:
2555
2556 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2557
2558    1: CURLYM[1] {1,32767}(18)
2559    5:   BRANCH(8)
2560    6:     EXACT <ac>(16)
2561    8:   BRANCH(11)
2562    9:     EXACT <ad>(16)
2563   11:   BRANCH(14)
2564   12:     EXACT <ab>(16)
2565   16:   SUCCEED(0)
2566   17:   NOTHING(18)
2567   18: END(0)
2568
2569 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2570 and should turn into:
2571
2572    1: CURLYM[1] {1,32767}(18)
2573    5:   TRIE(16)
2574         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2575           <ac>
2576           <ad>
2577           <ab>
2578   16:   SUCCEED(0)
2579   17:   NOTHING(18)
2580   18: END(0)
2581
2582 Cases where tail != last would be like /(?foo|bar)baz/:
2583
2584    1: BRANCH(4)
2585    2:   EXACT <foo>(8)
2586    4: BRANCH(7)
2587    5:   EXACT <bar>(8)
2588    7: TAIL(8)
2589    8: EXACT <baz>(10)
2590   10: END(0)
2591
2592 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2593 and would end up looking like:
2594
2595     1: TRIE(8)
2596       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2597         <foo>
2598         <bar>
2599    7: TAIL(8)
2600    8: EXACT <baz>(10)
2601   10: END(0)
2602
2603     d = uvchr_to_utf8_flags(d, uv, 0);
2604
2605 is the recommended Unicode-aware way of saying
2606
2607     *(d++) = uv;
2608 */
2609
2610 #define TRIE_STORE_REVCHAR(val)                                            \
2611     STMT_START {                                                           \
2612         if (UTF) {                                                         \
2613             SV *zlopp = newSV(UTF8_MAXBYTES);                              \
2614             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
2615             unsigned char *const kapow = uvchr_to_utf8(flrbbbbb, val);     \
2616             *kapow = '\0';                                                 \
2617             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
2618             SvPOK_on(zlopp);                                               \
2619             SvUTF8_on(zlopp);                                              \
2620             av_push(revcharmap, zlopp);                                    \
2621         } else {                                                           \
2622             char ooooff = (char)val;                                           \
2623             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
2624         }                                                                  \
2625         } STMT_END
2626
2627 /* This gets the next character from the input, folding it if not already
2628  * folded. */
2629 #define TRIE_READ_CHAR STMT_START {                                           \
2630     wordlen++;                                                                \
2631     if ( UTF ) {                                                              \
2632         /* if it is UTF then it is either already folded, or does not need    \
2633          * folding */                                                         \
2634         uvc = valid_utf8_to_uvchr( (const U8*) uc, &len);                     \
2635     }                                                                         \
2636     else if (folder == PL_fold_latin1) {                                      \
2637         /* This folder implies Unicode rules, which in the range expressible  \
2638          *  by not UTF is the lower case, with the two exceptions, one of     \
2639          *  which should have been taken care of before calling this */       \
2640         assert(*uc != LATIN_SMALL_LETTER_SHARP_S);                            \
2641         uvc = toLOWER_L1(*uc);                                                \
2642         if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU;         \
2643         len = 1;                                                              \
2644     } else {                                                                  \
2645         /* raw data, will be folded later if needed */                        \
2646         uvc = (U32)*uc;                                                       \
2647         len = 1;                                                              \
2648     }                                                                         \
2649 } STMT_END
2650
2651
2652
2653 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
2654     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
2655         U32 ging = TRIE_LIST_LEN( state ) * 2;                  \
2656         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2657         TRIE_LIST_LEN( state ) = ging;                          \
2658     }                                                           \
2659     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
2660     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
2661     TRIE_LIST_CUR( state )++;                                   \
2662 } STMT_END
2663
2664 #define TRIE_LIST_NEW(state) STMT_START {                       \
2665     Newx( trie->states[ state ].trans.list,                     \
2666         4, reg_trie_trans_le );                                 \
2667      TRIE_LIST_CUR( state ) = 1;                                \
2668      TRIE_LIST_LEN( state ) = 4;                                \
2669 } STMT_END
2670
2671 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
2672     U16 dupe= trie->states[ state ].wordnum;                    \
2673     regnode * const noper_next = regnext( noper );              \
2674                                                                 \
2675     DEBUG_r({                                                   \
2676         /* store the word for dumping */                        \
2677         SV* tmp;                                                \
2678         if (OP(noper) != NOTHING)                               \
2679             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
2680         else                                                    \
2681             tmp = newSVpvn_utf8( "", 0, UTF );                  \
2682         av_push( trie_words, tmp );                             \
2683     });                                                         \
2684                                                                 \
2685     curword++;                                                  \
2686     trie->wordinfo[curword].prev   = 0;                         \
2687     trie->wordinfo[curword].len    = wordlen;                   \
2688     trie->wordinfo[curword].accept = state;                     \
2689                                                                 \
2690     if ( noper_next < tail ) {                                  \
2691         if (!trie->jump)                                        \
2692             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2693                                                  sizeof(U16) ); \
2694         trie->jump[curword] = (U16)(noper_next - convert);      \
2695         if (!jumper)                                            \
2696             jumper = noper_next;                                \
2697         if (!nextbranch)                                        \
2698             nextbranch= regnext(cur);                           \
2699     }                                                           \
2700                                                                 \
2701     if ( dupe ) {                                               \
2702         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
2703         /* chain, so that when the bits of chain are later    */\
2704         /* linked together, the dups appear in the chain      */\
2705         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2706         trie->wordinfo[dupe].prev = curword;                    \
2707     } else {                                                    \
2708         /* we haven't inserted this word yet.                */ \
2709         trie->states[ state ].wordnum = curword;                \
2710     }                                                           \
2711 } STMT_END
2712
2713
2714 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
2715      ( ( base + charid >=  ucharcount                                   \
2716          && base + charid < ubound                                      \
2717          && state == trie->trans[ base - ucharcount + charid ].check    \
2718          && trie->trans[ base - ucharcount + charid ].next )            \
2719            ? trie->trans[ base - ucharcount + charid ].next             \
2720            : ( state==1 ? special : 0 )                                 \
2721       )
2722
2723 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder)           \
2724 STMT_START {                                                \
2725     TRIE_BITMAP_SET(trie, uvc);                             \
2726     /* store the folded codepoint */                        \
2727     if ( folder )                                           \
2728         TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);           \
2729                                                             \
2730     if ( !UTF ) {                                           \
2731         /* store first byte of utf8 representation of */    \
2732         /* variant codepoints */                            \
2733         if (! UVCHR_IS_INVARIANT(uvc)) {                    \
2734             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));   \
2735         }                                                   \
2736     }                                                       \
2737 } STMT_END
2738 #define MADE_TRIE       1
2739 #define MADE_JUMP_TRIE  2
2740 #define MADE_EXACT_TRIE 4
2741
2742 STATIC I32
2743 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2744                   regnode *first, regnode *last, regnode *tail,
2745                   U32 word_count, U32 flags, U32 depth)
2746 {
2747     /* first pass, loop through and scan words */
2748     reg_trie_data *trie;
2749     HV *widecharmap = NULL;
2750     AV *revcharmap = newAV();
2751     regnode *cur;
2752     STRLEN len = 0;
2753     UV uvc = 0;
2754     U16 curword = 0;
2755     U32 next_alloc = 0;
2756     regnode *jumper = NULL;
2757     regnode *nextbranch = NULL;
2758     regnode *convert = NULL;
2759     U32 *prev_states; /* temp array mapping each state to previous one */
2760     /* we just use folder as a flag in utf8 */
2761     const U8 * folder = NULL;
2762
2763     /* in the below add_data call we are storing either 'tu' or 'tuaa'
2764      * which stands for one trie structure, one hash, optionally followed
2765      * by two arrays */
2766 #ifdef DEBUGGING
2767     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2768     AV *trie_words = NULL;
2769     /* along with revcharmap, this only used during construction but both are
2770      * useful during debugging so we store them in the struct when debugging.
2771      */
2772 #else
2773     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2774     STRLEN trie_charcount=0;
2775 #endif
2776     SV *re_trie_maxbuff;
2777     DECLARE_AND_GET_RE_DEBUG_FLAGS;
2778
2779     PERL_ARGS_ASSERT_MAKE_TRIE;
2780 #ifndef DEBUGGING
2781     PERL_UNUSED_ARG(depth);
2782 #endif
2783
2784     switch (flags) {
2785         case EXACT: case EXACT_REQ8: case EXACTL: break;
2786         case EXACTFAA:
2787         case EXACTFUP:
2788         case EXACTFU:
2789         case EXACTFLU8: folder = PL_fold_latin1; break;
2790         case EXACTF:  folder = PL_fold; break;
2791         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2792     }
2793
2794     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2795     trie->refcount = 1;
2796     trie->startstate = 1;
2797     trie->wordcount = word_count;
2798     RExC_rxi->data->data[ data_slot ] = (void*)trie;
2799     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2800     if (flags == EXACT || flags == EXACT_REQ8 || flags == EXACTL)
2801         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2802     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2803                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
2804
2805     DEBUG_r({
2806         trie_words = newAV();
2807     });
2808
2809     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD);
2810     assert(re_trie_maxbuff);
2811     if (!SvIOK(re_trie_maxbuff)) {
2812         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2813     }
2814     DEBUG_TRIE_COMPILE_r({
2815         Perl_re_indentf( aTHX_
2816           "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2817           depth+1,
2818           REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2819           REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2820     });
2821
2822    /* Find the node we are going to overwrite */
2823     if ( first == startbranch && OP( last ) != BRANCH ) {
2824         /* whole branch chain */
2825         convert = first;
2826     } else {
2827         /* branch sub-chain */
2828         convert = NEXTOPER( first );
2829     }
2830
2831     /*  -- First loop and Setup --
2832
2833        We first traverse the branches and scan each word to determine if it
2834        contains widechars, and how many unique chars there are, this is
2835        important as we have to build a table with at least as many columns as we
2836        have unique chars.
2837
2838        We use an array of integers to represent the character codes 0..255
2839        (trie->charmap) and we use a an HV* to store Unicode characters. We use
2840        the native representation of the character value as the key and IV's for
2841        the coded index.
2842
2843        *TODO* If we keep track of how many times each character is used we can
2844        remap the columns so that the table compression later on is more
2845        efficient in terms of memory by ensuring the most common value is in the
2846        middle and the least common are on the outside.  IMO this would be better
2847        than a most to least common mapping as theres a decent chance the most
2848        common letter will share a node with the least common, meaning the node
2849        will not be compressible. With a middle is most common approach the worst
2850        case is when we have the least common nodes twice.
2851
2852      */
2853
2854     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2855         regnode *noper = NEXTOPER( cur );
2856         const U8 *uc;
2857         const U8 *e;
2858         int foldlen = 0;
2859         U32 wordlen      = 0;         /* required init */
2860         STRLEN minchars = 0;
2861         STRLEN maxchars = 0;
2862         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2863                                                bitmap?*/
2864
2865         if (OP(noper) == NOTHING) {
2866             /* skip past a NOTHING at the start of an alternation
2867              * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2868              *
2869              * If the next node is not something we are supposed to process
2870              * we will just ignore it due to the condition guarding the
2871              * next block.
2872              */
2873
2874             regnode *noper_next= regnext(noper);
2875             if (noper_next < tail)
2876                 noper= noper_next;
2877         }
2878
2879         if (    noper < tail
2880             && (    OP(noper) == flags
2881                 || (flags == EXACT && OP(noper) == EXACT_REQ8)
2882                 || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
2883                                          || OP(noper) == EXACTFUP))))
2884         {
2885             uc= (U8*)STRING(noper);
2886             e= uc + STR_LEN(noper);
2887         } else {
2888             trie->minlen= 0;
2889             continue;
2890         }
2891
2892
2893         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2894             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2895                                           regardless of encoding */
2896             if (OP( noper ) == EXACTFUP) {
2897                 /* false positives are ok, so just set this */
2898                 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2899             }
2900         }
2901
2902         for ( ; uc < e ; uc += len ) {  /* Look at each char in the current
2903                                            branch */
2904             TRIE_CHARCOUNT(trie)++;
2905             TRIE_READ_CHAR;
2906
2907             /* TRIE_READ_CHAR returns the current character, or its fold if /i
2908              * is in effect.  Under /i, this character can match itself, or
2909              * anything that folds to it.  If not under /i, it can match just
2910              * itself.  Most folds are 1-1, for example k, K, and KELVIN SIGN
2911              * all fold to k, and all are single characters.   But some folds
2912              * expand to more than one character, so for example LATIN SMALL
2913              * LIGATURE FFI folds to the three character sequence 'ffi'.  If
2914              * the string beginning at 'uc' is 'ffi', it could be matched by
2915              * three characters, or just by the one ligature character. (It
2916              * could also be matched by two characters: LATIN SMALL LIGATURE FF
2917              * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2918              * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2919              * match.)  The trie needs to know the minimum and maximum number
2920              * of characters that could match so that it can use size alone to
2921              * quickly reject many match attempts.  The max is simple: it is
2922              * the number of folded characters in this branch (since a fold is
2923              * never shorter than what folds to it. */
2924
2925             maxchars++;
2926
2927             /* And the min is equal to the max if not under /i (indicated by
2928              * 'folder' being NULL), or there are no multi-character folds.  If
2929              * there is a multi-character fold, the min is incremented just
2930              * once, for the character that folds to the sequence.  Each
2931              * character in the sequence needs to be added to the list below of
2932              * characters in the trie, but we count only the first towards the
2933              * min number of characters needed.  This is done through the
2934              * variable 'foldlen', which is returned by the macros that look
2935              * for these sequences as the number of bytes the sequence
2936              * occupies.  Each time through the loop, we decrement 'foldlen' by
2937              * how many bytes the current char occupies.  Only when it reaches
2938              * 0 do we increment 'minchars' or look for another multi-character
2939              * sequence. */
2940             if (folder == NULL) {
2941                 minchars++;
2942             }
2943             else if (foldlen > 0) {
2944                 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2945             }
2946             else {
2947                 minchars++;
2948
2949                 /* See if *uc is the beginning of a multi-character fold.  If
2950                  * so, we decrement the length remaining to look at, to account
2951                  * for the current character this iteration.  (We can use 'uc'
2952                  * instead of the fold returned by TRIE_READ_CHAR because for
2953                  * non-UTF, the latin1_safe macro is smart enough to account
2954                  * for all the unfolded characters, and because for UTF, the
2955                  * string will already have been folded earlier in the
2956                  * compilation process */
2957                 if (UTF) {
2958                     if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2959                         foldlen -= UTF8SKIP(uc);
2960                     }
2961                 }
2962                 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2963                     foldlen--;
2964                 }
2965             }
2966
2967             /* The current character (and any potential folds) should be added
2968              * to the possible matching characters for this position in this
2969              * branch */
2970             if ( uvc < 256 ) {
2971                 if ( folder ) {
2972                     U8 folded= folder[ (U8) uvc ];
2973                     if ( !trie->charmap[ folded ] ) {
2974                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
2975                         TRIE_STORE_REVCHAR( folded );
2976                     }
2977                 }
2978                 if ( !trie->charmap[ uvc ] ) {
2979                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2980                     TRIE_STORE_REVCHAR( uvc );
2981                 }
2982                 if ( set_bit ) {
2983                     /* store the codepoint in the bitmap, and its folded
2984                      * equivalent. */
2985                     TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2986                     set_bit = 0; /* We've done our bit :-) */
2987                 }
2988             } else {
2989
2990                 /* XXX We could come up with the list of code points that fold
2991                  * to this using PL_utf8_foldclosures, except not for
2992                  * multi-char folds, as there may be multiple combinations
2993                  * there that could work, which needs to wait until runtime to
2994                  * resolve (The comment about LIGATURE FFI above is such an
2995                  * example */
2996
2997                 SV** svpp;
2998                 if ( !widecharmap )
2999                     widecharmap = newHV();
3000
3001                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
3002
3003                 if ( !svpp )
3004                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
3005
3006                 if ( !SvTRUE( *svpp ) ) {
3007                     sv_setiv( *svpp, ++trie->uniquecharcount );
3008                     TRIE_STORE_REVCHAR(uvc);
3009                 }
3010             }
3011         } /* end loop through characters in this branch of the trie */
3012
3013         /* We take the min and max for this branch and combine to find the min
3014          * and max for all branches processed so far */
3015         if( cur == first ) {
3016             trie->minlen = minchars;
3017             trie->maxlen = maxchars;
3018         } else if (minchars < trie->minlen) {
3019             trie->minlen = minchars;
3020         } else if (maxchars > trie->maxlen) {
3021             trie->maxlen = maxchars;
3022         }
3023     } /* end first pass */
3024     DEBUG_TRIE_COMPILE_r(
3025         Perl_re_indentf( aTHX_
3026                 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
3027                 depth+1,
3028                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
3029                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
3030                 (int)trie->minlen, (int)trie->maxlen )
3031     );
3032
3033     /*
3034         We now know what we are dealing with in terms of unique chars and
3035         string sizes so we can calculate how much memory a naive
3036         representation using a flat table  will take. If it's over a reasonable
3037         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
3038         conservative but potentially much slower representation using an array
3039         of lists.
3040
3041         At the end we convert both representations into the same compressed
3042         form that will be used in regexec.c for matching with. The latter
3043         is a form that cannot be used to construct with but has memory
3044         properties similar to the list form and access properties similar
3045         to the table form making it both suitable for fast searches and
3046         small enough that its feasable to store for the duration of a program.
3047
3048         See the comment in the code where the compressed table is produced
3049         inplace from the flat tabe representation for an explanation of how
3050         the compression works.
3051
3052     */
3053
3054
3055     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
3056     prev_states[1] = 0;
3057
3058     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
3059                                                     > SvIV(re_trie_maxbuff) )
3060     {
3061         /*
3062             Second Pass -- Array Of Lists Representation
3063
3064             Each state will be represented by a list of charid:state records
3065             (reg_trie_trans_le) the first such element holds the CUR and LEN
3066             points of the allocated array. (See defines above).
3067
3068             We build the initial structure using the lists, and then convert
3069             it into the compressed table form which allows faster lookups
3070             (but cant be modified once converted).
3071         */
3072
3073         STRLEN transcount = 1;
3074
3075         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using list compiler\n",
3076             depth+1));
3077
3078         trie->states = (reg_trie_state *)
3079             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3080                                   sizeof(reg_trie_state) );
3081         TRIE_LIST_NEW(1);
3082         next_alloc = 2;
3083
3084         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3085
3086             regnode *noper   = NEXTOPER( cur );
3087             U32 state        = 1;         /* required init */
3088             U16 charid       = 0;         /* sanity init */
3089             U32 wordlen      = 0;         /* required init */
3090
3091             if (OP(noper) == NOTHING) {
3092                 regnode *noper_next= regnext(noper);
3093                 if (noper_next < tail)
3094                     noper= noper_next;
3095                 /* we will undo this assignment if noper does not
3096                  * point at a trieable type in the else clause of
3097                  * the following statement. */
3098             }
3099
3100             if (    noper < tail
3101                 && (    OP(noper) == flags
3102                     || (flags == EXACT && OP(noper) == EXACT_REQ8)
3103                     || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
3104                                              || OP(noper) == EXACTFUP))))
3105             {
3106                 const U8 *uc= (U8*)STRING(noper);
3107                 const U8 *e= uc + STR_LEN(noper);
3108
3109                 for ( ; uc < e ; uc += len ) {
3110
3111                     TRIE_READ_CHAR;
3112
3113                     if ( uvc < 256 ) {
3114                         charid = trie->charmap[ uvc ];
3115                     } else {
3116                         SV** const svpp = hv_fetch( widecharmap,
3117                                                     (char*)&uvc,
3118                                                     sizeof( UV ),
3119                                                     0);
3120                         if ( !svpp ) {
3121                             charid = 0;
3122                         } else {
3123                             charid=(U16)SvIV( *svpp );
3124                         }
3125                     }
3126                     /* charid is now 0 if we dont know the char read, or
3127                      * nonzero if we do */
3128                     if ( charid ) {
3129
3130                         U16 check;
3131                         U32 newstate = 0;
3132
3133                         charid--;
3134                         if ( !trie->states[ state ].trans.list ) {
3135                             TRIE_LIST_NEW( state );
3136                         }
3137                         for ( check = 1;
3138                               check <= TRIE_LIST_USED( state );
3139                               check++ )
3140                         {
3141                             if ( TRIE_LIST_ITEM( state, check ).forid
3142                                                                     == charid )
3143                             {
3144                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3145                                 break;
3146                             }
3147                         }
3148                         if ( ! newstate ) {
3149                             newstate = next_alloc++;
3150                             prev_states[newstate] = state;
3151                             TRIE_LIST_PUSH( state, charid, newstate );
3152                             transcount++;
3153                         }
3154                         state = newstate;
3155                     } else {
3156                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3157                     }
3158                 }
3159             } else {
3160                 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3161                  * on a trieable type. So we need to reset noper back to point at the first regop
3162                  * in the branch before we call TRIE_HANDLE_WORD()
3163                 */
3164                 noper= NEXTOPER(cur);
3165             }
3166             TRIE_HANDLE_WORD(state);
3167
3168         } /* end second pass */
3169
3170         /* next alloc is the NEXT state to be allocated */
3171         trie->statecount = next_alloc;
3172         trie->states = (reg_trie_state *)
3173             PerlMemShared_realloc( trie->states,
3174                                    next_alloc
3175                                    * sizeof(reg_trie_state) );
3176
3177         /* and now dump it out before we compress it */
3178         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3179                                                          revcharmap, next_alloc,
3180                                                          depth+1)
3181         );
3182
3183         trie->trans = (reg_trie_trans *)
3184             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3185         {
3186             U32 state;
3187             U32 tp = 0;
3188             U32 zp = 0;
3189
3190
3191             for( state=1 ; state < next_alloc ; state ++ ) {
3192                 U32 base=0;
3193
3194                 /*
3195                 DEBUG_TRIE_COMPILE_MORE_r(
3196                     Perl_re_printf( aTHX_  "tp: %d zp: %d ",tp,zp)
3197                 );
3198                 */
3199
3200                 if (trie->states[state].trans.list) {
3201                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3202                     U16 maxid=minid;
3203                     U16 idx;
3204
3205                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3206                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3207                         if ( forid < minid ) {
3208                             minid=forid;
3209                         } else if ( forid > maxid ) {
3210                             maxid=forid;
3211                         }
3212                     }
3213                     if ( transcount < tp + maxid - minid + 1) {
3214                         transcount *= 2;
3215                         trie->trans = (reg_trie_trans *)
3216                             PerlMemShared_realloc( trie->trans,
3217                                                      transcount
3218                                                      * sizeof(reg_trie_trans) );
3219                         Zero( trie->trans + (transcount / 2),
3220                               transcount / 2,
3221                               reg_trie_trans );
3222                     }
3223                     base = trie->uniquecharcount + tp - minid;
3224                     if ( maxid == minid ) {
3225                         U32 set = 0;
3226                         for ( ; zp < tp ; zp++ ) {
3227                             if ( ! trie->trans[ zp ].next ) {
3228                                 base = trie->uniquecharcount + zp - minid;
3229                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3230                                                                    1).newstate;
3231                                 trie->trans[ zp ].check = state;
3232                                 set = 1;
3233                                 break;
3234                             }
3235                         }
3236                         if ( !set ) {
3237                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3238                                                                    1).newstate;
3239                             trie->trans[ tp ].check = state;
3240                             tp++;
3241                             zp = tp;
3242                         }
3243                     } else {
3244                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3245                             const U32 tid = base
3246                                            - trie->uniquecharcount
3247                                            + TRIE_LIST_ITEM( state, idx ).forid;
3248                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3249                                                                 idx ).newstate;
3250                             trie->trans[ tid ].check = state;
3251                         }
3252                         tp += ( maxid - minid + 1 );
3253                     }
3254                     Safefree(trie->states[ state ].trans.list);
3255                 }
3256                 /*
3257                 DEBUG_TRIE_COMPILE_MORE_r(
3258                     Perl_re_printf( aTHX_  " base: %d\n",base);
3259                 );
3260                 */
3261                 trie->states[ state ].trans.base=base;
3262             }
3263             trie->lasttrans = tp + 1;
3264         }
3265     } else {
3266         /*
3267            Second Pass -- Flat Table Representation.
3268
3269            we dont use the 0 slot of either trans[] or states[] so we add 1 to
3270            each.  We know that we will need Charcount+1 trans at most to store
3271            the data (one row per char at worst case) So we preallocate both
3272            structures assuming worst case.
3273
3274            We then construct the trie using only the .next slots of the entry
3275            structs.
3276
3277            We use the .check field of the first entry of the node temporarily
3278            to make compression both faster and easier by keeping track of how
3279            many non zero fields are in the node.
3280
3281            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3282            transition.
3283
3284            There are two terms at use here: state as a TRIE_NODEIDX() which is
3285            a number representing the first entry of the node, and state as a
3286            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3287            and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3288            if there are 2 entrys per node. eg:
3289
3290              A B       A B
3291           1. 2 4    1. 3 7
3292           2. 0 3    3. 0 5
3293           3. 0 0    5. 0 0
3294           4. 0 0    7. 0 0
3295
3296            The table is internally in the right hand, idx form. However as we
3297            also have to deal with the states array which is indexed by nodenum
3298            we have to use TRIE_NODENUM() to convert.
3299
3300         */
3301         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using table compiler\n",
3302             depth+1));
3303
3304         trie->trans = (reg_trie_trans *)
3305             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3306                                   * trie->uniquecharcount + 1,
3307                                   sizeof(reg_trie_trans) );
3308         trie->states = (reg_trie_state *)
3309             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3310                                   sizeof(reg_trie_state) );
3311         next_alloc = trie->uniquecharcount + 1;
3312
3313
3314         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3315
3316             regnode *noper   = NEXTOPER( cur );
3317
3318             U32 state        = 1;         /* required init */
3319
3320             U16 charid       = 0;         /* sanity init */
3321             U32 accept_state = 0;         /* sanity init */
3322
3323             U32 wordlen      = 0;         /* required init */
3324
3325             if (OP(noper) == NOTHING) {
3326                 regnode *noper_next= regnext(noper);
3327                 if (noper_next < tail)
3328                     noper= noper_next;
3329                 /* we will undo this assignment if noper does not
3330                  * point at a trieable type in the else clause of
3331                  * the following statement. */
3332             }
3333
3334             if (    noper < tail
3335                 && (    OP(noper) == flags
3336                     || (flags == EXACT && OP(noper) == EXACT_REQ8)
3337                     || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
3338                                              || OP(noper) == EXACTFUP))))
3339             {
3340                 const U8 *uc= (U8*)STRING(noper);
3341                 const U8 *e= uc + STR_LEN(noper);
3342
3343                 for ( ; uc < e ; uc += len ) {
3344
3345                     TRIE_READ_CHAR;
3346
3347                     if ( uvc < 256 ) {
3348                         charid = trie->charmap[ uvc ];
3349                     } else {
3350                         SV* const * const svpp = hv_fetch( widecharmap,
3351                                                            (char*)&uvc,
3352                                                            sizeof( UV ),
3353                                                            0);
3354                         charid = svpp ? (U16)SvIV(*svpp) : 0;
3355                     }
3356                     if ( charid ) {
3357                         charid--;
3358                         if ( !trie->trans[ state + charid ].next ) {
3359                             trie->trans[ state + charid ].next = next_alloc;
3360                             trie->trans[ state ].check++;
3361                             prev_states[TRIE_NODENUM(next_alloc)]
3362                                     = TRIE_NODENUM(state);
3363                             next_alloc += trie->uniquecharcount;
3364                         }
3365                         state = trie->trans[ state + charid ].next;
3366                     } else {
3367                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3368                     }
3369                     /* charid is now 0 if we dont know the char read, or
3370                      * nonzero if we do */
3371                 }
3372             } else {
3373                 /* If we end up here it is because we skipped past a NOTHING, but did not end up
3374                  * on a trieable type. So we need to reset noper back to point at the first regop
3375                  * in the branch before we call TRIE_HANDLE_WORD().
3376                 */
3377                 noper= NEXTOPER(cur);
3378             }
3379             accept_state = TRIE_NODENUM( state );
3380             TRIE_HANDLE_WORD(accept_state);
3381
3382         } /* end second pass */
3383
3384         /* and now dump it out before we compress it */
3385         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3386                                                           revcharmap,
3387                                                           next_alloc, depth+1));
3388
3389         {
3390         /*
3391            * Inplace compress the table.*
3392
3393            For sparse data sets the table constructed by the trie algorithm will
3394            be mostly 0/FAIL transitions or to put it another way mostly empty.
3395            (Note that leaf nodes will not contain any transitions.)
3396
3397            This algorithm compresses the tables by eliminating most such
3398            transitions, at the cost of a modest bit of extra work during lookup:
3399
3400            - Each states[] entry contains a .base field which indicates the
3401            index in the state[] array wheres its transition data is stored.
3402
3403            - If .base is 0 there are no valid transitions from that node.
3404
3405            - If .base is nonzero then charid is added to it to find an entry in
3406            the trans array.
3407
3408            -If trans[states[state].base+charid].check!=state then the
3409            transition is taken to be a 0/Fail transition. Thus if there are fail
3410            transitions at the front of the node then the .base offset will point
3411            somewhere inside the previous nodes data (or maybe even into a node
3412            even earlier), but the .check field determines if the transition is
3413            valid.
3414
3415            XXX - wrong maybe?
3416            The following process inplace converts the table to the compressed
3417            table: We first do not compress the root node 1,and mark all its
3418            .check pointers as 1 and set its .base pointer as 1 as well. This
3419            allows us to do a DFA construction from the compressed table later,
3420            and ensures that any .base pointers we calculate later are greater
3421            than 0.
3422
3423            - We set 'pos' to indicate the first entry of the second node.
3424
3425            - We then iterate over the columns of the node, finding the first and
3426            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3427            and set the .check pointers accordingly, and advance pos
3428            appropriately and repreat for the next node. Note that when we copy
3429            the next pointers we have to convert them from the original
3430            NODEIDX form to NODENUM form as the former is not valid post
3431            compression.
3432
3433            - If a node has no transitions used we mark its base as 0 and do not
3434            advance the pos pointer.
3435
3436            - If a node only has one transition we use a second pointer into the
3437            structure to fill in allocated fail transitions from other states.
3438            This pointer is independent of the main pointer and scans forward
3439            looking for null transitions that are allocated to a state. When it
3440            finds one it writes the single transition into the "hole".  If the
3441            pointer doesnt find one the single transition is appended as normal.
3442
3443            - Once compressed we can Renew/realloc the structures to release the
3444            excess space.
3445
3446            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3447            specifically Fig 3.47 and the associated pseudocode.
3448
3449            demq
3450         */
3451         const U32 laststate = TRIE_NODENUM( next_alloc );
3452         U32 state, charid;
3453         U32 pos = 0, zp=0;
3454         trie->statecount = laststate;
3455
3456         for ( state = 1 ; state < laststate ; state++ ) {
3457             U8 flag = 0;
3458             const U32 stateidx = TRIE_NODEIDX( state );
3459             const U32 o_used = trie->trans[ stateidx ].check;
3460             U32 used = trie->trans[ stateidx ].check;
3461             trie->trans[ stateidx ].check = 0;
3462
3463             for ( charid = 0;
3464                   used && charid < trie->uniquecharcount;
3465                   charid++ )
3466             {
3467                 if ( flag || trie->trans[ stateidx + charid ].next ) {
3468                     if ( trie->trans[ stateidx + charid ].next ) {
3469                         if (o_used == 1) {
3470                             for ( ; zp < pos ; zp++ ) {
3471                                 if ( ! trie->trans[ zp ].next ) {
3472                                     break;
3473                                 }
3474                             }
3475                             trie->states[ state ].trans.base
3476                                                     = zp
3477                                                       + trie->uniquecharcount
3478                                                       - charid ;
3479                             trie->trans[ zp ].next
3480                                 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3481                                                              + charid ].next );
3482                             trie->trans[ zp ].check = state;
3483                             if ( ++zp > pos ) pos = zp;
3484                             break;
3485                         }
3486                         used--;
3487                     }
3488                     if ( !flag ) {
3489                         flag = 1;
3490                         trie->states[ state ].trans.base
3491                                        = pos + trie->uniquecharcount - charid ;
3492                     }
3493                     trie->trans[ pos ].next
3494                         = SAFE_TRIE_NODENUM(
3495                                        trie->trans[ stateidx + charid ].next );
3496                     trie->trans[ pos ].check = state;
3497                     pos++;
3498                 }
3499             }
3500         }
3501         trie->lasttrans = pos + 1;
3502         trie->states = (reg_trie_state *)
3503             PerlMemShared_realloc( trie->states, laststate
3504                                    * sizeof(reg_trie_state) );
3505         DEBUG_TRIE_COMPILE_MORE_r(
3506             Perl_re_indentf( aTHX_  "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3507                 depth+1,
3508                 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3509                        + 1 ),
3510                 (IV)next_alloc,
3511                 (IV)pos,
3512                 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3513             );
3514
3515         } /* end table compress */
3516     }
3517     DEBUG_TRIE_COMPILE_MORE_r(
3518             Perl_re_indentf( aTHX_  "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3519                 depth+1,
3520                 (UV)trie->statecount,
3521                 (UV)trie->lasttrans)
3522     );
3523     /* resize the trans array to remove unused space */
3524     trie->trans = (reg_trie_trans *)
3525         PerlMemShared_realloc( trie->trans, trie->lasttrans
3526                                * sizeof(reg_trie_trans) );
3527
3528     {   /* Modify the program and insert the new TRIE node */
3529         U8 nodetype =(U8)(flags & 0xFF);
3530         char *str=NULL;
3531
3532 #ifdef DEBUGGING
3533         regnode *optimize = NULL;
3534 #ifdef RE_TRACK_PATTERN_OFFSETS
3535
3536         U32 mjd_offset = 0;
3537         U32 mjd_nodelen = 0;
3538 #endif /* RE_TRACK_PATTERN_OFFSETS */
3539 #endif /* DEBUGGING */
3540         /*
3541            This means we convert either the first branch or the first Exact,
3542            depending on whether the thing following (in 'last') is a branch
3543            or not and whther first is the startbranch (ie is it a sub part of
3544            the alternation or is it the whole thing.)
3545            Assuming its a sub part we convert the EXACT otherwise we convert
3546            the whole branch sequence, including the first.
3547          */
3548         /* Find the node we are going to overwrite */
3549         if ( first != startbranch || OP( last ) == BRANCH ) {
3550             /* branch sub-chain */
3551             NEXT_OFF( first ) = (U16)(last - first);
3552 #ifdef RE_TRACK_PATTERN_OFFSETS
3553             DEBUG_r({
3554                 mjd_offset= Node_Offset((convert));
3555                 mjd_nodelen= Node_Length((convert));
3556             });
3557 #endif
3558             /* whole branch chain */
3559         }
3560 #ifdef RE_TRACK_PATTERN_OFFSETS
3561         else {
3562             DEBUG_r({
3563                 const  regnode *nop = NEXTOPER( convert );
3564                 mjd_offset= Node_Offset((nop));
3565                 mjd_nodelen= Node_Length((nop));
3566             });
3567         }
3568         DEBUG_OPTIMISE_r(
3569             Perl_re_indentf( aTHX_  "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3570                 depth+1,
3571                 (UV)mjd_offset, (UV)mjd_nodelen)
3572         );
3573 #endif
3574         /* But first we check to see if there is a common prefix we can
3575            split out as an EXACT and put in front of the TRIE node.  */
3576         trie->startstate= 1;
3577         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
3578             /* we want to find the first state that has more than
3579              * one transition, if that state is not the first state
3580              * then we have a common prefix which we can remove.
3581              */
3582             U32 state;
3583             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3584                 U32 ofs = 0;
3585                 I32 first_ofs = -1; /* keeps track of the ofs of the first
3586                                        transition, -1 means none */
3587                 U32 count = 0;
3588                 const U32 base = trie->states[ state ].trans.base;
3589
3590                 /* does this state terminate an alternation? */
3591                 if ( trie->states[state].wordnum )
3592                         count = 1;
3593
3594                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3595                     if ( ( base + ofs >= trie->uniquecharcount ) &&
3596                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3597                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3598                     {
3599                         if ( ++count > 1 ) {
3600                             /* we have more than one transition */
3601                             SV **tmp;
3602                             U8 *ch;
3603                             /* if this is the first state there is no common prefix
3604                              * to extract, so we can exit */
3605                             if ( state == 1 ) break;
3606                             tmp = av_fetch( revcharmap, ofs, 0);
3607                             ch = (U8*)SvPV_nolen_const( *tmp );
3608
3609                             /* if we are on count 2 then we need to initialize the
3610                              * bitmap, and store the previous char if there was one
3611                              * in it*/
3612                             if ( count == 2 ) {
3613                                 /* clear the bitmap */
3614                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3615                                 DEBUG_OPTIMISE_r(
3616                                     Perl_re_indentf( aTHX_  "New Start State=%" UVuf " Class: [",
3617                                         depth+1,
3618                                         (UV)state));
3619                                 if (first_ofs >= 0) {
3620                                     SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3621                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3622
3623                                     TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3624                                     DEBUG_OPTIMISE_r(
3625                                         Perl_re_printf( aTHX_  "%s", (char*)ch)
3626                                     );
3627                                 }
3628                             }
3629                             /* store the current firstchar in the bitmap */
3630                             TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3631                             DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3632                         }
3633                         first_ofs = ofs;
3634                     }
3635                 }
3636                 if ( count == 1 ) {
3637                     /* This state has only one transition, its transition is part
3638                      * of a common prefix - we need to concatenate the char it
3639                      * represents to what we have so far. */
3640                     SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3641                     STRLEN len;
3642                     char *ch = SvPV( *tmp, len );
3643                     DEBUG_OPTIMISE_r({
3644                         SV *sv=sv_newmortal();
3645                         Perl_re_indentf( aTHX_  "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3646                             depth+1,
3647                             (UV)state, (UV)first_ofs,
3648                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3649                                 PL_colors[0], PL_colors[1],
3650                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3651                                 PERL_PV_ESCAPE_FIRSTCHAR
3652                             )
3653                         );
3654                     });
3655                     if ( state==1 ) {
3656                         OP( convert ) = nodetype;
3657                         str=STRING(convert);
3658                         setSTR_LEN(convert, 0);
3659                     }
3660                     assert( ( STR_LEN(convert) + len ) < 256 );
3661                     setSTR_LEN(convert, (U8)(STR_LEN(convert) + len));
3662                     while (len--)
3663                         *str++ = *ch++;
3664                 } else {
3665 #ifdef DEBUGGING
3666                     if (state>1)
3667                         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3668 #endif
3669                     break;
3670                 }
3671             }
3672             trie->prefixlen = (state-1);
3673             if (str) {
3674                 regnode *n = convert+NODE_SZ_STR(convert);
3675                 assert( NODE_SZ_STR(convert) <= U16_MAX );
3676                 NEXT_OFF(convert) = (U16)(NODE_SZ_STR(convert));
3677                 trie->startstate = state;
3678                 trie->minlen -= (state - 1);
3679                 trie->maxlen -= (state - 1);
3680 #ifdef DEBUGGING
3681                /* At least the UNICOS C compiler choked on this
3682                 * being argument to DEBUG_r(), so let's just have
3683                 * it right here. */
3684                if (
3685 #ifdef PERL_EXT_RE_BUILD
3686                    1
3687 #else
3688                    DEBUG_r_TEST
3689 #endif
3690                    ) {
3691                    regnode *fix = convert;
3692                    U32 word = trie->wordcount;
3693 #ifdef RE_TRACK_PATTERN_OFFSETS
3694                    mjd_nodelen++;
3695 #endif
3696                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3697                    while( ++fix < n ) {
3698                        Set_Node_Offset_Length(fix, 0, 0);
3699                    }
3700                    while (word--) {
3701                        SV ** const tmp = av_fetch( trie_words, word, 0 );
3702                        if (tmp) {
3703                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
3704                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3705                            else
3706                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3707                        }
3708                    }
3709                }
3710 #endif
3711                 if (trie->maxlen) {
3712                     convert = n;
3713                 } else {
3714                     NEXT_OFF(convert) = (U16)(tail - convert);
3715                     DEBUG_r(optimize= n);
3716                 }
3717             }
3718         }
3719         if (!jumper)
3720             jumper = last;
3721         if ( trie->maxlen ) {
3722             NEXT_OFF( convert ) = (U16)(tail - convert);
3723             ARG_SET( convert, data_slot );
3724             /* Store the offset to the first unabsorbed branch in
3725                jump[0], which is otherwise unused by the jump logic.
3726                We use this when dumping a trie and during optimisation. */
3727             if (trie->jump)
3728                 trie->jump[0] = (U16)(nextbranch - convert);
3729
3730             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3731              *   and there is a bitmap
3732              *   and the first "jump target" node we found leaves enough room
3733              * then convert the TRIE node into a TRIEC node, with the bitmap
3734              * embedded inline in the opcode - this is hypothetically faster.
3735              */
3736             if ( !trie->states[trie->startstate].wordnum
3737                  && trie->bitmap
3738                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3739             {
3740                 OP( convert ) = TRIEC;
3741                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3742                 PerlMemShared_free(trie->bitmap);
3743                 trie->bitmap= NULL;
3744             } else
3745                 OP( convert ) = TRIE;
3746
3747             /* store the type in the flags */
3748             convert->flags = nodetype;
3749             DEBUG_r({
3750             optimize = convert
3751                       + NODE_STEP_REGNODE
3752                       + regarglen[ OP( convert ) ];
3753             });
3754             /* XXX We really should free up the resource in trie now,
3755                    as we won't use them - (which resources?) dmq */
3756         }
3757         /* needed for dumping*/
3758         DEBUG_r(if (optimize) {
3759             regnode *opt = convert;
3760
3761             while ( ++opt < optimize) {
3762                 Set_Node_Offset_Length(opt, 0, 0);
3763             }
3764             /*
3765                 Try to clean up some of the debris left after the
3766                 optimisation.
3767              */
3768             while( optimize < jumper ) {
3769                 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3770                 OP( optimize ) = OPTIMIZED;
3771                 Set_Node_Offset_Length(optimize, 0, 0);
3772                 optimize++;
3773             }
3774             Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3775         });
3776     } /* end node insert */
3777
3778     /*  Finish populating the prev field of the wordinfo array.  Walk back
3779      *  from each accept state until we find another accept state, and if
3780      *  so, point the first word's .prev field at the second word. If the
3781      *  second already has a .prev field set, stop now. This will be the
3782      *  case either if we've already processed that word's accept state,
3783      *  or that state had multiple words, and the overspill words were
3784      *  already linked up earlier.
3785      */
3786     {
3787         U16 word;
3788         U32 state;
3789         U16 prev;
3790
3791         for (word=1; word <= trie->wordcount; word++) {
3792             prev = 0;
3793             if (trie->wordinfo[word].prev)
3794                 continue;
3795             state = trie->wordinfo[word].accept;
3796             while (state) {
3797                 state = prev_states[state];
3798                 if (!state)
3799                     break;
3800                 prev = trie->states[state].wordnum;
3801                 if (prev)
3802                     break;
3803             }
3804             trie->wordinfo[word].prev = prev;
3805         }
3806         Safefree(prev_states);
3807     }
3808
3809
3810     /* and now dump out the compressed format */
3811     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3812
3813     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3814 #ifdef DEBUGGING
3815     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3816     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3817 #else
3818     SvREFCNT_dec_NN(revcharmap);
3819 #endif
3820     return trie->jump
3821            ? MADE_JUMP_TRIE
3822            : trie->startstate>1
3823              ? MADE_EXACT_TRIE
3824              : MADE_TRIE;
3825 }
3826
3827 STATIC regnode *
3828 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3829 {
3830 /* The Trie is constructed and compressed now so we can build a fail array if
3831  * it's needed
3832
3833    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3834    3.32 in the
3835    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3836    Ullman 1985/88
3837    ISBN 0-201-10088-6
3838
3839    We find the fail state for each state in the trie, this state is the longest
3840    proper suffix of the current state's 'word' that is also a proper prefix of
3841    another word in our trie. State 1 represents the word '' and is thus the
3842    default fail state. This allows the DFA not to have to restart after its
3843    tried and failed a word at a given point, it simply continues as though it
3844    had been matching the other word in the first place.
3845    Consider
3846       'abcdgu'=~/abcdefg|cdgu/
3847    When we get to 'd' we are still matching the first word, we would encounter
3848    'g' which would fail, which would bring us to the state representing 'd' in
3849    the second word where we would try 'g' and succeed, proceeding to match
3850    'cdgu'.
3851  */
3852  /* add a fail transition */
3853     const U32 trie_offset = ARG(source);
3854     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3855     U32 *q;
3856     const U32 ucharcount = trie->uniquecharcount;
3857     const U32 numstates = trie->statecount;
3858     const U32 ubound = trie->lasttrans + ucharcount;
3859     U32 q_read = 0;
3860     U32 q_write = 0;
3861     U32 charid;
3862     U32 base = trie->states[ 1 ].trans.base;
3863     U32 *fail;
3864     reg_ac_data *aho;
3865     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3866     regnode *stclass;
3867     DECLARE_AND_GET_RE_DEBUG_FLAGS;
3868
3869     PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3870     PERL_UNUSED_CONTEXT;
3871 #ifndef DEBUGGING
3872     PERL_UNUSED_ARG(depth);
3873 #endif
3874
3875     if ( OP(source) == TRIE ) {
3876         struct regnode_1 *op = (struct regnode_1 *)
3877             PerlMemShared_calloc(1, sizeof(struct regnode_1));
3878         StructCopy(source, op, struct regnode_1);
3879         stclass = (regnode *)op;
3880     } else {
3881         struct regnode_charclass *op = (struct regnode_charclass *)
3882             PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3883         StructCopy(source, op, struct regnode_charclass);
3884         stclass = (regnode *)op;
3885     }
3886     OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3887
3888     ARG_SET( stclass, data_slot );
3889     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3890     RExC_rxi->data->data[ data_slot ] = (void*)aho;
3891     aho->trie=trie_offset;
3892     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3893     Copy( trie->states, aho->states, numstates, reg_trie_state );
3894     Newx( q, numstates, U32);
3895     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3896     aho->refcount = 1;
3897     fail = aho->fail;
3898     /* initialize fail[0..1] to be 1 so that we always have
3899        a valid final fail state */
3900     fail[ 0 ] = fail[ 1 ] = 1;
3901
3902     for ( charid = 0; charid < ucharcount ; charid++ ) {
3903         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3904         if ( newstate ) {
3905             q[ q_write ] = newstate;
3906             /* set to point at the root */
3907             fail[ q[ q_write++ ] ]=1;
3908         }
3909     }
3910     while ( q_read < q_write) {
3911         const U32 cur = q[ q_read++ % numstates ];
3912         base = trie->states[ cur ].trans.base;
3913
3914         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3915             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3916             if (ch_state) {
3917                 U32 fail_state = cur;
3918                 U32 fail_base;
3919                 do {
3920                     fail_state = fail[ fail_state ];
3921                     fail_base = aho->states[ fail_state ].trans.base;
3922                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3923
3924                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3925                 fail[ ch_state ] = fail_state;
3926                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3927                 {
3928                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
3929                 }
3930                 q[ q_write++ % numstates] = ch_state;
3931             }
3932         }
3933     }
3934     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3935        when we fail in state 1, this allows us to use the
3936        charclass scan to find a valid start char. This is based on the principle
3937        that theres a good chance the string being searched contains lots of stuff
3938        that cant be a start char.
3939      */
3940     fail[ 0 ] = fail[ 1 ] = 0;
3941     DEBUG_TRIE_COMPILE_r({
3942         Perl_re_indentf( aTHX_  "Stclass Failtable (%" UVuf " states): 0",
3943                       depth, (UV)numstates
3944         );
3945         for( q_read=1; q_read<numstates; q_read++ ) {
3946             Perl_re_printf( aTHX_  ", %" UVuf, (UV)fail[q_read]);
3947         }
3948         Perl_re_printf( aTHX_  "\n");
3949     });
3950     Safefree(q);
3951     /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3952     return stclass;
3953 }
3954
3955
3956 /* The below joins as many adjacent EXACTish nodes as possible into a single
3957  * one.  The regop may be changed if the node(s) contain certain sequences that
3958  * require special handling.  The joining is only done if:
3959  * 1) there is room in the current conglomerated node to entirely contain the
3960  *    next one.
3961  * 2) they are compatible node types
3962  *
3963  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3964  * these get optimized out
3965  *
3966  * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3967  * as possible, even if that means splitting an existing node so that its first
3968  * part is moved to the preceeding node.  This would maximise the efficiency of
3969  * memEQ during matching.
3970  *
3971  * If a node is to match under /i (folded), the number of characters it matches
3972  * can be different than its character length if it contains a multi-character
3973  * fold.  *min_subtract is set to the total delta number of characters of the
3974  * input nodes.
3975  *
3976  * And *unfolded_multi_char is set to indicate whether or not the node contains
3977  * an unfolded multi-char fold.  This happens when it won't be known until
3978  * runtime whether the fold is valid or not; namely
3979  *  1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3980  *      target string being matched against turns out to be UTF-8 is that fold
3981  *      valid; or
3982  *  2) for EXACTFL nodes whose folding rules depend on the locale in force at
3983  *      runtime.
3984  * (Multi-char folds whose components are all above the Latin1 range are not
3985  * run-time locale dependent, and have already been folded by the time this
3986  * function is called.)
3987  *
3988  * This is as good a place as any to discuss the design of handling these
3989  * multi-character fold sequences.  It's been wrong in Perl for a very long
3990  * time.  There are three code points in Unicode whose multi-character folds
3991  * were long ago discovered to mess things up.  The previous designs for
3992  * dealing with these involved assigning a special node for them.  This
3993  * approach doesn't always work, as evidenced by this example:
3994  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
3995  * Both sides fold to "sss", but if the pattern is parsed to create a node that
3996  * would match just the \xDF, it won't be able to handle the case where a
3997  * successful match would have to cross the node's boundary.  The new approach
3998  * that hopefully generally solves the problem generates an EXACTFUP node
3999  * that is "sss" in this case.
4000  *
4001  * It turns out that there are problems with all multi-character folds, and not
4002  * just these three.  Now the code is general, for all such cases.  The
4003  * approach taken is:
4004  * 1)   This routine examines each EXACTFish node that could contain multi-
4005  *      character folded sequences.  Since a single character can fold into
4006  *      such a sequence, the minimum match length for this node is less than
4007  *      the number of characters in the node.  This routine returns in
4008  *      *min_subtract how many characters to subtract from the actual
4009  *      length of the string to get a real minimum match length; it is 0 if
4010  *      there are no multi-char foldeds.  This delta is used by the caller to
4011  *      adjust the min length of the match, and the delta between min and max,
4012  *      so that the optimizer doesn't reject these possibilities based on size
4013  *      constraints.
4014  *
4015  * 2)   For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
4016  *      under /u, we fold it to 'ss' in regatom(), and in this routine, after
4017  *      joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
4018  *      EXACTFU nodes.  The node type of such nodes is then changed to
4019  *      EXACTFUP, indicating it is problematic, and needs careful handling.
4020  *      (The procedures in step 1) above are sufficient to handle this case in
4021  *      UTF-8 encoded nodes.)  The reason this is problematic is that this is
4022  *      the only case where there is a possible fold length change in non-UTF-8
4023  *      patterns.  By reserving a special node type for problematic cases, the
4024  *      far more common regular EXACTFU nodes can be processed faster.
4025  *      regexec.c takes advantage of this.
4026  *
4027  *      EXACTFUP has been created as a grab-bag for (hopefully uncommon)
4028  *      problematic cases.   These all only occur when the pattern is not
4029  *      UTF-8.  In addition to the 'ss' sequence where there is a possible fold
4030  *      length change, it handles the situation where the string cannot be
4031  *      entirely folded.  The strings in an EXACTFish node are folded as much
4032  *      as possible during compilation in regcomp.c.  This saves effort in
4033  *      regex matching.  By using an EXACTFUP node when it is not possible to
4034  *      fully fold at compile time, regexec.c can know that everything in an
4035  *      EXACTFU node is folded, so folding can be skipped at runtime.  The only
4036  *      case where folding in EXACTFU nodes can't be done at compile time is
4037  *      the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8.  This
4038  *      is because its fold requires UTF-8 to represent.  Thus EXACTFUP nodes
4039  *      handle two very different cases.  Alternatively, there could have been
4040  *      a node type where there are length changes, one for unfolded, and one
4041  *      for both.  If yet another special case needed to be created, the number
4042  *      of required node types would have to go to 7.  khw figures that even
4043  *      though there are plenty of node types to spare, that the maintenance
4044  *      cost wasn't worth the small speedup of doing it that way, especially
4045  *      since he thinks the MICRO SIGN is rarely encountered in practice.
4046  *
4047  *      There are other cases where folding isn't done at compile time, but
4048  *      none of them are under /u, and hence not for EXACTFU nodes.  The folds
4049  *      in EXACTFL nodes aren't known until runtime, and vary as the locale
4050  *      changes.  Some folds in EXACTF depend on if the runtime target string
4051  *      is UTF-8 or not.  (regatom() will create an EXACTFU node even under /di
4052  *      when no fold in it depends on the UTF-8ness of the target string.)
4053  *
4054  * 3)   A problem remains for unfolded multi-char folds. (These occur when the
4055  *      validity of the fold won't be known until runtime, and so must remain
4056  *      unfolded for now.  This happens for the sharp s in EXACTF and EXACTFAA
4057  *      nodes when the pattern isn't in UTF-8.  (Note, BTW, that there cannot
4058  *      be an EXACTF node with a UTF-8 pattern.)  They also occur for various
4059  *      folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
4060  *      The reason this is a problem is that the optimizer part of regexec.c
4061  *      (probably unwittingly, in Perl_regexec_flags()) makes an assumption
4062  *      that a character in the pattern corresponds to at most a single
4063  *      character in the target string.  (And I do mean character, and not byte
4064  *      here, unlike other parts of the documentation that have never been
4065  *      updated to account for multibyte Unicode.)  Sharp s in EXACTF and
4066  *      EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
4067  *      nodes it can match "\x{17F}\x{17F}".  These, along with other ones in
4068  *      EXACTFL nodes, violate the assumption, and they are the only instances
4069  *      where it is violated.  I'm reluctant to try to change the assumption,
4070  *      as the code involved is impenetrable to me (khw), so instead the code
4071  *      here punts.  This routine examines EXACTFL nodes, and (when the pattern
4072  *      isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
4073  *      boolean indicating whether or not the node contains such a fold.  When
4074  *      it is true, the caller sets a flag that later causes the optimizer in
4075  *      this file to not set values for the floating and fixed string lengths,
4076  *      and thus avoids the optimizer code in regexec.c that makes the invalid
4077  *      assumption.  Thus, there is no optimization based on string lengths for
4078  *      EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
4079  *      EXACTF and EXACTFAA nodes that contain the sharp s.  (The reason the
4080  *      assumption is wrong only in these cases is that all other non-UTF-8
4081  *      folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
4082  *      their expanded versions.  (Again, we can't prefold sharp s to 'ss' in
4083  *      EXACTF nodes because we don't know at compile time if it actually
4084  *      matches 'ss' or not.  For EXACTF nodes it will match iff the target
4085  *      string is in UTF-8.  This is in contrast to EXACTFU nodes, where it
4086  *      always matches; and EXACTFAA where it never does.  In an EXACTFAA node
4087  *      in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
4088  *      problem; but in a non-UTF8 pattern, folding it to that above-Latin1
4089  *      string would require the pattern to be forced into UTF-8, the overhead
4090  *      of which we want to avoid.  Similarly the unfolded multi-char folds in
4091  *      EXACTFL nodes will match iff the locale at the time of match is a UTF-8
4092  *      locale.)
4093  *
4094  *      Similarly, the code that generates tries doesn't currently handle
4095  *      not-already-folded multi-char folds, and it looks like a pain to change
4096  *      that.  Therefore, trie generation of EXACTFAA nodes with the sharp s
4097  *      doesn't work.  Instead, such an EXACTFAA is turned into a new regnode,
4098  *      EXACTFAA_NO_TRIE, which the trie code knows not to handle.  Most people
4099  *      using /iaa matching will be doing so almost entirely with ASCII
4100  *      strings, so this should rarely be encountered in practice */
4101
4102 STATIC U32
4103 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
4104                    UV *min_subtract, bool *unfolded_multi_char,
4105                    U32 flags, regnode *val, U32 depth)
4106 {
4107     /* Merge several consecutive EXACTish nodes into one. */
4108
4109     regnode *n = regnext(scan);
4110     U32 stringok = 1;
4111     regnode *next = scan + NODE_SZ_STR(scan);
4112     U32 merged = 0;
4113     U32 stopnow = 0;
4114 #ifdef DEBUGGING
4115     regnode *stop = scan;
4116     DECLARE_AND_GET_RE_DEBUG_FLAGS;
4117 #else
4118     PERL_UNUSED_ARG(depth);
4119 #endif
4120
4121     PERL_ARGS_ASSERT_JOIN_EXACT;
4122 #ifndef EXPERIMENTAL_INPLACESCAN
4123     PERL_UNUSED_ARG(flags);
4124     PERL_UNUSED_ARG(val);
4125 #endif
4126     DEBUG_PEEP("join", scan, depth, 0);
4127
4128     assert(PL_regkind[OP(scan)] == EXACT);
4129
4130     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
4131      * EXACT ones that are mergeable to the current one. */
4132     while (    n
4133            && (    PL_regkind[OP(n)] == NOTHING
4134                || (stringok && PL_regkind[OP(n)] == EXACT))
4135            && NEXT_OFF(n)
4136            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
4137     {
4138
4139         if (OP(n) == TAIL || n > next)
4140             stringok = 0;
4141         if (PL_regkind[OP(n)] == NOTHING) {
4142             DEBUG_PEEP("skip:", n, depth, 0);
4143             NEXT_OFF(scan) += NEXT_OFF(n);
4144             next = n + NODE_STEP_REGNODE;
4145 #ifdef DEBUGGING
4146             if (stringok)
4147                 stop = n;
4148 #endif
4149             n = regnext(n);
4150         }
4151         else if (stringok) {
4152             const unsigned int oldl = STR_LEN(scan);
4153             regnode * const nnext = regnext(n);
4154
4155             /* XXX I (khw) kind of doubt that this works on platforms (should
4156              * Perl ever run on one) where U8_MAX is above 255 because of lots
4157              * of other assumptions */
4158             /* Don't join if the sum can't fit into a single node */
4159             if (oldl + STR_LEN(n) > U8_MAX)
4160                 break;
4161
4162             /* Joining something that requires UTF-8 with something that
4163              * doesn't, means the result requires UTF-8. */
4164             if (OP(scan) == EXACT && (OP(n) == EXACT_REQ8)) {
4165                 OP(scan) = EXACT_REQ8;
4166             }
4167             else if (OP(scan) == EXACT_REQ8 && (OP(n) == EXACT)) {
4168                 ;   /* join is compatible, no need to change OP */
4169             }
4170             else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_REQ8)) {
4171                 OP(scan) = EXACTFU_REQ8;
4172             }
4173             else if ((OP(scan) == EXACTFU_REQ8) && (OP(n) == EXACTFU)) {
4174                 ;   /* join is compatible, no need to change OP */
4175             }
4176             else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
4177                 ;   /* join is compatible, no need to change OP */
4178             }
4179             else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
4180
4181                  /* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
4182                   * which can join with EXACTFU ones.  We check for this case
4183                   * here.  These need to be resolved to either EXACTFU or
4184                   * EXACTF at joining time.  They have nothing in them that
4185                   * would forbid them from being the more desirable EXACTFU
4186                   * nodes except that they begin and/or end with a single [Ss].
4187                   * The reason this is problematic is because they could be
4188                   * joined in this loop with an adjacent node that ends and/or
4189                   * begins with [Ss] which would then form the sequence 'ss',
4190                   * which matches differently under /di than /ui, in which case
4191                   * EXACTFU can't be used.  If the 'ss' sequence doesn't get
4192                   * formed, the nodes get absorbed into any adjacent EXACTFU
4193                   * node.  And if the only adjacent node is EXACTF, they get
4194                   * absorbed into that, under the theory that a longer node is
4195                   * better than two shorter ones, even if one is EXACTFU.  Note
4196                   * that EXACTFU_REQ8 is generated only for UTF-8 patterns,
4197                   * and the EXACTFU_S_EDGE ones only for non-UTF-8.  */
4198
4199                 if (STRING(n)[STR_LEN(n)-1] == 's') {
4200
4201                     /* Here the joined node would end with 's'.  If the node
4202                      * following the combination is an EXACTF one, it's better to
4203                      * join this trailing edge 's' node with that one, leaving the
4204                      * current one in 'scan' be the more desirable EXACTFU */
4205                     if (OP(nnext) == EXACTF) {
4206                         break;
4207                     }
4208
4209                     OP(scan) = EXACTFU_S_EDGE;
4210
4211                 }   /* Otherwise, the beginning 's' of the 2nd node just
4212                        becomes an interior 's' in 'scan' */
4213             }
4214             else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
4215                 ;   /* join is compatible, no need to change OP */
4216             }
4217             else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
4218
4219                 /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
4220                  * nodes.  But the latter nodes can be also joined with EXACTFU
4221                  * ones, and that is a better outcome, so if the node following
4222                  * 'n' is EXACTFU, quit now so that those two can be joined
4223                  * later */
4224                 if (OP(nnext) == EXACTFU) {
4225                     break;
4226                 }
4227
4228                 /* The join is compatible, and the combined node will be
4229                  * EXACTF.  (These don't care if they begin or end with 's' */
4230             }
4231             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
4232                 if (   STRING(scan)[STR_LEN(scan)-1] == 's'
4233                     && STRING(n)[0] == 's')
4234                 {
4235                     /* When combined, we have the sequence 'ss', which means we
4236                      * have to remain /di */
4237                     OP(scan) = EXACTF;
4238                 }
4239             }
4240             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
4241                 if (STRING(n)[0] == 's') {
4242                     ;   /* Here the join is compatible and the combined node
4243                            starts with 's', no need to change OP */
4244                 }
4245                 else {  /* Now the trailing 's' is in the interior */
4246                     OP(scan) = EXACTFU;
4247                 }
4248             }
4249             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
4250
4251                 /* The join is compatible, and the combined node will be
4252                  * EXACTF.  (These don't care if they begin or end with 's' */
4253                 OP(scan) = EXACTF;
4254             }
4255             else if (OP(scan) != OP(n)) {
4256
4257                 /* The only other compatible joinings are the same node type */
4258                 break;
4259             }
4260
4261             DEBUG_PEEP("merg", n, depth, 0);
4262             merged++;
4263
4264             NEXT_OFF(scan) += NEXT_OFF(n);
4265             assert( ( STR_LEN(scan) + STR_LEN(n) ) < 256 );
4266             setSTR_LEN(scan, (U8)(STR_LEN(scan) + STR_LEN(n)));
4267             next = n + NODE_SZ_STR(n);
4268             /* Now we can overwrite *n : */
4269             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
4270 #ifdef DEBUGGING
4271             stop = next - 1;
4272 #endif
4273             n = nnext;
4274             if (stopnow) break;
4275         }
4276
4277 #ifdef EXPERIMENTAL_INPLACESCAN
4278         if (flags && !NEXT_OFF(n)) {
4279             DEBUG_PEEP("atch", val, depth, 0);
4280             if (reg_off_by_arg[OP(n)]) {
4281                 ARG_SET(n, val - n);
4282             }
4283             else {
4284                 NEXT_OFF(n) = val - n;
4285             }
4286             stopnow = 1;
4287         }
4288 #endif
4289     }
4290
4291     /* This temporary node can now be turned into EXACTFU, and must, as
4292      * regexec.c doesn't handle it */
4293     if (OP(scan) == EXACTFU_S_EDGE) {
4294         OP(scan) = EXACTFU;
4295     }
4296
4297     *min_subtract = 0;
4298     *unfolded_multi_char = FALSE;
4299
4300     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
4301      * can now analyze for sequences of problematic code points.  (Prior to
4302      * this final joining, sequences could have been split over boundaries, and
4303      * hence missed).  The sequences only happen in folding, hence for any
4304      * non-EXACT EXACTish node */
4305     if (OP(scan) != EXACT && OP(scan) != EXACT_REQ8 && OP(scan) != EXACTL) {
4306         U8* s0 = (U8*) STRING(scan);
4307         U8* s = s0;
4308         U8* s_end = s0 + STR_LEN(scan);
4309
4310         int total_count_delta = 0;  /* Total delta number of characters that
4311                                        multi-char folds expand to */
4312
4313         /* One pass is made over the node's string looking for all the
4314          * possibilities.  To avoid some tests in the loop, there are two main
4315          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4316          * non-UTF-8 */
4317         if (UTF) {
4318             U8* folded = NULL;
4319
4320             if (OP(scan) == EXACTFL) {
4321                 U8 *d;
4322
4323                 /* An EXACTFL node would already have been changed to another
4324                  * node type unless there is at least one character in it that
4325                  * is problematic; likely a character whose fold definition
4326                  * won't be known until runtime, and so has yet to be folded.
4327                  * For all but the UTF-8 locale, folds are 1-1 in length, but
4328                  * to handle the UTF-8 case, we need to create a temporary
4329                  * folded copy using UTF-8 locale rules in order to analyze it.
4330                  * This is because our macros that look to see if a sequence is
4331                  * a multi-char fold assume everything is folded (otherwise the
4332                  * tests in those macros would be too complicated and slow).
4333                  * Note that here, the non-problematic folds will have already
4334                  * been done, so we can just copy such characters.  We actually
4335                  * don't completely fold the EXACTFL string.  We skip the
4336                  * unfolded multi-char folds, as that would just create work
4337                  * below to figure out the size they already are */
4338
4339                 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4340                 d = folded;
4341                 while (s < s_end) {
4342                     STRLEN s_len = UTF8SKIP(s);
4343                     if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4344                         Copy(s, d, s_len, U8);
4345                         d += s_len;
4346                     }
4347                     else if (is_FOLDS_TO_MULTI_utf8(s)) {
4348                         *unfolded_multi_char = TRUE;
4349                         Copy(s, d, s_len, U8);
4350                         d += s_len;
4351                     }
4352                     else if (isASCII(*s)) {
4353                         *(d++) = toFOLD(*s);
4354                     }
4355                     else {
4356                         STRLEN len;
4357                         _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4358                         d += len;
4359                     }
4360                     s += s_len;
4361                 }
4362
4363                 /* Point the remainder of the routine to look at our temporary
4364                  * folded copy */
4365                 s = folded;
4366                 s_end = d;
4367             } /* End of creating folded copy of EXACTFL string */
4368
4369             /* Examine the string for a multi-character fold sequence.  UTF-8
4370              * patterns have all characters pre-folded by the time this code is
4371              * executed */
4372             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4373                                      length sequence we are looking for is 2 */
4374             {
4375                 int count = 0;  /* How many characters in a multi-char fold */
4376                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4377                 if (! len) {    /* Not a multi-char fold: get next char */
4378                     s += UTF8SKIP(s);
4379                     continue;
4380                 }
4381
4382                 { /* Here is a generic multi-char fold. */
4383                     U8* multi_end  = s + len;
4384
4385                     /* Count how many characters are in it.  In the case of
4386                      * /aa, no folds which contain ASCII code points are
4387                      * allowed, so check for those, and skip if found. */
4388                     if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4389                         count = utf8_length(s, multi_end);
4390                         s = multi_end;
4391                     }
4392                     else {
4393                         while (s < multi_end) {
4394                             if (isASCII(*s)) {
4395                                 s++;
4396                                 goto next_iteration;
4397                             }
4398                             else {
4399                                 s += UTF8SKIP(s);
4400                             }
4401                             count++;
4402                         }
4403                     }
4404                 }
4405
4406                 /* The delta is how long the sequence is minus 1 (1 is how long
4407                  * the character that folds to the sequence is) */
4408                 total_count_delta += count - 1;
4409               next_iteration: ;
4410             }
4411
4412             /* We created a temporary folded copy of the string in EXACTFL
4413              * nodes.  Therefore we need to be sure it doesn't go below zero,
4414              * as the real string could be shorter */
4415             if (OP(scan) == EXACTFL) {
4416                 int total_chars = utf8_length((U8*) STRING(scan),
4417                                            (U8*) STRING(scan) + STR_LEN(scan));
4418                 if (total_count_delta > total_chars) {
4419                     total_count_delta = total_chars;
4420                 }
4421             }
4422
4423             *min_subtract += total_count_delta;
4424             Safefree(folded);
4425         }
4426         else if (OP(scan) == EXACTFAA) {
4427
4428             /* Non-UTF-8 pattern, EXACTFAA node.  There can't be a multi-char
4429              * fold to the ASCII range (and there are no existing ones in the
4430              * upper latin1 range).  But, as outlined in the comments preceding
4431              * this function, we need to flag any occurrences of the sharp s.
4432              * This character forbids trie formation (because of added
4433              * complexity) */
4434 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
4435    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
4436                                       || UNICODE_DOT_DOT_VERSION > 0)
4437             while (s < s_end) {
4438                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4439                     OP(scan) = EXACTFAA_NO_TRIE;
4440                     *unfolded_multi_char = TRUE;
4441                     break;
4442                 }
4443                 s++;
4444             }
4445         }
4446         else if (OP(scan) != EXACTFAA_NO_TRIE) {
4447
4448             /* Non-UTF-8 pattern, not EXACTFAA node.  Look for the multi-char
4449              * folds that are all Latin1.  As explained in the comments
4450              * preceding this function, we look also for the sharp s in EXACTF
4451              * and EXACTFL nodes; it can be in the final position.  Otherwise
4452              * we can stop looking 1 byte earlier because have to find at least
4453              * two characters for a multi-fold */
4454             const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4455                               ? s_end
4456                               : s_end -1;
4457
4458             while (s < upper) {
4459                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4460                 if (! len) {    /* Not a multi-char fold. */
4461                     if (*s == LATIN_SMALL_LETTER_SHARP_S
4462                         && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4463                     {
4464                         *unfolded_multi_char = TRUE;
4465                     }
4466                     s++;
4467                     continue;
4468                 }
4469
4470                 if (len == 2
4471                     && isALPHA_FOLD_EQ(*s, 's')
4472                     && isALPHA_FOLD_EQ(*(s+1), 's'))
4473                 {
4474
4475                     /* EXACTF nodes need to know that the minimum length
4476                      * changed so that a sharp s in the string can match this
4477                      * ss in the pattern, but they remain EXACTF nodes, as they
4478                      * won't match this unless the target string is in UTF-8,
4479                      * which we don't know until runtime.  EXACTFL nodes can't
4480                      * transform into EXACTFU nodes */
4481                     if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4482                         OP(scan) = EXACTFUP;
4483                     }
4484                 }
4485
4486                 *min_subtract += len - 1;
4487                 s += len;
4488             }
4489 #endif
4490         }
4491     }
4492
4493 #ifdef DEBUGGING
4494     /* Allow dumping but overwriting the collection of skipped
4495      * ops and/or strings with fake optimized ops */
4496     n = scan + NODE_SZ_STR(scan);
4497     while (n <= stop) {
4498         OP(n) = OPTIMIZED;
4499         FLAGS(n) = 0;
4500         NEXT_OFF(n) = 0;
4501         n++;
4502     }
4503 #endif
4504     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4505     return stopnow;
4506 }
4507
4508 /* REx optimizer.  Converts nodes into quicker variants "in place".
4509    Finds fixed substrings.  */
4510
4511 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4512    to the position after last scanned or to NULL. */
4513
4514 #define INIT_AND_WITHP \
4515     assert(!and_withp); \
4516     Newx(and_withp, 1, regnode_ssc); \
4517     SAVEFREEPV(and_withp)
4518
4519
4520 static void
4521 S_unwind_scan_frames(pTHX_ const void *p)
4522 {
4523     scan_frame *f= (scan_frame *)p;
4524     do {
4525         scan_frame *n= f->next_frame;
4526         Safefree(f);
4527         f= n;
4528     } while (f);
4529 }
4530
4531 /* Follow the next-chain of the current node and optimize away
4532    all the NOTHINGs from it.
4533  */
4534 STATIC void
4535 S_rck_elide_nothing(pTHX_ regnode *node)
4536 {
4537     dVAR;
4538
4539     PERL_ARGS_ASSERT_RCK_ELIDE_NOTHING;
4540
4541     if (OP(node) != CURLYX) {
4542         const int max = (reg_off_by_arg[OP(node)]
4543                         ? I32_MAX
4544                           /* I32 may be smaller than U16 on CRAYs! */
4545                         : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4546         int off = (reg_off_by_arg[OP(node)] ? ARG(node) : NEXT_OFF(node));
4547         int noff;
4548         regnode *n = node;
4549
4550         /* Skip NOTHING and LONGJMP. */
4551         while (
4552             (n = regnext(n))
4553             && (
4554                 (PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4555                 || ((OP(n) == LONGJMP) && (noff = ARG(n)))
4556             )
4557             && off + noff < max
4558         ) {
4559             off += noff;
4560         }
4561         if (reg_off_by_arg[OP(node)])
4562             ARG(node) = off;
4563         else
4564             NEXT_OFF(node) = off;
4565     }
4566     return;
4567 }
4568
4569 /* the return from this sub is the minimum length that could possibly match */
4570 STATIC SSize_t
4571 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4572                         SSize_t *minlenp, SSize_t *deltap,
4573                         regnode *last,
4574                         scan_data_t *data,
4575                         I32 stopparen,
4576                         U32 recursed_depth,
4577                         regnode_ssc *and_withp,
4578                         U32 flags, U32 depth, bool was_mutate_ok)
4579                         /* scanp: Start here (read-write). */
4580                         /* deltap: Write maxlen-minlen here. */
4581                         /* last: Stop before this one. */
4582                         /* data: string data about the pattern */
4583                         /* stopparen: treat close N as END */
4584                         /* recursed: which subroutines have we recursed into */
4585                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4586 {
4587     dVAR;
4588     SSize_t final_minlen;
4589     /* There must be at least this number of characters to match */
4590     SSize_t min = 0;
4591     I32 pars = 0, code;
4592     regnode *scan = *scanp, *next;
4593     SSize_t delta = 0;
4594     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4595     int is_inf_internal = 0;            /* The studied chunk is infinite */
4596     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4597     scan_data_t data_fake;
4598     SV *re_trie_maxbuff = NULL;
4599     regnode *first_non_open = scan;
4600     SSize_t stopmin = OPTIMIZE_INFTY;
4601     scan_frame *frame = NULL;
4602     DECLARE_AND_GET_RE_DEBUG_FLAGS;
4603
4604     PERL_ARGS_ASSERT_STUDY_CHUNK;
4605     RExC_study_started= 1;
4606
4607     Zero(&data_fake, 1, scan_data_t);
4608
4609     if ( depth == 0 ) {
4610         while (first_non_open && OP(first_non_open) == OPEN)
4611             first_non_open=regnext(first_non_open);
4612     }
4613
4614
4615   fake_study_recurse:
4616     DEBUG_r(
4617         RExC_study_chunk_recursed_count++;
4618     );
4619     DEBUG_OPTIMISE_MORE_r(
4620     {
4621         Perl_re_indentf( aTHX_  "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4622             depth, (long)stopparen,
4623             (unsigned long)RExC_study_chunk_recursed_count,
4624             (unsigned long)depth, (unsigned long)recursed_depth,
4625             scan,
4626             last);
4627         if (recursed_depth) {
4628             U32 i;
4629             U32 j;
4630             for ( j = 0 ; j < recursed_depth ; j++ ) {
4631                 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4632                     if (PAREN_TEST(j, i) && (!j || !PAREN_TEST(j - 1, i))) {
4633                         Perl_re_printf( aTHX_ " %d",(int)i);
4634                         break;
4635                     }
4636                 }
4637                 if ( j + 1 < recursed_depth ) {
4638                     Perl_re_printf( aTHX_  ",");
4639                 }
4640             }
4641         }
4642         Perl_re_printf( aTHX_ "\n");
4643     }
4644     );
4645     while ( scan && OP(scan) != END && scan < last ){
4646         UV min_subtract = 0;    /* How mmany chars to subtract from the minimum
4647                                    node length to get a real minimum (because
4648                                    the folded version may be shorter) */
4649         bool unfolded_multi_char = FALSE;
4650         /* avoid mutating ops if we are anywhere within the recursed or
4651          * enframed handling for a GOSUB: the outermost level will handle it.
4652          */
4653         bool mutate_ok = was_mutate_ok && !(frame && frame->in_gosub);
4654         /* Peephole optimizer: */
4655         DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4656         DEBUG_PEEP("Peep", scan, depth, flags);
4657
4658
4659         /* The reason we do this here is that we need to deal with things like
4660          * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4661          * parsing code, as each (?:..) is handled by a different invocation of
4662          * reg() -- Yves
4663          */
4664         if (PL_regkind[OP(scan)] == EXACT
4665             && OP(scan) != LEXACT
4666             && OP(scan) != LEXACT_REQ8
4667             && mutate_ok
4668         ) {
4669             join_exact(pRExC_state, scan, &min_subtract, &unfolded_multi_char,
4670                     0, NULL, depth + 1);
4671         }
4672
4673         /* Follow the next-chain of the current node and optimize
4674            away all the NOTHINGs from it.
4675          */
4676         rck_elide_nothing(scan);
4677
4678         /* The principal pseudo-switch.  Cannot be a switch, since we look into
4679          * several different things.  */
4680         if ( OP(scan) == DEFINEP ) {
4681             SSize_t minlen = 0;
4682             SSize_t deltanext = 0;
4683             SSize_t fake_last_close = 0;
4684             I32 f = SCF_IN_DEFINE;
4685
4686             StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4687             scan = regnext(scan);
4688             assert( OP(scan) == IFTHEN );
4689             DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4690
4691             data_fake.last_closep= &fake_last_close;
4692             minlen = *minlenp;
4693             next = regnext(scan);
4694             scan = NEXTOPER(NEXTOPER(scan));
4695             DEBUG_PEEP("scan", scan, depth, flags);
4696             DEBUG_PEEP("next", next, depth, flags);
4697
4698             /* we suppose the run is continuous, last=next...
4699              * NOTE we dont use the return here! */
4700             /* DEFINEP study_chunk() recursion */
4701             (void)study_chunk(pRExC_state, &scan, &minlen,
4702                               &deltanext, next, &data_fake, stopparen,
4703                               recursed_depth, NULL, f, depth+1, mutate_ok);
4704
4705             scan = next;
4706         } else
4707         if (
4708             OP(scan) == BRANCH  ||
4709             OP(scan) == BRANCHJ ||
4710             OP(scan) == IFTHEN
4711         ) {
4712             next = regnext(scan);
4713             code = OP(scan);
4714
4715             /* The op(next)==code check below is to see if we
4716              * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4717              * IFTHEN is special as it might not appear in pairs.
4718              * Not sure whether BRANCH-BRANCHJ is possible, regardless
4719              * we dont handle it cleanly. */
4720             if (OP(next) == code || code == IFTHEN) {
4721                 /* NOTE - There is similar code to this block below for
4722                  * handling TRIE nodes on a re-study.  If you change stuff here
4723                  * check there too. */
4724                 SSize_t max1 = 0, min1 = OPTIMIZE_INFTY, num = 0;
4725                 regnode_ssc accum;
4726                 regnode * const startbranch=scan;
4727
4728                 if (flags & SCF_DO_SUBSTR) {
4729                     /* Cannot merge strings after this. */
4730                     scan_commit(pRExC_state, data, minlenp, is_inf);
4731                 }
4732
4733                 if (flags & SCF_DO_STCLASS)
4734                     ssc_init_zero(pRExC_state, &accum);
4735
4736                 while (OP(scan) == code) {
4737                     SSize_t deltanext, minnext, fake;
4738                     I32 f = 0;
4739                     regnode_ssc this_class;
4740
4741                     DEBUG_PEEP("Branch", scan, depth, flags);
4742
4743                     num++;
4744                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4745                     if (data) {
4746                         data_fake.whilem_c = data->whilem_c;
4747                         data_fake.last_closep = data->last_closep;
4748                     }
4749                     else
4750                         data_fake.last_closep = &fake;
4751
4752                     data_fake.pos_delta = delta;
4753                     next = regnext(scan);
4754
4755                     scan = NEXTOPER(scan); /* everything */
4756                     if (code != BRANCH)    /* everything but BRANCH */
4757                         scan = NEXTOPER(scan);
4758
4759                     if (flags & SCF_DO_STCLASS) {
4760                         ssc_init(pRExC_state, &this_class);
4761                         data_fake.start_class = &this_class;
4762                         f = SCF_DO_STCLASS_AND;
4763                     }
4764                     if (flags & SCF_WHILEM_VISITED_POS)
4765                         f |= SCF_WHILEM_VISITED_POS;
4766
4767                     /* we suppose the run is continuous, last=next...*/
4768                     /* recurse study_chunk() for each BRANCH in an alternation */
4769                     minnext = study_chunk(pRExC_state, &scan, minlenp,
4770                                       &deltanext, next, &data_fake, stopparen,
4771                                       recursed_depth, NULL, f, depth+1,
4772                                       mutate_ok);
4773
4774                     if (min1 > minnext)
4775                         min1 = minnext;
4776                     if (deltanext == OPTIMIZE_INFTY) {
4777                         is_inf = is_inf_internal = 1;
4778                         max1 = OPTIMIZE_INFTY;
4779                     } else if (max1 < minnext + deltanext)
4780                         max1 = minnext + deltanext;
4781                     scan = next;
4782                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4783                         pars++;
4784                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4785                         if ( stopmin > minnext)
4786                             stopmin = min + min1;
4787                         flags &= ~SCF_DO_SUBSTR;
4788                         if (data)
4789                             data->flags |= SCF_SEEN_ACCEPT;
4790                     }
4791                     if (data) {
4792                         if (data_fake.flags & SF_HAS_EVAL)
4793                             data->flags |= SF_HAS_EVAL;
4794                         data->whilem_c = data_fake.whilem_c;
4795                     }
4796                     if (flags & SCF_DO_STCLASS)
4797                         ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4798                 }
4799                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4800                     min1 = 0;
4801                 if (flags & SCF_DO_SUBSTR) {
4802                     data->pos_min += min1;
4803                     if (data->pos_delta >= OPTIMIZE_INFTY - (max1 - min1))
4804                         data->pos_delta = OPTIMIZE_INFTY;
4805                     else
4806                         data->pos_delta += max1 - min1;
4807                     if (max1 != min1 || is_inf)
4808                         data->cur_is_floating = 1;
4809                 }
4810                 min += min1;
4811                 if (delta == OPTIMIZE_INFTY
4812                  || OPTIMIZE_INFTY - delta - (max1 - min1) < 0)
4813                     delta = OPTIMIZE_INFTY;
4814                 else
4815                     delta += max1 - min1;
4816                 if (flags & SCF_DO_STCLASS_OR) {
4817                     ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4818                     if (min1) {
4819                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4820                         flags &= ~SCF_DO_STCLASS;
4821                     }
4822                 }
4823                 else if (flags & SCF_DO_STCLASS_AND) {
4824                     if (min1) {
4825                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4826                         flags &= ~SCF_DO_STCLASS;
4827                     }
4828                     else {
4829                         /* Switch to OR mode: cache the old value of
4830                          * data->start_class */
4831                         INIT_AND_WITHP;
4832                         StructCopy(data->start_class, and_withp, regnode_ssc);
4833                         flags &= ~SCF_DO_STCLASS_AND;
4834                         StructCopy(&accum, data->start_class, regnode_ssc);
4835                         flags |= SCF_DO_STCLASS_OR;
4836                     }
4837                 }
4838
4839                 if (PERL_ENABLE_TRIE_OPTIMISATION
4840                     && OP(startbranch) == BRANCH
4841                     && mutate_ok
4842                 ) {
4843                 /* demq.
4844
4845                    Assuming this was/is a branch we are dealing with: 'scan'
4846                    now points at the item that follows the branch sequence,
4847                    whatever it is. We now start at the beginning of the
4848                    sequence and look for subsequences of
4849
4850                    BRANCH->EXACT=>x1
4851                    BRANCH->EXACT=>x2
4852                    tail
4853
4854                    which would be constructed from a pattern like
4855                    /A|LIST|OF|WORDS/
4856
4857                    If we can find such a subsequence we need to turn the first
4858                    element into a trie and then add the subsequent branch exact
4859                    strings to the trie.
4860
4861                    We have two cases
4862
4863                      1. patterns where the whole set of branches can be
4864                         converted.
4865
4866                      2. patterns where only a subset can be converted.
4867
4868                    In case 1 we can replace the whole set with a single regop
4869                    for the trie. In case 2 we need to keep the start and end
4870                    branches so
4871
4872                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4873                      becomes BRANCH TRIE; BRANCH X;
4874
4875                   There is an additional case, that being where there is a
4876                   common prefix, which gets split out into an EXACT like node
4877                   preceding the TRIE node.
4878
4879                   If x(1..n)==tail then we can do a simple trie, if not we make
4880                   a "jump" trie, such that when we match the appropriate word
4881                   we "jump" to the appropriate tail node. Essentially we turn
4882                   a nested if into a case structure of sorts.
4883
4884                 */
4885
4886                     int made=0;
4887                     if (!re_trie_maxbuff) {
4888                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4889                         if (!SvIOK(re_trie_maxbuff))
4890                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4891                     }
4892                     if ( SvIV(re_trie_maxbuff)>=0  ) {
4893                         regnode *cur;
4894                         regnode *first = (regnode *)NULL;
4895                         regnode *prev = (regnode *)NULL;
4896                         regnode *tail = scan;
4897                         U8 trietype = 0;
4898                         U32 count=0;
4899
4900                         /* var tail is used because there may be a TAIL
4901                            regop in the way. Ie, the exacts will point to the
4902                            thing following the TAIL, but the last branch will
4903                            point at the TAIL. So we advance tail. If we
4904                            have nested (?:) we may have to move through several
4905                            tails.
4906                          */
4907
4908                         while ( OP( tail ) == TAIL ) {
4909                             /* this is the TAIL generated by (?:) */
4910                             tail = regnext( tail );
4911                         }
4912
4913
4914                         DEBUG_TRIE_COMPILE_r({
4915                             regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4916                             Perl_re_indentf( aTHX_  "%s %" UVuf ":%s\n",
4917                               depth+1,
4918                               "Looking for TRIE'able sequences. Tail node is ",
4919                               (UV) REGNODE_OFFSET(tail),
4920                               SvPV_nolen_const( RExC_mysv )
4921                             );
4922                         });
4923
4924                         /*
4925
4926                             Step through the branches
4927                                 cur represents each branch,
4928                                 noper is the first thing to be matched as part
4929                                       of that branch
4930                                 noper_next is the regnext() of that node.
4931
4932                             We normally handle a case like this
4933                             /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4934                             support building with NOJUMPTRIE, which restricts
4935                             the trie logic to structures like /FOO|BAR/.
4936
4937                             If noper is a trieable nodetype then the branch is
4938                             a possible optimization target. If we are building
4939                             under NOJUMPTRIE then we require that noper_next is
4940                             the same as scan (our current position in the regex
4941                             program).
4942
4943                             Once we have two or more consecutive such branches
4944                             we can create a trie of the EXACT's contents and
4945                             stitch it in place into the program.
4946
4947                             If the sequence represents all of the branches in
4948                             the alternation we replace the entire thing with a
4949                             single TRIE node.
4950
4951                             Otherwise when it is a subsequence we need to
4952                             stitch it in place and replace only the relevant
4953                             branches. This means the first branch has to remain
4954                             as it is used by the alternation logic, and its
4955                             next pointer, and needs to be repointed at the item
4956                             on the branch chain following the last branch we
4957                             have optimized away.
4958
4959                             This could be either a BRANCH, in which case the
4960                             subsequence is internal, or it could be the item
4961                             following the branch sequence in which case the
4962                             subsequence is at the end (which does not
4963                             necessarily mean the first node is the start of the
4964                             alternation).
4965
4966                             TRIE_TYPE(X) is a define which maps the optype to a
4967                             trietype.
4968
4969                                 optype          |  trietype
4970                                 ----------------+-----------
4971                                 NOTHING         | NOTHING
4972                                 EXACT           | EXACT
4973                                 EXACT_REQ8     | EXACT
4974                                 EXACTFU         | EXACTFU
4975                                 EXACTFU_REQ8   | EXACTFU
4976                                 EXACTFUP        | EXACTFU
4977                                 EXACTFAA        | EXACTFAA
4978                                 EXACTL          | EXACTL
4979                                 EXACTFLU8       | EXACTFLU8
4980
4981
4982                         */
4983 #define TRIE_TYPE(X) ( ( NOTHING == (X) )                                   \
4984                        ? NOTHING                                            \
4985                        : ( EXACT == (X) || EXACT_REQ8 == (X) )             \
4986                          ? EXACT                                            \
4987                          : (     EXACTFU == (X)                             \
4988                               || EXACTFU_REQ8 == (X)                       \
4989                               || EXACTFUP == (X) )                          \
4990                            ? EXACTFU                                        \
4991                            : ( EXACTFAA == (X) )                            \
4992                              ? EXACTFAA                                     \
4993                              : ( EXACTL == (X) )                            \
4994                                ? EXACTL                                     \
4995                                : ( EXACTFLU8 == (X) )                       \
4996                                  ? EXACTFLU8                                \
4997                                  : 0 )
4998
4999                         /* dont use tail as the end marker for this traverse */
5000                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
5001                             regnode * const noper = NEXTOPER( cur );
5002                             U8 noper_type = OP( noper );
5003                             U8 noper_trietype = TRIE_TYPE( noper_type );
5004 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
5005                             regnode * const noper_next = regnext( noper );
5006                             U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
5007                             U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
5008 #endif
5009
5010                             DEBUG_TRIE_COMPILE_r({
5011                                 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5012                                 Perl_re_indentf( aTHX_  "- %d:%s (%d)",
5013                                    depth+1,
5014                                    REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
5015
5016                                 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
5017                                 Perl_re_printf( aTHX_  " -> %d:%s",
5018                                     REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
5019
5020                                 if ( noper_next ) {
5021                                   regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
5022                                   Perl_re_printf( aTHX_ "\t=> %d:%s\t",
5023                                     REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
5024                                 }
5025                                 Perl_re_printf( aTHX_  "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
5026                                    REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5027                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
5028                                 );
5029                             });
5030
5031                             /* Is noper a trieable nodetype that can be merged
5032                              * with the current trie (if there is one)? */
5033                             if ( noper_trietype
5034                                   &&
5035                                   (
5036                                         ( noper_trietype == NOTHING )
5037                                         || ( trietype == NOTHING )
5038                                         || ( trietype == noper_trietype )
5039                                   )
5040 #ifdef NOJUMPTRIE
5041                                   && noper_next >= tail
5042 #endif
5043                                   && count < U16_MAX)
5044                             {
5045                                 /* Handle mergable triable node Either we are
5046                                  * the first node in a new trieable sequence,
5047                                  * in which case we do some bookkeeping,
5048                                  * otherwise we update the end pointer. */
5049                                 if ( !first ) {
5050                                     first = cur;
5051                                     if ( noper_trietype == NOTHING ) {
5052 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
5053                                         regnode * const noper_next = regnext( noper );
5054                                         U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
5055                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
5056 #endif
5057
5058                                         if ( noper_next_trietype ) {
5059                                             trietype = noper_next_trietype;
5060                                         } else if (noper_next_type)  {
5061                                             /* a NOTHING regop is 1 regop wide.
5062                                              * We need at least two for a trie
5063                                              * so we can't merge this in */
5064                                             first = NULL;
5065                                         }
5066                                     } else {
5067                                         trietype = noper_trietype;
5068                                     }
5069                                 } else {
5070                                     if ( trietype == NOTHING )
5071                                         trietype = noper_trietype;
5072                                     prev = cur;
5073                                 }
5074                                 if (first)
5075                                     count++;
5076                             } /* end handle mergable triable node */
5077                             else {
5078                                 /* handle unmergable node -
5079                                  * noper may either be a triable node which can
5080                                  * not be tried together with the current trie,
5081                                  * or a non triable node */
5082                                 if ( prev ) {
5083                                     /* If last is set and trietype is not
5084                                      * NOTHING then we have found at least two
5085                                      * triable branch sequences in a row of a
5086                                      * similar trietype so we can turn them
5087                                      * into a trie. If/when we allow NOTHING to
5088                                      * start a trie sequence this condition
5089                                      * will be required, and it isn't expensive
5090                                      * so we leave it in for now. */
5091                                     if ( trietype && trietype != NOTHING )
5092                                         make_trie( pRExC_state,
5093                                                 startbranch, first, cur, tail,
5094                                                 count, trietype, depth+1 );
5095                                     prev = NULL; /* note: we clear/update
5096                                                     first, trietype etc below,
5097                                                     so we dont do it here */
5098                                 }
5099                                 if ( noper_trietype
5100 #ifdef NOJUMPTRIE
5101                                      && noper_next >= tail
5102 #endif
5103                                 ){
5104                                     /* noper is triable, so we can start a new
5105                                      * trie sequence */
5106                                     count = 1;
5107                                     first = cur;
5108                                     trietype = noper_trietype;
5109                                 } else if (first) {
5110                                     /* if we already saw a first but the
5111                                      * current node is not triable then we have
5112                                      * to reset the first information. */
5113                                     count = 0;
5114                                     first = NULL;
5115                                     trietype = 0;
5116                                 }
5117                             } /* end handle unmergable node */
5118                         } /* loop over branches */
5119                         DEBUG_TRIE_COMPILE_r({
5120                             regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5121                             Perl_re_indentf( aTHX_  "- %s (%d) <SCAN FINISHED> ",
5122                               depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5123                             Perl_re_printf( aTHX_  "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
5124                                REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5125                                PL_reg_name[trietype]
5126                             );
5127
5128                         });
5129                         if ( prev && trietype ) {
5130                             if ( trietype != NOTHING ) {
5131                                 /* the last branch of the sequence was part of
5132                                  * a trie, so we have to construct it here
5133                                  * outside of the loop */
5134                                 made= make_trie( pRExC_state, startbranch,
5135                                                  first, scan, tail, count,
5136                                                  trietype, depth+1 );
5137 #ifdef TRIE_STUDY_OPT
5138                                 if ( ((made == MADE_EXACT_TRIE &&
5139                                      startbranch == first)
5140                                      || ( first_non_open == first )) &&
5141                                      depth==0 ) {
5142                                     flags |= SCF_TRIE_RESTUDY;
5143                                     if ( startbranch == first
5144                                          && scan >= tail )
5145                                     {
5146                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
5147                                     }
5148                                 }
5149 #endif
5150                             } else {
5151                                 /* at this point we know whatever we have is a
5152                                  * NOTHING sequence/branch AND if 'startbranch'
5153                                  * is 'first' then we can turn the whole thing
5154                                  * into a NOTHING
5155                                  */
5156                                 if ( startbranch == first ) {
5157                                     regnode *opt;
5158                                     /* the entire thing is a NOTHING sequence,
5159                                      * something like this: (?:|) So we can
5160                                      * turn it into a plain NOTHING op. */
5161                                     DEBUG_TRIE_COMPILE_r({
5162                                         regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5163                                         Perl_re_indentf( aTHX_  "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
5164                                           depth+1,
5165                                           SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5166
5167                                     });
5168                                     OP(startbranch)= NOTHING;
5169                                     NEXT_OFF(startbranch)= tail - startbranch;
5170                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
5171                                         OP(opt)= OPTIMIZED;
5172                                 }
5173                             }
5174                         } /* end if ( prev) */
5175                     } /* TRIE_MAXBUF is non zero */
5176                 } /* do trie */
5177
5178             }
5179             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
5180                 scan = NEXTOPER(NEXTOPER(scan));
5181             } else                      /* single branch is optimized. */
5182                 scan = NEXTOPER(scan);
5183             continue;
5184         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
5185             I32 paren = 0;
5186             regnode *start = NULL;
5187             regnode *end = NULL;
5188             U32 my_recursed_depth= recursed_depth;
5189
5190             if (OP(scan) != SUSPEND) { /* GOSUB */
5191                 /* Do setup, note this code has side effects beyond
5192                  * the rest of this block. Specifically setting
5193                  * RExC_recurse[] must happen at least once during
5194                  * study_chunk(). */
5195                 paren = ARG(scan);
5196                 RExC_recurse[ARG2L(scan)] = scan;
5197                 start = REGNODE_p(RExC_open_parens[paren]);
5198                 end   = REGNODE_p(RExC_close_parens[paren]);
5199
5200                 /* NOTE we MUST always execute the above code, even
5201                  * if we do nothing with a GOSUB */
5202                 if (
5203                     ( flags & SCF_IN_DEFINE )
5204                     ||
5205                     (
5206                         (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
5207                         &&
5208                         ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
5209                     )
5210                 ) {
5211                     /* no need to do anything here if we are in a define. */
5212                     /* or we are after some kind of infinite construct
5213                      * so we can skip recursing into this item.
5214                      * Since it is infinite we will not change the maxlen
5215                      * or delta, and if we miss something that might raise
5216                      * the minlen it will merely pessimise a little.
5217                      *
5218                      * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
5219                      * might result in a minlen of 1 and not of 4,
5220                      * but this doesn't make us mismatch, just try a bit
5221                      * harder than we should.
5222                      * */
5223                     scan= regnext(scan);
5224                     continue;
5225                 }
5226
5227                 if (
5228                     !recursed_depth
5229                     || !PAREN_TEST(recursed_depth - 1, paren)
5230                 ) {
5231                     /* it is quite possible that there are more efficient ways
5232                      * to do this. We maintain a bitmap per level of recursion
5233                      * of which patterns we have entered so we can detect if a
5234                      * pattern creates a possible infinite loop. When we
5235                      * recurse down a level we copy the previous levels bitmap
5236                      * down. When we are at recursion level 0 we zero the top
5237                      * level bitmap. It would be nice to implement a different
5238                      * more efficient way of doing this. In particular the top
5239                      * level bitmap may be unnecessary.
5240                      */
5241                     if (!recursed_depth) {
5242                         Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
5243                     } else {
5244                         Copy(PAREN_OFFSET(recursed_depth - 1),
5245                              PAREN_OFFSET(recursed_depth),
5246                              RExC_study_chunk_recursed_bytes, U8);
5247                     }
5248                     /* we havent recursed into this paren yet, so recurse into it */
5249                     DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
5250                     PAREN_SET(recursed_depth, paren);
5251                     my_recursed_depth= recursed_depth + 1;
5252                 } else {
5253                     DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
5254                     /* some form of infinite recursion, assume infinite length
5255                      * */
5256                     if (flags & SCF_DO_SUBSTR) {
5257                         scan_commit(pRExC_state, data, minlenp, is_inf);
5258                         data->cur_is_floating = 1;
5259                     }
5260                     is_inf = is_inf_internal = 1;
5261                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5262                         ssc_anything(data->start_class);
5263                     flags &= ~SCF_DO_STCLASS;
5264
5265                     start= NULL; /* reset start so we dont recurse later on. */
5266                 }
5267             } else {
5268                 paren = stopparen;
5269                 start = scan + 2;
5270                 end = regnext(scan);
5271             }
5272             if (start) {
5273                 scan_frame *newframe;
5274                 assert(end);
5275                 if (!RExC_frame_last) {
5276                     Newxz(newframe, 1, scan_frame);
5277                     SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
5278                     RExC_frame_head= newframe;
5279                     RExC_frame_count++;
5280                 } else if (!RExC_frame_last->next_frame) {
5281                     Newxz(newframe, 1, scan_frame);
5282                     RExC_frame_last->next_frame= newframe;
5283                     newframe->prev_frame= RExC_frame_last;
5284                     RExC_frame_count++;
5285                 } else {
5286                     newframe= RExC_frame_last->next_frame;
5287                 }
5288                 RExC_frame_last= newframe;
5289
5290                 newframe->next_regnode = regnext(scan);
5291                 newframe->last_regnode = last;
5292                 newframe->stopparen = stopparen;
5293                 newframe->prev_recursed_depth = recursed_depth;
5294                 newframe->this_prev_frame= frame;
5295                 newframe->in_gosub = (
5296                     (frame && frame->in_gosub) || OP(scan) == GOSUB
5297                 );
5298
5299                 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
5300                 DEBUG_PEEP("fnew", scan, depth, flags);
5301
5302                 frame = newframe;
5303                 scan =  start;
5304                 stopparen = paren;
5305                 last = end;
5306                 depth = depth + 1;
5307                 recursed_depth= my_recursed_depth;
5308
5309                 continue;
5310             }
5311         }
5312         else if (   OP(scan) == EXACT
5313                  || OP(scan) == LEXACT
5314                  || OP(scan) == EXACT_REQ8
5315                  || OP(scan) == LEXACT_REQ8
5316                  || OP(scan) == EXACTL)
5317         {
5318             SSize_t bytelen = STR_LEN(scan), charlen;
5319             UV uc;
5320             assert(bytelen);
5321             if (UTF) {
5322                 const U8 * const s = (U8*)STRING(scan);
5323                 uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
5324                 charlen = utf8_length(s, s + bytelen);
5325             } else {
5326                 uc = *((U8*)STRING(scan));
5327                 charlen = bytelen;
5328             }
5329             min += charlen;
5330             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5331                 /* The code below prefers earlier match for fixed
5332                    offset, later match for variable offset.  */
5333                 if (data->last_end == -1) { /* Update the start info. */
5334                     data->last_start_min = data->pos_min;
5335                     data->last_start_max =
5336                         is_inf ? OPTIMIZE_INFTY
5337                         : (data->pos_delta > OPTIMIZE_INFTY - data->pos_min)
5338                             ? OPTIMIZE_INFTY : data->pos_min + data->pos_delta;
5339                 }
5340                 sv_catpvn(data->last_found, STRING(scan), bytelen);
5341                 if (UTF)
5342                     SvUTF8_on(data->last_found);
5343                 {
5344                     SV * const sv = data->last_found;
5345                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5346                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5347                     if (mg && mg->mg_len >= 0)
5348                         mg->mg_len += charlen;
5349                 }
5350                 data->last_end = data->pos_min + charlen;
5351                 data->pos_min += charlen; /* As in the first entry. */
5352                 data->flags &= ~SF_BEFORE_EOL;
5353             }
5354
5355             /* ANDing the code point leaves at most it, and not in locale, and
5356              * can't match null string */
5357             if (flags & SCF_DO_STCLASS_AND) {
5358                 ssc_cp_and(data->start_class, uc);
5359                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5360                 ssc_clear_locale(data->start_class);
5361             }
5362             else if (flags & SCF_DO_STCLASS_OR) {
5363                 ssc_add_cp(data->start_class, uc);
5364                 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5365
5366                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5367                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5368             }
5369             flags &= ~SCF_DO_STCLASS;
5370         }
5371         else if (PL_regkind[OP(scan)] == EXACT) {
5372             /* But OP != EXACT!, so is EXACTFish */
5373             SSize_t bytelen = STR_LEN(scan), charlen;
5374             const U8 * s = (U8*)STRING(scan);
5375
5376             /* Replace a length 1 ASCII fold pair node with an ANYOFM node,
5377              * with the mask set to the complement of the bit that differs
5378              * between upper and lower case, and the lowest code point of the
5379              * pair (which the '&' forces) */
5380             if (     bytelen == 1
5381                 &&   isALPHA_A(*s)
5382                 &&  (         OP(scan) == EXACTFAA
5383                      || (     OP(scan) == EXACTFU
5384                          && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(*s)))
5385                 &&   mutate_ok
5386             ) {
5387                 U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
5388
5389                 OP(scan) = ANYOFM;
5390                 ARG_SET(scan, *s & mask);
5391                 FLAGS(scan) = mask;
5392                 /* we're not EXACTFish any more, so restudy */
5393                 continue;
5394             }
5395
5396             /* Search for fixed substrings supports EXACT only. */
5397             if (flags & SCF_DO_SUBSTR) {
5398                 assert(data);
5399                 scan_commit(pRExC_state, data, minlenp, is_inf);
5400             }
5401             charlen = UTF ? (SSize_t) utf8_length(s, s + bytelen) : bytelen;
5402             if (unfolded_multi_char) {
5403                 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5404             }
5405             min += charlen - min_subtract;
5406             assert (min >= 0);
5407             delta += min_subtract;
5408             if (flags & SCF_DO_SUBSTR) {
5409                 data->pos_min += charlen - min_subtract;
5410                 if (data->pos_min < 0) {
5411                     data->pos_min = 0;
5412                 }
5413                 data->pos_delta += min_subtract;
5414                 if (min_subtract) {
5415                     data->cur_is_floating = 1; /* float */
5416                 }
5417             }
5418
5419             if (flags & SCF_DO_STCLASS) {
5420                 SV* EXACTF_invlist = make_exactf_invlist(pRExC_state, scan);
5421
5422                 assert(EXACTF_invlist);
5423                 if (flags & SCF_DO_STCLASS_AND) {
5424                     if (OP(scan) != EXACTFL)
5425                         ssc_clear_locale(data->start_class);
5426                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5427                     ANYOF_POSIXL_ZERO(data->start_class);
5428                     ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5429                 }
5430                 else {  /* SCF_DO_STCLASS_OR */
5431                     ssc_union(data->start_class, EXACTF_invlist, FALSE);
5432                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5433
5434                     /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5435                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5436                 }
5437                 flags &= ~SCF_DO_STCLASS;
5438                 SvREFCNT_dec(EXACTF_invlist);
5439             }
5440         }
5441         else if (REGNODE_VARIES(OP(scan))) {
5442             SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5443             I32 fl = 0, f = flags;
5444             regnode * const oscan = scan;
5445             regnode_ssc this_class;
5446             regnode_ssc *oclass = NULL;
5447             I32 next_is_eval = 0;
5448
5449             switch (PL_regkind[OP(scan)]) {
5450             case WHILEM:                /* End of (?:...)* . */
5451                 scan = NEXTOPER(scan);
5452                 goto finish;
5453             case PLUS:
5454                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5455                     next = NEXTOPER(scan);
5456                     if (   OP(next) == EXACT
5457                         || OP(next) == LEXACT
5458                         || OP(next) == EXACT_REQ8
5459                         || OP(next) == LEXACT_REQ8
5460                         || OP(next) == EXACTL
5461                         || (flags & SCF_DO_STCLASS))
5462                     {
5463                         mincount = 1;
5464                         maxcount = REG_INFTY;
5465                         next = regnext(scan);
5466                         scan = NEXTOPER(scan);
5467                         goto do_curly;
5468                     }
5469                 }
5470                 if (flags & SCF_DO_SUBSTR)
5471                     data->pos_min++;
5472                 min++;
5473                 /* FALLTHROUGH */
5474             case STAR:
5475                 next = NEXTOPER(scan);
5476
5477                 /* This temporary node can now be turned into EXACTFU, and
5478                  * must, as regexec.c doesn't handle it */
5479                 if (OP(next) == EXACTFU_S_EDGE && mutate_ok) {
5480                     OP(next) = EXACTFU;
5481                 }
5482
5483                 if (     STR_LEN(next) == 1
5484                     &&   isALPHA_A(* STRING(next))
5485                     && (         OP(next) == EXACTFAA
5486                         || (     OP(next) == EXACTFU
5487                             && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))
5488                     &&   mutate_ok
5489                 ) {
5490                     /* These differ in just one bit */
5491                     U8 mask = ~ ('A' ^ 'a');
5492
5493                     assert(isALPHA_A(* STRING(next)));
5494
5495                     /* Then replace it by an ANYOFM node, with
5496                     * the mask set to the complement of the
5497                     * bit that differs between upper and lower
5498                     * case, and the lowest code point of the
5499                     * pair (which the '&' forces) */
5500                     OP(next) = ANYOFM;
5501                     ARG_SET(next, *STRING(next) & mask);
5502                     FLAGS(next) = mask;
5503                 }
5504
5505                 if (flags & SCF_DO_STCLASS) {
5506                     mincount = 0;
5507                     maxcount = REG_INFTY;
5508                     next = regnext(scan);
5509                     scan = NEXTOPER(scan);
5510                     goto do_curly;
5511                 }
5512                 if (flags & SCF_DO_SUBSTR) {
5513                     scan_commit(pRExC_state, data, minlenp, is_inf);
5514                     /* Cannot extend fixed substrings */
5515                     data->cur_is_floating = 1; /* float */
5516                 }
5517                 is_inf = is_inf_internal = 1;
5518                 scan = regnext(scan);
5519                 goto optimize_curly_tail;
5520             case CURLY:
5521                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5522                     && (scan->flags == stopparen))
5523                 {
5524                     mincount = 1;
5525                     maxcount = 1;
5526                 } else {
5527                     mincount = ARG1(scan);
5528                     maxcount = ARG2(scan);
5529                 }
5530                 next = regnext(scan);
5531                 if (OP(scan) == CURLYX) {
5532                     I32 lp = (data ? *(data->last_closep) : 0);
5533                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5534                 }
5535                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5536                 next_is_eval = (OP(scan) == EVAL);
5537               do_curly:
5538                 if (flags & SCF_DO_SUBSTR) {
5539                     if (mincount == 0)
5540                         scan_commit(pRExC_state, data, minlenp, is_inf);
5541                     /* Cannot extend fixed substrings */
5542                     pos_before = data->pos_min;
5543                 }
5544                 if (data) {
5545                     fl = data->flags;
5546                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5547                     if (is_inf)
5548                         data->flags |= SF_IS_INF;
5549                 }
5550                 if (flags & SCF_DO_STCLASS) {
5551                     ssc_init(pRExC_state, &this_class);
5552                     oclass = data->start_class;
5553                     data->start_class = &this_class;
5554                     f |= SCF_DO_STCLASS_AND;
5555                     f &= ~SCF_DO_STCLASS_OR;
5556                 }
5557                 /* Exclude from super-linear cache processing any {n,m}
5558                    regops for which the combination of input pos and regex
5559                    pos is not enough information to determine if a match
5560                    will be possible.
5561
5562                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
5563                    regex pos at the \s*, the prospects for a match depend not
5564                    only on the input position but also on how many (bar\s*)
5565                    repeats into the {4,8} we are. */
5566                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5567                     f &= ~SCF_WHILEM_VISITED_POS;
5568
5569                 /* This will finish on WHILEM, setting scan, or on NULL: */
5570                 /* recurse study_chunk() on loop bodies */
5571                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5572                                   last, data, stopparen, recursed_depth, NULL,
5573                                   (mincount == 0
5574                                    ? (f & ~SCF_DO_SUBSTR)
5575                                    : f)
5576                                   , depth+1, mutate_ok);
5577
5578                 if (flags & SCF_DO_STCLASS)
5579                     data->start_class = oclass;
5580                 if (mincount == 0 || minnext == 0) {
5581                     if (flags & SCF_DO_STCLASS_OR) {
5582                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5583                     }
5584                     else if (flags & SCF_DO_STCLASS_AND) {
5585                         /* Switch to OR mode: cache the old value of
5586                          * data->start_class */
5587                         INIT_AND_WITHP;
5588                         StructCopy(data->start_class, and_withp, regnode_ssc);
5589                         flags &= ~SCF_DO_STCLASS_AND;
5590                         StructCopy(&this_class, data->start_class, regnode_ssc);
5591                         flags |= SCF_DO_STCLASS_OR;
5592                         ANYOF_FLAGS(data->start_class)
5593                                                 |= SSC_MATCHES_EMPTY_STRING;
5594                     }
5595                 } else {                /* Non-zero len */
5596                     if (flags & SCF_DO_STCLASS_OR) {
5597                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5598                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5599                     }
5600                     else if (flags & SCF_DO_STCLASS_AND)
5601                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5602                     flags &= ~SCF_DO_STCLASS;
5603                 }
5604                 if (!scan)              /* It was not CURLYX, but CURLY. */
5605                     scan = next;
5606                 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5607                     /* ? quantifier ok, except for (?{ ... }) */
5608                     && (next_is_eval || !(mincount == 0 && maxcount == 1))
5609                     && (minnext == 0) && (deltanext == 0)
5610                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5611                     && maxcount <= REG_INFTY/3) /* Complement check for big
5612                                                    count */
5613                 {
5614                     _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5615                         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5616                             "Quantifier unexpected on zero-length expression "
5617                             "in regex m/%" UTF8f "/",
5618                              UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5619                                   RExC_precomp)));
5620                 }
5621
5622                 if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext )
5623                     || min >= SSize_t_MAX - minnext * mincount )
5624                 {
5625                     FAIL("Regexp out of space");
5626                 }
5627
5628                 min += minnext * mincount;
5629                 is_inf_internal |= deltanext == OPTIMIZE_INFTY
5630                          || (maxcount == REG_INFTY && minnext + deltanext > 0);
5631                 is_inf |= is_inf_internal;
5632                 if (is_inf) {
5633                     delta = OPTIMIZE_INFTY;
5634                 } else {
5635                     delta += (minnext + deltanext) * maxcount
5636                              - minnext * mincount;
5637                 }
5638                 /* Try powerful optimization CURLYX => CURLYN. */
5639                 if (  OP(oscan) == CURLYX && data
5640                       && data->flags & SF_IN_PAR
5641                       && !(data->flags & SF_HAS_EVAL)
5642                       && !deltanext && minnext == 1
5643                       && mutate_ok
5644                 ) {
5645                     /* Try to optimize to CURLYN.  */
5646                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5647                     regnode * const nxt1 = nxt;
5648 #ifdef DEBUGGING
5649                     regnode *nxt2;
5650 #endif
5651
5652                     /* Skip open. */
5653                     nxt = regnext(nxt);
5654                     if (!REGNODE_SIMPLE(OP(nxt))
5655                         && !(PL_regkind[OP(nxt)] == EXACT
5656                              && STR_LEN(nxt) == 1))
5657                         goto nogo;
5658 #ifdef DEBUGGING
5659                     nxt2 = nxt;
5660 #endif
5661                     nxt = regnext(nxt);
5662                     if (OP(nxt) != CLOSE)
5663                         goto nogo;
5664                     if (RExC_open_parens) {
5665
5666                         /*open->CURLYM*/
5667                         RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5668
5669                         /*close->while*/
5670                         RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5671                     }
5672                     /* Now we know that nxt2 is the only contents: */
5673                     oscan->flags = (U8)ARG(nxt);
5674                     OP(oscan) = CURLYN;
5675                     OP(nxt1) = NOTHING; /* was OPEN. */
5676
5677 #ifdef DEBUGGING
5678                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5679                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5680                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5681                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
5682                     OP(nxt + 1) = OPTIMIZED; /* was count. */
5683                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5684 #endif
5685                 }
5686               nogo:
5687
5688                 /* Try optimization CURLYX => CURLYM. */
5689                 if (  OP(oscan) == CURLYX && data
5690                       && !(data->flags & SF_HAS_PAR)
5691                       && !(data->flags & SF_HAS_EVAL)
5692                       && !deltanext     /* atom is fixed width */
5693                       && minnext != 0   /* CURLYM can't handle zero width */
5694                          /* Nor characters whose fold at run-time may be
5695                           * multi-character */
5696                       && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5697                       && mutate_ok
5698                 ) {
5699                     /* XXXX How to optimize if data == 0? */
5700                     /* Optimize to a simpler form.  */
5701                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5702                     regnode *nxt2;
5703
5704                     OP(oscan) = CURLYM;
5705                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5706                             && (OP(nxt2) != WHILEM))
5707                         nxt = nxt2;
5708                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
5709                     /* Need to optimize away parenths. */
5710                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5711                         /* Set the parenth number.  */
5712                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5713
5714                         oscan->flags = (U8)ARG(nxt);
5715                         if (RExC_open_parens) {
5716                              /*open->CURLYM*/
5717                             RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5718
5719                             /*close->NOTHING*/
5720                             RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5721                                                          + 1;
5722                         }
5723                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
5724                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
5725
5726 #ifdef DEBUGGING
5727                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5728                         OP(nxt + 1) = OPTIMIZED; /* was count. */
5729                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5730                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5731 #endif
5732 #if 0
5733                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
5734                             regnode *nnxt = regnext(nxt1);
5735                             if (nnxt == nxt) {
5736                                 if (reg_off_by_arg[OP(nxt1)])
5737                                     ARG_SET(nxt1, nxt2 - nxt1);
5738                                 else if (nxt2 - nxt1 < U16_MAX)
5739                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
5740                                 else
5741                                     OP(nxt) = NOTHING;  /* Cannot beautify */
5742                             }
5743                             nxt1 = nnxt;
5744                         }
5745 #endif
5746                         /* Optimize again: */
5747                         /* recurse study_chunk() on optimised CURLYX => CURLYM */
5748                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5749                                     NULL, stopparen, recursed_depth, NULL, 0,
5750                                     depth+1, mutate_ok);
5751                     }
5752                     else
5753                         oscan->flags = 0;
5754                 }
5755                 else if ((OP(oscan) == CURLYX)
5756                          && (flags & SCF_WHILEM_VISITED_POS)
5757                          /* See the comment on a similar expression above.
5758                             However, this time it's not a subexpression
5759                             we care about, but the expression itself. */
5760                          && (maxcount == REG_INFTY)
5761                          && data) {
5762                     /* This stays as CURLYX, we can put the count/of pair. */
5763                     /* Find WHILEM (as in regexec.c) */
5764                     regnode *nxt = oscan + NEXT_OFF(oscan);
5765
5766                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5767                         nxt += ARG(nxt);
5768                     nxt = PREVOPER(nxt);
5769                     if (nxt->flags & 0xf) {
5770                         /* we've already set whilem count on this node */
5771                     } else if (++data->whilem_c < 16) {
5772                         assert(data->whilem_c <= RExC_whilem_seen);
5773                         nxt->flags = (U8)(data->whilem_c
5774                             | (RExC_whilem_seen << 4)); /* On WHILEM */
5775                     }
5776                 }
5777                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5778                     pars++;
5779                 if (flags & SCF_DO_SUBSTR) {
5780                     SV *last_str = NULL;
5781                     STRLEN last_chrs = 0;
5782                     int counted = mincount != 0;
5783
5784                     if (data->last_end > 0 && mincount != 0) { /* Ends with a
5785                                                                   string. */
5786                         SSize_t b = pos_before >= data->last_start_min
5787                             ? pos_before : data->last_start_min;
5788                         STRLEN l;
5789                         const char * const s = SvPV_const(data->last_found, l);
5790                         SSize_t old = b - data->last_start_min;
5791                         assert(old >= 0);
5792
5793                         if (UTF)
5794                             old = utf8_hop_forward((U8*)s, old,
5795                                                (U8 *) SvEND(data->last_found))
5796                                 - (U8*)s;
5797                         l -= old;
5798                         /* Get the added string: */
5799                         last_str = newSVpvn_utf8(s  + old, l, UTF);
5800                         last_chrs = UTF ? utf8_length((U8*)(s + old),
5801                                             (U8*)(s + old + l)) : l;
5802                         if (deltanext == 0 && pos_before == b) {
5803                             /* What was added is a constant string */
5804                             if (mincount > 1) {
5805
5806                                 SvGROW(last_str, (mincount * l) + 1);
5807                                 repeatcpy(SvPVX(last_str) + l,
5808                                           SvPVX_const(last_str), l,
5809                                           mincount - 1);
5810                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5811                                 /* Add additional parts. */
5812                                 SvCUR_set(data->last_found,
5813                                           SvCUR(data->last_found) - l);
5814                                 sv_catsv(data->last_found, last_str);
5815                                 {
5816                                     SV * sv = data->last_found;
5817                                     MAGIC *mg =
5818                                         SvUTF8(sv) && SvMAGICAL(sv) ?
5819                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5820                                     if (mg && mg->mg_len >= 0)
5821                                         mg->mg_len += last_chrs * (mincount-1);
5822                                 }
5823                                 last_chrs *= mincount;
5824                                 data->last_end += l * (mincount - 1);
5825                             }
5826                         } else {
5827                             /* start offset must point into the last copy */
5828                             data->last_start_min += minnext * (mincount - 1);
5829                             data->last_start_max =
5830                               is_inf
5831                                ? OPTIMIZE_INFTY
5832                                : data->last_start_max +
5833                                  (maxcount - 1) * (minnext + data->pos_delta);
5834                         }
5835                     }
5836                     /* It is counted once already... */
5837                     data->pos_min += minnext * (mincount - counted);
5838 #if 0
5839 Perl_re_printf( aTHX_  "counted=%" UVuf " deltanext=%" UVuf
5840                               " OPTIMIZE_INFTY=%" UVuf " minnext=%" UVuf
5841                               " maxcount=%" UVuf " mincount=%" UVuf "\n",
5842     (UV)counted, (UV)deltanext, (UV)OPTIMIZE_INFTY, (UV)minnext, (UV)maxcount,
5843     (UV)mincount);
5844 if (deltanext != OPTIMIZE_INFTY)
5845 Perl_re_printf( aTHX_  "LHS=%" UVuf " RHS=%" UVuf "\n",
5846     (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5847           - minnext * mincount), (UV)(OPTIMIZE_INFTY - data->pos_delta));
5848 #endif
5849                     if (deltanext == OPTIMIZE_INFTY
5850                         || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= OPTIMIZE_INFTY - data->pos_delta)
5851                         data->pos_delta = OPTIMIZE_INFTY;
5852                     else
5853                         data->pos_delta += - counted * deltanext +
5854                         (minnext + deltanext) * maxcount - minnext * mincount;
5855                     if (mincount != maxcount) {
5856                          /* Cannot extend fixed substrings found inside
5857                             the group.  */
5858                         scan_commit(pRExC_state, data, minlenp, is_inf);
5859                         if (mincount && last_str) {
5860                             SV * const sv = data->last_found;
5861                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5862                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5863
5864                             if (mg)
5865                                 mg->mg_len = -1;
5866                             sv_setsv(sv, last_str);
5867                             data->last_end = data->pos_min;
5868                             data->last_start_min = data->pos_min - last_chrs;
5869                             data->last_start_max = is_inf
5870                                 ? OPTIMIZE_INFTY
5871                                 : data->pos_min + data->pos_delta - last_chrs;
5872                         }
5873                         data->cur_is_floating = 1; /* float */
5874                     }
5875                     SvREFCNT_dec(last_str);
5876                 }
5877                 if (data && (fl & SF_HAS_EVAL))
5878                     data->flags |= SF_HAS_EVAL;
5879               optimize_curly_tail:
5880                 rck_elide_nothing(oscan);
5881                 continue;
5882
5883             default:
5884                 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5885                                                                     OP(scan));
5886             case REF:
5887             case CLUMP:
5888                 if (flags & SCF_DO_SUBSTR) {
5889                     /* Cannot expect anything... */
5890                     scan_commit(pRExC_state, data, minlenp, is_inf);
5891                     data->cur_is_floating = 1; /* float */
5892                 }
5893                 is_inf = is_inf_internal = 1;
5894                 if (flags & SCF_DO_STCLASS_OR) {
5895                     if (OP(scan) == CLUMP) {
5896                         /* Actually is any start char, but very few code points
5897                          * aren't start characters */
5898                         ssc_match_all_cp(data->start_class);
5899                     }
5900                     else {
5901                         ssc_anything(data->start_class);
5902                     }
5903                 }
5904                 flags &= ~SCF_DO_STCLASS;
5905                 break;
5906             }
5907         }
5908         else if (OP(scan) == LNBREAK) {
5909             if (flags & SCF_DO_STCLASS) {
5910                 if (flags & SCF_DO_STCLASS_AND) {
5911                     ssc_intersection(data->start_class,
5912                                     PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5913                     ssc_clear_locale(data->start_class);
5914                     ANYOF_FLAGS(data->start_class)
5915                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5916                 }
5917                 else if (flags & SCF_DO_STCLASS_OR) {
5918                     ssc_union(data->start_class,
5919                               PL_XPosix_ptrs[_CC_VERTSPACE],
5920                               FALSE);
5921                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5922
5923                     /* See commit msg for
5924                      * 749e076fceedeb708a624933726e7989f2302f6a */
5925                     ANYOF_FLAGS(data->start_class)
5926                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5927                 }
5928                 flags &= ~SCF_DO_STCLASS;
5929             }
5930             min++;
5931             if (delta != OPTIMIZE_INFTY)
5932                 delta++;    /* Because of the 2 char string cr-lf */
5933             if (flags & SCF_DO_SUBSTR) {
5934                 /* Cannot expect anything... */
5935                 scan_commit(pRExC_state, data, minlenp, is_inf);
5936                 data->pos_min += 1;
5937                 if (data->pos_delta != OPTIMIZE_INFTY) {
5938                     data->pos_delta += 1;
5939                 }
5940                 data->cur_is_floating = 1; /* float */
5941             }
5942         }
5943         else if (REGNODE_SIMPLE(OP(scan))) {
5944
5945             if (flags & SCF_DO_SUBSTR) {
5946                 scan_commit(pRExC_state, data, minlenp, is_inf);
5947                 data->pos_min++;
5948             }
5949             min++;
5950             if (flags & SCF_DO_STCLASS) {
5951                 bool invert = 0;
5952                 SV* my_invlist = NULL;
5953                 U8 namedclass;
5954
5955                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5956                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5957
5958                 /* Some of the logic below assumes that switching
5959                    locale on will only add false positives. */
5960                 switch (OP(scan)) {
5961
5962                 default:
5963 #ifdef DEBUGGING
5964                    Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5965                                                                      OP(scan));
5966 #endif
5967                 case SANY:
5968                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5969                         ssc_match_all_cp(data->start_class);
5970                     break;
5971
5972                 case REG_ANY:
5973                     {
5974                         SV* REG_ANY_invlist = _new_invlist(2);
5975                         REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5976                                                             '\n');
5977                         if (flags & SCF_DO_STCLASS_OR) {
5978                             ssc_union(data->start_class,
5979                                       REG_ANY_invlist,
5980                                       TRUE /* TRUE => invert, hence all but \n
5981                                             */
5982                                       );
5983                         }
5984                         else if (flags & SCF_DO_STCLASS_AND) {
5985                             ssc_intersection(data->start_class,
5986                                              REG_ANY_invlist,
5987                                              TRUE  /* TRUE => invert */
5988                                              );
5989                             ssc_clear_locale(data->start_class);
5990                         }
5991                         SvREFCNT_dec_NN(REG_ANY_invlist);
5992                     }
5993                     break;
5994
5995                 case ANYOFD:
5996                 case ANYOFL:
5997                 case ANYOFPOSIXL:
5998                 case ANYOFH:
5999                 case ANYOFHb:
6000                 case ANYOFHr:
6001                 case ANYOFHs:
6002                 case ANYOF:
6003                     if (flags & SCF_DO_STCLASS_AND)
6004                         ssc_and(pRExC_state, data->start_class,
6005                                 (regnode_charclass *) scan);
6006                     else
6007                         ssc_or(pRExC_state, data->start_class,
6008                                                           (regnode_charclass *) scan);
6009                     break;
6010
6011                 case NANYOFM: /* NANYOFM already contains the inversion of the
6012                                  input ANYOF data, so, unlike things like
6013                                  NPOSIXA, don't change 'invert' to TRUE */
6014                     /* FALLTHROUGH */
6015                 case ANYOFM:
6016                   {
6017                     SV* cp_list = get_ANYOFM_contents(scan);
6018
6019                     if (flags & SCF_DO_STCLASS_OR) {
6020                         ssc_union(data->start_class, cp_list, invert);
6021                     }
6022                     else if (flags & SCF_DO_STCLASS_AND) {
6023                         ssc_intersection(data->start_class, cp_list, invert);
6024                     }
6025
6026                     SvREFCNT_dec_NN(cp_list);
6027                     break;
6028                   }
6029
6030                 case ANYOFR:
6031                 case ANYOFRb:
6032                   {
6033                     SV* cp_list = NULL;
6034
6035                     cp_list = _add_range_to_invlist(cp_list,
6036                                         ANYOFRbase(scan),
6037                                         ANYOFRbase(scan) + ANYOFRdelta(scan));
6038
6039                     if (flags & SCF_DO_STCLASS_OR) {
6040                         ssc_union(data->start_class, cp_list, invert);
6041                     }
6042                     else if (flags & SCF_DO_STCLASS_AND) {
6043                         ssc_intersection(data->start_class, cp_list, invert);
6044                     }
6045
6046                     SvREFCNT_dec_NN(cp_list);
6047                     break;
6048                   }
6049
6050                 case NPOSIXL:
6051                     invert = 1;
6052                     /* FALLTHROUGH */
6053
6054                 case POSIXL:
6055                     namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
6056                     if (flags & SCF_DO_STCLASS_AND) {
6057                         bool was_there = cBOOL(
6058                                           ANYOF_POSIXL_TEST(data->start_class,
6059                                                                  namedclass));
6060                         ANYOF_POSIXL_ZERO(data->start_class);
6061                         if (was_there) {    /* Do an AND */
6062                             ANYOF_POSIXL_SET(data->start_class, namedclass);
6063                         }
6064                         /* No individual code points can now match */
6065                         data->start_class->invlist
6066                                                 = sv_2mortal(_new_invlist(0));
6067                     }
6068                     else {
6069                         int complement = namedclass + ((invert) ? -1 : 1);
6070
6071                         assert(flags & SCF_DO_STCLASS_OR);
6072
6073                         /* If the complement of this class was already there,
6074                          * the result is that they match all code points,
6075                          * (\d + \D == everything).  Remove the classes from
6076                          * future consideration.  Locale is not relevant in
6077                          * this case */
6078                         if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
6079                             ssc_match_all_cp(data->start_class);
6080                             ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
6081                             ANYOF_POSIXL_CLEAR(data->start_class, complement);
6082                         }
6083                         else {  /* The usual case; just add this class to the
6084                                    existing set */
6085                             ANYOF_POSIXL_SET(data->start_class, namedclass);
6086                         }
6087                     }
6088                     break;
6089
6090                 case NPOSIXA:   /* For these, we always know the exact set of
6091                                    what's matched */
6092                     invert = 1;
6093                     /* FALLTHROUGH */
6094                 case POSIXA:
6095                     my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
6096                     goto join_posix_and_ascii;
6097
6098                 case NPOSIXD:
6099                 case NPOSIXU:
6100                     invert = 1;
6101                     /* FALLTHROUGH */
6102                 case POSIXD:
6103                 case POSIXU:
6104                     my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
6105
6106                     /* NPOSIXD matches all upper Latin1 code points unless the
6107                      * target string being matched is UTF-8, which is
6108                      * unknowable until match time.  Since we are going to
6109                      * invert, we want to get rid of all of them so that the
6110                      * inversion will match all */
6111                     if (OP(scan) == NPOSIXD) {
6112                         _invlist_subtract(my_invlist, PL_UpperLatin1,
6113                                           &my_invlist);
6114                     }
6115
6116                   join_posix_and_ascii:
6117
6118                     if (flags & SCF_DO_STCLASS_AND) {
6119                         ssc_intersection(data->start_class, my_invlist, invert);
6120                         ssc_clear_locale(data->start_class);
6121                     }
6122                     else {
6123                         assert(flags & SCF_DO_STCLASS_OR);
6124                         ssc_union(data->start_class, my_invlist, invert);
6125                     }
6126                     SvREFCNT_dec(my_invlist);
6127                 }
6128                 if (flags & SCF_DO_STCLASS_OR)
6129                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6130                 flags &= ~SCF_DO_STCLASS;
6131             }
6132         }
6133         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
6134             data->flags |= (OP(scan) == MEOL
6135                             ? SF_BEFORE_MEOL
6136                             : SF_BEFORE_SEOL);
6137             scan_commit(pRExC_state, data, minlenp, is_inf);
6138
6139         }
6140         else if (  PL_regkind[OP(scan)] == BRANCHJ
6141                  /* Lookbehind, or need to calculate parens/evals/stclass: */
6142                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
6143                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
6144         {
6145             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6146                 || OP(scan) == UNLESSM )
6147             {
6148                 /* Negative Lookahead/lookbehind
6149                    In this case we can't do fixed string optimisation.
6150                 */
6151
6152                 SSize_t deltanext, minnext, fake = 0;
6153                 regnode *nscan;
6154                 regnode_ssc intrnl;
6155                 int f = 0;
6156
6157                 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6158                 if (data) {
6159                     data_fake.whilem_c = data->whilem_c;
6160                     data_fake.last_closep = data->last_closep;
6161                 }
6162                 else
6163                     data_fake.last_closep = &fake;
6164                 data_fake.pos_delta = delta;
6165                 if ( flags & SCF_DO_STCLASS && !scan->flags
6166                      && OP(scan) == IFMATCH ) { /* Lookahead */
6167                     ssc_init(pRExC_state, &intrnl);
6168                     data_fake.start_class = &intrnl;
6169                     f |= SCF_DO_STCLASS_AND;
6170                 }
6171                 if (flags & SCF_WHILEM_VISITED_POS)
6172                     f |= SCF_WHILEM_VISITED_POS;
6173                 next = regnext(scan);
6174                 nscan = NEXTOPER(NEXTOPER(scan));
6175
6176                 /* recurse study_chunk() for lookahead body */
6177                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
6178                                       last, &data_fake, stopparen,
6179                                       recursed_depth, NULL, f, depth+1,
6180                                       mutate_ok);
6181                 if (scan->flags) {
6182                     if (   deltanext < 0
6183                         || deltanext > (I32) U8_MAX
6184                         || minnext > (I32)U8_MAX
6185                         || minnext + deltanext > (I32)U8_MAX)
6186                     {
6187                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
6188                               (UV)U8_MAX);
6189                     }
6190
6191                     /* The 'next_off' field has been repurposed to count the
6192                      * additional starting positions to try beyond the initial
6193                      * one.  (This leaves it at 0 for non-variable length
6194                      * matches to avoid breakage for those not using this
6195                      * extension) */
6196                     if (deltanext) {
6197                         scan->next_off = deltanext;
6198                         ckWARNexperimental(RExC_parse,
6199                             WARN_EXPERIMENTAL__VLB,
6200                             "Variable length lookbehind is experimental");
6201                     }
6202                     scan->flags = (U8)minnext + deltanext;
6203                 }
6204                 if (data) {
6205                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6206                         pars++;
6207                     if (data_fake.flags & SF_HAS_EVAL)
6208                         data->flags |= SF_HAS_EVAL;
6209                     data->whilem_c = data_fake.whilem_c;
6210                 }
6211                 if (f & SCF_DO_STCLASS_AND) {
6212                     if (flags & SCF_DO_STCLASS_OR) {
6213                         /* OR before, AND after: ideally we would recurse with
6214                          * data_fake to get the AND applied by study of the
6215                          * remainder of the pattern, and then derecurse;
6216                          * *** HACK *** for now just treat as "no information".
6217                          * See [perl #56690].
6218                          */
6219                         ssc_init(pRExC_state, data->start_class);
6220                     }  else {
6221                         /* AND before and after: combine and continue.  These
6222                          * assertions are zero-length, so can match an EMPTY
6223                          * string */
6224                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6225                         ANYOF_FLAGS(data->start_class)
6226                                                    |= SSC_MATCHES_EMPTY_STRING;
6227                     }
6228                 }
6229             }
6230 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6231             else {
6232                 /* Positive Lookahead/lookbehind
6233                    In this case we can do fixed string optimisation,
6234                    but we must be careful about it. Note in the case of
6235                    lookbehind the positions will be offset by the minimum
6236                    length of the pattern, something we won't know about
6237                    until after the recurse.
6238                 */
6239                 SSize_t deltanext, fake = 0;
6240                 regnode *nscan;
6241                 regnode_ssc intrnl;
6242                 int f = 0;
6243                 /* We use SAVEFREEPV so that when the full compile
6244                     is finished perl will clean up the allocated
6245                     minlens when it's all done. This way we don't
6246                     have to worry about freeing them when we know
6247                     they wont be used, which would be a pain.
6248                  */
6249                 SSize_t *minnextp;
6250                 Newx( minnextp, 1, SSize_t );
6251                 SAVEFREEPV(minnextp);
6252
6253                 if (data) {
6254                     StructCopy(data, &data_fake, scan_data_t);
6255                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
6256                         f |= SCF_DO_SUBSTR;
6257                         if (scan->flags)
6258                             scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
6259                         data_fake.last_found=newSVsv(data->last_found);
6260                     }
6261                 }
6262                 else
6263                     data_fake.last_closep = &fake;
6264                 data_fake.flags = 0;
6265                 data_fake.substrs[0].flags = 0;
6266                 data_fake.substrs[1].flags = 0;
6267                 data_fake.pos_delta = delta;
6268                 if (is_inf)
6269                     data_fake.flags |= SF_IS_INF;
6270                 if ( flags & SCF_DO_STCLASS && !scan->flags
6271                      && OP(scan) == IFMATCH ) { /* Lookahead */
6272                     ssc_init(pRExC_state, &intrnl);
6273                     data_fake.start_class = &intrnl;
6274                     f |= SCF_DO_STCLASS_AND;
6275                 }
6276                 if (flags & SCF_WHILEM_VISITED_POS)
6277                     f |= SCF_WHILEM_VISITED_POS;
6278                 next = regnext(scan);
6279                 nscan = NEXTOPER(NEXTOPER(scan));
6280
6281                 /* positive lookahead study_chunk() recursion */
6282                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
6283                                         &deltanext, last, &data_fake,
6284                                         stopparen, recursed_depth, NULL,
6285                                         f, depth+1, mutate_ok);
6286                 if (scan->flags) {
6287                     assert(0);  /* This code has never been tested since this
6288                                    is normally not compiled */
6289                     if (   deltanext < 0
6290                         || deltanext > (I32) U8_MAX
6291                         || *minnextp > (I32)U8_MAX
6292                         || *minnextp + deltanext > (I32)U8_MAX)
6293                     {
6294                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
6295                               (UV)U8_MAX);
6296                     }
6297
6298                     if (deltanext) {
6299                         scan->next_off = deltanext;
6300                     }
6301                     scan->flags = (U8)*minnextp + deltanext;
6302                 }
6303
6304                 *minnextp += min;
6305
6306                 if (f & SCF_DO_STCLASS_AND) {
6307                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6308                     ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
6309                 }
6310                 if (data) {
6311                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6312                         pars++;
6313                     if (data_fake.flags & SF_HAS_EVAL)
6314                         data->flags |= SF_HAS_EVAL;
6315                     data->whilem_c = data_fake.whilem_c;
6316                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
6317                         int i;
6318                         if (RExC_rx->minlen<*minnextp)
6319                             RExC_rx->minlen=*minnextp;
6320                         scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
6321                         SvREFCNT_dec_NN(data_fake.last_found);
6322
6323                         for (i = 0; i < 2; i++) {
6324                             if (data_fake.substrs[i].minlenp != minlenp) {
6325                                 data->substrs[i].min_offset =
6326                                             data_fake.substrs[i].min_offset;
6327                                 data->substrs[i].max_offset =
6328                                             data_fake.substrs[i].max_offset;
6329                                 data->substrs[i].minlenp =
6330                                             data_fake.substrs[i].minlenp;
6331                                 data->substrs[i].lookbehind += scan->flags;
6332                             }
6333                         }
6334                     }
6335                 }
6336             }
6337 #endif
6338         }
6339         else if (OP(scan) == OPEN) {
6340             if (stopparen != (I32)ARG(scan))
6341                 pars++;
6342         }
6343         else if (OP(scan) == CLOSE) {
6344             if (stopparen == (I32)ARG(scan)) {
6345                 break;
6346             }
6347             if ((I32)ARG(scan) == is_par) {
6348                 next = regnext(scan);
6349
6350                 if ( next && (OP(next) != WHILEM) && next < last)
6351                     is_par = 0;         /* Disable optimization */
6352             }
6353             if (data)
6354                 *(data->last_closep) = ARG(scan);
6355         }
6356         else if (OP(scan) == EVAL) {
6357                 if (data)
6358                     data->flags |= SF_HAS_EVAL;
6359         }
6360         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
6361             if (flags & SCF_DO_SUBSTR) {
6362                 scan_commit(pRExC_state, data, minlenp, is_inf);
6363                 flags &= ~SCF_DO_SUBSTR;
6364             }
6365             if (data && OP(scan)==ACCEPT) {
6366                 data->flags |= SCF_SEEN_ACCEPT;
6367                 if (stopmin > min)
6368                     stopmin = min;
6369             }
6370         }
6371         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
6372         {
6373                 if (flags & SCF_DO_SUBSTR) {
6374                     scan_commit(pRExC_state, data, minlenp, is_inf);
6375                     data->cur_is_floating = 1; /* float */
6376                 }
6377                 is_inf = is_inf_internal = 1;
6378                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
6379                     ssc_anything(data->start_class);
6380                 flags &= ~SCF_DO_STCLASS;
6381         }
6382         else if (OP(scan) == GPOS) {
6383             if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
6384                 !(delta || is_inf || (data && data->pos_delta)))
6385             {
6386                 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
6387                     RExC_rx->intflags |= PREGf_ANCH_GPOS;
6388                 if (RExC_rx->gofs < (STRLEN)min)
6389                     RExC_rx->gofs = min;
6390             } else {
6391                 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
6392                 RExC_rx->gofs = 0;
6393             }
6394         }
6395 #ifdef TRIE_STUDY_OPT
6396 #ifdef FULL_TRIE_STUDY
6397         else if (PL_regkind[OP(scan)] == TRIE) {
6398             /* NOTE - There is similar code to this block above for handling
6399                BRANCH nodes on the initial study.  If you change stuff here
6400                check there too. */
6401             regnode *trie_node= scan;
6402             regnode *tail= regnext(scan);
6403             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6404             SSize_t max1 = 0, min1 = OPTIMIZE_INFTY;
6405             regnode_ssc accum;
6406
6407             if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
6408                 /* Cannot merge strings after this. */
6409                 scan_commit(pRExC_state, data, minlenp, is_inf);
6410             }
6411             if (flags & SCF_DO_STCLASS)
6412                 ssc_init_zero(pRExC_state, &accum);
6413
6414             if (!trie->jump) {
6415                 min1= trie->minlen;
6416                 max1= trie->maxlen;
6417             } else {
6418                 const regnode *nextbranch= NULL;
6419                 U32 word;
6420
6421                 for ( word=1 ; word <= trie->wordcount ; word++)
6422                 {
6423                     SSize_t deltanext=0, minnext=0, f = 0, fake;
6424                     regnode_ssc this_class;
6425
6426                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6427                     if (data) {
6428                         data_fake.whilem_c = data->whilem_c;
6429                         data_fake.last_closep = data->last_closep;
6430                     }
6431                     else
6432                         data_fake.last_closep = &fake;
6433                     data_fake.pos_delta = delta;
6434                     if (flags & SCF_DO_STCLASS) {
6435                         ssc_init(pRExC_state, &this_class);
6436                         data_fake.start_class = &this_class;
6437                         f = SCF_DO_STCLASS_AND;
6438                     }
6439                     if (flags & SCF_WHILEM_VISITED_POS)
6440                         f |= SCF_WHILEM_VISITED_POS;
6441
6442                     if (trie->jump[word]) {
6443                         if (!nextbranch)
6444                             nextbranch = trie_node + trie->jump[0];
6445                         scan= trie_node + trie->jump[word];
6446                         /* We go from the jump point to the branch that follows
6447                            it. Note this means we need the vestigal unused
6448                            branches even though they arent otherwise used. */
6449                         /* optimise study_chunk() for TRIE */
6450                         minnext = study_chunk(pRExC_state, &scan, minlenp,
6451                             &deltanext, (regnode *)nextbranch, &data_fake,
6452                             stopparen, recursed_depth, NULL, f, depth+1,
6453                             mutate_ok);
6454                     }
6455                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6456                         nextbranch= regnext((regnode*)nextbranch);
6457
6458                     if (min1 > (SSize_t)(minnext + trie->minlen))
6459                         min1 = minnext + trie->minlen;
6460                     if (deltanext == OPTIMIZE_INFTY) {
6461                         is_inf = is_inf_internal = 1;
6462                         max1 = OPTIMIZE_INFTY;
6463                     } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6464                         max1 = minnext + deltanext + trie->maxlen;
6465
6466                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6467                         pars++;
6468                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
6469                         if ( stopmin > min + min1)
6470                             stopmin = min + min1;
6471                         flags &= ~SCF_DO_SUBSTR;
6472                         if (data)
6473                             data->flags |= SCF_SEEN_ACCEPT;
6474                     }
6475                     if (data) {
6476                         if (data_fake.flags & SF_HAS_EVAL)
6477                             data->flags |= SF_HAS_EVAL;
6478                         data->whilem_c = data_fake.whilem_c;
6479                     }
6480                     if (flags & SCF_DO_STCLASS)
6481                         ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6482                 }
6483             }
6484             if (flags & SCF_DO_SUBSTR) {
6485                 data->pos_min += min1;
6486                 data->pos_delta += max1 - min1;
6487                 if (max1 != min1 || is_inf)
6488                     data->cur_is_floating = 1; /* float */
6489             }
6490             min += min1;
6491             if (delta != OPTIMIZE_INFTY) {
6492                 if (OPTIMIZE_INFTY - (max1 - min1) >= delta)
6493                     delta += max1 - min1;
6494                 else
6495                     delta = OPTIMIZE_INFTY;
6496             }
6497             if (flags & SCF_DO_STCLASS_OR) {
6498                 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6499                 if (min1) {
6500                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6501                     flags &= ~SCF_DO_STCLASS;
6502                 }
6503             }
6504             else if (flags & SCF_DO_STCLASS_AND) {
6505                 if (min1) {
6506                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6507                     flags &= ~SCF_DO_STCLASS;
6508                 }
6509                 else {
6510                     /* Switch to OR mode: cache the old value of
6511                      * data->start_class */
6512                     INIT_AND_WITHP;
6513                     StructCopy(data->start_class, and_withp, regnode_ssc);
6514                     flags &= ~SCF_DO_STCLASS_AND;
6515                     StructCopy(&accum, data->start_class, regnode_ssc);
6516                     flags |= SCF_DO_STCLASS_OR;
6517                 }
6518             }
6519             scan= tail;
6520             continue;
6521         }
6522 #else
6523         else if (PL_regkind[OP(scan)] == TRIE) {
6524             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6525             U8*bang=NULL;
6526
6527             min += trie->minlen;
6528             delta += (trie->maxlen - trie->minlen);
6529             flags &= ~SCF_DO_STCLASS; /* xxx */
6530             if (flags & SCF_DO_SUBSTR) {
6531                 /* Cannot expect anything... */
6532                 scan_commit(pRExC_state, data, minlenp, is_inf);
6533                 data->pos_min += trie->minlen;
6534                 data->pos_delta += (trie->maxlen - trie->minlen);
6535                 if (trie->maxlen != trie->minlen)
6536                     data->cur_is_floating = 1; /* float */
6537             }
6538             if (trie->jump) /* no more substrings -- for now /grr*/
6539                flags &= ~SCF_DO_SUBSTR;
6540         }
6541         else if (OP(scan) == REGEX_SET) {
6542             Perl_croak(aTHX_ "panic: %s regnode should be resolved"
6543                              " before optimization", reg_name[REGEX_SET]);
6544         }
6545
6546 #endif /* old or new */
6547 #endif /* TRIE_STUDY_OPT */
6548
6549         /* Else: zero-length, ignore. */
6550         scan = regnext(scan);
6551     }
6552
6553   finish:
6554     if (frame) {
6555         /* we need to unwind recursion. */
6556         depth = depth - 1;
6557
6558         DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6559         DEBUG_PEEP("fend", scan, depth, flags);
6560
6561         /* restore previous context */
6562         last = frame->last_regnode;
6563         scan = frame->next_regnode;
6564         stopparen = frame->stopparen;
6565         recursed_depth = frame->prev_recursed_depth;
6566
6567         RExC_frame_last = frame->prev_frame;
6568         frame = frame->this_prev_frame;
6569         goto fake_study_recurse;
6570     }
6571
6572     assert(!frame);
6573     DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6574
6575     *scanp = scan;
6576     *deltap = is_inf_internal ? OPTIMIZE_INFTY : delta;
6577
6578     if (flags & SCF_DO_SUBSTR && is_inf)
6579         data->pos_delta = OPTIMIZE_INFTY - data->pos_min;
6580     if (is_par > (I32)U8_MAX)
6581         is_par = 0;
6582     if (is_par && pars==1 && data) {
6583         data->flags |= SF_IN_PAR;
6584         data->flags &= ~SF_HAS_PAR;
6585     }
6586     else if (pars && data) {
6587         data->flags |= SF_HAS_PAR;
6588         data->flags &= ~SF_IN_PAR;
6589     }
6590     if (flags & SCF_DO_STCLASS_OR)
6591         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6592     if (flags & SCF_TRIE_RESTUDY)
6593         data->flags |=  SCF_TRIE_RESTUDY;
6594
6595     DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6596
6597     final_minlen = min < stopmin
6598             ? min : stopmin;
6599
6600     if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6601         if (final_minlen > OPTIMIZE_INFTY - delta)
6602             RExC_maxlen = OPTIMIZE_INFTY;
6603         else if (RExC_maxlen < final_minlen + delta)
6604             RExC_maxlen = final_minlen + delta;
6605     }
6606     return final_minlen;
6607 }
6608
6609 STATIC U32
6610 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6611 {
6612     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6613
6614     PERL_ARGS_ASSERT_ADD_DATA;
6615
6616     Renewc(RExC_rxi->data,
6617            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6618            char, struct reg_data);
6619     if(count)
6620         Renew(RExC_rxi->data->what, count + n, U8);
6621     else
6622         Newx(RExC_rxi->data->what, n, U8);
6623     RExC_rxi->data->count = count + n;
6624     Copy(s, RExC_rxi->data->what + count, n, U8);
6625     return count;
6626 }
6627
6628 /*XXX: todo make this not included in a non debugging perl, but appears to be
6629  * used anyway there, in 'use re' */
6630 #ifndef PERL_IN_XSUB_RE
6631 void
6632 Perl_reginitcolors(pTHX)
6633 {
6634     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6635     if (s) {
6636         char *t = savepv(s);
6637         int i = 0;
6638         PL_colors[0] = t;
6639         while (++i < 6) {
6640             t = strchr(t, '\t');
6641             if (t) {
6642                 *t = '\0';
6643                 PL_colors[i] = ++t;
6644             }
6645             else
6646                 PL_colors[i] = t = (char *)"";
6647         }
6648     } else {
6649         int i = 0;
6650         while (i < 6)
6651             PL_colors[i++] = (char *)"";
6652     }
6653     PL_colorset = 1;
6654 }
6655 #endif
6656
6657
6658 #ifdef TRIE_STUDY_OPT
6659 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething)            \
6660     STMT_START {                                            \
6661         if (                                                \
6662               (data.flags & SCF_TRIE_RESTUDY)               \
6663               && ! restudied++                              \
6664         ) {                                                 \
6665             dOsomething;                                    \
6666             goto reStudy;                                   \
6667         }                                                   \
6668     } STMT_END
6669 #else
6670 #define CHECK_RESTUDY_GOTO_butfirst
6671 #endif
6672
6673 /*
6674  * pregcomp - compile a regular expression into internal code
6675  *
6676  * Decides which engine's compiler to call based on the hint currently in
6677  * scope
6678  */
6679
6680 #ifndef PERL_IN_XSUB_RE
6681
6682 /* return the currently in-scope regex engine (or the default if none)  */
6683
6684 regexp_engine const *
6685 Perl_current_re_engine(pTHX)
6686 {
6687     if (IN_PERL_COMPILETIME) {
6688         HV * const table = GvHV(PL_hintgv);
6689         SV **ptr;
6690
6691         if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6692             return &PL_core_reg_engine;
6693         ptr = hv_fetchs(table, "regcomp", FALSE);
6694         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6695             return &PL_core_reg_engine;
6696         return INT2PTR(regexp_engine*, SvIV(*ptr));
6697     }
6698     else {
6699         SV *ptr;
6700         if (!PL_curcop->cop_hints_hash)
6701             return &PL_core_reg_engine;
6702         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6703         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6704             return &PL_core_reg_engine;
6705         return INT2PTR(regexp_engine*, SvIV(ptr));
6706     }
6707 }
6708
6709
6710 REGEXP *
6711 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6712 {
6713     regexp_engine const *eng = current_re_engine();
6714     DECLARE_AND_GET_RE_DEBUG_FLAGS;
6715
6716     PERL_ARGS_ASSERT_PREGCOMP;
6717
6718     /* Dispatch a request to compile a regexp to correct regexp engine. */
6719     DEBUG_COMPILE_r({
6720         Perl_re_printf( aTHX_  "Using engine %" UVxf "\n",
6721                         PTR2UV(eng));
6722     });
6723     return CALLREGCOMP_ENG(eng, pattern, flags);
6724 }
6725 #endif
6726
6727 /* public(ish) entry point for the perl core's own regex compiling code.
6728  * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6729  * pattern rather than a list of OPs, and uses the internal engine rather
6730  * than the current one */
6731
6732 REGEXP *
6733 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6734 {
6735     SV *pat = pattern; /* defeat constness! */
6736
6737     PERL_ARGS_ASSERT_RE_COMPILE;
6738
6739     return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6740 #ifdef PERL_IN_XSUB_RE
6741                                 &my_reg_engine,
6742 #else
6743                                 &PL_core_reg_engine,
6744 #endif
6745                                 NULL, NULL, rx_flags, 0);
6746 }
6747
6748 static void
6749 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6750 {
6751     int n;
6752
6753     if (--cbs->refcnt > 0)
6754         return;
6755     for (n = 0; n < cbs->count; n++) {
6756         REGEXP *rx = cbs->cb[n].src_regex;
6757         if (rx) {
6758             cbs->cb[n].src_regex = NULL;
6759             SvREFCNT_dec_NN(rx);
6760         }
6761     }
6762     Safefree(cbs->cb);
6763     Safefree(cbs);
6764 }
6765
6766
6767 static struct reg_code_blocks *
6768 S_alloc_code_blocks(pTHX_  int ncode)
6769 {
6770      struct reg_code_blocks *cbs;
6771     Newx(cbs, 1, struct reg_code_blocks);
6772     cbs->count = ncode;
6773     cbs->refcnt = 1;
6774     SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6775     if (ncode)
6776         Newx(cbs->cb, ncode, struct reg_code_block);
6777     else
6778         cbs->cb = NULL;
6779     return cbs;
6780 }
6781
6782
6783 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6784  * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6785  * point to the realloced string and length.
6786  *
6787  * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6788  * stuff added */
6789
6790 static void
6791 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6792                     char **pat_p, STRLEN *plen_p, int num_code_blocks)
6793 {
6794     U8 *const src = (U8*)*pat_p;
6795     U8 *dst, *d;
6796     int n=0;
6797     STRLEN s = 0;
6798     bool do_end = 0;
6799     DECLARE_AND_GET_RE_DEBUG_FLAGS;
6800
6801     DEBUG_PARSE_r(Perl_re_printf( aTHX_
6802         "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6803
6804     /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6805     Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6806     d = dst;
6807
6808     while (s < *plen_p) {
6809         append_utf8_from_native_byte(src[s], &d);
6810
6811         if (n < num_code_blocks) {
6812             assert(pRExC_state->code_blocks);
6813             if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6814                 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6815                 assert(*(d - 1) == '(');
6816                 do_end = 1;
6817             }
6818             else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6819                 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6820                 assert(*(d - 1) == ')');
6821                 do_end = 0;
6822                 n++;
6823             }
6824         }
6825         s++;
6826     }
6827     *d = '\0';
6828     *plen_p = d - dst;
6829     *pat_p = (char*) dst;
6830     SAVEFREEPV(*pat_p);
6831     RExC_orig_utf8 = RExC_utf8 = 1;
6832 }
6833
6834
6835
6836 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6837  * while recording any code block indices, and handling overloading,
6838  * nested qr// objects etc.  If pat is null, it will allocate a new
6839  * string, or just return the first arg, if there's only one.
6840  *
6841  * Returns the malloced/updated pat.
6842  * patternp and pat_count is the array of SVs to be concatted;
6843  * oplist is the optional list of ops that generated the SVs;
6844  * recompile_p is a pointer to a boolean that will be set if
6845  *   the regex will need to be recompiled.
6846  * delim, if non-null is an SV that will be inserted between each element
6847  */
6848
6849 static SV*
6850 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6851                 SV *pat, SV ** const patternp, int pat_count,
6852                 OP *oplist, bool *recompile_p, SV *delim)
6853 {
6854     SV **svp;
6855     int n = 0;
6856     bool use_delim = FALSE;
6857     bool alloced = FALSE;
6858
6859     /* if we know we have at least two args, create an empty string,
6860      * then concatenate args to that. For no args, return an empty string */
6861     if (!pat && pat_count != 1) {
6862         pat = newSVpvs("");
6863         SAVEFREESV(pat);
6864         alloced = TRUE;
6865     }
6866
6867     for (svp = patternp; svp < patternp + pat_count; svp++) {
6868         SV *sv;
6869         SV *rx  = NULL;
6870         STRLEN orig_patlen = 0;
6871         bool code = 0;
6872         SV *msv = use_delim ? delim : *svp;
6873         if (!msv) msv = &PL_sv_undef;
6874
6875         /* if we've got a delimiter, we go round the loop twice for each
6876          * svp slot (except the last), using the delimiter the second
6877          * time round */
6878         if (use_delim) {
6879             svp--;
6880             use_delim = FALSE;
6881         }
6882         else if (delim)
6883             use_delim = TRUE;
6884
6885         if (SvTYPE(msv) == SVt_PVAV) {
6886             /* we've encountered an interpolated array within
6887              * the pattern, e.g. /...@a..../. Expand the list of elements,
6888              * then recursively append elements.
6889              * The code in this block is based on S_pushav() */
6890
6891             AV *const av = (AV*)msv;
6892             const SSize_t maxarg = AvFILL(av) + 1;
6893             SV **array;
6894
6895             if (oplist) {
6896                 assert(oplist->op_type == OP_PADAV
6897                     || oplist->op_type == OP_RV2AV);
6898                 oplist = OpSIBLING(oplist);
6899             }
6900
6901             if (SvRMAGICAL(av)) {
6902                 SSize_t i;
6903
6904                 Newx(array, maxarg, SV*);
6905                 SAVEFREEPV(array);
6906                 for (i=0; i < maxarg; i++) {
6907                     SV ** const svp = av_fetch(av, i, FALSE);
6908                     array[i] = svp ? *svp : &PL_sv_undef;
6909                 }
6910             }
6911             else
6912                 array = AvARRAY(av);
6913
6914             pat = S_concat_pat(aTHX_ pRExC_state, pat,
6915                                 array, maxarg, NULL, recompile_p,
6916                                 /* $" */
6917                                 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6918
6919             continue;
6920         }
6921
6922
6923         /* we make the assumption here that each op in the list of
6924          * op_siblings maps to one SV pushed onto the stack,
6925          * except for code blocks, with have both an OP_NULL and
6926          * an OP_CONST.
6927          * This allows us to match up the list of SVs against the
6928          * list of OPs to find the next code block.
6929          *
6930          * Note that       PUSHMARK PADSV PADSV ..
6931          * is optimised to
6932          *                 PADRANGE PADSV  PADSV  ..
6933          * so the alignment still works. */
6934
6935         if (oplist) {
6936             if (oplist->op_type == OP_NULL
6937                 && (oplist->op_flags & OPf_SPECIAL))
6938             {
6939                 assert(n < pRExC_state->code_blocks->count);
6940                 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6941                 pRExC_state->code_blocks->cb[n].block = oplist;
6942                 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6943                 n++;
6944                 code = 1;
6945                 oplist = OpSIBLING(oplist); /* skip CONST */
6946                 assert(oplist);
6947             }
6948             oplist = OpSIBLING(oplist);;
6949         }
6950
6951         /* apply magic and QR overloading to arg */
6952
6953         SvGETMAGIC(msv);
6954         if (SvROK(msv) && SvAMAGIC(msv)) {
6955             SV *sv = AMG_CALLunary(msv, regexp_amg);
6956             if (sv) {
6957                 if (SvROK(sv))
6958                     sv = SvRV(sv);
6959                 if (SvTYPE(sv) != SVt_REGEXP)
6960                     Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6961                 msv = sv;
6962             }
6963         }
6964
6965         /* try concatenation overload ... */
6966         if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6967                 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6968         {
6969             sv_setsv(pat, sv);
6970             /* overloading involved: all bets are off over literal
6971              * code. Pretend we haven't seen it */
6972             if (n)
6973                 pRExC_state->code_blocks->count -= n;
6974             n = 0;
6975         }
6976         else {
6977             /* ... or failing that, try "" overload */
6978             while (SvAMAGIC(msv)
6979                     && (sv = AMG_CALLunary(msv, string_amg))
6980                     && sv != msv
6981                     &&  !(   SvROK(msv)
6982                           && SvROK(sv)
6983                           && SvRV(msv) == SvRV(sv))
6984             ) {
6985                 msv = sv;
6986                 SvGETMAGIC(msv);
6987             }
6988             if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6989                 msv = SvRV(msv);
6990
6991             if (pat) {
6992                 /* this is a partially unrolled
6993                  *     sv_catsv_nomg(pat, msv);
6994                  * that allows us to adjust code block indices if
6995                  * needed */
6996                 STRLEN dlen;
6997                 char *dst = SvPV_force_nomg(pat, dlen);
6998                 orig_patlen = dlen;
6999                 if (SvUTF8(msv) && !SvUTF8(pat)) {
7000                     S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
7001                     sv_setpvn(pat, dst, dlen);
7002                     SvUTF8_on(pat);
7003                 }
7004                 sv_catsv_nomg(pat, msv);
7005                 rx = msv;
7006             }
7007             else {
7008                 /* We have only one SV to process, but we need to verify
7009                  * it is properly null terminated or we will fail asserts
7010                  * later. In theory we probably shouldn't get such SV's,
7011                  * but if we do we should handle it gracefully. */
7012                 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
7013                     /* not a string, or a string with a trailing null */
7014                     pat = msv;
7015                 } else {
7016                     /* a string with no trailing null, we need to copy it
7017                      * so it has a trailing null */
7018                     pat = sv_2mortal(newSVsv(msv));
7019                 }
7020             }
7021
7022             if (code)
7023                 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
7024         }
7025
7026         /* extract any code blocks within any embedded qr//'s */
7027         if (rx && SvTYPE(rx) == SVt_REGEXP
7028             && RX_ENGINE((REGEXP*)rx)->op_comp)
7029         {
7030
7031             RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
7032             if (ri->code_blocks && ri->code_blocks->count) {
7033                 int i;
7034                 /* the presence of an embedded qr// with code means
7035                  * we should always recompile: the text of the
7036                  * qr// may not have changed, but it may be a
7037                  * different closure than last time */
7038                 *recompile_p = 1;
7039                 if (pRExC_state->code_blocks) {
7040                     int new_count = pRExC_state->code_blocks->count
7041                             + ri->code_blocks->count;
7042                     Renew(pRExC_state->code_blocks->cb,
7043                             new_count, struct reg_code_block);
7044                     pRExC_state->code_blocks->count = new_count;
7045                 }
7046                 else
7047                     pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
7048                                                     ri->code_blocks->count);
7049
7050                 for (i=0; i < ri->code_blocks->count; i++) {
7051                     struct reg_code_block *src, *dst;
7052                     STRLEN offset =  orig_patlen
7053                         + ReANY((REGEXP *)rx)->pre_prefix;
7054                     assert(n < pRExC_state->code_blocks->count);
7055                     src = &ri->code_blocks->cb[i];
7056                     dst = &pRExC_state->code_blocks->cb[n];
7057                     dst->start      = src->start + offset;
7058                     dst->end        = src->end   + offset;
7059                     dst->block      = src->block;
7060                     dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
7061                                             src->src_regex
7062                                                 ? src->src_regex
7063                                                 : (REGEXP*)rx);
7064                     n++;
7065                 }
7066             }
7067         }
7068     }
7069     /* avoid calling magic multiple times on a single element e.g. =~ $qr */
7070     if (alloced)
7071         SvSETMAGIC(pat);
7072
7073     return pat;
7074 }
7075
7076
7077
7078 /* see if there are any run-time code blocks in the pattern.
7079  * False positives are allowed */
7080
7081 static bool
7082 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7083                     char *pat, STRLEN plen)
7084 {
7085     int n = 0;
7086     STRLEN s;
7087
7088     PERL_UNUSED_CONTEXT;
7089
7090     for (s = 0; s < plen; s++) {
7091         if (   pRExC_state->code_blocks
7092             && n < pRExC_state->code_blocks->count
7093             && s == pRExC_state->code_blocks->cb[n].start)
7094         {
7095             s = pRExC_state->code_blocks->cb[n].end;
7096             n++;
7097             continue;
7098         }
7099         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
7100          * positives here */
7101         if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
7102             (pat[s+2] == '{'
7103                 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
7104         )
7105             return 1;
7106     }
7107     return 0;
7108 }
7109
7110 /* Handle run-time code blocks. We will already have compiled any direct
7111  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
7112  * copy of it, but with any literal code blocks blanked out and
7113  * appropriate chars escaped; then feed it into
7114  *
7115  *    eval "qr'modified_pattern'"
7116  *
7117  * For example,
7118  *
7119  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
7120  *
7121  * becomes
7122  *
7123  *    qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
7124  *
7125  * After eval_sv()-ing that, grab any new code blocks from the returned qr
7126  * and merge them with any code blocks of the original regexp.
7127  *
7128  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
7129  * instead, just save the qr and return FALSE; this tells our caller that
7130  * the original pattern needs upgrading to utf8.
7131  */
7132
7133 static bool
7134 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7135     char *pat, STRLEN plen)
7136 {
7137     SV *qr;
7138
7139     DECLARE_AND_GET_RE_DEBUG_FLAGS;
7140
7141     if (pRExC_state->runtime_code_qr) {
7142         /* this is the second time we've been called; this should
7143          * only happen if the main pattern got upgraded to utf8
7144          * during compilation; re-use the qr we compiled first time
7145          * round (which should be utf8 too)
7146          */
7147         qr = pRExC_state->runtime_code_qr;
7148         pRExC_state->runtime_code_qr = NULL;
7149         assert(RExC_utf8 && SvUTF8(qr));
7150     }
7151     else {
7152         int n = 0;
7153         STRLEN s;
7154         char *p, *newpat;
7155         int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
7156         SV *sv, *qr_ref;
7157         dSP;
7158
7159         /* determine how many extra chars we need for ' and \ escaping */
7160         for (s = 0; s < plen; s++) {
7161             if (pat[s] == '\'' || pat[s] == '\\')
7162                 newlen++;
7163         }
7164
7165         Newx(newpat, newlen, char);
7166         p = newpat;
7167         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
7168
7169         for (s = 0; s < plen; s++) {
7170             if (   pRExC_state->code_blocks
7171                 && n < pRExC_state->code_blocks->count
7172                 && s == pRExC_state->code_blocks->cb[n].start)
7173             {
7174                 /* blank out literal code block so that they aren't
7175                  * recompiled: eg change from/to:
7176                  *     /(?{xyz})/
7177                  *     /(?=====)/
7178                  * and
7179                  *     /(??{xyz})/
7180                  *     /(?======)/
7181                  * and
7182                  *     /(?(?{xyz}))/
7183                  *     /(?(?=====))/
7184                 */
7185                 assert(pat[s]   == '(');
7186                 assert(pat[s+1] == '?');
7187                 *p++ = '(';
7188                 *p++ = '?';
7189                 s += 2;
7190                 while (s < pRExC_state->code_blocks->cb[n].end) {
7191                     *p++ = '=';
7192                     s++;
7193                 }
7194                 *p++ = ')';
7195                 n++;
7196                 continue;
7197             }
7198             if (pat[s] == '\'' || pat[s] == '\\')
7199                 *p++ = '\\';
7200             *p++ = pat[s];
7201         }
7202         *p++ = '\'';
7203         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
7204             *p++ = 'x';
7205             if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
7206                 *p++ = 'x';
7207             }
7208         }
7209         *p++ = '\0';
7210         DEBUG_COMPILE_r({
7211             Perl_re_printf( aTHX_
7212                 "%sre-parsing pattern for runtime code:%s %s\n",
7213                 PL_colors[4], PL_colors[5], newpat);
7214         });
7215
7216         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
7217         Safefree(newpat);
7218
7219         ENTER;
7220         SAVETMPS;
7221         save_re_context();
7222         PUSHSTACKi(PERLSI_REQUIRE);
7223         /* G_RE_REPARSING causes the toker to collapse \\ into \ when
7224          * parsing qr''; normally only q'' does this. It also alters
7225          * hints handling */
7226         eval_sv(sv, G_SCALAR|G_RE_REPARSING);
7227         SvREFCNT_dec_NN(sv);
7228         SPAGAIN;
7229         qr_ref = POPs;
7230         PUTBACK;
7231         {
7232             SV * const errsv = ERRSV;
7233             if (SvTRUE_NN(errsv))
7234                 /* use croak_sv ? */
7235                 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
7236         }
7237         assert(SvROK(qr_ref));
7238         qr = SvRV(qr_ref);
7239         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
7240         /* the leaving below frees the tmp qr_ref.
7241          * Give qr a life of its own */
7242         SvREFCNT_inc(qr);
7243         POPSTACK;
7244         FREETMPS;
7245         LEAVE;
7246
7247     }
7248
7249     if (!RExC_utf8 && SvUTF8(qr)) {
7250         /* first time through; the pattern got upgraded; save the
7251          * qr for the next time through */
7252         assert(!pRExC_state->runtime_code_qr);
7253         pRExC_state->runtime_code_qr = qr;
7254         return 0;
7255     }
7256
7257
7258     /* extract any code blocks within the returned qr//  */
7259
7260
7261     /* merge the main (r1) and run-time (r2) code blocks into one */
7262     {
7263         RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
7264         struct reg_code_block *new_block, *dst;
7265         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
7266         int i1 = 0, i2 = 0;
7267         int r1c, r2c;
7268
7269         if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
7270         {
7271             SvREFCNT_dec_NN(qr);
7272             return 1;
7273         }
7274
7275         if (!r1->code_blocks)
7276             r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
7277
7278         r1c = r1->code_blocks->count;
7279         r2c = r2->code_blocks->count;
7280
7281         Newx(new_block, r1c + r2c, struct reg_code_block);
7282
7283         dst = new_block;
7284
7285         while (i1 < r1c || i2 < r2c) {
7286             struct reg_code_block *src;
7287             bool is_qr = 0;
7288
7289             if (i1 == r1c) {
7290                 src = &r2->code_blocks->cb[i2++];
7291                 is_qr = 1;
7292             }
7293             else if (i2 == r2c)
7294                 src = &r1->code_blocks->cb[i1++];
7295             else if (  r1->code_blocks->cb[i1].start
7296                      < r2->code_blocks->cb[i2].start)
7297             {
7298                 src = &r1->code_blocks->cb[i1++];
7299                 assert(src->end < r2->code_blocks->cb[i2].start);
7300             }
7301             else {
7302                 assert(  r1->code_blocks->cb[i1].start
7303                        > r2->code_blocks->cb[i2].start);
7304                 src = &r2->code_blocks->cb[i2++];
7305                 is_qr = 1;
7306                 assert(src->end < r1->code_blocks->cb[i1].start);
7307             }
7308
7309             assert(pat[src->start] == '(');
7310             assert(pat[src->end]   == ')');
7311             dst->start      = src->start;
7312             dst->end        = src->end;
7313             dst->block      = src->block;
7314             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
7315                                     : src->src_regex;
7316             dst++;
7317         }
7318         r1->code_blocks->count += r2c;
7319         Safefree(r1->code_blocks->cb);
7320         r1->code_blocks->cb = new_block;
7321     }
7322
7323     SvREFCNT_dec_NN(qr);
7324     return 1;
7325 }
7326
7327
7328 STATIC bool
7329 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
7330                       struct reg_substr_datum  *rsd,
7331                       struct scan_data_substrs *sub,
7332                       STRLEN longest_length)
7333 {
7334     /* This is the common code for setting up the floating and fixed length
7335      * string data extracted from Perl_re_op_compile() below.  Returns a boolean
7336      * as to whether succeeded or not */
7337
7338     I32 t;
7339     SSize_t ml;
7340     bool eol  = cBOOL(sub->flags & SF_BEFORE_EOL);
7341     bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
7342
7343     if (! (longest_length
7344            || (eol /* Can't have SEOL and MULTI */
7345                && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
7346           )
7347             /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
7348         || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
7349     {
7350         return FALSE;
7351     }
7352
7353     /* copy the information about the longest from the reg_scan_data
7354         over to the program. */
7355     if (SvUTF8(sub->str)) {
7356         rsd->substr      = NULL;
7357         rsd->utf8_substr = sub->str;
7358     } else {
7359         rsd->substr      = sub->str;
7360         rsd->utf8_substr = NULL;
7361     }
7362     /* end_shift is how many chars that must be matched that
7363         follow this item. We calculate it ahead of time as once the
7364         lookbehind offset is added in we lose the ability to correctly
7365         calculate it.*/
7366     ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
7367     rsd->end_shift = ml - sub->min_offset
7368         - longest_length
7369             /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
7370              * intead? - DAPM
7371             + (SvTAIL(sub->str) != 0)
7372             */
7373         + sub->lookbehind;
7374
7375     t = (eol/* Can't have SEOL and MULTI */
7376          && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
7377     fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
7378
7379     return TRUE;
7380 }
7381
7382 STATIC void
7383 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
7384 {
7385     /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
7386      * properly wrapped with the right modifiers */
7387
7388     bool has_p     = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7389     bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
7390                                                 != REGEX_DEPENDS_CHARSET);
7391
7392     /* The caret is output if there are any defaults: if not all the STD
7393         * flags are set, or if no character set specifier is needed */
7394     bool has_default =
7395                 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7396                 || ! has_charset);
7397     bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7398                                                 == REG_RUN_ON_COMMENT_SEEN);
7399     U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
7400                         >> RXf_PMf_STD_PMMOD_SHIFT);
7401     const char *fptr = STD_PAT_MODS;        /*"msixxn"*/
7402     char *p;
7403     STRLEN pat_len = RExC_precomp_end - RExC_precomp;
7404
7405     /* We output all the necessary flags; we never output a minus, as all
7406         * those are defaults, so are
7407         * covered by the caret */
7408     const STRLEN wraplen = pat_len + has_p + has_runon
7409         + has_default       /* If needs a caret */
7410         + PL_bitcount[reganch] /* 1 char for each set standard flag */
7411
7412             /* If needs a character set specifier */
7413         + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7414         + (sizeof("(?:)") - 1);
7415
7416     PERL_ARGS_ASSERT_SET_REGEX_PV;
7417
7418     /* make sure PL_bitcount bounds not exceeded */
7419     STATIC_ASSERT_STMT(sizeof(STD_PAT_MODS) <= 8);
7420
7421     p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
7422     SvPOK_on(Rx);
7423     if (RExC_utf8)
7424         SvFLAGS(Rx) |= SVf_UTF8;
7425     *p++='('; *p++='?';
7426
7427     /* If a default, cover it using the caret */
7428     if (has_default) {
7429         *p++= DEFAULT_PAT_MOD;
7430     }
7431     if (has_charset) {
7432         STRLEN len;
7433         const char* name;
7434
7435         name = get_regex_charset_name(RExC_rx->extflags, &len);
7436         if (strEQ(name, DEPENDS_PAT_MODS)) {  /* /d under UTF-8 => /u */
7437             assert(RExC_utf8);
7438             name = UNICODE_PAT_MODS;
7439             len = sizeof(UNICODE_PAT_MODS) - 1;
7440         }
7441         Copy(name, p, len, char);
7442         p += len;
7443     }
7444     if (has_p)
7445         *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7446     {
7447         char ch;
7448         while((ch = *fptr++)) {
7449             if(reganch & 1)
7450                 *p++ = ch;
7451             reganch >>= 1;
7452         }
7453     }
7454
7455     *p++ = ':';
7456     Copy(RExC_precomp, p, pat_len, char);
7457     assert ((RX_WRAPPED(Rx) - p) < 16);
7458     RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7459     p += pat_len;
7460
7461     /* Adding a trailing \n causes this to compile properly:
7462             my $R = qr / A B C # D E/x; /($R)/
7463         Otherwise the parens are considered part of the comment */
7464     if (has_runon)
7465         *p++ = '\n';
7466     *p++ = ')';
7467     *p = 0;
7468     SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7469 }
7470
7471 /*
7472  * Perl_re_op_compile - the perl internal RE engine's function to compile a
7473  * regular expression into internal code.
7474  * The pattern may be passed either as:
7475  *    a list of SVs (patternp plus pat_count)
7476  *    a list of OPs (expr)
7477  * If both are passed, the SV list is used, but the OP list indicates
7478  * which SVs are actually pre-compiled code blocks
7479  *
7480  * The SVs in the list have magic and qr overloading applied to them (and
7481  * the list may be modified in-place with replacement SVs in the latter
7482  * case).
7483  *
7484  * If the pattern hasn't changed from old_re, then old_re will be
7485  * returned.
7486  *
7487  * eng is the current engine. If that engine has an op_comp method, then
7488  * handle directly (i.e. we assume that op_comp was us); otherwise, just
7489  * do the initial concatenation of arguments and pass on to the external
7490  * engine.
7491  *
7492  * If is_bare_re is not null, set it to a boolean indicating whether the
7493  * arg list reduced (after overloading) to a single bare regex which has
7494  * been returned (i.e. /$qr/).
7495  *
7496  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7497  *
7498  * pm_flags contains the PMf_* flags, typically based on those from the
7499  * pm_flags field of the related PMOP. Currently we're only interested in
7500  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL, PMf_WILDCARD.
7501  *
7502  * For many years this code had an initial sizing pass that calculated
7503  * (sometimes incorrectly, leading to security holes) the size needed for the
7504  * compiled pattern.  That was changed by commit
7505  * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7506  * node at a time, as parsing goes along.  Patches welcome to fix any obsolete
7507  * references to this sizing pass.
7508  *
7509  * Now, an initial crude guess as to the size needed is made, based on the
7510  * length of the pattern.  Patches welcome to improve that guess.  That amount
7511  * of space is malloc'd and then immediately freed, and then clawed back node
7512  * by node.  This design is to minimze, to the extent possible, memory churn
7513  * when doing the reallocs.
7514  *
7515  * A separate parentheses counting pass may be needed in some cases.
7516  * (Previously the sizing pass did this.)  Patches welcome to reduce the number
7517  * of these cases.
7518  *
7519  * The existence of a sizing pass necessitated design decisions that are no
7520  * longer needed.  There are potential areas of simplification.
7521  *
7522  * Beware that the optimization-preparation code in here knows about some
7523  * of the structure of the compiled regexp.  [I'll say.]
7524  */
7525
7526 REGEXP *
7527 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7528                     OP *expr, const regexp_engine* eng, REGEXP *old_re,
7529                      bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7530 {
7531     dVAR;
7532     REGEXP *Rx;         /* Capital 'R' means points to a REGEXP */
7533     STRLEN plen;
7534     char *exp;
7535     regnode *scan;
7536     I32 flags;
7537     SSize_t minlen = 0;
7538     U32 rx_flags;
7539     SV *pat;
7540     SV** new_patternp = patternp;
7541
7542     /* these are all flags - maybe they should be turned
7543      * into a single int with different bit masks */
7544     I32 sawlookahead = 0;
7545     I32 sawplus = 0;
7546     I32 sawopen = 0;
7547     I32 sawminmod = 0;
7548
7549     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7550     bool recompile = 0;
7551     bool runtime_code = 0;
7552     scan_data_t data;
7553     RExC_state_t RExC_state;
7554     RExC_state_t * const pRExC_state = &RExC_state;
7555 #ifdef TRIE_STUDY_OPT
7556     int restudied = 0;
7557     RExC_state_t copyRExC_state;
7558 #endif
7559     DECLARE_AND_GET_RE_DEBUG_FLAGS;
7560
7561     PERL_ARGS_ASSERT_RE_OP_COMPILE;
7562
7563     DEBUG_r(if (!PL_colorset) reginitcolors());
7564
7565
7566     pRExC_state->warn_text = NULL;
7567     pRExC_state->unlexed_names = NULL;
7568     pRExC_state->code_blocks = NULL;
7569
7570     if (is_bare_re)
7571         *is_bare_re = FALSE;
7572
7573     if (expr && (expr->op_type == OP_LIST ||
7574                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7575         /* allocate code_blocks if needed */
7576         OP *o;
7577         int ncode = 0;
7578
7579         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7580             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7581                 ncode++; /* count of DO blocks */
7582
7583         if (ncode)
7584             pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7585     }
7586
7587     if (!pat_count) {
7588         /* compile-time pattern with just OP_CONSTs and DO blocks */
7589
7590         int n;
7591         OP *o;
7592
7593         /* find how many CONSTs there are */
7594         assert(expr);
7595         n = 0;
7596         if (expr->op_type == OP_CONST)
7597             n = 1;
7598         else
7599             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7600                 if (o->op_type == OP_CONST)
7601                     n++;
7602             }
7603
7604         /* fake up an SV array */
7605
7606         assert(!new_patternp);
7607         Newx(new_patternp, n, SV*);
7608         SAVEFREEPV(new_patternp);
7609         pat_count = n;
7610
7611         n = 0;
7612         if (expr->op_type == OP_CONST)
7613             new_patternp[n] = cSVOPx_sv(expr);
7614         else
7615             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7616                 if (o->op_type == OP_CONST)
7617                     new_patternp[n++] = cSVOPo_sv;
7618             }
7619
7620     }
7621
7622     DEBUG_PARSE_r(Perl_re_printf( aTHX_
7623         "Assembling pattern from %d elements%s\n", pat_count,
7624             orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7625
7626     /* set expr to the first arg op */
7627
7628     if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7629          && expr->op_type != OP_CONST)
7630     {
7631             expr = cLISTOPx(expr)->op_first;
7632             assert(   expr->op_type == OP_PUSHMARK
7633                    || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7634                    || expr->op_type == OP_PADRANGE);
7635             expr = OpSIBLING(expr);
7636     }
7637
7638     pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7639                         expr, &recompile, NULL);
7640
7641     /* handle bare (possibly after overloading) regex: foo =~ $re */
7642     {
7643         SV *re = pat;
7644         if (SvROK(re))
7645             re = SvRV(re);
7646         if (SvTYPE(re) == SVt_REGEXP) {
7647             if (is_bare_re)
7648                 *is_bare_re = TRUE;
7649             SvREFCNT_inc(re);
7650             DEBUG_PARSE_r(Perl_re_printf( aTHX_
7651                 "Precompiled pattern%s\n",
7652                     orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7653
7654             return (REGEXP*)re;
7655         }
7656     }
7657
7658     exp = SvPV_nomg(pat, plen);
7659
7660     if (!eng->op_comp) {
7661         if ((SvUTF8(pat) && IN_BYTES)
7662                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7663         {
7664             /* make a temporary copy; either to convert to bytes,
7665              * or to avoid repeating get-magic / overloaded stringify */
7666             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7667                                         (IN_BYTES ? 0 : SvUTF8(pat)));
7668         }
7669         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7670     }
7671
7672     /* ignore the utf8ness if the pattern is 0 length */
7673     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7674     RExC_uni_semantics = 0;
7675     RExC_contains_locale = 0;
7676     RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7677     RExC_in_script_run = 0;
7678     RExC_study_started = 0;
7679     pRExC_state->runtime_code_qr = NULL;
7680     RExC_frame_head= NULL;
7681     RExC_frame_last= NULL;
7682     RExC_frame_count= 0;
7683     RExC_latest_warn_offset = 0;
7684     RExC_use_BRANCHJ = 0;
7685     RExC_warned_WARN_EXPERIMENTAL__VLB = 0;
7686     RExC_warned_WARN_EXPERIMENTAL__REGEX_SETS = 0;
7687     RExC_total_parens = 0;
7688     RExC_open_parens = NULL;
7689     RExC_close_parens = NULL;
7690     RExC_paren_names = NULL;
7691     RExC_size = 0;
7692     RExC_seen_d_op = FALSE;
7693 #ifdef DEBUGGING
7694     RExC_paren_name_list = NULL;
7695 #endif
7696
7697     DEBUG_r({
7698         RExC_mysv1= sv_newmortal();
7699         RExC_mysv2= sv_newmortal();
7700     });
7701
7702     DEBUG_COMPILE_r({
7703             SV *dsv= sv_newmortal();
7704             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7705             Perl_re_printf( aTHX_  "%sCompiling REx%s %s\n",
7706                           PL_colors[4], PL_colors[5], s);
7707         });
7708
7709     /* we jump here if we have to recompile, e.g., from upgrading the pattern
7710      * to utf8 */
7711
7712     if ((pm_flags & PMf_USE_RE_EVAL)
7713                 /* this second condition covers the non-regex literal case,
7714                  * i.e.  $foo =~ '(?{})'. */
7715                 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7716     )
7717         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7718
7719   redo_parse:
7720     /* return old regex if pattern hasn't changed */
7721     /* XXX: note in the below we have to check the flags as well as the
7722      * pattern.
7723      *
7724      * Things get a touch tricky as we have to compare the utf8 flag
7725      * independently from the compile flags.  */
7726
7727     if (   old_re
7728         && !recompile
7729         && !!RX_UTF8(old_re) == !!RExC_utf8
7730         && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7731         && RX_PRECOMP(old_re)
7732         && RX_PRELEN(old_re) == plen
7733         && memEQ(RX_PRECOMP(old_re), exp, plen)
7734         && !runtime_code /* with runtime code, always recompile */ )
7735     {
7736         DEBUG_COMPILE_r({
7737             SV *dsv= sv_newmortal();
7738             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7739             Perl_re_printf( aTHX_  "%sSkipping recompilation of unchanged REx%s %s\n",
7740                           PL_colors[4], PL_colors[5], s);
7741         });
7742         return old_re;
7743     }
7744
7745     /* Allocate the pattern's SV */
7746     RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7747     RExC_rx = ReANY(Rx);
7748     if ( RExC_rx == NULL )
7749         FAIL("Regexp out of space");
7750
7751     rx_flags = orig_rx_flags;
7752
7753     if (   (UTF || RExC_uni_semantics)
7754         && initial_charset == REGEX_DEPENDS_CHARSET)
7755     {
7756
7757         /* Set to use unicode semantics if the pattern is in utf8 and has the
7758          * 'depends' charset specified, as it means unicode when utf8  */
7759         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7760         RExC_uni_semantics = 1;
7761     }
7762
7763     RExC_pm_flags = pm_flags;
7764
7765     if (runtime_code) {
7766         assert(TAINTING_get || !TAINT_get);
7767         if (TAINT_get)
7768             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7769
7770         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7771             /* whoops, we have a non-utf8 pattern, whilst run-time code
7772              * got compiled as utf8. Try again with a utf8 pattern */
7773             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7774                 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7775             goto redo_parse;
7776         }
7777     }
7778     assert(!pRExC_state->runtime_code_qr);
7779
7780     RExC_sawback = 0;
7781
7782     RExC_seen = 0;
7783     RExC_maxlen = 0;
7784     RExC_in_lookbehind = 0;
7785     RExC_in_lookahead = 0;
7786     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7787     RExC_recode_x_to_native = 0;
7788     RExC_in_multi_char_class = 0;
7789
7790     RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7791     RExC_precomp_end = RExC_end = exp + plen;
7792     RExC_nestroot = 0;
7793     RExC_whilem_seen = 0;
7794     RExC_end_op = NULL;
7795     RExC_recurse = NULL;
7796     RExC_study_chunk_recursed = NULL;
7797     RExC_study_chunk_recursed_bytes= 0;
7798     RExC_recurse_count = 0;
7799     RExC_sets_depth = 0;
7800     pRExC_state->code_index = 0;
7801
7802     /* Initialize the string in the compiled pattern.  This is so that there is
7803      * something to output if necessary */
7804     set_regex_pv(pRExC_state, Rx);
7805
7806     DEBUG_PARSE_r({
7807         Perl_re_printf( aTHX_
7808             "Starting parse and generation\n");
7809         RExC_lastnum=0;
7810         RExC_lastparse=NULL;
7811     });
7812
7813     /* Allocate space and zero-initialize. Note, the two step process
7814        of zeroing when in debug mode, thus anything assigned has to
7815        happen after that */
7816     if (!  RExC_size) {
7817
7818         /* On the first pass of the parse, we guess how big this will be.  Then
7819          * we grow in one operation to that amount and then give it back.  As
7820          * we go along, we re-allocate what we need.
7821          *
7822          * XXX Currently the guess is essentially that the pattern will be an
7823          * EXACT node with one byte input, one byte output.  This is crude, and
7824          * better heuristics are welcome.
7825          *
7826          * On any subsequent passes, we guess what we actually computed in the
7827          * latest earlier pass.  Such a pass probably didn't complete so is
7828          * missing stuff.  We could improve those guesses by knowing where the
7829          * parse stopped, and use the length so far plus apply the above
7830          * assumption to what's left. */
7831         RExC_size = STR_SZ(RExC_end - RExC_start);
7832     }
7833
7834     Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7835     if ( RExC_rxi == NULL )
7836         FAIL("Regexp out of space");
7837
7838     Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7839     RXi_SET( RExC_rx, RExC_rxi );
7840
7841     /* We start from 0 (over from 0 in the case this is a reparse.  The first
7842      * node parsed will give back any excess memory we have allocated so far).
7843      * */
7844     RExC_size = 0;
7845
7846     /* non-zero initialization begins here */
7847     RExC_rx->engine= eng;
7848     RExC_rx->extflags = rx_flags;
7849     RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7850
7851     if (pm_flags & PMf_IS_QR) {
7852         RExC_rxi->code_blocks = pRExC_state->code_blocks;
7853         if (RExC_rxi->code_blocks) {
7854             RExC_rxi->code_blocks->refcnt++;
7855         }
7856     }
7857
7858     RExC_rx->intflags = 0;
7859
7860     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
7861     RExC_parse = exp;
7862
7863     /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7864      * code makes sure the final byte is an uncounted NUL.  But should this
7865      * ever not be the case, lots of things could read beyond the end of the
7866      * buffer: loops like
7867      *      while(isFOO(*RExC_parse)) RExC_parse++;
7868      *      strchr(RExC_parse, "foo");
7869      * etc.  So it is worth noting. */
7870     assert(*RExC_end == '\0');
7871
7872     RExC_naughty = 0;
7873     RExC_npar = 1;
7874     RExC_parens_buf_size = 0;
7875     RExC_emit_start = RExC_rxi->program;
7876     pRExC_state->code_index = 0;
7877
7878     *((char*) RExC_emit_start) = (char) REG_MAGIC;
7879     RExC_emit = 1;
7880
7881     /* Do the parse */
7882     if (reg(pRExC_state, 0, &flags, 1)) {
7883
7884         /* Success!, But we may need to redo the parse knowing how many parens
7885          * there actually are */
7886         if (IN_PARENS_PASS) {
7887             flags |= RESTART_PARSE;
7888         }
7889
7890         /* We have that number in RExC_npar */
7891         RExC_total_parens = RExC_npar;
7892
7893         /* XXX For backporting, use long jumps if there is any possibility of
7894          * overflow */
7895         if (RExC_size > U16_MAX && ! RExC_use_BRANCHJ) {
7896             RExC_use_BRANCHJ = TRUE;
7897             flags |= RESTART_PARSE;
7898         }
7899     }
7900     else if (! MUST_RESTART(flags)) {
7901         ReREFCNT_dec(Rx);
7902         Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7903     }
7904
7905     /* Here, we either have success, or we have to redo the parse for some reason */
7906     if (MUST_RESTART(flags)) {
7907
7908         /* It's possible to write a regexp in ascii that represents Unicode
7909         codepoints outside of the byte range, such as via \x{100}. If we
7910         detect such a sequence we have to convert the entire pattern to utf8
7911         and then recompile, as our sizing calculation will have been based
7912         on 1 byte == 1 character, but we will need to use utf8 to encode
7913         at least some part of the pattern, and therefore must convert the whole
7914         thing.
7915         -- dmq */
7916         if (flags & NEED_UTF8) {
7917
7918             /* We have stored the offset of the final warning output so far.
7919              * That must be adjusted.  Any variant characters between the start
7920              * of the pattern and this warning count for 2 bytes in the final,
7921              * so just add them again */
7922             if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7923                 RExC_latest_warn_offset +=
7924                             variant_under_utf8_count((U8 *) exp, (U8 *) exp
7925                                                 + RExC_latest_warn_offset);
7926             }
7927             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7928             pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7929             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7930         }
7931         else {
7932             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7933         }
7934
7935         if (ALL_PARENS_COUNTED) {
7936             /* Make enough room for all the known parens, and zero it */
7937             Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7938             Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7939             RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
7940
7941             Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7942             Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7943         }
7944         else { /* Parse did not complete.  Reinitialize the parentheses
7945                   structures */
7946             RExC_total_parens = 0;
7947             if (RExC_open_parens) {
7948                 Safefree(RExC_open_parens);
7949                 RExC_open_parens = NULL;
7950             }
7951             if (RExC_close_parens) {
7952                 Safefree(RExC_close_parens);
7953                 RExC_close_parens = NULL;
7954             }
7955         }
7956
7957         /* Clean up what we did in this parse */
7958         SvREFCNT_dec_NN(RExC_rx_sv);
7959
7960         goto redo_parse;
7961     }
7962
7963     /* Here, we have successfully parsed and generated the pattern's program
7964      * for the regex engine.  We are ready to finish things up and look for
7965      * optimizations. */
7966
7967     /* Update the string to compile, with correct modifiers, etc */
7968     set_regex_pv(pRExC_state, Rx);
7969
7970     RExC_rx->nparens = RExC_total_parens - 1;
7971
7972     /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7973     if (RExC_whilem_seen > 15)
7974         RExC_whilem_seen = 15;
7975
7976     DEBUG_PARSE_r({
7977         Perl_re_printf( aTHX_
7978             "Required size %" IVdf " nodes\n", (IV)RExC_size);
7979         RExC_lastnum=0;
7980         RExC_lastparse=NULL;
7981     });
7982
7983 #ifdef RE_TRACK_PATTERN_OFFSETS
7984     DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7985                           "%s %" UVuf " bytes for offset annotations.\n",
7986                           RExC_offsets ? "Got" : "Couldn't get",
7987                           (UV)((RExC_offsets[0] * 2 + 1))));
7988     DEBUG_OFFSETS_r(if (RExC_offsets) {
7989         const STRLEN len = RExC_offsets[0];
7990         STRLEN i;
7991         DECLARE_AND_GET_RE_DEBUG_FLAGS;
7992         Perl_re_printf( aTHX_
7993                       "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7994         for (i = 1; i <= len; i++) {
7995             if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7996                 Perl_re_printf( aTHX_  "%" UVuf ":%" UVuf "[%" UVuf "] ",
7997                 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7998         }
7999         Perl_re_printf( aTHX_  "\n");
8000     });
8001
8002 #else
8003     SetProgLen(RExC_rxi,RExC_size);
8004 #endif
8005
8006     DEBUG_DUMP_PRE_OPTIMIZE_r({
8007         SV * const sv = sv_newmortal();
8008         RXi_GET_DECL(RExC_rx, ri);
8009         DEBUG_RExC_seen();
8010         Perl_re_printf( aTHX_ "Program before optimization:\n");
8011
8012         (void)dumpuntil(RExC_rx, ri->program, ri->program + 1, NULL, NULL,
8013                         sv, 0, 0);
8014     });
8015
8016     DEBUG_OPTIMISE_r(
8017         Perl_re_printf( aTHX_  "Starting post parse optimization\n");
8018     );
8019
8020     /* XXXX To minimize changes to RE engine we always allocate
8021        3-units-long substrs field. */
8022     Newx(RExC_rx->substrs, 1, struct reg_substr_data);
8023     if (RExC_recurse_count) {
8024         Newx(RExC_recurse, RExC_recurse_count, regnode *);
8025         SAVEFREEPV(RExC_recurse);
8026     }
8027
8028     if (RExC_seen & REG_RECURSE_SEEN) {
8029         /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
8030          * So its 1 if there are no parens. */
8031         RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
8032                                          ((RExC_total_parens & 0x07) != 0);
8033         Newx(RExC_study_chunk_recursed,
8034              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
8035         SAVEFREEPV(RExC_study_chunk_recursed);
8036     }
8037
8038   reStudy:
8039     RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
8040     DEBUG_r(
8041         RExC_study_chunk_recursed_count= 0;
8042     );
8043     Zero(RExC_rx->substrs, 1, struct reg_substr_data);
8044     if (RExC_study_chunk_recursed) {
8045         Zero(RExC_study_chunk_recursed,
8046              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
8047     }
8048
8049
8050 #ifdef TRIE_STUDY_OPT
8051     if (!restudied) {
8052         StructCopy(&zero_scan_data, &data, scan_data_t);
8053         copyRExC_state = RExC_state;
8054     } else {
8055         U32 seen=RExC_seen;
8056         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
8057
8058         RExC_state = copyRExC_state;
8059         if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
8060             RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
8061         else
8062             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
8063         StructCopy(&zero_scan_data, &data, scan_data_t);
8064     }
8065 #else
8066     StructCopy(&zero_scan_data, &data, scan_data_t);
8067 #endif
8068
8069     /* Dig out information for optimizations. */
8070     RExC_rx->extflags = RExC_flags; /* was pm_op */
8071     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
8072
8073     if (UTF)
8074         SvUTF8_on(Rx);  /* Unicode in it? */
8075     RExC_rxi->regstclass = NULL;
8076     if (RExC_naughty >= TOO_NAUGHTY)    /* Probably an expensive pattern. */
8077         RExC_rx->intflags |= PREGf_NAUGHTY;
8078     scan = RExC_rxi->program + 1;               /* First BRANCH. */
8079
8080     /* testing for BRANCH here tells us whether there is "must appear"
8081        data in the pattern. If there is then we can use it for optimisations */
8082     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /*  Only one top-level choice.
8083                                                   */
8084         SSize_t fake;
8085         STRLEN longest_length[2];
8086         regnode_ssc ch_class; /* pointed to by data */
8087         int stclass_flag;
8088         SSize_t last_close = 0; /* pointed to by data */
8089         regnode *first= scan;
8090         regnode *first_next= regnext(first);
8091         int i;
8092
8093         /*
8094          * Skip introductions and multiplicators >= 1
8095          * so that we can extract the 'meat' of the pattern that must
8096          * match in the large if() sequence following.
8097          * NOTE that EXACT is NOT covered here, as it is normally
8098          * picked up by the optimiser separately.
8099          *
8100          * This is unfortunate as the optimiser isnt handling lookahead
8101          * properly currently.
8102          *
8103          */
8104         while ((OP(first) == OPEN && (sawopen = 1)) ||
8105                /* An OR of *one* alternative - should not happen now. */
8106             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
8107             /* for now we can't handle lookbehind IFMATCH*/
8108             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
8109             (OP(first) == PLUS) ||
8110             (OP(first) == MINMOD) ||
8111                /* An {n,m} with n>0 */
8112             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
8113             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
8114         {
8115                 /*
8116                  * the only op that could be a regnode is PLUS, all the rest
8117                  * will be regnode_1 or regnode_2.
8118                  *
8119                  * (yves doesn't think this is true)
8120                  */
8121                 if (OP(first) == PLUS)
8122                     sawplus = 1;
8123                 else {
8124                     if (OP(first) == MINMOD)
8125                         sawminmod = 1;
8126                     first += regarglen[OP(first)];
8127                 }
8128                 first = NEXTOPER(first);
8129                 first_next= regnext(first);
8130         }
8131
8132         /* Starting-point info. */
8133       again:
8134         DEBUG_PEEP("first:", first, 0, 0);
8135         /* Ignore EXACT as we deal with it later. */
8136         if (PL_regkind[OP(first)] == EXACT) {
8137             if (   OP(first) == EXACT
8138                 || OP(first) == LEXACT
8139                 || OP(first) == EXACT_REQ8
8140                 || OP(first) == LEXACT_REQ8
8141                 || OP(first) == EXACTL)
8142             {
8143                 NOOP;   /* Empty, get anchored substr later. */
8144             }
8145             else
8146                 RExC_rxi->regstclass = first;
8147         }
8148 #ifdef TRIE_STCLASS
8149         else if (PL_regkind[OP(first)] == TRIE &&
8150                 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
8151         {
8152             /* this can happen only on restudy */
8153             RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
8154         }
8155 #endif
8156         else if (REGNODE_SIMPLE(OP(first)))
8157             RExC_rxi->regstclass = first;
8158         else if (PL_regkind[OP(first)] == BOUND ||
8159                  PL_regkind[OP(first)] == NBOUND)
8160             RExC_rxi->regstclass = first;
8161         else if (PL_regkind[OP(first)] == BOL) {
8162             RExC_rx->intflags |= (OP(first) == MBOL
8163                            ? PREGf_ANCH_MBOL
8164                            : PREGf_ANCH_SBOL);
8165             first = NEXTOPER(first);
8166             goto again;
8167         }
8168         else if (OP(first) == GPOS) {
8169             RExC_rx->intflags |= PREGf_ANCH_GPOS;
8170             first = NEXTOPER(first);
8171             goto again;
8172         }
8173         else if ((!sawopen || !RExC_sawback) &&
8174             !sawlookahead &&
8175             (OP(first) == STAR &&
8176             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
8177             !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
8178         {
8179             /* turn .* into ^.* with an implied $*=1 */
8180             const int type =
8181                 (OP(NEXTOPER(first)) == REG_ANY)
8182                     ? PREGf_ANCH_MBOL
8183                     : PREGf_ANCH_SBOL;
8184             RExC_rx->intflags |= (type | PREGf_IMPLICIT);
8185             first = NEXTOPER(first);
8186             goto again;
8187         }
8188         if (sawplus && !sawminmod && !sawlookahead
8189             && (!sawopen || !RExC_sawback)
8190             && !pRExC_state->code_blocks) /* May examine pos and $& */
8191             /* x+ must match at the 1st pos of run of x's */
8192             RExC_rx->intflags |= PREGf_SKIP;
8193
8194         /* Scan is after the zeroth branch, first is atomic matcher. */
8195 #ifdef TRIE_STUDY_OPT
8196         DEBUG_PARSE_r(
8197             if (!restudied)
8198                 Perl_re_printf( aTHX_  "first at %" IVdf "\n",
8199                               (IV)(first - scan + 1))
8200         );
8201 #else
8202         DEBUG_PARSE_r(
8203             Perl_re_printf( aTHX_  "first at %" IVdf "\n",
8204                 (IV)(first - scan + 1))
8205         );
8206 #endif
8207
8208
8209         /*
8210         * If there's something expensive in the r.e., find the
8211         * longest literal string that must appear and make it the
8212         * regmust.  Resolve ties in favor of later strings, since
8213         * the regstart check works with the beginning of the r.e.
8214         * and avoiding duplication strengthens checking.  Not a
8215         * strong reason, but sufficient in the absence of others.
8216         * [Now we resolve ties in favor of the earlier string if
8217         * it happens that c_offset_min has been invalidated, since the
8218         * earlier string may buy us something the later one won't.]
8219         */
8220
8221         data.substrs[0].str = newSVpvs("");
8222         data.substrs[1].str = newSVpvs("");
8223         data.last_found = newSVpvs("");
8224         data.cur_is_floating = 0; /* initially any found substring is fixed */
8225         ENTER_with_name("study_chunk");
8226         SAVEFREESV(data.substrs[0].str);
8227         SAVEFREESV(data.substrs[1].str);
8228         SAVEFREESV(data.last_found);
8229         first = scan;
8230         if (!RExC_rxi->regstclass) {
8231             ssc_init(pRExC_state, &ch_class);
8232             data.start_class = &ch_class;
8233             stclass_flag = SCF_DO_STCLASS_AND;
8234         } else                          /* XXXX Check for BOUND? */
8235             stclass_flag = 0;
8236         data.last_closep = &last_close;
8237
8238         DEBUG_RExC_seen();
8239         /*
8240          * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
8241          * (NO top level branches)
8242          */
8243         minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
8244                              scan + RExC_size, /* Up to end */
8245             &data, -1, 0, NULL,
8246             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
8247                           | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
8248             0, TRUE);
8249
8250
8251         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
8252
8253
8254         if ( RExC_total_parens == 1 && !data.cur_is_floating
8255              && data.last_start_min == 0 && data.last_end > 0
8256              && !RExC_seen_zerolen
8257              && !(RExC_seen & REG_VERBARG_SEEN)
8258              && !(RExC_seen & REG_GPOS_SEEN)
8259         ){
8260             RExC_rx->extflags |= RXf_CHECK_ALL;
8261         }
8262         scan_commit(pRExC_state, &data,&minlen, 0);
8263
8264
8265         /* XXX this is done in reverse order because that's the way the
8266          * code was before it was parameterised. Don't know whether it
8267          * actually needs doing in reverse order. DAPM */
8268         for (i = 1; i >= 0; i--) {
8269             longest_length[i] = CHR_SVLEN(data.substrs[i].str);
8270
8271             if (   !(   i
8272                      && SvCUR(data.substrs[0].str)  /* ok to leave SvCUR */
8273                      &&    data.substrs[0].min_offset
8274                         == data.substrs[1].min_offset
8275                      &&    SvCUR(data.substrs[0].str)
8276                         == SvCUR(data.substrs[1].str)
8277                     )
8278                 && S_setup_longest (aTHX_ pRExC_state,
8279                                         &(RExC_rx->substrs->data[i]),
8280                                         &(data.substrs[i]),
8281                                         longest_length[i]))
8282             {
8283                 RExC_rx->substrs->data[i].min_offset =
8284                         data.substrs[i].min_offset - data.substrs[i].lookbehind;
8285
8286                 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
8287                 /* Don't offset infinity */
8288                 if (data.substrs[i].max_offset < OPTIMIZE_INFTY)
8289                     RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
8290                 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
8291             }
8292             else {
8293                 RExC_rx->substrs->data[i].substr      = NULL;
8294                 RExC_rx->substrs->data[i].utf8_substr = NULL;
8295                 longest_length[i] = 0;
8296             }
8297         }
8298
8299         LEAVE_with_name("study_chunk");
8300
8301         if (RExC_rxi->regstclass
8302             && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
8303             RExC_rxi->regstclass = NULL;
8304
8305         if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
8306               || RExC_rx->substrs->data[0].min_offset)
8307             && stclass_flag
8308             && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8309             && is_ssc_worth_it(pRExC_state, data.start_class))
8310         {
8311             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8312
8313             ssc_finalize(pRExC_state, data.start_class);
8314
8315             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8316             StructCopy(data.start_class,
8317                        (regnode_ssc*)RExC_rxi->data->data[n],
8318                        regnode_ssc);
8319             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8320             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
8321             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
8322                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8323                       Perl_re_printf( aTHX_
8324                                     "synthetic stclass \"%s\".\n",
8325                                     SvPVX_const(sv));});
8326             data.start_class = NULL;
8327         }
8328
8329         /* A temporary algorithm prefers floated substr to fixed one of
8330          * same length to dig more info. */
8331         i = (longest_length[0] <= longest_length[1]);
8332         RExC_rx->substrs->check_ix = i;
8333         RExC_rx->check_end_shift  = RExC_rx->substrs->data[i].end_shift;
8334         RExC_rx->check_substr     = RExC_rx->substrs->data[i].substr;
8335         RExC_rx->check_utf8       = RExC_rx->substrs->data[i].utf8_substr;
8336         RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
8337         RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
8338         if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
8339             RExC_rx->intflags |= PREGf_NOSCAN;
8340
8341         if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
8342             RExC_rx->extflags |= RXf_USE_INTUIT;
8343             if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
8344                 RExC_rx->extflags |= RXf_INTUIT_TAIL;
8345         }
8346
8347         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
8348         if ( (STRLEN)minlen < longest_length[1] )
8349             minlen= longest_length[1];
8350         if ( (STRLEN)minlen < longest_length[0] )
8351             minlen= longest_length[0];
8352         */
8353     }
8354     else {
8355         /* Several toplevels. Best we can is to set minlen. */
8356         SSize_t fake;
8357         regnode_ssc ch_class;
8358         SSize_t last_close = 0;
8359
8360         DEBUG_PARSE_r(Perl_re_printf( aTHX_  "\nMulti Top Level\n"));
8361
8362         scan = RExC_rxi->program + 1;
8363         ssc_init(pRExC_state, &ch_class);
8364         data.start_class = &ch_class;
8365         data.last_closep = &last_close;
8366
8367         DEBUG_RExC_seen();
8368         /*
8369          * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
8370          * (patterns WITH top level branches)
8371          */
8372         minlen = study_chunk(pRExC_state,
8373             &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
8374             SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
8375                                                       ? SCF_TRIE_DOING_RESTUDY
8376                                                       : 0),
8377             0, TRUE);
8378
8379         CHECK_RESTUDY_GOTO_butfirst(NOOP);
8380
8381         RExC_rx->check_substr = NULL;
8382         RExC_rx->check_utf8 = NULL;
8383         RExC_rx->substrs->data[0].substr      = NULL;
8384         RExC_rx->substrs->data[0].utf8_substr = NULL;
8385         RExC_rx->substrs->data[1].substr      = NULL;
8386         RExC_rx->substrs->data[1].utf8_substr = NULL;
8387
8388         if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8389             && is_ssc_worth_it(pRExC_state, data.start_class))
8390         {
8391             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8392
8393             ssc_finalize(pRExC_state, data.start_class);
8394
8395             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8396             StructCopy(data.start_class,
8397                        (regnode_ssc*)RExC_rxi->data->data[n],
8398                        regnode_ssc);
8399             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8400             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
8401             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
8402                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8403                       Perl_re_printf( aTHX_
8404                                     "synthetic stclass \"%s\".\n",
8405                                     SvPVX_const(sv));});
8406             data.start_class = NULL;
8407         }
8408     }
8409
8410     if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
8411         RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
8412         RExC_rx->maxlen = REG_INFTY;
8413     }
8414     else {
8415         RExC_rx->maxlen = RExC_maxlen;
8416     }
8417
8418     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
8419        the "real" pattern. */
8420     DEBUG_OPTIMISE_r({
8421         Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
8422                       (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
8423     });
8424     RExC_rx->minlenret = minlen;
8425     if (RExC_rx->minlen < minlen)
8426         RExC_rx->minlen = minlen;
8427
8428     if (RExC_seen & REG_RECURSE_SEEN ) {
8429         RExC_rx->intflags |= PREGf_RECURSE_SEEN;
8430         Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
8431     }
8432     if (RExC_seen & REG_GPOS_SEEN)
8433         RExC_rx->intflags |= PREGf_GPOS_SEEN;
8434     if (RExC_seen & REG_LOOKBEHIND_SEEN)
8435         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
8436                                                 lookbehind */
8437     if (pRExC_state->code_blocks)
8438         RExC_rx->extflags |= RXf_EVAL_SEEN;
8439     if (RExC_seen & REG_VERBARG_SEEN)
8440     {
8441         RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8442         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8443     }
8444     if (RExC_seen & REG_CUTGROUP_SEEN)
8445         RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8446     if (pm_flags & PMf_USE_RE_EVAL)
8447         RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8448     if (RExC_paren_names)
8449         RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8450     else
8451         RXp_PAREN_NAMES(RExC_rx) = NULL;
8452
8453     /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8454      * so it can be used in pp.c */
8455     if (RExC_rx->intflags & PREGf_ANCH)
8456         RExC_rx->extflags |= RXf_IS_ANCHORED;
8457
8458
8459     {
8460         /* this is used to identify "special" patterns that might result
8461          * in Perl NOT calling the regex engine and instead doing the match "itself",
8462          * particularly special cases in split//. By having the regex compiler
8463          * do this pattern matching at a regop level (instead of by inspecting the pattern)
8464          * we avoid weird issues with equivalent patterns resulting in different behavior,
8465          * AND we allow non Perl engines to get the same optimizations by the setting the
8466          * flags appropriately - Yves */
8467         regnode *first = RExC_rxi->program + 1;
8468         U8 fop = OP(first);
8469         regnode *next = regnext(first);
8470         U8 nop = OP(next);
8471
8472         if (PL_regkind[fop] == NOTHING && nop == END)
8473             RExC_rx->extflags |= RXf_NULL;
8474         else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8475             /* when fop is SBOL first->flags will be true only when it was
8476              * produced by parsing /\A/, and not when parsing /^/. This is
8477              * very important for the split code as there we want to
8478              * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8479              * See rt #122761 for more details. -- Yves */
8480             RExC_rx->extflags |= RXf_START_ONLY;
8481         else if (fop == PLUS
8482                  && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8483                  && nop == END)
8484             RExC_rx->extflags |= RXf_WHITE;
8485         else if ( RExC_rx->extflags & RXf_SPLIT
8486                   && (   fop == EXACT || fop == LEXACT
8487                       || fop == EXACT_REQ8 || fop == LEXACT_REQ8
8488                       || fop == EXACTL)
8489                   && STR_LEN(first) == 1
8490                   && *(STRING(first)) == ' '
8491                   && nop == END )
8492             RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8493
8494     }
8495
8496     if (RExC_contains_locale) {
8497         RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8498     }
8499
8500 #ifdef DEBUGGING
8501     if (RExC_paren_names) {
8502         RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8503         RExC_rxi->data->data[RExC_rxi->name_list_idx]
8504                                    = (void*)SvREFCNT_inc(RExC_paren_name_list);
8505     } else
8506 #endif
8507     RExC_rxi->name_list_idx = 0;
8508
8509     while ( RExC_recurse_count > 0 ) {
8510         const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8511         /*
8512          * This data structure is set up in study_chunk() and is used
8513          * to calculate the distance between a GOSUB regopcode and
8514          * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8515          * it refers to.
8516          *
8517          * If for some reason someone writes code that optimises
8518          * away a GOSUB opcode then the assert should be changed to
8519          * an if(scan) to guard the ARG2L_SET() - Yves
8520          *
8521          */
8522         assert(scan && OP(scan) == GOSUB);
8523         ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8524     }
8525
8526     Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8527     /* assume we don't need to swap parens around before we match */
8528     DEBUG_TEST_r({
8529         Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8530             (unsigned long)RExC_study_chunk_recursed_count);
8531     });
8532     DEBUG_DUMP_r({
8533         DEBUG_RExC_seen();
8534         Perl_re_printf( aTHX_ "Final program:\n");
8535         regdump(RExC_rx);
8536     });
8537
8538     if (RExC_open_parens) {
8539         Safefree(RExC_open_parens);
8540         RExC_open_parens = NULL;
8541     }
8542     if (RExC_close_parens) {
8543         Safefree(RExC_close_parens);
8544         RExC_close_parens = NULL;
8545     }
8546
8547 #ifdef USE_ITHREADS
8548     /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8549      * by setting the regexp SV to readonly-only instead. If the
8550      * pattern's been recompiled, the USEDness should remain. */
8551     if (old_re && SvREADONLY(old_re))
8552         SvREADONLY_on(Rx);
8553 #endif
8554     return Rx;
8555 }
8556
8557
8558 SV*
8559 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8560                     const U32 flags)
8561 {
8562     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8563
8564     PERL_UNUSED_ARG(value);
8565
8566     if (flags & RXapif_FETCH) {
8567         return reg_named_buff_fetch(rx, key, flags);
8568     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8569         Perl_croak_no_modify();
8570         return NULL;
8571     } else if (flags & RXapif_EXISTS) {
8572         return reg_named_buff_exists(rx, key, flags)
8573             ? &PL_sv_yes
8574             : &PL_sv_no;
8575     } else if (flags & RXapif_REGNAMES) {
8576         return reg_named_buff_all(rx, flags);
8577     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8578         return reg_named_buff_scalar(rx, flags);
8579     } else {
8580         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8581         return NULL;
8582     }
8583 }
8584
8585 SV*
8586 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8587                          const U32 flags)
8588 {
8589     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8590     PERL_UNUSED_ARG(lastkey);
8591
8592     if (flags & RXapif_FIRSTKEY)
8593         return reg_named_buff_firstkey(rx, flags);
8594     else if (flags & RXapif_NEXTKEY)
8595         return reg_named_buff_nextkey(rx, flags);
8596     else {
8597         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8598                                             (int)flags);
8599         return NULL;
8600     }
8601 }
8602
8603 SV*
8604 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8605                           const U32 flags)
8606 {
8607     SV *ret;
8608     struct regexp *const rx = ReANY(r);
8609
8610     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8611
8612     if (rx && RXp_PAREN_NAMES(rx)) {
8613         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8614         if (he_str) {
8615             IV i;
8616             SV* sv_dat=HeVAL(he_str);
8617             I32 *nums=(I32*)SvPVX(sv_dat);
8618             AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8619             for ( i=0; i<SvIVX(sv_dat); i++ ) {
8620                 if ((I32)(rx->nparens) >= nums[i]
8621                     && rx->offs[nums[i]].start != -1
8622                     && rx->offs[nums[i]].end != -1)
8623                 {
8624                     ret = newSVpvs("");
8625                     CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8626                     if (!retarray)
8627                         return ret;
8628                 } else {
8629                     if (retarray)
8630                         ret = newSVsv(&PL_sv_undef);
8631                 }
8632                 if (retarray)
8633                     av_push(retarray, ret);
8634             }
8635             if (retarray)
8636                 return newRV_noinc(MUTABLE_SV(retarray));
8637         }
8638     }
8639     return NULL;
8640 }
8641
8642 bool
8643 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8644                            const U32 flags)
8645 {
8646     struct regexp *const rx = ReANY(r);
8647
8648     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8649
8650     if (rx && RXp_PAREN_NAMES(rx)) {
8651         if (flags & RXapif_ALL) {
8652             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8653         } else {
8654             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8655             if (sv) {
8656                 SvREFCNT_dec_NN(sv);
8657                 return TRUE;
8658             } else {
8659                 return FALSE;
8660             }
8661         }
8662     } else {
8663         return FALSE;
8664     }
8665 }
8666
8667 SV*
8668 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8669 {
8670     struct regexp *const rx = ReANY(r);
8671
8672     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8673
8674     if ( rx && RXp_PAREN_NAMES(rx) ) {
8675         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8676
8677         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8678     } else {
8679         return FALSE;
8680     }
8681 }
8682
8683 SV*
8684 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8685 {
8686     struct regexp *const rx = ReANY(r);
8687     DECLARE_AND_GET_RE_DEBUG_FLAGS;
8688
8689     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8690
8691     if (rx && RXp_PAREN_NAMES(rx)) {
8692         HV *hv = RXp_PAREN_NAMES(rx);
8693         HE *temphe;
8694         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8695             IV i;
8696             IV parno = 0;
8697             SV* sv_dat = HeVAL(temphe);
8698             I32 *nums = (I32*)SvPVX(sv_dat);
8699             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8700                 if ((I32)(rx->lastparen) >= nums[i] &&
8701                     rx->offs[nums[i]].start != -1 &&
8702                     rx->offs[nums[i]].end != -1)
8703                 {
8704                     parno = nums[i];
8705                     break;
8706                 }
8707             }
8708             if (parno || flags & RXapif_ALL) {
8709                 return newSVhek(HeKEY_hek(temphe));
8710             }
8711         }
8712     }
8713     return NULL;
8714 }
8715
8716 SV*
8717 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8718 {
8719     SV *ret;
8720     AV *av;
8721     SSize_t length;
8722     struct regexp *const rx = ReANY(r);
8723
8724     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8725
8726     if (rx && RXp_PAREN_NAMES(rx)) {
8727         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8728             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8729         } else if (flags & RXapif_ONE) {
8730             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8731             av = MUTABLE_AV(SvRV(ret));
8732             length = av_tindex(av);
8733             SvREFCNT_dec_NN(ret);
8734             return newSViv(length + 1);
8735         } else {
8736             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8737                                                 (int)flags);
8738             return NULL;
8739         }
8740     }
8741     return &PL_sv_undef;
8742 }
8743
8744 SV*
8745 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8746 {
8747     struct regexp *const rx = ReANY(r);
8748     AV *av = newAV();
8749
8750     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8751
8752     if (rx && RXp_PAREN_NAMES(rx)) {
8753         HV *hv= RXp_PAREN_NAMES(rx);
8754         HE *temphe;
8755         (void)hv_iterinit(hv);
8756         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8757             IV i;
8758             IV parno = 0;
8759             SV* sv_dat = HeVAL(temphe);
8760             I32 *nums = (I32*)SvPVX(sv_dat);
8761             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8762                 if ((I32)(rx->lastparen) >= nums[i] &&
8763                     rx->offs[nums[i]].start != -1 &&
8764                     rx->offs[nums[i]].end != -1)
8765                 {
8766                     parno = nums[i];
8767                     break;
8768                 }
8769             }
8770             if (parno || flags & RXapif_ALL) {
8771                 av_push(av, newSVhek(HeKEY_hek(temphe)));
8772             }
8773         }
8774     }
8775
8776     return newRV_noinc(MUTABLE_SV(av));
8777 }
8778
8779 void
8780 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8781                              SV * const sv)
8782 {
8783     struct regexp *const rx = ReANY(r);
8784     char *s = NULL;
8785     SSize_t i = 0;
8786     SSize_t s1, t1;
8787     I32 n = paren;
8788
8789     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8790
8791     if (      n == RX_BUFF_IDX_CARET_PREMATCH
8792            || n == RX_BUFF_IDX_CARET_FULLMATCH
8793            || n == RX_BUFF_IDX_CARET_POSTMATCH
8794        )
8795     {
8796         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8797         if (!keepcopy) {
8798             /* on something like
8799              *    $r = qr/.../;
8800              *    /$qr/p;
8801              * the KEEPCOPY is set on the PMOP rather than the regex */
8802             if (PL_curpm && r == PM_GETRE(PL_curpm))
8803                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8804         }
8805         if (!keepcopy)
8806             goto ret_undef;
8807     }
8808
8809     if (!rx->subbeg)
8810         goto ret_undef;
8811
8812     if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8813         /* no need to distinguish between them any more */
8814         n = RX_BUFF_IDX_FULLMATCH;
8815
8816     if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8817         && rx->offs[0].start != -1)
8818     {
8819         /* $`, ${^PREMATCH} */
8820         i = rx->offs[0].start;
8821         s = rx->subbeg;
8822     }
8823     else
8824     if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8825         && rx->offs[0].end != -1)
8826     {
8827         /* $', ${^POSTMATCH} */
8828         s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8829         i = rx->sublen + rx->suboffset - rx->offs[0].end;
8830     }
8831     else
8832     if (inRANGE(n, 0, (I32)rx->nparens) &&
8833         (s1 = rx->offs[n].start) != -1  &&
8834         (t1 = rx->offs[n].end) != -1)
8835     {
8836         /* $&, ${^MATCH},  $1 ... */
8837         i = t1 - s1;
8838         s = rx->subbeg + s1 - rx->suboffset;
8839     } else {
8840         goto ret_undef;
8841     }
8842
8843     assert(s >= rx->subbeg);
8844     assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8845     if (i >= 0) {
8846 #ifdef NO_TAINT_SUPPORT
8847         sv_setpvn(sv, s, i);
8848 #else
8849         const int oldtainted = TAINT_get;
8850         TAINT_NOT;
8851         sv_setpvn(sv, s, i);
8852         TAINT_set(oldtainted);
8853 #endif
8854         if (RXp_MATCH_UTF8(rx))
8855             SvUTF8_on(sv);
8856         else
8857             SvUTF8_off(sv);
8858         if (TAINTING_get) {
8859             if (RXp_MATCH_TAINTED(rx)) {
8860                 if (SvTYPE(sv) >= SVt_PVMG) {
8861                     MAGIC* const mg = SvMAGIC(sv);
8862                     MAGIC* mgt;
8863                     TAINT;
8864                     SvMAGIC_set(sv, mg->mg_moremagic);
8865                     SvTAINT(sv);
8866                     if ((mgt = SvMAGIC(sv))) {
8867                         mg->mg_moremagic = mgt;
8868                         SvMAGIC_set(sv, mg);
8869                     }
8870                 } else {
8871                     TAINT;
8872                     SvTAINT(sv);
8873                 }
8874             } else
8875                 SvTAINTED_off(sv);
8876         }
8877     } else {
8878       ret_undef:
8879         sv_set_undef(sv);
8880         return;
8881     }
8882 }
8883
8884 void
8885 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8886                                                          SV const * const value)
8887 {
8888     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8889
8890     PERL_UNUSED_ARG(rx);
8891     PERL_UNUSED_ARG(paren);
8892     PERL_UNUSED_ARG(value);
8893
8894     if (!PL_localizing)
8895         Perl_croak_no_modify();
8896 }
8897
8898 I32
8899 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8900                               const I32 paren)
8901 {
8902     struct regexp *const rx = ReANY(r);
8903     I32 i;
8904     I32 s1, t1;
8905
8906     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8907
8908     if (   paren == RX_BUFF_IDX_CARET_PREMATCH
8909         || paren == RX_BUFF_IDX_CARET_FULLMATCH
8910         || paren == RX_BUFF_IDX_CARET_POSTMATCH
8911     )
8912     {
8913         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8914         if (!keepcopy) {
8915             /* on something like
8916              *    $r = qr/.../;
8917              *    /$qr/p;
8918              * the KEEPCOPY is set on the PMOP rather than the regex */
8919             if (PL_curpm && r == PM_GETRE(PL_curpm))
8920                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8921         }
8922         if (!keepcopy)
8923             goto warn_undef;
8924     }
8925
8926     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8927     switch (paren) {
8928       case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8929       case RX_BUFF_IDX_PREMATCH:       /* $` */
8930         if (rx->offs[0].start != -1) {
8931                         i = rx->offs[0].start;
8932                         if (i > 0) {
8933                                 s1 = 0;
8934                                 t1 = i;
8935                                 goto getlen;
8936                         }
8937             }
8938         return 0;
8939
8940       case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8941       case RX_BUFF_IDX_POSTMATCH:       /* $' */
8942             if (rx->offs[0].end != -1) {
8943                         i = rx->sublen - rx->offs[0].end;
8944                         if (i > 0) {
8945                                 s1 = rx->offs[0].end;
8946                                 t1 = rx->sublen;
8947                                 goto getlen;
8948                         }
8949             }
8950         return 0;
8951
8952       default: /* $& / ${^MATCH}, $1, $2, ... */
8953             if (paren <= (I32)rx->nparens &&
8954             (s1 = rx->offs[paren].start) != -1 &&
8955             (t1 = rx->offs[paren].end) != -1)
8956             {
8957             i = t1 - s1;
8958             goto getlen;
8959         } else {
8960           warn_undef:
8961             if (ckWARN(WARN_UNINITIALIZED))
8962                 report_uninit((const SV *)sv);
8963             return 0;
8964         }
8965     }
8966   getlen:
8967     if (i > 0 && RXp_MATCH_UTF8(rx)) {
8968         const char * const s = rx->subbeg - rx->suboffset + s1;
8969         const U8 *ep;
8970         STRLEN el;
8971
8972         i = t1 - s1;
8973         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8974             i = el;
8975     }
8976     return i;
8977 }
8978
8979 SV*
8980 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8981 {
8982     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8983         PERL_UNUSED_ARG(rx);
8984         if (0)
8985             return NULL;
8986         else
8987             return newSVpvs("Regexp");
8988 }
8989
8990 /* Scans the name of a named buffer from the pattern.
8991  * If flags is REG_RSN_RETURN_NULL returns null.
8992  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8993  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8994  * to the parsed name as looked up in the RExC_paren_names hash.
8995  * If there is an error throws a vFAIL().. type exception.
8996  */
8997
8998 #define REG_RSN_RETURN_NULL    0
8999 #define REG_RSN_RETURN_NAME    1
9000 #define REG_RSN_RETURN_DATA    2
9001
9002 STATIC SV*
9003 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
9004 {
9005     char *name_start = RExC_parse;
9006     SV* sv_name;
9007
9008     PERL_ARGS_ASSERT_REG_SCAN_NAME;
9009
9010     assert (RExC_parse <= RExC_end);
9011     if (RExC_parse == RExC_end) NOOP;
9012     else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
9013          /* Note that the code here assumes well-formed UTF-8.  Skip IDFIRST by
9014           * using do...while */
9015         if (UTF)
9016             do {
9017                 RExC_parse += UTF8SKIP(RExC_parse);
9018             } while (   RExC_parse < RExC_end
9019                      && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
9020         else
9021             do {
9022                 RExC_parse++;
9023             } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
9024     } else {
9025         RExC_parse++; /* so the <- from the vFAIL is after the offending
9026                          character */
9027         vFAIL("Group name must start with a non-digit word character");
9028     }
9029     sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
9030                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
9031     if ( flags == REG_RSN_RETURN_NAME)
9032         return sv_name;
9033     else if (flags==REG_RSN_RETURN_DATA) {
9034         HE *he_str = NULL;
9035         SV *sv_dat = NULL;
9036         if ( ! sv_name )      /* should not happen*/
9037             Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
9038         if (RExC_paren_names)
9039             he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
9040         if ( he_str )
9041             sv_dat = HeVAL(he_str);
9042         if ( ! sv_dat ) {   /* Didn't find group */
9043
9044             /* It might be a forward reference; we can't fail until we
9045                 * know, by completing the parse to get all the groups, and
9046                 * then reparsing */
9047             if (ALL_PARENS_COUNTED)  {
9048                 vFAIL("Reference to nonexistent named group");
9049             }
9050             else {
9051                 REQUIRE_PARENS_PASS;
9052             }
9053         }
9054         return sv_dat;
9055     }
9056
9057     Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
9058                      (unsigned long) flags);
9059 }
9060
9061 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
9062     if (RExC_lastparse!=RExC_parse) {                           \
9063         Perl_re_printf( aTHX_  "%s",                            \
9064             Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse,        \
9065                 RExC_end - RExC_parse, 16,                      \
9066                 "", "",                                         \
9067                 PERL_PV_ESCAPE_UNI_DETECT |                     \
9068                 PERL_PV_PRETTY_ELLIPSES   |                     \
9069                 PERL_PV_PRETTY_LTGT       |                     \
9070                 PERL_PV_ESCAPE_RE         |                     \
9071                 PERL_PV_PRETTY_EXACTSIZE                        \
9072             )                                                   \
9073         );                                                      \
9074     } else                                                      \
9075         Perl_re_printf( aTHX_ "%16s","");                       \
9076                                                                 \
9077     if (RExC_lastnum!=RExC_emit)                                \
9078        Perl_re_printf( aTHX_ "|%4zu", RExC_emit);                \
9079     else                                                        \
9080        Perl_re_printf( aTHX_ "|%4s","");                        \
9081     Perl_re_printf( aTHX_ "|%*s%-4s",                           \
9082         (int)((depth*2)), "",                                   \
9083         (funcname)                                              \
9084     );                                                          \
9085     RExC_lastnum=RExC_emit;                                     \
9086     RExC_lastparse=RExC_parse;                                  \
9087 })
9088
9089
9090
9091 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
9092     DEBUG_PARSE_MSG((funcname));                            \
9093     Perl_re_printf( aTHX_ "%4s","\n");                                  \
9094 })
9095 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({\
9096     DEBUG_PARSE_MSG((funcname));                            \
9097     Perl_re_printf( aTHX_ fmt "\n",args);                               \
9098 })
9099
9100 /* This section of code defines the inversion list object and its methods.  The
9101  * interfaces are highly subject to change, so as much as possible is static to
9102  * this file.  An inversion list is here implemented as a malloc'd C UV array
9103  * as an SVt_INVLIST scalar.
9104  *
9105  * An inversion list for Unicode is an array of code points, sorted by ordinal
9106  * number.  Each element gives the code point that begins a range that extends
9107  * up-to but not including the code point given by the next element.  The final
9108  * element gives the first code point of a range that extends to the platform's
9109  * infinity.  The even-numbered elements (invlist[0], invlist[2], invlist[4],
9110  * ...) give ranges whose code points are all in the inversion list.  We say
9111  * that those ranges are in the set.  The odd-numbered elements give ranges
9112  * whose code points are not in the inversion list, and hence not in the set.
9113  * Thus, element [0] is the first code point in the list.  Element [1]
9114  * is the first code point beyond that not in the list; and element [2] is the
9115  * first code point beyond that that is in the list.  In other words, the first
9116  * range is invlist[0]..(invlist[1]-1), and all code points in that range are
9117  * in the inversion list.  The second range is invlist[1]..(invlist[2]-1), and
9118  * all code points in that range are not in the inversion list.  The third
9119  * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
9120  * list, and so forth.  Thus every element whose index is divisible by two
9121  * gives the beginning of a range that is in the list, and every element whose
9122  * index is not divisible by two gives the beginning of a range not in the
9123  * list.  If the final element's index is divisible by two, the inversion list
9124  * extends to the platform's infinity; otherwise the highest code point in the
9125  * inversion list is the contents of that element minus 1.
9126  *
9127  * A range that contains just a single code point N will look like
9128  *  invlist[i]   == N
9129  *  invlist[i+1] == N+1
9130  *
9131  * If N is UV_MAX (the highest representable code point on the machine), N+1 is
9132  * impossible to represent, so element [i+1] is omitted.  The single element
9133  * inversion list
9134  *  invlist[0] == UV_MAX
9135  * contains just UV_MAX, but is interpreted as matching to infinity.
9136  *
9137  * Taking the complement (inverting) an inversion list is quite simple, if the
9138  * first element is 0, remove it; otherwise add a 0 element at the beginning.
9139  * This implementation reserves an element at the beginning of each inversion
9140  * list to always contain 0; there is an additional flag in the header which
9141  * indicates if the list begins at the 0, or is offset to begin at the next
9142  * element.  This means that the inversion list can be inverted without any
9143  * copying; just flip the flag.
9144  *
9145  * More about inversion lists can be found in "Unicode Demystified"
9146  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
9147  *
9148  * The inversion list data structure is currently implemented as an SV pointing
9149  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
9150  * array of UV whose memory management is automatically handled by the existing
9151  * facilities for SV's.
9152  *
9153  * Some of the methods should always be private to the implementation, and some
9154  * should eventually be made public */
9155
9156 /* The header definitions are in F<invlist_inline.h> */
9157
9158 #ifndef PERL_IN_XSUB_RE
9159
9160 PERL_STATIC_INLINE UV*
9161 S__invlist_array_init(SV* const invlist, const bool will_have_0)
9162 {
9163     /* Returns a pointer to the first element in the inversion list's array.
9164      * This is called upon initialization of an inversion list.  Where the
9165      * array begins depends on whether the list has the code point U+0000 in it
9166      * or not.  The other parameter tells it whether the code that follows this
9167      * call is about to put a 0 in the inversion list or not.  The first
9168      * element is either the element reserved for 0, if TRUE, or the element
9169      * after it, if FALSE */
9170
9171     bool* offset = get_invlist_offset_addr(invlist);
9172     UV* zero_addr = (UV *) SvPVX(invlist);
9173
9174     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
9175
9176     /* Must be empty */
9177     assert(! _invlist_len(invlist));
9178
9179     *zero_addr = 0;
9180
9181     /* 1^1 = 0; 1^0 = 1 */
9182     *offset = 1 ^ will_have_0;
9183     return zero_addr + *offset;
9184 }
9185
9186 STATIC void
9187 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
9188 {
9189     /* Replaces the inversion list in 'dest' with the one from 'src'.  It
9190      * steals the list from 'src', so 'src' is made to have a NULL list.  This
9191      * is similar to what SvSetMagicSV() would do, if it were implemented on
9192      * inversion lists, though this routine avoids a copy */
9193
9194     const UV src_len          = _invlist_len(src);
9195     const bool src_offset     = *get_invlist_offset_addr(src);
9196     const STRLEN src_byte_len = SvLEN(src);
9197     char * array              = SvPVX(src);
9198
9199     const int oldtainted = TAINT_get;
9200
9201     PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
9202
9203     assert(is_invlist(src));
9204     assert(is_invlist(dest));
9205     assert(! invlist_is_iterating(src));
9206     assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
9207
9208     /* Make sure it ends in the right place with a NUL, as our inversion list
9209      * manipulations aren't careful to keep this true, but sv_usepvn_flags()
9210      * asserts it */
9211     array[src_byte_len - 1] = '\0';
9212
9213     TAINT_NOT;      /* Otherwise it breaks */
9214     sv_usepvn_flags(dest,
9215                     (char *) array,
9216                     src_byte_len - 1,
9217
9218                     /* This flag is documented to cause a copy to be avoided */
9219                     SV_HAS_TRAILING_NUL);
9220     TAINT_set(oldtainted);
9221     SvPV_set(src, 0);
9222     SvLEN_set(src, 0);
9223     SvCUR_set(src, 0);
9224
9225     /* Finish up copying over the other fields in an inversion list */
9226     *get_invlist_offset_addr(dest) = src_offset;
9227     invlist_set_len(dest, src_len, src_offset);
9228     *get_invlist_previous_index_addr(dest) = 0;
9229     invlist_iterfinish(dest);
9230 }
9231
9232 PERL_STATIC_INLINE IV*
9233 S_get_invlist_previous_index_addr(SV* invlist)
9234 {
9235     /* Return the address of the IV that is reserved to hold the cached index
9236      * */
9237     PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
9238
9239     assert(is_invlist(invlist));
9240
9241     return &(((XINVLIST*) SvANY(invlist))->prev_index);
9242 }
9243
9244 PERL_STATIC_INLINE IV
9245 S_invlist_previous_index(SV* const invlist)
9246 {
9247     /* Returns cached index of previous search */
9248
9249     PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
9250
9251     return *get_invlist_previous_index_addr(invlist);
9252 }
9253
9254 PERL_STATIC_INLINE void
9255 S_invlist_set_previous_index(SV* const invlist, const IV index)
9256 {
9257     /* Caches <index> for later retrieval */
9258
9259     PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
9260
9261     assert(index == 0 || index < (int) _invlist_len(invlist));
9262
9263     *get_invlist_previous_index_addr(invlist) = index;
9264 }
9265
9266 PERL_STATIC_INLINE void
9267 S_invlist_trim(SV* invlist)
9268 {
9269     /* Free the not currently-being-used space in an inversion list */
9270
9271     /* But don't free up the space needed for the 0 UV that is always at the
9272      * beginning of the list, nor the trailing NUL */
9273     const UV min_size = TO_INTERNAL_SIZE(1) + 1;
9274
9275     PERL_ARGS_ASSERT_INVLIST_TRIM;
9276
9277     assert(is_invlist(invlist));
9278
9279     SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
9280 }
9281
9282 PERL_STATIC_INLINE void
9283 S_invlist_clear(pTHX_ SV* invlist)    /* Empty the inversion list */
9284 {
9285     PERL_ARGS_ASSERT_INVLIST_CLEAR;
9286
9287     assert(is_invlist(invlist));
9288
9289     invlist_set_len(invlist, 0, 0);
9290     invlist_trim(invlist);
9291 }
9292
9293 #endif /* ifndef PERL_IN_XSUB_RE */
9294
9295 PERL_STATIC_INLINE bool
9296 S_invlist_is_iterating(SV* const invlist)
9297 {
9298     PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
9299
9300     return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
9301 }
9302
9303 #ifndef PERL_IN_XSUB_RE
9304
9305 PERL_STATIC_INLINE UV
9306 S_invlist_max(SV* const invlist)
9307 {
9308     /* Returns the maximum number of elements storable in the inversion list's
9309      * array, without having to realloc() */
9310
9311     PERL_ARGS_ASSERT_INVLIST_MAX;
9312
9313     assert(is_invlist(invlist));
9314
9315     /* Assumes worst case, in which the 0 element is not counted in the
9316      * inversion list, so subtracts 1 for that */
9317     return SvLEN(invlist) == 0  /* This happens under _new_invlist_C_array */
9318            ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
9319            : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
9320 }
9321
9322 STATIC void
9323 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
9324 {
9325     PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
9326
9327     /* First 1 is in case the zero element isn't in the list; second 1 is for
9328      * trailing NUL */
9329     SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
9330     invlist_set_len(invlist, 0, 0);
9331
9332     /* Force iterinit() to be used to get iteration to work */
9333     invlist_iterfinish(invlist);
9334
9335     *get_invlist_previous_index_addr(invlist) = 0;
9336     SvPOK_on(invlist);  /* This allows B to extract the PV */
9337 }
9338
9339 SV*
9340 Perl__new_invlist(pTHX_ IV initial_size)
9341 {
9342
9343     /* Return a pointer to a newly constructed inversion list, with enough
9344      * space to store 'initial_size' elements.  If that number is negative, a
9345      * system default is used instead */
9346
9347     SV* new_list;
9348
9349     if (initial_size < 0) {
9350         initial_size = 10;
9351     }
9352
9353     new_list = newSV_type(SVt_INVLIST);
9354     initialize_invlist_guts(new_list, initial_size);
9355
9356     return new_list;
9357 }
9358
9359 SV*
9360 Perl__new_invlist_C_array(pTHX_ const UV* const list)
9361 {
9362     /* Return a pointer to a newly constructed inversion list, initialized to
9363      * point to <list>, which has to be in the exact correct inversion list
9364      * form, including internal fields.  Thus this is a dangerous routine that
9365      * should not be used in the wrong hands.  The passed in 'list' contains
9366      * several header fields at the beginning that are not part of the
9367      * inversion list body proper */
9368
9369     const STRLEN length = (STRLEN) list[0];
9370     const UV version_id =          list[1];
9371     const bool offset   =    cBOOL(list[2]);
9372 #define HEADER_LENGTH 3
9373     /* If any of the above changes in any way, you must change HEADER_LENGTH
9374      * (if appropriate) and regenerate INVLIST_VERSION_ID by running
9375      *      perl -E 'say int(rand 2**31-1)'
9376      */
9377 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
9378                                         data structure type, so that one being
9379                                         passed in can be validated to be an
9380                                         inversion list of the correct vintage.
9381                                        */
9382
9383     SV* invlist = newSV_type(SVt_INVLIST);
9384
9385     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
9386
9387     if (version_id != INVLIST_VERSION_ID) {
9388         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
9389     }
9390
9391     /* The generated array passed in includes header elements that aren't part
9392      * of the list proper, so start it just after them */
9393     SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
9394
9395     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
9396                                shouldn't touch it */
9397
9398     *(get_invlist_offset_addr(invlist)) = offset;
9399
9400     /* The 'length' passed to us is the physical number of elements in the
9401      * inversion list.  But if there is an offset the logical number is one
9402      * less than that */
9403     invlist_set_len(invlist, length  - offset, offset);
9404
9405     invlist_set_previous_index(invlist, 0);
9406
9407     /* Initialize the iteration pointer. */
9408     invlist_iterfinish(invlist);
9409
9410     SvREADONLY_on(invlist);
9411     SvPOK_on(invlist);
9412
9413     return invlist;
9414 }
9415
9416 STATIC void
9417 S__append_range_to_invlist(pTHX_ SV* const invlist,
9418                                  const UV start, const UV end)
9419 {
9420    /* Subject to change or removal.  Append the range from 'start' to 'end' at
9421     * the end of the inversion list.  The range must be above any existing
9422     * ones. */
9423
9424     UV* array;
9425     UV max = invlist_max(invlist);
9426     UV len = _invlist_len(invlist);
9427     bool offset;
9428
9429     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9430
9431     if (len == 0) { /* Empty lists must be initialized */
9432         offset = start != 0;
9433         array = _invlist_array_init(invlist, ! offset);
9434     }
9435     else {
9436         /* Here, the existing list is non-empty. The current max entry in the
9437          * list is generally the first value not in the set, except when the
9438          * set extends to the end of permissible values, in which case it is
9439          * the first entry in that final set, and so this call is an attempt to
9440          * append out-of-order */
9441
9442         UV final_element = len - 1;
9443         array = invlist_array(invlist);
9444         if (   array[final_element] > start
9445             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9446         {
9447             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",
9448                      array[final_element], start,
9449                      ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9450         }
9451
9452         /* Here, it is a legal append.  If the new range begins 1 above the end
9453          * of the range below it, it is extending the range below it, so the
9454          * new first value not in the set is one greater than the newly
9455          * extended range.  */
9456         offset = *get_invlist_offset_addr(invlist);
9457         if (array[final_element] == start) {
9458             if (end != UV_MAX) {
9459                 array[final_element] = end + 1;
9460             }
9461             else {
9462                 /* But if the end is the maximum representable on the machine,
9463                  * assume that infinity was actually what was meant.  Just let
9464                  * the range that this would extend to have no end */
9465                 invlist_set_len(invlist, len - 1, offset);
9466             }
9467             return;
9468         }
9469     }
9470
9471     /* Here the new range doesn't extend any existing set.  Add it */
9472
9473     len += 2;   /* Includes an element each for the start and end of range */
9474
9475     /* If wll overflow the existing space, extend, which may cause the array to
9476      * be moved */
9477     if (max < len) {
9478         invlist_extend(invlist, len);
9479
9480         /* Have to set len here to avoid assert failure in invlist_array() */
9481         invlist_set_len(invlist, len, offset);
9482
9483         array = invlist_array(invlist);
9484     }
9485     else {
9486         invlist_set_len(invlist, len, offset);
9487     }
9488
9489     /* The next item on the list starts the range, the one after that is
9490      * one past the new range.  */
9491     array[len - 2] = start;
9492     if (end != UV_MAX) {
9493         array[len - 1] = end + 1;
9494     }
9495     else {
9496         /* But if the end is the maximum representable on the machine, just let
9497          * the range have no end */
9498         invlist_set_len(invlist, len - 1, offset);
9499     }
9500 }
9501
9502 SSize_t
9503 Perl__invlist_search(SV* const invlist, const UV cp)
9504 {
9505     /* Searches the inversion list for the entry that contains the input code
9506      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
9507      * return value is the index into the list's array of the range that
9508      * contains <cp>, that is, 'i' such that
9509      *  array[i] <= cp < array[i+1]
9510      */
9511
9512     IV low = 0;
9513     IV mid;
9514     IV high = _invlist_len(invlist);
9515     const IV highest_element = high - 1;
9516     const UV* array;
9517
9518     PERL_ARGS_ASSERT__INVLIST_SEARCH;
9519
9520     /* If list is empty, return failure. */
9521     if (high == 0) {
9522         return -1;
9523     }
9524
9525     /* (We can't get the array unless we know the list is non-empty) */
9526     array = invlist_array(invlist);
9527
9528     mid = invlist_previous_index(invlist);
9529     assert(mid >=0);
9530     if (mid > highest_element) {
9531         mid = highest_element;
9532     }
9533
9534     /* <mid> contains the cache of the result of the previous call to this
9535      * function (0 the first time).  See if this call is for the same result,
9536      * or if it is for mid-1.  This is under the theory that calls to this
9537      * function will often be for related code points that are near each other.
9538      * And benchmarks show that caching gives better results.  We also test
9539      * here if the code point is within the bounds of the list.  These tests
9540      * replace others that would have had to be made anyway to make sure that
9541      * the array bounds were not exceeded, and these give us extra information
9542      * at the same time */
9543     if (cp >= array[mid]) {
9544         if (cp >= array[highest_element]) {
9545             return highest_element;
9546         }
9547
9548         /* Here, array[mid] <= cp < array[highest_element].  This means that
9549          * the final element is not the answer, so can exclude it; it also
9550          * means that <mid> is not the final element, so can refer to 'mid + 1'
9551          * safely */
9552         if (cp < array[mid + 1]) {
9553             return mid;
9554         }
9555         high--;
9556         low = mid + 1;
9557     }
9558     else { /* cp < aray[mid] */
9559         if (cp < array[0]) { /* Fail if outside the array */
9560             return -1;
9561         }
9562         high = mid;
9563         if (cp >= array[mid - 1]) {
9564             goto found_entry;
9565         }
9566     }
9567
9568     /* Binary search.  What we are looking for is <i> such that
9569      *  array[i] <= cp < array[i+1]
9570      * The loop below converges on the i+1.  Note that there may not be an
9571      * (i+1)th element in the array, and things work nonetheless */
9572     while (low < high) {
9573         mid = (low + high) / 2;
9574         assert(mid <= highest_element);
9575         if (array[mid] <= cp) { /* cp >= array[mid] */
9576             low = mid + 1;
9577
9578             /* We could do this extra test to exit the loop early.
9579             if (cp < array[low]) {
9580                 return mid;
9581             }
9582             */
9583         }
9584         else { /* cp < array[mid] */
9585             high = mid;
9586         }
9587     }
9588
9589   found_entry:
9590     high--;
9591     invlist_set_previous_index(invlist, high);
9592     return high;
9593 }
9594
9595 void
9596 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9597                                          const bool complement_b, SV** output)
9598 {
9599     /* Take the union of two inversion lists and point '*output' to it.  On
9600      * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9601      * even 'a' or 'b').  If to an inversion list, the contents of the original
9602      * list will be replaced by the union.  The first list, 'a', may be
9603      * NULL, in which case a copy of the second list is placed in '*output'.
9604      * If 'complement_b' is TRUE, the union is taken of the complement
9605      * (inversion) of 'b' instead of b itself.
9606      *
9607      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9608      * Richard Gillam, published by Addison-Wesley, and explained at some
9609      * length there.  The preface says to incorporate its examples into your
9610      * code at your own risk.
9611      *
9612      * The algorithm is like a merge sort. */
9613
9614     const UV* array_a;    /* a's array */
9615     const UV* array_b;
9616     UV len_a;       /* length of a's array */
9617     UV len_b;
9618
9619     SV* u;                      /* the resulting union */
9620     UV* array_u;
9621     UV len_u = 0;
9622
9623     UV i_a = 0;             /* current index into a's array */
9624     UV i_b = 0;
9625     UV i_u = 0;
9626
9627     /* running count, as explained in the algorithm source book; items are
9628      * stopped accumulating and are output when the count changes to/from 0.
9629      * The count is incremented when we start a range that's in an input's set,
9630      * and decremented when we start a range that's not in a set.  So this
9631      * variable can be 0, 1, or 2.  When it is 0 neither input is in their set,
9632      * and hence nothing goes into the union; 1, just one of the inputs is in
9633      * its set (and its current range gets added to the union); and 2 when both
9634      * inputs are in their sets.  */
9635     UV count = 0;
9636
9637     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9638     assert(a != b);
9639     assert(*output == NULL || is_invlist(*output));
9640
9641     len_b = _invlist_len(b);
9642     if (len_b == 0) {
9643
9644         /* Here, 'b' is empty, hence it's complement is all possible code
9645          * points.  So if the union includes the complement of 'b', it includes
9646          * everything, and we need not even look at 'a'.  It's easiest to
9647          * create a new inversion list that matches everything.  */
9648         if (complement_b) {
9649             SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9650
9651             if (*output == NULL) { /* If the output didn't exist, just point it
9652                                       at the new list */
9653                 *output = everything;
9654             }
9655             else { /* Otherwise, replace its contents with the new list */
9656                 invlist_replace_list_destroys_src(*output, everything);
9657                 SvREFCNT_dec_NN(everything);
9658             }
9659
9660             return;
9661         }
9662
9663         /* Here, we don't want the complement of 'b', and since 'b' is empty,
9664          * the union will come entirely from 'a'.  If 'a' is NULL or empty, the
9665          * output will be empty */
9666
9667         if (a == NULL || _invlist_len(a) == 0) {
9668             if (*output == NULL) {
9669                 *output = _new_invlist(0);
9670             }
9671             else {
9672                 invlist_clear(*output);
9673             }
9674             return;
9675         }
9676
9677         /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9678          * union.  We can just return a copy of 'a' if '*output' doesn't point
9679          * to an existing list */
9680         if (*output == NULL) {
9681             *output = invlist_clone(a, NULL);
9682             return;
9683         }
9684
9685         /* If the output is to overwrite 'a', we have a no-op, as it's
9686          * already in 'a' */
9687         if (*output == a) {
9688             return;
9689         }
9690
9691         /* Here, '*output' is to be overwritten by 'a' */
9692         u = invlist_clone(a, NULL);
9693         invlist_replace_list_destroys_src(*output, u);
9694         SvREFCNT_dec_NN(u);
9695
9696         return;
9697     }
9698
9699     /* Here 'b' is not empty.  See about 'a' */
9700
9701     if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9702
9703         /* Here, 'a' is empty (and b is not).  That means the union will come
9704          * entirely from 'b'.  If '*output' is NULL, we can directly return a
9705          * clone of 'b'.  Otherwise, we replace the contents of '*output' with
9706          * the clone */
9707
9708         SV ** dest = (*output == NULL) ? output : &u;
9709         *dest = invlist_clone(b, NULL);
9710         if (complement_b) {
9711             _invlist_invert(*dest);
9712         }
9713
9714         if (dest == &u) {
9715             invlist_replace_list_destroys_src(*output, u);
9716             SvREFCNT_dec_NN(u);
9717         }
9718
9719         return;
9720     }
9721
9722     /* Here both lists exist and are non-empty */
9723     array_a = invlist_array(a);
9724     array_b = invlist_array(b);
9725
9726     /* If are to take the union of 'a' with the complement of b, set it
9727      * up so are looking at b's complement. */
9728     if (complement_b) {
9729
9730         /* To complement, we invert: if the first element is 0, remove it.  To
9731          * do this, we just pretend the array starts one later */
9732         if (array_b[0] == 0) {
9733             array_b++;
9734             len_b--;
9735         }
9736         else {
9737
9738             /* But if the first element is not zero, we pretend the list starts
9739              * at the 0 that is always stored immediately before the array. */
9740             array_b--;
9741             len_b++;
9742         }
9743     }
9744
9745     /* Size the union for the worst case: that the sets are completely
9746      * disjoint */
9747     u = _new_invlist(len_a + len_b);
9748
9749     /* Will contain U+0000 if either component does */
9750     array_u = _invlist_array_init(u, (    len_a > 0 && array_a[0] == 0)
9751                                       || (len_b > 0 && array_b[0] == 0));
9752
9753     /* Go through each input list item by item, stopping when have exhausted
9754      * one of them */
9755     while (i_a < len_a && i_b < len_b) {
9756         UV cp;      /* The element to potentially add to the union's array */
9757         bool cp_in_set;   /* is it in the input list's set or not */
9758
9759         /* We need to take one or the other of the two inputs for the union.
9760          * Since we are merging two sorted lists, we take the smaller of the
9761          * next items.  In case of a tie, we take first the one that is in its
9762          * set.  If we first took the one not in its set, it would decrement
9763          * the count, possibly to 0 which would cause it to be output as ending
9764          * the range, and the next time through we would take the same number,
9765          * and output it again as beginning the next range.  By doing it the
9766          * opposite way, there is no possibility that the count will be
9767          * momentarily decremented to 0, and thus the two adjoining ranges will
9768          * be seamlessly merged.  (In a tie and both are in the set or both not
9769          * in the set, it doesn't matter which we take first.) */
9770         if (       array_a[i_a] < array_b[i_b]
9771             || (   array_a[i_a] == array_b[i_b]
9772                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9773         {
9774             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9775             cp = array_a[i_a++];
9776         }
9777         else {
9778             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9779             cp = array_b[i_b++];
9780         }
9781
9782         /* Here, have chosen which of the two inputs to look at.  Only output
9783          * if the running count changes to/from 0, which marks the
9784          * beginning/end of a range that's in the set */
9785         if (cp_in_set) {
9786             if (count == 0) {
9787                 array_u[i_u++] = cp;
9788             }
9789             count++;
9790         }
9791         else {
9792             count--;
9793             if (count == 0) {
9794                 array_u[i_u++] = cp;
9795             }
9796         }
9797     }
9798
9799
9800     /* The loop above increments the index into exactly one of the input lists
9801      * each iteration, and ends when either index gets to its list end.  That
9802      * means the other index is lower than its end, and so something is
9803      * remaining in that one.  We decrement 'count', as explained below, if
9804      * that list is in its set.  (i_a and i_b each currently index the element
9805      * beyond the one we care about.) */
9806     if (   (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9807         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9808     {
9809         count--;
9810     }
9811
9812     /* Above we decremented 'count' if the list that had unexamined elements in
9813      * it was in its set.  This has made it so that 'count' being non-zero
9814      * means there isn't anything left to output; and 'count' equal to 0 means
9815      * that what is left to output is precisely that which is left in the
9816      * non-exhausted input list.
9817      *
9818      * To see why, note first that the exhausted input obviously has nothing
9819      * left to add to the union.  If it was in its set at its end, that means
9820      * the set extends from here to the platform's infinity, and hence so does
9821      * the union and the non-exhausted set is irrelevant.  The exhausted set
9822      * also contributed 1 to 'count'.  If 'count' was 2, it got decremented to
9823      * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9824      * 'count' remains at 1.  This is consistent with the decremented 'count'
9825      * != 0 meaning there's nothing left to add to the union.
9826      *
9827      * But if the exhausted input wasn't in its set, it contributed 0 to
9828      * 'count', and the rest of the union will be whatever the other input is.
9829      * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9830      * otherwise it gets decremented to 0.  This is consistent with 'count'
9831      * == 0 meaning the remainder of the union is whatever is left in the
9832      * non-exhausted list. */
9833     if (count != 0) {
9834         len_u = i_u;
9835     }
9836     else {
9837         IV copy_count = len_a - i_a;
9838         if (copy_count > 0) {   /* The non-exhausted input is 'a' */
9839             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9840         }
9841         else { /* The non-exhausted input is b */
9842             copy_count = len_b - i_b;
9843             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9844         }
9845         len_u = i_u + copy_count;
9846     }
9847
9848     /* Set the result to the final length, which can change the pointer to
9849      * array_u, so re-find it.  (Note that it is unlikely that this will
9850      * change, as we are shrinking the space, not enlarging it) */
9851     if (len_u != _invlist_len(u)) {
9852         invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9853         invlist_trim(u);
9854         array_u = invlist_array(u);
9855     }
9856
9857     if (*output == NULL) {  /* Simply return the new inversion list */
9858         *output = u;
9859     }
9860     else {
9861         /* Otherwise, overwrite the inversion list that was in '*output'.  We
9862          * could instead free '*output', and then set it to 'u', but experience
9863          * has shown [perl #127392] that if the input is a mortal, we can get a
9864          * huge build-up of these during regex compilation before they get
9865          * freed. */
9866         invlist_replace_list_destroys_src(*output, u);
9867         SvREFCNT_dec_NN(u);
9868     }
9869
9870     return;
9871 }
9872
9873 void
9874 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9875                                                const bool complement_b, SV** i)
9876 {
9877     /* Take the intersection of two inversion lists and point '*i' to it.  On
9878      * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9879      * even 'a' or 'b').  If to an inversion list, the contents of the original
9880      * list will be replaced by the intersection.  The first list, 'a', may be
9881      * NULL, in which case '*i' will be an empty list.  If 'complement_b' is
9882      * TRUE, the result will be the intersection of 'a' and the complement (or
9883      * inversion) of 'b' instead of 'b' directly.
9884      *
9885      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9886      * Richard Gillam, published by Addison-Wesley, and explained at some
9887      * length there.  The preface says to incorporate its examples into your
9888      * code at your own risk.  In fact, it had bugs
9889      *
9890      * The algorithm is like a merge sort, and is essentially the same as the
9891      * union above
9892      */
9893
9894     const UV* array_a;          /* a's array */
9895     const UV* array_b;
9896     UV len_a;   /* length of a's array */
9897     UV len_b;
9898
9899     SV* r;                   /* the resulting intersection */
9900     UV* array_r;
9901     UV len_r = 0;
9902
9903     UV i_a = 0;             /* current index into a's array */
9904     UV i_b = 0;
9905     UV i_r = 0;
9906
9907     /* running count of how many of the two inputs are postitioned at ranges
9908      * that are in their sets.  As explained in the algorithm source book,
9909      * items are stopped accumulating and are output when the count changes
9910      * to/from 2.  The count is incremented when we start a range that's in an
9911      * input's set, and decremented when we start a range that's not in a set.
9912      * Only when it is 2 are we in the intersection. */
9913     UV count = 0;
9914
9915     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9916     assert(a != b);
9917     assert(*i == NULL || is_invlist(*i));
9918
9919     /* Special case if either one is empty */
9920     len_a = (a == NULL) ? 0 : _invlist_len(a);
9921     if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9922         if (len_a != 0 && complement_b) {
9923
9924             /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9925              * must be empty.  Here, also we are using 'b's complement, which
9926              * hence must be every possible code point.  Thus the intersection
9927              * is simply 'a'. */
9928
9929             if (*i == a) {  /* No-op */
9930                 return;
9931             }
9932
9933             if (*i == NULL) {
9934                 *i = invlist_clone(a, NULL);
9935                 return;
9936             }
9937
9938             r = invlist_clone(a, NULL);
9939             invlist_replace_list_destroys_src(*i, r);
9940             SvREFCNT_dec_NN(r);
9941             return;
9942         }
9943
9944         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
9945          * intersection must be empty */
9946         if (*i == NULL) {
9947             *i = _new_invlist(0);
9948             return;
9949         }
9950
9951         invlist_clear(*i);
9952         return;
9953     }
9954
9955     /* Here both lists exist and are non-empty */
9956     array_a = invlist_array(a);
9957     array_b = invlist_array(b);
9958
9959     /* If are to take the intersection of 'a' with the complement of b, set it
9960      * up so are looking at b's complement. */
9961     if (complement_b) {
9962
9963         /* To complement, we invert: if the first element is 0, remove it.  To
9964          * do this, we just pretend the array starts one later */
9965         if (array_b[0] == 0) {
9966             array_b++;
9967             len_b--;
9968         }
9969         else {
9970
9971             /* But if the first element is not zero, we pretend the list starts
9972              * at the 0 that is always stored immediately before the array. */
9973             array_b--;
9974             len_b++;
9975         }
9976     }
9977
9978     /* Size the intersection for the worst case: that the intersection ends up
9979      * fragmenting everything to be completely disjoint */
9980     r= _new_invlist(len_a + len_b);
9981
9982     /* Will contain U+0000 iff both components do */
9983     array_r = _invlist_array_init(r,    len_a > 0 && array_a[0] == 0
9984                                      && len_b > 0 && array_b[0] == 0);
9985
9986     /* Go through each list item by item, stopping when have exhausted one of
9987      * them */
9988     while (i_a < len_a && i_b < len_b) {
9989         UV cp;      /* The element to potentially add to the intersection's
9990                        array */
9991         bool cp_in_set; /* Is it in the input list's set or not */
9992
9993         /* We need to take one or the other of the two inputs for the
9994          * intersection.  Since we are merging two sorted lists, we take the
9995          * smaller of the next items.  In case of a tie, we take first the one
9996          * that is not in its set (a difference from the union algorithm).  If
9997          * we first took the one in its set, it would increment the count,
9998          * possibly to 2 which would cause it to be output as starting a range
9999          * in the intersection, and the next time through we would take that
10000          * same number, and output it again as ending the set.  By doing the
10001          * opposite of this, there is no possibility that the count will be
10002          * momentarily incremented to 2.  (In a tie and both are in the set or
10003          * both not in the set, it doesn't matter which we take first.) */
10004         if (       array_a[i_a] < array_b[i_b]
10005             || (   array_a[i_a] == array_b[i_b]
10006                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
10007         {
10008             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
10009             cp = array_a[i_a++];
10010         }
10011         else {
10012             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
10013             cp= array_b[i_b++];
10014         }
10015
10016         /* Here, have chosen which of the two inputs to look at.  Only output
10017          * if the running count changes to/from 2, which marks the
10018          * beginning/end of a range that's in the intersection */
10019         if (cp_in_set) {
10020             count++;
10021             if (count == 2) {
10022                 array_r[i_r++] = cp;
10023             }
10024         }
10025         else {
10026             if (count == 2) {
10027                 array_r[i_r++] = cp;
10028             }
10029             count--;
10030         }
10031
10032     }
10033
10034     /* The loop above increments the index into exactly one of the input lists
10035      * each iteration, and ends when either index gets to its list end.  That
10036      * means the other index is lower than its end, and so something is
10037      * remaining in that one.  We increment 'count', as explained below, if the
10038      * exhausted list was in its set.  (i_a and i_b each currently index the
10039      * element beyond the one we care about.) */
10040     if (   (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
10041         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
10042     {
10043         count++;
10044     }
10045
10046     /* Above we incremented 'count' if the exhausted list was in its set.  This
10047      * has made it so that 'count' being below 2 means there is nothing left to
10048      * output; otheriwse what's left to add to the intersection is precisely
10049      * that which is left in the non-exhausted input list.
10050      *
10051      * To see why, note first that the exhausted input obviously has nothing
10052      * left to affect the intersection.  If it was in its set at its end, that
10053      * means the set extends from here to the platform's infinity, and hence
10054      * anything in the non-exhausted's list will be in the intersection, and
10055      * anything not in it won't be.  Hence, the rest of the intersection is
10056      * precisely what's in the non-exhausted list  The exhausted set also
10057      * contributed 1 to 'count', meaning 'count' was at least 1.  Incrementing
10058      * it means 'count' is now at least 2.  This is consistent with the
10059      * incremented 'count' being >= 2 means to add the non-exhausted list to
10060      * the intersection.
10061      *
10062      * But if the exhausted input wasn't in its set, it contributed 0 to
10063      * 'count', and the intersection can't include anything further; the
10064      * non-exhausted set is irrelevant.  'count' was at most 1, and doesn't get
10065      * incremented.  This is consistent with 'count' being < 2 meaning nothing
10066      * further to add to the intersection. */
10067     if (count < 2) { /* Nothing left to put in the intersection. */
10068         len_r = i_r;
10069     }
10070     else { /* copy the non-exhausted list, unchanged. */
10071         IV copy_count = len_a - i_a;
10072         if (copy_count > 0) {   /* a is the one with stuff left */
10073             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
10074         }
10075         else {  /* b is the one with stuff left */
10076             copy_count = len_b - i_b;
10077             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
10078         }
10079         len_r = i_r + copy_count;
10080     }
10081
10082     /* Set the result to the final length, which can change the pointer to
10083      * array_r, so re-find it.  (Note that it is unlikely that this will
10084      * change, as we are shrinking the space, not enlarging it) */
10085     if (len_r != _invlist_len(r)) {
10086         invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
10087         invlist_trim(r);
10088         array_r = invlist_array(r);
10089     }
10090
10091     if (*i == NULL) { /* Simply return the calculated intersection */
10092         *i = r;
10093     }
10094     else { /* Otherwise, replace the existing inversion list in '*i'.  We could
10095               instead free '*i', and then set it to 'r', but experience has
10096               shown [perl #127392] that if the input is a mortal, we can get a
10097               huge build-up of these during regex compilation before they get
10098               freed. */
10099         if (len_r) {
10100             invlist_replace_list_destroys_src(*i, r);
10101         }
10102         else {
10103             invlist_clear(*i);
10104         }
10105         SvREFCNT_dec_NN(r);
10106     }
10107
10108     return;
10109 }
10110
10111 SV*
10112 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
10113 {
10114     /* Add the range from 'start' to 'end' inclusive to the inversion list's
10115      * set.  A pointer to the inversion list is returned.  This may actually be
10116      * a new list, in which case the passed in one has been destroyed.  The
10117      * passed-in inversion list can be NULL, in which case a new one is created
10118      * with just the one range in it.  The new list is not necessarily
10119      * NUL-terminated.  Space is not freed if the inversion list shrinks as a
10120      * result of this function.  The gain would not be large, and in many
10121      * cases, this is called multiple times on a single inversion list, so
10122      * anything freed may almost immediately be needed again.
10123      *
10124      * This used to mostly call the 'union' routine, but that is much more
10125      * heavyweight than really needed for a single range addition */
10126
10127     UV* array;              /* The array implementing the inversion list */
10128     UV len;                 /* How many elements in 'array' */
10129     SSize_t i_s;            /* index into the invlist array where 'start'
10130                                should go */
10131     SSize_t i_e = 0;        /* And the index where 'end' should go */
10132     UV cur_highest;         /* The highest code point in the inversion list
10133                                upon entry to this function */
10134
10135     /* This range becomes the whole inversion list if none already existed */
10136     if (invlist == NULL) {
10137         invlist = _new_invlist(2);
10138         _append_range_to_invlist(invlist, start, end);
10139         return invlist;
10140     }
10141
10142     /* Likewise, if the inversion list is currently empty */
10143     len = _invlist_len(invlist);
10144     if (len == 0) {
10145         _append_range_to_invlist(invlist, start, end);
10146         return invlist;
10147     }
10148
10149     /* Starting here, we have to know the internals of the list */
10150     array = invlist_array(invlist);
10151
10152     /* If the new range ends higher than the current highest ... */
10153     cur_highest = invlist_highest(invlist);
10154     if (end > cur_highest) {
10155
10156         /* If the whole range is higher, we can just append it */
10157         if (start > cur_highest) {
10158             _append_range_to_invlist(invlist, start, end);
10159             return invlist;
10160         }
10161
10162         /* Otherwise, add the portion that is higher ... */
10163         _append_range_to_invlist(invlist, cur_highest + 1, end);
10164
10165         /* ... and continue on below to handle the rest.  As a result of the
10166          * above append, we know that the index of the end of the range is the
10167          * final even numbered one of the array.  Recall that the final element
10168          * always starts a range that extends to infinity.  If that range is in
10169          * the set (meaning the set goes from here to infinity), it will be an
10170          * even index, but if it isn't in the set, it's odd, and the final
10171          * range in the set is one less, which is even. */
10172         if (end == UV_MAX) {
10173             i_e = len;
10174         }
10175         else {
10176             i_e = len - 2;
10177         }
10178     }
10179
10180     /* We have dealt with appending, now see about prepending.  If the new
10181      * range starts lower than the current lowest ... */
10182     if (start < array[0]) {
10183
10184         /* Adding something which has 0 in it is somewhat tricky, and uncommon.
10185          * Let the union code handle it, rather than having to know the
10186          * trickiness in two code places.  */
10187         if (UNLIKELY(start == 0)) {
10188             SV* range_invlist;
10189
10190             range_invlist = _new_invlist(2);
10191             _append_range_to_invlist(range_invlist, start, end);
10192
10193             _invlist_union(invlist, range_invlist, &invlist);
10194
10195             SvREFCNT_dec_NN(range_invlist);
10196
10197             return invlist;
10198         }
10199
10200         /* If the whole new range comes before the first entry, and doesn't
10201          * extend it, we have to insert it as an additional range */
10202         if (end < array[0] - 1) {
10203             i_s = i_e = -1;
10204             goto splice_in_new_range;
10205         }
10206
10207         /* Here the new range adjoins the existing first range, extending it
10208          * downwards. */
10209         array[0] = start;
10210
10211         /* And continue on below to handle the rest.  We know that the index of
10212          * the beginning of the range is the first one of the array */
10213         i_s = 0;
10214     }
10215     else { /* Not prepending any part of the new range to the existing list.
10216             * Find where in the list it should go.  This finds i_s, such that:
10217             *     invlist[i_s] <= start < array[i_s+1]
10218             */
10219         i_s = _invlist_search(invlist, start);
10220     }
10221
10222     /* At this point, any extending before the beginning of the inversion list
10223      * and/or after the end has been done.  This has made it so that, in the
10224      * code below, each endpoint of the new range is either in a range that is
10225      * in the set, or is in a gap between two ranges that are.  This means we
10226      * don't have to worry about exceeding the array bounds.
10227      *
10228      * Find where in the list the new range ends (but we can skip this if we
10229      * have already determined what it is, or if it will be the same as i_s,
10230      * which we already have computed) */
10231     if (i_e == 0) {
10232         i_e = (start == end)
10233               ? i_s
10234               : _invlist_search(invlist, end);
10235     }
10236
10237     /* Here generally invlist[i_e] <= end < array[i_e+1].  But if invlist[i_e]
10238      * is a range that goes to infinity there is no element at invlist[i_e+1],
10239      * so only the first relation holds. */
10240
10241     if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10242
10243         /* Here, the ranges on either side of the beginning of the new range
10244          * are in the set, and this range starts in the gap between them.
10245          *
10246          * The new range extends the range above it downwards if the new range
10247          * ends at or above that range's start */
10248         const bool extends_the_range_above = (   end == UV_MAX
10249                                               || end + 1 >= array[i_s+1]);
10250
10251         /* The new range extends the range below it upwards if it begins just
10252          * after where that range ends */
10253         if (start == array[i_s]) {
10254
10255             /* If the new range fills the entire gap between the other ranges,
10256              * they will get merged together.  Other ranges may also get
10257              * merged, depending on how many of them the new range spans.  In
10258              * the general case, we do the merge later, just once, after we
10259              * figure out how many to merge.  But in the case where the new
10260              * range exactly spans just this one gap (possibly extending into
10261              * the one above), we do the merge here, and an early exit.  This
10262              * is done here to avoid having to special case later. */
10263             if (i_e - i_s <= 1) {
10264
10265                 /* If i_e - i_s == 1, it means that the new range terminates
10266                  * within the range above, and hence 'extends_the_range_above'
10267                  * must be true.  (If the range above it extends to infinity,
10268                  * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
10269                  * will be 0, so no harm done.) */
10270                 if (extends_the_range_above) {
10271                     Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
10272                     invlist_set_len(invlist,
10273                                     len - 2,
10274                                     *(get_invlist_offset_addr(invlist)));
10275                     return invlist;
10276                 }
10277
10278                 /* Here, i_e must == i_s.  We keep them in sync, as they apply
10279                  * to the same range, and below we are about to decrement i_s
10280                  * */
10281                 i_e--;
10282             }
10283
10284             /* Here, the new range is adjacent to the one below.  (It may also
10285              * span beyond the range above, but that will get resolved later.)
10286              * Extend the range below to include this one. */
10287             array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
10288             i_s--;
10289             start = array[i_s];
10290         }
10291         else if (extends_the_range_above) {
10292
10293             /* Here the new range only extends the range above it, but not the
10294              * one below.  It merges with the one above.  Again, we keep i_e
10295              * and i_s in sync if they point to the same range */
10296             if (i_e == i_s) {
10297                 i_e++;
10298             }
10299             i_s++;
10300             array[i_s] = start;
10301         }
10302     }
10303
10304     /* Here, we've dealt with the new range start extending any adjoining
10305      * existing ranges.
10306      *
10307      * If the new range extends to infinity, it is now the final one,
10308      * regardless of what was there before */
10309     if (UNLIKELY(end == UV_MAX)) {
10310         invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10311         return invlist;
10312     }
10313
10314     /* If i_e started as == i_s, it has also been dealt with,
10315      * and been updated to the new i_s, which will fail the following if */
10316     if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10317
10318         /* Here, the ranges on either side of the end of the new range are in
10319          * the set, and this range ends in the gap between them.
10320          *
10321          * If this range is adjacent to (hence extends) the range above it, it
10322          * becomes part of that range; likewise if it extends the range below,
10323          * it becomes part of that range */
10324         if (end + 1 == array[i_e+1]) {
10325             i_e++;
10326             array[i_e] = start;
10327         }
10328         else if (start <= array[i_e]) {
10329             array[i_e] = end + 1;
10330             i_e--;
10331         }
10332     }
10333
10334     if (i_s == i_e) {
10335
10336         /* If the range fits entirely in an existing range (as possibly already
10337          * extended above), it doesn't add anything new */
10338         if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10339             return invlist;
10340         }
10341
10342         /* Here, no part of the range is in the list.  Must add it.  It will
10343          * occupy 2 more slots */
10344       splice_in_new_range:
10345
10346         invlist_extend(invlist, len + 2);
10347         array = invlist_array(invlist);
10348         /* Move the rest of the array down two slots. Don't include any
10349          * trailing NUL */
10350         Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10351
10352         /* Do the actual splice */
10353         array[i_e+1] = start;
10354         array[i_e+2] = end + 1;
10355         invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10356         return invlist;
10357     }
10358
10359     /* Here the new range crossed the boundaries of a pre-existing range.  The
10360      * code above has adjusted things so that both ends are in ranges that are
10361      * in the set.  This means everything in between must also be in the set.
10362      * Just squash things together */
10363     Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10364     invlist_set_len(invlist,
10365                     len - i_e + i_s,
10366                     *(get_invlist_offset_addr(invlist)));
10367
10368     return invlist;
10369 }
10370
10371 SV*
10372 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10373                                  UV** other_elements_ptr)
10374 {
10375     /* Create and return an inversion list whose contents are to be populated
10376      * by the caller.  The caller gives the number of elements (in 'size') and
10377      * the very first element ('element0').  This function will set
10378      * '*other_elements_ptr' to an array of UVs, where the remaining elements
10379      * are to be placed.
10380      *
10381      * Obviously there is some trust involved that the caller will properly
10382      * fill in the other elements of the array.
10383      *
10384      * (The first element needs to be passed in, as the underlying code does
10385      * things differently depending on whether it is zero or non-zero) */
10386
10387     SV* invlist = _new_invlist(size);
10388     bool offset;
10389
10390     PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10391
10392     invlist = add_cp_to_invlist(invlist, element0);
10393     offset = *get_invlist_offset_addr(invlist);
10394
10395     invlist_set_len(invlist, size, offset);
10396     *other_elements_ptr = invlist_array(invlist) + 1;
10397     return invlist;
10398 }
10399
10400 #endif
10401
10402 #ifndef PERL_IN_XSUB_RE
10403 void
10404 Perl__invlist_invert(pTHX_ SV* const invlist)
10405 {
10406     /* Complement the input inversion list.  This adds a 0 if the list didn't
10407      * have a zero; removes it otherwise.  As described above, the data
10408      * structure is set up so that this is very efficient */
10409
10410     PERL_ARGS_ASSERT__INVLIST_INVERT;
10411
10412     assert(! invlist_is_iterating(invlist));
10413
10414     /* The inverse of matching nothing is matching everything */
10415     if (_invlist_len(invlist) == 0) {
10416         _append_range_to_invlist(invlist, 0, UV_MAX);
10417         return;
10418     }
10419
10420     *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10421 }
10422
10423 SV*
10424 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10425 {
10426     /* Return a new inversion list that is a copy of the input one, which is
10427      * unchanged.  The new list will not be mortal even if the old one was. */
10428
10429     const STRLEN nominal_length = _invlist_len(invlist);
10430     const STRLEN physical_length = SvCUR(invlist);
10431     const bool offset = *(get_invlist_offset_addr(invlist));
10432
10433     PERL_ARGS_ASSERT_INVLIST_CLONE;
10434
10435     if (new_invlist == NULL) {
10436         new_invlist = _new_invlist(nominal_length);
10437     }
10438     else {
10439         sv_upgrade(new_invlist, SVt_INVLIST);
10440         initialize_invlist_guts(new_invlist, nominal_length);
10441     }
10442
10443     *(get_invlist_offset_addr(new_invlist)) = offset;
10444     invlist_set_len(new_invlist, nominal_length, offset);
10445     Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10446
10447     return new_invlist;
10448 }
10449
10450 #endif
10451
10452 PERL_STATIC_INLINE UV
10453 S_invlist_lowest(SV* const invlist)
10454 {
10455     /* Returns the lowest code point that matches an inversion list.  This API
10456      * has an ambiguity, as it returns 0 under either the lowest is actually
10457      * 0, or if the list is empty.  If this distinction matters to you, check
10458      * for emptiness before calling this function */
10459
10460     UV len = _invlist_len(invlist);
10461     UV *array;
10462
10463     PERL_ARGS_ASSERT_INVLIST_LOWEST;
10464
10465     if (len == 0) {
10466         return 0;
10467     }
10468
10469     array = invlist_array(invlist);
10470
10471     return array[0];
10472 }
10473
10474 STATIC SV *
10475 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10476 {
10477     /* Get the contents of an inversion list into a string SV so that they can
10478      * be printed out.  If 'traditional_style' is TRUE, it uses the format
10479      * traditionally done for debug tracing; otherwise it uses a format
10480      * suitable for just copying to the output, with blanks between ranges and
10481      * a dash between range components */
10482
10483     UV start, end;
10484     SV* output;
10485     const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10486     const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10487
10488     if (traditional_style) {
10489         output = newSVpvs("\n");
10490     }
10491     else {
10492         output = newSVpvs("");
10493     }
10494
10495     PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10496
10497     assert(! invlist_is_iterating(invlist));
10498
10499     invlist_iterinit(invlist);
10500     while (invlist_iternext(invlist, &start, &end)) {
10501         if (end == UV_MAX) {
10502             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
10503                                           start, intra_range_delimiter,
10504                                                  inter_range_delimiter);
10505         }
10506         else if (end != start) {
10507             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10508                                           start,
10509                                                    intra_range_delimiter,
10510                                                   end, inter_range_delimiter);
10511         }
10512         else {
10513             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10514                                           start, inter_range_delimiter);
10515         }
10516     }
10517
10518     if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10519         SvCUR_set(output, SvCUR(output) - 1);
10520     }
10521
10522     return output;
10523 }
10524
10525 #ifndef PERL_IN_XSUB_RE
10526 void
10527 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10528                          const char * const indent, SV* const invlist)
10529 {
10530     /* Designed to be called only by do_sv_dump().  Dumps out the ranges of the
10531      * inversion list 'invlist' to 'file' at 'level'  Each line is prefixed by
10532      * the string 'indent'.  The output looks like this:
10533          [0] 0x000A .. 0x000D
10534          [2] 0x0085
10535          [4] 0x2028 .. 0x2029
10536          [6] 0x3104 .. INFTY
10537      * This means that the first range of code points matched by the list are
10538      * 0xA through 0xD; the second range contains only the single code point
10539      * 0x85, etc.  An inversion list is an array of UVs.  Two array elements
10540      * are used to define each range (except if the final range extends to
10541      * infinity, only a single element is needed).  The array index of the
10542      * first element for the corresponding range is given in brackets. */
10543
10544     UV start, end;
10545     STRLEN count = 0;
10546
10547     PERL_ARGS_ASSERT__INVLIST_DUMP;
10548
10549     if (invlist_is_iterating(invlist)) {
10550         Perl_dump_indent(aTHX_ level, file,
10551              "%sCan't dump inversion list because is in middle of iterating\n",
10552              indent);
10553         return;
10554     }
10555
10556     invlist_iterinit(invlist);
10557     while (invlist_iternext(invlist, &start, &end)) {
10558         if (end == UV_MAX) {
10559             Perl_dump_indent(aTHX_ level, file,
10560                                        "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
10561                                    indent, (UV)count, start);
10562         }
10563         else if (end != start) {
10564             Perl_dump_indent(aTHX_ level, file,
10565                                     "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10566                                 indent, (UV)count, start,         end);
10567         }
10568         else {
10569             Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10570                                             indent, (UV)count, start);
10571         }
10572         count += 2;
10573     }
10574 }
10575
10576 #endif
10577
10578 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10579 bool
10580 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10581 {
10582     /* Return a boolean as to if the two passed in inversion lists are
10583      * identical.  The final argument, if TRUE, says to take the complement of
10584      * the second inversion list before doing the comparison */
10585
10586     const UV len_a = _invlist_len(a);
10587     UV len_b = _invlist_len(b);
10588
10589     const UV* array_a = NULL;
10590     const UV* array_b = NULL;
10591
10592     PERL_ARGS_ASSERT__INVLISTEQ;
10593
10594     /* This code avoids accessing the arrays unless it knows the length is
10595      * non-zero */
10596
10597     if (len_a == 0) {
10598         if (len_b == 0) {
10599             return ! complement_b;
10600         }
10601     }
10602     else {
10603         array_a = invlist_array(a);
10604     }
10605
10606     if (len_b != 0) {
10607         array_b = invlist_array(b);
10608     }
10609
10610     /* If are to compare 'a' with the complement of b, set it
10611      * up so are looking at b's complement. */
10612     if (complement_b) {
10613
10614         /* The complement of nothing is everything, so <a> would have to have
10615          * just one element, starting at zero (ending at infinity) */
10616         if (len_b == 0) {
10617             return (len_a == 1 && array_a[0] == 0);
10618         }
10619         if (array_b[0] == 0) {
10620
10621             /* Otherwise, to complement, we invert.  Here, the first element is
10622              * 0, just remove it.  To do this, we just pretend the array starts
10623              * one later */
10624
10625             array_b++;
10626             len_b--;
10627         }
10628         else {
10629
10630             /* But if the first element is not zero, we pretend the list starts
10631              * at the 0 that is always stored immediately before the array. */
10632             array_b--;
10633             len_b++;
10634         }
10635     }
10636
10637     return    len_a == len_b
10638            && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10639
10640 }
10641 #endif
10642
10643 /*
10644  * As best we can, determine the characters that can match the start of
10645  * the given EXACTF-ish node.  This is for use in creating ssc nodes, so there
10646  * can be false positive matches
10647  *
10648  * Returns the invlist as a new SV*; it is the caller's responsibility to
10649  * call SvREFCNT_dec() when done with it.
10650  */
10651 STATIC SV*
10652 S_make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10653 {
10654     dVAR;
10655     const U8 * s = (U8*)STRING(node);
10656     SSize_t bytelen = STR_LEN(node);
10657     UV uc;
10658     /* Start out big enough for 2 separate code points */
10659     SV* invlist = _new_invlist(4);
10660
10661     PERL_ARGS_ASSERT_MAKE_EXACTF_INVLIST;
10662
10663     if (! UTF) {
10664         uc = *s;
10665
10666         /* We punt and assume can match anything if the node begins
10667          * with a multi-character fold.  Things are complicated.  For
10668          * example, /ffi/i could match any of:
10669          *  "\N{LATIN SMALL LIGATURE FFI}"
10670          *  "\N{LATIN SMALL LIGATURE FF}I"
10671          *  "F\N{LATIN SMALL LIGATURE FI}"
10672          *  plus several other things; and making sure we have all the
10673          *  possibilities is hard. */
10674         if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10675             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10676         }
10677         else {
10678             /* Any Latin1 range character can potentially match any
10679              * other depending on the locale, and in Turkic locales, U+130 and
10680              * U+131 */
10681             if (OP(node) == EXACTFL) {
10682                 _invlist_union(invlist, PL_Latin1, &invlist);
10683                 invlist = add_cp_to_invlist(invlist,
10684                                                 LATIN_SMALL_LETTER_DOTLESS_I);
10685                 invlist = add_cp_to_invlist(invlist,
10686                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10687             }
10688             else {
10689                 /* But otherwise, it matches at least itself.  We can
10690                  * quickly tell if it has a distinct fold, and if so,
10691                  * it matches that as well */
10692                 invlist = add_cp_to_invlist(invlist, uc);
10693                 if (IS_IN_SOME_FOLD_L1(uc))
10694                     invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10695             }
10696
10697             /* Some characters match above-Latin1 ones under /i.  This
10698              * is true of EXACTFL ones when the locale is UTF-8 */
10699             if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10700                 && (! isASCII(uc) || (OP(node) != EXACTFAA
10701                                     && OP(node) != EXACTFAA_NO_TRIE)))
10702             {
10703                 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10704             }
10705         }
10706     }
10707     else {  /* Pattern is UTF-8 */
10708         U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10709         const U8* e = s + bytelen;
10710         IV fc;
10711
10712         fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10713
10714         /* The only code points that aren't folded in a UTF EXACTFish
10715          * node are the problematic ones in EXACTFL nodes */
10716         if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10717             /* We need to check for the possibility that this EXACTFL
10718              * node begins with a multi-char fold.  Therefore we fold
10719              * the first few characters of it so that we can make that
10720              * check */
10721             U8 *d = folded;
10722             int i;
10723
10724             fc = -1;
10725             for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10726                 if (isASCII(*s)) {
10727                     *(d++) = (U8) toFOLD(*s);
10728                     if (fc < 0) {       /* Save the first fold */
10729                         fc = *(d-1);
10730                     }
10731                     s++;
10732                 }
10733                 else {
10734                     STRLEN len;
10735                     UV fold = toFOLD_utf8_safe(s, e, d, &len);
10736                     if (fc < 0) {       /* Save the first fold */
10737                         fc = fold;
10738                     }
10739                     d += len;
10740                     s += UTF8SKIP(s);
10741                 }
10742             }
10743
10744             /* And set up so the code below that looks in this folded
10745              * buffer instead of the node's string */
10746             e = d;
10747             s = folded;
10748         }
10749
10750         /* When we reach here 's' points to the fold of the first
10751          * character(s) of the node; and 'e' points to far enough along
10752          * the folded string to be just past any possible multi-char
10753          * fold.
10754          *
10755          * Unlike the non-UTF-8 case, the macro for determining if a
10756          * string is a multi-char fold requires all the characters to
10757          * already be folded.  This is because of all the complications
10758          * if not.  Note that they are folded anyway, except in EXACTFL
10759          * nodes.  Like the non-UTF case above, we punt if the node
10760          * begins with a multi-char fold  */
10761
10762         if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10763             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10764         }
10765         else {  /* Single char fold */
10766             unsigned int k;
10767             U32 first_fold;
10768             const U32 * remaining_folds;
10769             Size_t folds_count;
10770
10771             /* It matches itself */
10772             invlist = add_cp_to_invlist(invlist, fc);
10773
10774             /* ... plus all the things that fold to it, which are found in
10775              * PL_utf8_foldclosures */
10776             folds_count = _inverse_folds(fc, &first_fold,
10777                                                 &remaining_folds);
10778             for (k = 0; k < folds_count; k++) {
10779                 UV c = (k == 0) ? first_fold : remaining_folds[k-1];
10780
10781                 /* /aa doesn't allow folds between ASCII and non- */
10782                 if (   (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10783                     && isASCII(c) != isASCII(fc))
10784                 {
10785                     continue;
10786                 }
10787
10788                 invlist = add_cp_to_invlist(invlist, c);
10789             }
10790
10791             if (OP(node) == EXACTFL) {
10792
10793                 /* If either [iI] are present in an EXACTFL node the above code
10794                  * should have added its normal case pair, but under a Turkish
10795                  * locale they could match instead the case pairs from it.  Add
10796                  * those as potential matches as well */
10797                 if (isALPHA_FOLD_EQ(fc, 'I')) {
10798                     invlist = add_cp_to_invlist(invlist,
10799                                                 LATIN_SMALL_LETTER_DOTLESS_I);
10800                     invlist = add_cp_to_invlist(invlist,
10801                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10802                 }
10803                 else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
10804                     invlist = add_cp_to_invlist(invlist, 'I');
10805                 }
10806                 else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10807                     invlist = add_cp_to_invlist(invlist, 'i');
10808                 }
10809             }
10810         }
10811     }
10812
10813     return invlist;
10814 }
10815
10816 #undef HEADER_LENGTH
10817 #undef TO_INTERNAL_SIZE
10818 #undef FROM_INTERNAL_SIZE
10819 #undef INVLIST_VERSION_ID
10820
10821 /* End of inversion list object */
10822
10823 STATIC void
10824 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10825 {
10826     /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10827      * constructs, and updates RExC_flags with them.  On input, RExC_parse
10828      * should point to the first flag; it is updated on output to point to the
10829      * final ')' or ':'.  There needs to be at least one flag, or this will
10830      * abort */
10831
10832     /* for (?g), (?gc), and (?o) warnings; warning
10833        about (?c) will warn about (?g) -- japhy    */
10834
10835 #define WASTED_O  0x01
10836 #define WASTED_G  0x02
10837 #define WASTED_C  0x04
10838 #define WASTED_GC (WASTED_G|WASTED_C)
10839     I32 wastedflags = 0x00;
10840     U32 posflags = 0, negflags = 0;
10841     U32 *flagsp = &posflags;
10842     char has_charset_modifier = '\0';
10843     regex_charset cs;
10844     bool has_use_defaults = FALSE;
10845     const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10846     int x_mod_count = 0;
10847
10848     PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10849
10850     /* '^' as an initial flag sets certain defaults */
10851     if (UCHARAT(RExC_parse) == '^') {
10852         RExC_parse++;
10853         has_use_defaults = TRUE;
10854         STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10855         cs = (RExC_uni_semantics)
10856              ? REGEX_UNICODE_CHARSET
10857              : REGEX_DEPENDS_CHARSET;
10858         set_regex_charset(&RExC_flags, cs);
10859     }
10860     else {
10861         cs = get_regex_charset(RExC_flags);
10862         if (   cs == REGEX_DEPENDS_CHARSET
10863             && RExC_uni_semantics)
10864         {
10865             cs = REGEX_UNICODE_CHARSET;
10866         }
10867     }
10868
10869     while (RExC_parse < RExC_end) {
10870         /* && memCHRs("iogcmsx", *RExC_parse) */
10871         /* (?g), (?gc) and (?o) are useless here
10872            and must be globally applied -- japhy */
10873         if ((RExC_pm_flags & PMf_WILDCARD)) {
10874             if (flagsp == & negflags) {
10875                 if (*RExC_parse == 'm') {
10876                     RExC_parse++;
10877                     /* diag_listed_as: Use of %s is not allowed in Unicode
10878                        property wildcard subpatterns in regex; marked by <--
10879                        HERE in m/%s/ */
10880                     vFAIL("Use of modifier '-m' is not allowed in Unicode"
10881                           " property wildcard subpatterns");
10882                 }
10883             }
10884             else {
10885                 if (*RExC_parse == 's') {
10886                     goto modifier_illegal_in_wildcard;
10887                 }
10888             }
10889         }
10890
10891         switch (*RExC_parse) {
10892
10893             /* Code for the imsxn flags */
10894             CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10895
10896             case LOCALE_PAT_MOD:
10897                 if (has_charset_modifier) {
10898                     goto excess_modifier;
10899                 }
10900                 else if (flagsp == &negflags) {
10901                     goto neg_modifier;
10902                 }
10903                 cs = REGEX_LOCALE_CHARSET;
10904                 has_charset_modifier = LOCALE_PAT_MOD;
10905                 break;
10906             case UNICODE_PAT_MOD:
10907                 if (has_charset_modifier) {
10908                     goto excess_modifier;
10909                 }
10910                 else if (flagsp == &negflags) {
10911                     goto neg_modifier;
10912                 }
10913                 cs = REGEX_UNICODE_CHARSET;
10914                 has_charset_modifier = UNICODE_PAT_MOD;
10915                 break;
10916             case ASCII_RESTRICT_PAT_MOD:
10917                 if (flagsp == &negflags) {
10918                     goto neg_modifier;
10919                 }
10920                 if (has_charset_modifier) {
10921                     if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10922                         goto excess_modifier;
10923                     }
10924                     /* Doubled modifier implies more restricted */
10925                     cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10926                 }
10927                 else {
10928                     cs = REGEX_ASCII_RESTRICTED_CHARSET;
10929                 }
10930                 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10931                 break;
10932             case DEPENDS_PAT_MOD:
10933                 if (has_use_defaults) {
10934                     goto fail_modifiers;
10935                 }
10936                 else if (flagsp == &negflags) {
10937                     goto neg_modifier;
10938                 }
10939                 else if (has_charset_modifier) {
10940                     goto excess_modifier;
10941                 }
10942
10943                 /* The dual charset means unicode semantics if the
10944                  * pattern (or target, not known until runtime) are
10945                  * utf8, or something in the pattern indicates unicode
10946                  * semantics */
10947                 cs = (RExC_uni_semantics)
10948                      ? REGEX_UNICODE_CHARSET
10949                      : REGEX_DEPENDS_CHARSET;
10950                 has_charset_modifier = DEPENDS_PAT_MOD;
10951                 break;
10952               excess_modifier:
10953                 RExC_parse++;
10954                 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10955                     vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10956                 }
10957                 else if (has_charset_modifier == *(RExC_parse - 1)) {
10958                     vFAIL2("Regexp modifier \"%c\" may not appear twice",
10959                                         *(RExC_parse - 1));
10960                 }
10961                 else {
10962                     vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10963                 }
10964                 NOT_REACHED; /*NOTREACHED*/
10965               neg_modifier:
10966                 RExC_parse++;
10967                 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10968                                     *(RExC_parse - 1));
10969                 NOT_REACHED; /*NOTREACHED*/
10970             case GLOBAL_PAT_MOD: /* 'g' */
10971                 if (RExC_pm_flags & PMf_WILDCARD) {
10972                     goto modifier_illegal_in_wildcard;
10973                 }
10974                 /*FALLTHROUGH*/
10975             case ONCE_PAT_MOD: /* 'o' */
10976                 if (ckWARN(WARN_REGEXP)) {
10977                     const I32 wflagbit = *RExC_parse == 'o'
10978                                          ? WASTED_O
10979                                          : WASTED_G;
10980                     if (! (wastedflags & wflagbit) ) {
10981                         wastedflags |= wflagbit;
10982                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10983                         vWARN5(
10984                             RExC_parse + 1,
10985                             "Useless (%s%c) - %suse /%c modifier",
10986                             flagsp == &negflags ? "?-" : "?",
10987                             *RExC_parse,
10988                             flagsp == &negflags ? "don't " : "",
10989                             *RExC_parse
10990                         );
10991                     }
10992                 }
10993                 break;
10994
10995             case CONTINUE_PAT_MOD: /* 'c' */
10996                 if (RExC_pm_flags & PMf_WILDCARD) {
10997                     goto modifier_illegal_in_wildcard;
10998                 }
10999                 if (ckWARN(WARN_REGEXP)) {
11000                     if (! (wastedflags & WASTED_C) ) {
11001                         wastedflags |= WASTED_GC;
11002                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
11003                         vWARN3(
11004                             RExC_parse + 1,
11005                             "Useless (%sc) - %suse /gc modifier",
11006                             flagsp == &negflags ? "?-" : "?",
11007                             flagsp == &negflags ? "don't " : ""
11008                         );
11009                     }
11010                 }
11011                 break;
11012             case KEEPCOPY_PAT_MOD: /* 'p' */
11013                 if (RExC_pm_flags & PMf_WILDCARD) {
11014                     goto modifier_illegal_in_wildcard;
11015                 }
11016                 if (flagsp == &negflags) {
11017                     ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
11018                 } else {
11019                     *flagsp |= RXf_PMf_KEEPCOPY;
11020                 }
11021                 break;
11022             case '-':
11023                 /* A flag is a default iff it is following a minus, so
11024                  * if there is a minus, it means will be trying to
11025                  * re-specify a default which is an error */
11026                 if (has_use_defaults || flagsp == &negflags) {
11027                     goto fail_modifiers;
11028                 }
11029                 flagsp = &negflags;
11030                 wastedflags = 0;  /* reset so (?g-c) warns twice */
11031                 x_mod_count = 0;
11032                 break;
11033             case ':':
11034             case ')':
11035
11036                 if (  (RExC_pm_flags & PMf_WILDCARD)
11037                     && cs != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
11038                 {
11039                     RExC_parse++;
11040                     /* diag_listed_as: Use of %s is not allowed in Unicode
11041                        property wildcard subpatterns in regex; marked by <--
11042                        HERE in m/%s/ */
11043                     vFAIL2("Use of modifier '%c' is not allowed in Unicode"
11044                            " property wildcard subpatterns",
11045                            has_charset_modifier);
11046                 }
11047
11048                 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
11049                     negflags |= RXf_PMf_EXTENDED_MORE;
11050                 }
11051                 RExC_flags |= posflags;
11052
11053                 if (negflags & RXf_PMf_EXTENDED) {
11054                     negflags |= RXf_PMf_EXTENDED_MORE;
11055                 }
11056                 RExC_flags &= ~negflags;
11057                 set_regex_charset(&RExC_flags, cs);
11058
11059                 return;
11060             default:
11061               fail_modifiers:
11062                 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11063                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11064                 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
11065                       UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11066                 NOT_REACHED; /*NOTREACHED*/
11067         }
11068
11069         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11070     }
11071
11072     vFAIL("Sequence (?... not terminated");
11073
11074   modifier_illegal_in_wildcard:
11075     RExC_parse++;
11076     /* diag_listed_as: Use of %s is not allowed in Unicode property wildcard
11077        subpatterns in regex; marked by <-- HERE in m/%s/ */
11078     vFAIL2("Use of modifier '%c' is not allowed in Unicode property wildcard"
11079            " subpatterns", *(RExC_parse - 1));
11080 }
11081
11082 /*
11083  - reg - regular expression, i.e. main body or parenthesized thing
11084  *
11085  * Caller must absorb opening parenthesis.
11086  *
11087  * Combining parenthesis handling with the base level of regular expression
11088  * is a trifle forced, but the need to tie the tails of the branches to what
11089  * follows makes it hard to avoid.
11090  */
11091 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
11092 #ifdef DEBUGGING
11093 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
11094 #else
11095 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
11096 #endif
11097
11098 STATIC regnode_offset
11099 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
11100                              I32 *flagp,
11101                              char * parse_start,
11102                              char ch
11103                       )
11104 {
11105     regnode_offset ret;
11106     char* name_start = RExC_parse;
11107     U32 num = 0;
11108     SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11109     DECLARE_AND_GET_RE_DEBUG_FLAGS;
11110
11111     PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
11112
11113     if (RExC_parse == name_start || *RExC_parse != ch) {
11114         /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
11115         vFAIL2("Sequence %.3s... not terminated", parse_start);
11116     }
11117
11118     if (sv_dat) {
11119         num = add_data( pRExC_state, STR_WITH_LEN("S"));
11120         RExC_rxi->data->data[num]=(void*)sv_dat;
11121         SvREFCNT_inc_simple_void_NN(sv_dat);
11122     }
11123     RExC_sawback = 1;
11124     ret = reganode(pRExC_state,
11125                    ((! FOLD)
11126                      ? REFN
11127                      : (ASCII_FOLD_RESTRICTED)
11128                        ? REFFAN
11129                        : (AT_LEAST_UNI_SEMANTICS)
11130                          ? REFFUN
11131                          : (LOC)
11132                            ? REFFLN
11133                            : REFFN),
11134                     num);
11135     *flagp |= HASWIDTH;
11136
11137     Set_Node_Offset(REGNODE_p(ret), parse_start+1);
11138     Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
11139
11140     nextchar(pRExC_state);
11141     return ret;
11142 }
11143
11144 /* On success, returns the offset at which any next node should be placed into
11145  * the regex engine program being compiled.
11146  *
11147  * Returns 0 otherwise, with *flagp set to indicate why:
11148  *  TRYAGAIN        at the end of (?) that only sets flags.
11149  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
11150  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
11151  *  Otherwise would only return 0 if regbranch() returns 0, which cannot
11152  *  happen.  */
11153 STATIC regnode_offset
11154 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
11155     /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
11156      * 2 is like 1, but indicates that nextchar() has been called to advance
11157      * RExC_parse beyond the '('.  Things like '(?' are indivisible tokens, and
11158      * this flag alerts us to the need to check for that */
11159 {
11160     regnode_offset ret = 0;    /* Will be the head of the group. */
11161     regnode_offset br;
11162     regnode_offset lastbr;
11163     regnode_offset ender = 0;
11164     I32 parno = 0;
11165     I32 flags;
11166     U32 oregflags = RExC_flags;
11167     bool have_branch = 0;
11168     bool is_open = 0;
11169     I32 freeze_paren = 0;
11170     I32 after_freeze = 0;
11171     I32 num; /* numeric backreferences */
11172     SV * max_open;  /* Max number of unclosed parens */
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;                         /* Tentatively. */
11193
11194     if (RExC_in_lookbehind) {
11195         RExC_in_lookbehind++;
11196     }
11197     if (RExC_in_lookahead) {
11198         RExC_in_lookahead++;
11199     }
11200
11201     /* Having this true makes it feasible to have a lot fewer tests for the
11202      * parse pointer being in scope.  For example, we can write
11203      *      while(isFOO(*RExC_parse)) RExC_parse++;
11204      * instead of
11205      *      while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
11206      */
11207     assert(*RExC_end == '\0');
11208
11209     /* Make an OPEN node, if parenthesized. */
11210     if (paren) {
11211
11212         /* Under /x, space and comments can be gobbled up between the '(' and
11213          * here (if paren ==2).  The forms '(*VERB' and '(?...' disallow such
11214          * intervening space, as the sequence is a token, and a token should be
11215          * indivisible */
11216         bool has_intervening_patws = (paren == 2)
11217                                   && *(RExC_parse - 1) != '(';
11218
11219         if (RExC_parse >= RExC_end) {
11220             vFAIL("Unmatched (");
11221         }
11222
11223         if (paren == 'r') {     /* Atomic script run */
11224             paren = '>';
11225             goto parse_rest;
11226         }
11227         else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
11228             char *start_verb = RExC_parse + 1;
11229             STRLEN verb_len;
11230             char *start_arg = NULL;
11231             unsigned char op = 0;
11232             int arg_required = 0;
11233             int internal_argval = -1; /* if >-1 we are not allowed an argument*/
11234             bool has_upper = FALSE;
11235
11236             if (has_intervening_patws) {
11237                 RExC_parse++;   /* past the '*' */
11238
11239                 /* For strict backwards compatibility, don't change the message
11240                  * now that we also have lowercase operands */
11241                 if (isUPPER(*RExC_parse)) {
11242                     vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
11243                 }
11244                 else {
11245                     vFAIL("In '(*...)', the '(' and '*' must be adjacent");
11246                 }
11247             }
11248             while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
11249                 if ( *RExC_parse == ':' ) {
11250                     start_arg = RExC_parse + 1;
11251                     break;
11252                 }
11253                 else if (! UTF) {
11254                     if (isUPPER(*RExC_parse)) {
11255                         has_upper = TRUE;
11256                     }
11257                     RExC_parse++;
11258                 }
11259                 else {
11260                     RExC_parse += UTF8SKIP(RExC_parse);
11261                 }
11262             }
11263             verb_len = RExC_parse - start_verb;
11264             if ( start_arg ) {
11265                 if (RExC_parse >= RExC_end) {
11266                     goto unterminated_verb_pattern;
11267                 }
11268
11269                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11270                 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
11271                     RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11272                 }
11273                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11274                   unterminated_verb_pattern:
11275                     if (has_upper) {
11276                         vFAIL("Unterminated verb pattern argument");
11277                     }
11278                     else {
11279                         vFAIL("Unterminated '(*...' argument");
11280                     }
11281                 }
11282             } else {
11283                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11284                     if (has_upper) {
11285                         vFAIL("Unterminated verb pattern");
11286                     }
11287                     else {
11288                         vFAIL("Unterminated '(*...' construct");
11289                     }
11290                 }
11291             }
11292
11293             /* Here, we know that RExC_parse < RExC_end */
11294
11295             switch ( *start_verb ) {
11296             case 'A':  /* (*ACCEPT) */
11297                 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
11298                     op = ACCEPT;
11299                     internal_argval = RExC_nestroot;
11300                 }
11301                 break;
11302             case 'C':  /* (*COMMIT) */
11303                 if ( memEQs(start_verb, verb_len,"COMMIT") )
11304                     op = COMMIT;
11305                 break;
11306             case 'F':  /* (*FAIL) */
11307                 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
11308                     op = OPFAIL;
11309                 }
11310                 break;
11311             case ':':  /* (*:NAME) */
11312             case 'M':  /* (*MARK:NAME) */
11313                 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
11314                     op = MARKPOINT;
11315                     arg_required = 1;
11316                 }
11317                 break;
11318             case 'P':  /* (*PRUNE) */
11319                 if ( memEQs(start_verb, verb_len,"PRUNE") )
11320                     op = PRUNE;
11321                 break;
11322             case 'S':   /* (*SKIP) */
11323                 if ( memEQs(start_verb, verb_len,"SKIP") )
11324                     op = SKIP;
11325                 break;
11326             case 'T':  /* (*THEN) */
11327                 /* [19:06] <TimToady> :: is then */
11328                 if ( memEQs(start_verb, verb_len,"THEN") ) {
11329                     op = CUTGROUP;
11330                     RExC_seen |= REG_CUTGROUP_SEEN;
11331                 }
11332                 break;
11333             case 'a':
11334                 if (   memEQs(start_verb, verb_len, "asr")
11335                     || memEQs(start_verb, verb_len, "atomic_script_run"))
11336                 {
11337                     paren = 'r';        /* Mnemonic: recursed run */
11338                     goto script_run;
11339                 }
11340                 else if (memEQs(start_verb, verb_len, "atomic")) {
11341                     paren = 't';    /* AtOMIC */
11342                     goto alpha_assertions;
11343                 }
11344                 break;
11345             case 'p':
11346                 if (   memEQs(start_verb, verb_len, "plb")
11347                     || memEQs(start_verb, verb_len, "positive_lookbehind"))
11348                 {
11349                     paren = 'b';
11350                     goto lookbehind_alpha_assertions;
11351                 }
11352                 else if (   memEQs(start_verb, verb_len, "pla")
11353                          || memEQs(start_verb, verb_len, "positive_lookahead"))
11354                 {
11355                     paren = 'a';
11356                     goto alpha_assertions;
11357                 }
11358                 break;
11359             case 'n':
11360                 if (   memEQs(start_verb, verb_len, "nlb")
11361                     || memEQs(start_verb, verb_len, "negative_lookbehind"))
11362                 {
11363                     paren = 'B';
11364                     goto lookbehind_alpha_assertions;
11365                 }
11366                 else if (   memEQs(start_verb, verb_len, "nla")
11367                          || memEQs(start_verb, verb_len, "negative_lookahead"))
11368                 {
11369                     paren = 'A';
11370                     goto alpha_assertions;
11371                 }
11372                 break;
11373             case 's':
11374                 if (   memEQs(start_verb, verb_len, "sr")
11375                     || memEQs(start_verb, verb_len, "script_run"))
11376                 {
11377                     regnode_offset atomic;
11378
11379                     paren = 's';
11380
11381                    script_run:
11382
11383                     /* This indicates Unicode rules. */
11384                     REQUIRE_UNI_RULES(flagp, 0);
11385
11386                     if (! start_arg) {
11387                         goto no_colon;
11388                     }
11389
11390                     RExC_parse = start_arg;
11391
11392                     if (RExC_in_script_run) {
11393
11394                         /*  Nested script runs are treated as no-ops, because
11395                          *  if the nested one fails, the outer one must as
11396                          *  well.  It could fail sooner, and avoid (??{} with
11397                          *  side effects, but that is explicitly documented as
11398                          *  undefined behavior. */
11399
11400                         ret = 0;
11401
11402                         if (paren == 's') {
11403                             paren = ':';
11404                             goto parse_rest;
11405                         }
11406
11407                         /* But, the atomic part of a nested atomic script run
11408                          * isn't a no-op, but can be treated just like a '(?>'
11409                          * */
11410                         paren = '>';
11411                         goto parse_rest;
11412                     }
11413
11414                     if (paren == 's') {
11415                         /* Here, we're starting a new regular script run */
11416                         ret = reg_node(pRExC_state, SROPEN);
11417                         RExC_in_script_run = 1;
11418                         is_open = 1;
11419                         goto parse_rest;
11420                     }
11421
11422                     /* Here, we are starting an atomic script run.  This is
11423                      * handled by recursing to deal with the atomic portion
11424                      * separately, enclosed in SROPEN ... SRCLOSE nodes */
11425
11426                     ret = reg_node(pRExC_state, SROPEN);
11427
11428                     RExC_in_script_run = 1;
11429
11430                     atomic = reg(pRExC_state, 'r', &flags, depth);
11431                     if (flags & (RESTART_PARSE|NEED_UTF8)) {
11432                         *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11433                         return 0;
11434                     }
11435
11436                     if (! REGTAIL(pRExC_state, ret, atomic)) {
11437                         REQUIRE_BRANCHJ(flagp, 0);
11438                     }
11439
11440                     if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state,
11441                                                                 SRCLOSE)))
11442                     {
11443                         REQUIRE_BRANCHJ(flagp, 0);
11444                     }
11445
11446                     RExC_in_script_run = 0;
11447                     return ret;
11448                 }
11449
11450                 break;
11451
11452             lookbehind_alpha_assertions:
11453                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11454                 RExC_in_lookbehind++;
11455                 /*FALLTHROUGH*/
11456
11457             alpha_assertions:
11458
11459                 RExC_seen_zerolen++;
11460
11461                 if (! start_arg) {
11462                     goto no_colon;
11463                 }
11464
11465                 /* An empty negative lookahead assertion simply is failure */
11466                 if (paren == 'A' && RExC_parse == start_arg) {
11467                     ret=reganode(pRExC_state, OPFAIL, 0);
11468                     nextchar(pRExC_state);
11469                     return ret;
11470                 }
11471
11472                 RExC_parse = start_arg;
11473                 goto parse_rest;
11474
11475               no_colon:
11476                 vFAIL2utf8f(
11477                 "'(*%" UTF8f "' requires a terminating ':'",
11478                 UTF8fARG(UTF, verb_len, start_verb));
11479                 NOT_REACHED; /*NOTREACHED*/
11480
11481             } /* End of switch */
11482             if ( ! op ) {
11483                 RExC_parse += UTF
11484                               ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11485                               : 1;
11486                 if (has_upper || verb_len == 0) {
11487                     vFAIL2utf8f(
11488                     "Unknown verb pattern '%" UTF8f "'",
11489                     UTF8fARG(UTF, verb_len, start_verb));
11490                 }
11491                 else {
11492                     vFAIL2utf8f(
11493                     "Unknown '(*...)' construct '%" UTF8f "'",
11494                     UTF8fARG(UTF, verb_len, start_verb));
11495                 }
11496             }
11497             if ( RExC_parse == start_arg ) {
11498                 start_arg = NULL;
11499             }
11500             if ( arg_required && !start_arg ) {
11501                 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11502                     (int) verb_len, start_verb);
11503             }
11504             if (internal_argval == -1) {
11505                 ret = reganode(pRExC_state, op, 0);
11506             } else {
11507                 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11508             }
11509             RExC_seen |= REG_VERBARG_SEEN;
11510             if (start_arg) {
11511                 SV *sv = newSVpvn( start_arg,
11512                                     RExC_parse - start_arg);
11513                 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11514                                         STR_WITH_LEN("S"));
11515                 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11516                 FLAGS(REGNODE_p(ret)) = 1;
11517             } else {
11518                 FLAGS(REGNODE_p(ret)) = 0;
11519             }
11520             if ( internal_argval != -1 )
11521                 ARG2L_SET(REGNODE_p(ret), internal_argval);
11522             nextchar(pRExC_state);
11523             return ret;
11524         }
11525         else if (*RExC_parse == '?') { /* (?...) */
11526             bool is_logical = 0;
11527             const char * const seqstart = RExC_parse;
11528             const char * endptr;
11529             const char non_existent_group_msg[]
11530                                             = "Reference to nonexistent group";
11531             const char impossible_group[] = "Invalid reference to group";
11532
11533             if (has_intervening_patws) {
11534                 RExC_parse++;
11535                 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11536             }
11537
11538             RExC_parse++;           /* past the '?' */
11539             paren = *RExC_parse;    /* might be a trailing NUL, if not
11540                                        well-formed */
11541             RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11542             if (RExC_parse > RExC_end) {
11543                 paren = '\0';
11544             }
11545             ret = 0;                    /* For look-ahead/behind. */
11546             switch (paren) {
11547
11548             case 'P':   /* (?P...) variants for those used to PCRE/Python */
11549                 paren = *RExC_parse;
11550                 if ( paren == '<') {    /* (?P<...>) named capture */
11551                     RExC_parse++;
11552                     if (RExC_parse >= RExC_end) {
11553                         vFAIL("Sequence (?P<... not terminated");
11554                     }
11555                     goto named_capture;
11556                 }
11557                 else if (paren == '>') {   /* (?P>name) named recursion */
11558                     RExC_parse++;
11559                     if (RExC_parse >= RExC_end) {
11560                         vFAIL("Sequence (?P>... not terminated");
11561                     }
11562                     goto named_recursion;
11563                 }
11564                 else if (paren == '=') {   /* (?P=...)  named backref */
11565                     RExC_parse++;
11566                     return handle_named_backref(pRExC_state, flagp,
11567                                                 parse_start, ')');
11568                 }
11569                 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11570                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11571                 vFAIL3("Sequence (%.*s...) not recognized",
11572                                 (int) (RExC_parse - seqstart), seqstart);
11573                 NOT_REACHED; /*NOTREACHED*/
11574             case '<':           /* (?<...) */
11575                 /* If you want to support (?<*...), first reconcile with GH #17363 */
11576                 if (*RExC_parse == '!')
11577                     paren = ',';
11578                 else if (*RExC_parse != '=')
11579               named_capture:
11580                 {               /* (?<...>) */
11581                     char *name_start;
11582                     SV *svname;
11583                     paren= '>';
11584                 /* FALLTHROUGH */
11585             case '\'':          /* (?'...') */
11586                     name_start = RExC_parse;
11587                     svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11588                     if (   RExC_parse == name_start
11589                         || RExC_parse >= RExC_end
11590                         || *RExC_parse != paren)
11591                     {
11592                         vFAIL2("Sequence (?%c... not terminated",
11593                             paren=='>' ? '<' : (char) paren);
11594                     }
11595                     {
11596                         HE *he_str;
11597                         SV *sv_dat = NULL;
11598                         if (!svname) /* shouldn't happen */
11599                             Perl_croak(aTHX_
11600                                 "panic: reg_scan_name returned NULL");
11601                         if (!RExC_paren_names) {
11602                             RExC_paren_names= newHV();
11603                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
11604 #ifdef DEBUGGING
11605                             RExC_paren_name_list= newAV();
11606                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11607 #endif
11608                         }
11609                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11610                         if ( he_str )
11611                             sv_dat = HeVAL(he_str);
11612                         if ( ! sv_dat ) {
11613                             /* croak baby croak */
11614                             Perl_croak(aTHX_
11615                                 "panic: paren_name hash element allocation failed");
11616                         } else if ( SvPOK(sv_dat) ) {
11617                             /* (?|...) can mean we have dupes so scan to check
11618                                its already been stored. Maybe a flag indicating
11619                                we are inside such a construct would be useful,
11620                                but the arrays are likely to be quite small, so
11621                                for now we punt -- dmq */
11622                             IV count = SvIV(sv_dat);
11623                             I32 *pv = (I32*)SvPVX(sv_dat);
11624                             IV i;
11625                             for ( i = 0 ; i < count ; i++ ) {
11626                                 if ( pv[i] == RExC_npar ) {
11627                                     count = 0;
11628                                     break;
11629                                 }
11630                             }
11631                             if ( count ) {
11632                                 pv = (I32*)SvGROW(sv_dat,
11633                                                 SvCUR(sv_dat) + sizeof(I32)+1);
11634                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11635                                 pv[count] = RExC_npar;
11636                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11637                             }
11638                         } else {
11639                             (void)SvUPGRADE(sv_dat, SVt_PVNV);
11640                             sv_setpvn(sv_dat, (char *)&(RExC_npar),
11641                                                                 sizeof(I32));
11642                             SvIOK_on(sv_dat);
11643                             SvIV_set(sv_dat, 1);
11644                         }
11645 #ifdef DEBUGGING
11646                         /* Yes this does cause a memory leak in debugging Perls
11647                          * */
11648                         if (!av_store(RExC_paren_name_list,
11649                                       RExC_npar, SvREFCNT_inc_NN(svname)))
11650                             SvREFCNT_dec_NN(svname);
11651 #endif
11652
11653                         /*sv_dump(sv_dat);*/
11654                     }
11655                     nextchar(pRExC_state);
11656                     paren = 1;
11657                     goto capturing_parens;
11658                 }
11659
11660                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11661                 RExC_in_lookbehind++;
11662                 RExC_parse++;
11663                 if (RExC_parse >= RExC_end) {
11664                     vFAIL("Sequence (?... not terminated");
11665                 }
11666                 RExC_seen_zerolen++;
11667                 break;
11668             case '=':           /* (?=...) */
11669                 RExC_seen_zerolen++;
11670                 RExC_in_lookahead++;
11671                 break;
11672             case '!':           /* (?!...) */
11673                 RExC_seen_zerolen++;
11674                 /* check if we're really just a "FAIL" assertion */
11675                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11676                                         FALSE /* Don't force to /x */ );
11677                 if (*RExC_parse == ')') {
11678                     ret=reganode(pRExC_state, OPFAIL, 0);
11679                     nextchar(pRExC_state);
11680                     return ret;
11681                 }
11682                 break;
11683             case '|':           /* (?|...) */
11684                 /* branch reset, behave like a (?:...) except that
11685                    buffers in alternations share the same numbers */
11686                 paren = ':';
11687                 after_freeze = freeze_paren = RExC_npar;
11688
11689                 /* XXX This construct currently requires an extra pass.
11690                  * Investigation would be required to see if that could be
11691                  * changed */
11692                 REQUIRE_PARENS_PASS;
11693                 break;
11694             case ':':           /* (?:...) */
11695             case '>':           /* (?>...) */
11696                 break;
11697             case '$':           /* (?$...) */
11698             case '@':           /* (?@...) */
11699                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11700                 break;
11701             case '0' :           /* (?0) */
11702             case 'R' :           /* (?R) */
11703                 if (RExC_parse == RExC_end || *RExC_parse != ')')
11704                     FAIL("Sequence (?R) not terminated");
11705                 num = 0;
11706                 RExC_seen |= REG_RECURSE_SEEN;
11707
11708                 /* XXX These constructs currently require an extra pass.
11709                  * It probably could be changed */
11710                 REQUIRE_PARENS_PASS;
11711
11712                 *flagp |= POSTPONED;
11713                 goto gen_recurse_regop;
11714                 /*notreached*/
11715             /* named and numeric backreferences */
11716             case '&':            /* (?&NAME) */
11717                 parse_start = RExC_parse - 1;
11718               named_recursion:
11719                 {
11720                     SV *sv_dat = reg_scan_name(pRExC_state,
11721                                                REG_RSN_RETURN_DATA);
11722                    num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11723                 }
11724                 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11725                     vFAIL("Sequence (?&... not terminated");
11726                 goto gen_recurse_regop;
11727                 /* NOTREACHED */
11728             case '+':
11729                 if (! inRANGE(RExC_parse[0], '1', '9')) {
11730                     RExC_parse++;
11731                     vFAIL("Illegal pattern");
11732                 }
11733                 goto parse_recursion;
11734                 /* NOTREACHED*/
11735             case '-': /* (?-1) */
11736                 if (! inRANGE(RExC_parse[0], '1', '9')) {
11737                     RExC_parse--; /* rewind to let it be handled later */
11738                     goto parse_flags;
11739                 }
11740                 /* FALLTHROUGH */
11741             case '1': case '2': case '3': case '4': /* (?1) */
11742             case '5': case '6': case '7': case '8': case '9':
11743                 RExC_parse = (char *) seqstart + 1;  /* Point to the digit */
11744               parse_recursion:
11745                 {
11746                     bool is_neg = FALSE;
11747                     UV unum;
11748                     parse_start = RExC_parse - 1; /* MJD */
11749                     if (*RExC_parse == '-') {
11750                         RExC_parse++;
11751                         is_neg = TRUE;
11752                     }
11753                     endptr = RExC_end;
11754                     if (grok_atoUV(RExC_parse, &unum, &endptr)
11755                         && unum <= I32_MAX
11756                     ) {
11757                         num = (I32)unum;
11758                         RExC_parse = (char*)endptr;
11759                     }
11760                     else {  /* Overflow, or something like that.  Position
11761                                beyond all digits for the message */
11762                         while (RExC_parse < RExC_end && isDIGIT(*RExC_parse))  {
11763                             RExC_parse++;
11764                         }
11765                         vFAIL(impossible_group);
11766                     }
11767                     if (is_neg) {
11768                         /* -num is always representable on 1 and 2's complement
11769                          * machines */
11770                         num = -num;
11771                     }
11772                 }
11773                 if (*RExC_parse!=')')
11774                     vFAIL("Expecting close bracket");
11775
11776               gen_recurse_regop:
11777                 if (paren == '-' || paren == '+') {
11778
11779                     /* Don't overflow */
11780                     if (UNLIKELY(I32_MAX - RExC_npar < num)) {
11781                         RExC_parse++;
11782                         vFAIL(impossible_group);
11783                     }
11784
11785                     /*
11786                     Diagram of capture buffer numbering.
11787                     Top line is the normal capture buffer numbers
11788                     Bottom line is the negative indexing as from
11789                     the X (the (?-2))
11790
11791                         1 2    3 4 5 X   Y      6 7
11792                        /(a(x)y)(a(b(c(?+2)d)e)f)(g(h))/
11793                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11794                     -   5 4    3 2 1 X   Y      x x
11795
11796                     Resolve to absolute group.  Recall that RExC_npar is +1 of
11797                     the actual parenthesis group number.  For lookahead, we
11798                     have to compensate for that.  Using the above example, when
11799                     we get to Y in the parse, num is 2 and RExC_npar is 6.  We
11800                     want 7 for +2, and 4 for -2.
11801                     */
11802                     if ( paren == '+' ) {
11803                         num--;
11804                     }
11805
11806                     num += RExC_npar;
11807
11808                     if (paren == '-' && num < 1) {
11809                         RExC_parse++;
11810                         vFAIL(non_existent_group_msg);
11811                     }
11812                 }
11813
11814                 if (num >= RExC_npar) {
11815
11816                     /* It might be a forward reference; we can't fail until we
11817                      * know, by completing the parse to get all the groups, and
11818                      * then reparsing */
11819                     if (ALL_PARENS_COUNTED)  {
11820                         if (num >= RExC_total_parens) {
11821                             RExC_parse++;
11822                             vFAIL(non_existent_group_msg);
11823                         }
11824                     }
11825                     else {
11826                         REQUIRE_PARENS_PASS;
11827                     }
11828                 }
11829
11830                 /* We keep track how many GOSUB items we have produced.
11831                    To start off the ARG2L() of the GOSUB holds its "id",
11832                    which is used later in conjunction with RExC_recurse
11833                    to calculate the offset we need to jump for the GOSUB,
11834                    which it will store in the final representation.
11835                    We have to defer the actual calculation until much later
11836                    as the regop may move.
11837                  */
11838                 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11839                 RExC_recurse_count++;
11840                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11841                     "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11842                             22, "|    |", (int)(depth * 2 + 1), "",
11843                             (UV)ARG(REGNODE_p(ret)),
11844                             (IV)ARG2L(REGNODE_p(ret))));
11845                 RExC_seen |= REG_RECURSE_SEEN;
11846
11847                 Set_Node_Length(REGNODE_p(ret),
11848                                 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11849                 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11850
11851                 *flagp |= POSTPONED;
11852                 assert(*RExC_parse == ')');
11853                 nextchar(pRExC_state);
11854                 return ret;
11855
11856             /* NOTREACHED */
11857
11858             case '?':           /* (??...) */
11859                 is_logical = 1;
11860                 if (*RExC_parse != '{') {
11861                     RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11862                     /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11863                     vFAIL2utf8f(
11864                         "Sequence (%" UTF8f "...) not recognized",
11865                         UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11866                     NOT_REACHED; /*NOTREACHED*/
11867                 }
11868                 *flagp |= POSTPONED;
11869                 paren = '{';
11870                 RExC_parse++;
11871                 /* FALLTHROUGH */
11872             case '{':           /* (?{...}) */
11873             {
11874                 U32 n = 0;
11875                 struct reg_code_block *cb;
11876                 OP * o;
11877
11878                 RExC_seen_zerolen++;
11879
11880                 if (   !pRExC_state->code_blocks
11881                     || pRExC_state->code_index
11882                                         >= pRExC_state->code_blocks->count
11883                     || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11884                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11885                             - RExC_start)
11886                 ) {
11887                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
11888                         FAIL("panic: Sequence (?{...}): no code block found\n");
11889                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
11890                 }
11891                 /* this is a pre-compiled code block (?{...}) */
11892                 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11893                 RExC_parse = RExC_start + cb->end;
11894                 o = cb->block;
11895                 if (cb->src_regex) {
11896                     n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11897                     RExC_rxi->data->data[n] =
11898                         (void*)SvREFCNT_inc((SV*)cb->src_regex);
11899                     RExC_rxi->data->data[n+1] = (void*)o;
11900                 }
11901                 else {
11902                     n = add_data(pRExC_state,
11903                             (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11904                     RExC_rxi->data->data[n] = (void*)o;
11905                 }
11906                 pRExC_state->code_index++;
11907                 nextchar(pRExC_state);
11908
11909                 if (is_logical) {
11910                     regnode_offset eval;
11911                     ret = reg_node(pRExC_state, LOGICAL);
11912
11913                     eval = reg2Lanode(pRExC_state, EVAL,
11914                                        n,
11915
11916                                        /* for later propagation into (??{})
11917                                         * return value */
11918                                        RExC_flags & RXf_PMf_COMPILETIME
11919                                       );
11920                     FLAGS(REGNODE_p(ret)) = 2;
11921                     if (! REGTAIL(pRExC_state, ret, eval)) {
11922                         REQUIRE_BRANCHJ(flagp, 0);
11923                     }
11924                     /* deal with the length of this later - MJD */
11925                     return ret;
11926                 }
11927                 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11928                 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11929                 Set_Node_Offset(REGNODE_p(ret), parse_start);
11930                 return ret;
11931             }
11932             case '(':           /* (?(?{...})...) and (?(?=...)...) */
11933             {
11934                 int is_define= 0;
11935                 const int DEFINE_len = sizeof("DEFINE") - 1;
11936                 if (    RExC_parse < RExC_end - 1
11937                     && (   (       RExC_parse[0] == '?'        /* (?(?...)) */
11938                             && (   RExC_parse[1] == '='
11939                                 || RExC_parse[1] == '!'
11940                                 || RExC_parse[1] == '<'
11941                                 || RExC_parse[1] == '{'))
11942                         || (       RExC_parse[0] == '*'        /* (?(*...)) */
11943                             && (   memBEGINs(RExC_parse + 1,
11944                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11945                                          "pla:")
11946                                 || memBEGINs(RExC_parse + 1,
11947                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11948                                          "plb:")
11949                                 || memBEGINs(RExC_parse + 1,
11950                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11951                                          "nla:")
11952                                 || memBEGINs(RExC_parse + 1,
11953                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11954                                          "nlb:")
11955                                 || memBEGINs(RExC_parse + 1,
11956                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11957                                          "positive_lookahead:")
11958                                 || memBEGINs(RExC_parse + 1,
11959                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11960                                          "positive_lookbehind:")
11961                                 || memBEGINs(RExC_parse + 1,
11962                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11963                                          "negative_lookahead:")
11964                                 || memBEGINs(RExC_parse + 1,
11965                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11966                                          "negative_lookbehind:"))))
11967                 ) { /* Lookahead or eval. */
11968                     I32 flag;
11969                     regnode_offset tail;
11970
11971                     ret = reg_node(pRExC_state, LOGICAL);
11972                     FLAGS(REGNODE_p(ret)) = 1;
11973
11974                     tail = reg(pRExC_state, 1, &flag, depth+1);
11975                     RETURN_FAIL_ON_RESTART(flag, flagp);
11976                     if (! REGTAIL(pRExC_state, ret, tail)) {
11977                         REQUIRE_BRANCHJ(flagp, 0);
11978                     }
11979                     goto insert_if;
11980                 }
11981                 else if (   RExC_parse[0] == '<'     /* (?(<NAME>)...) */
11982                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11983                 {
11984                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
11985                     char *name_start= RExC_parse++;
11986                     U32 num = 0;
11987                     SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11988                     if (   RExC_parse == name_start
11989                         || RExC_parse >= RExC_end
11990                         || *RExC_parse != ch)
11991                     {
11992                         vFAIL2("Sequence (?(%c... not terminated",
11993                             (ch == '>' ? '<' : ch));
11994                     }
11995                     RExC_parse++;
11996                     if (sv_dat) {
11997                         num = add_data( pRExC_state, STR_WITH_LEN("S"));
11998                         RExC_rxi->data->data[num]=(void*)sv_dat;
11999                         SvREFCNT_inc_simple_void_NN(sv_dat);
12000                     }
12001                     ret = reganode(pRExC_state, GROUPPN, num);
12002                     goto insert_if_check_paren;
12003                 }
12004                 else if (memBEGINs(RExC_parse,
12005                                    (STRLEN) (RExC_end - RExC_parse),
12006                                    "DEFINE"))
12007                 {
12008                     ret = reganode(pRExC_state, DEFINEP, 0);
12009                     RExC_parse += DEFINE_len;
12010                     is_define = 1;
12011                     goto insert_if_check_paren;
12012                 }
12013                 else if (RExC_parse[0] == 'R') {
12014                     RExC_parse++;
12015                     /* parno == 0 => /(?(R)YES|NO)/  "in any form of recursion OR eval"
12016                      * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
12017                      * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
12018                      */
12019                     parno = 0;
12020                     if (RExC_parse[0] == '0') {
12021                         parno = 1;
12022                         RExC_parse++;
12023                     }
12024                     else if (inRANGE(RExC_parse[0], '1', '9')) {
12025                         UV uv;
12026                         endptr = RExC_end;
12027                         if (grok_atoUV(RExC_parse, &uv, &endptr)
12028                             && uv <= I32_MAX
12029                         ) {
12030                             parno = (I32)uv + 1;
12031                             RExC_parse = (char*)endptr;
12032                         }
12033                         /* else "Switch condition not recognized" below */
12034                     } else if (RExC_parse[0] == '&') {
12035                         SV *sv_dat;
12036                         RExC_parse++;
12037                         sv_dat = reg_scan_name(pRExC_state,
12038                                                REG_RSN_RETURN_DATA);
12039                         if (sv_dat)
12040                             parno = 1 + *((I32 *)SvPVX(sv_dat));
12041                     }
12042                     ret = reganode(pRExC_state, INSUBP, parno);
12043                     goto insert_if_check_paren;
12044                 }
12045                 else if (inRANGE(RExC_parse[0], '1', '9')) {
12046                     /* (?(1)...) */
12047                     char c;
12048                     UV uv;
12049                     endptr = RExC_end;
12050                     if (grok_atoUV(RExC_parse, &uv, &endptr)
12051                         && uv <= I32_MAX
12052                     ) {
12053                         parno = (I32)uv;
12054                         RExC_parse = (char*)endptr;
12055                     }
12056                     else {
12057                         vFAIL("panic: grok_atoUV returned FALSE");
12058                     }
12059                     ret = reganode(pRExC_state, GROUPP, parno);
12060
12061                  insert_if_check_paren:
12062                     if (UCHARAT(RExC_parse) != ')') {
12063                         RExC_parse += UTF
12064                                       ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
12065                                       : 1;
12066                         vFAIL("Switch condition not recognized");
12067                     }
12068                     nextchar(pRExC_state);
12069                   insert_if:
12070                     if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state,
12071                                                              IFTHEN, 0)))
12072                     {
12073                         REQUIRE_BRANCHJ(flagp, 0);
12074                     }
12075                     br = regbranch(pRExC_state, &flags, 1, depth+1);
12076                     if (br == 0) {
12077                         RETURN_FAIL_ON_RESTART(flags,flagp);
12078                         FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
12079                               (UV) flags);
12080                     } else
12081                     if (! REGTAIL(pRExC_state, br, reganode(pRExC_state,
12082                                                              LONGJMP, 0)))
12083                     {
12084                         REQUIRE_BRANCHJ(flagp, 0);
12085                     }
12086                     c = UCHARAT(RExC_parse);
12087                     nextchar(pRExC_state);
12088                     if (flags&HASWIDTH)
12089                         *flagp |= HASWIDTH;
12090                     if (c == '|') {
12091                         if (is_define)
12092                             vFAIL("(?(DEFINE)....) does not allow branches");
12093
12094                         /* Fake one for optimizer.  */
12095                         lastbr = reganode(pRExC_state, IFTHEN, 0);
12096
12097                         if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
12098                             RETURN_FAIL_ON_RESTART(flags, flagp);
12099                             FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
12100                                   (UV) flags);
12101                         }
12102                         if (! REGTAIL(pRExC_state, ret, lastbr)) {
12103                             REQUIRE_BRANCHJ(flagp, 0);
12104                         }
12105                         if (flags&HASWIDTH)
12106                             *flagp |= HASWIDTH;
12107                         c = UCHARAT(RExC_parse);
12108                         nextchar(pRExC_state);
12109                     }
12110                     else
12111                         lastbr = 0;
12112                     if (c != ')') {
12113                         if (RExC_parse >= RExC_end)
12114                             vFAIL("Switch (?(condition)... not terminated");
12115                         else
12116                             vFAIL("Switch (?(condition)... contains too many branches");
12117                     }
12118                     ender = reg_node(pRExC_state, TAIL);
12119                     if (! REGTAIL(pRExC_state, br, ender)) {
12120                         REQUIRE_BRANCHJ(flagp, 0);
12121                     }
12122                     if (lastbr) {
12123                         if (! REGTAIL(pRExC_state, lastbr, ender)) {
12124                             REQUIRE_BRANCHJ(flagp, 0);
12125                         }
12126                         if (! REGTAIL(pRExC_state,
12127                                       REGNODE_OFFSET(
12128                                                  NEXTOPER(
12129                                                  NEXTOPER(REGNODE_p(lastbr)))),
12130                                       ender))
12131                         {
12132                             REQUIRE_BRANCHJ(flagp, 0);
12133                         }
12134                     }
12135                     else
12136                         if (! REGTAIL(pRExC_state, ret, ender)) {
12137                             REQUIRE_BRANCHJ(flagp, 0);
12138                         }
12139 #if 0  /* Removing this doesn't cause failures in the test suite -- khw */
12140                     RExC_size++; /* XXX WHY do we need this?!!
12141                                     For large programs it seems to be required
12142                                     but I can't figure out why. -- dmq*/
12143 #endif
12144                     return ret;
12145                 }
12146                 RExC_parse += UTF
12147                               ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
12148                               : 1;
12149                 vFAIL("Unknown switch condition (?(...))");
12150             }
12151             case '[':           /* (?[ ... ]) */
12152                 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
12153                                          oregcomp_parse);
12154             case 0: /* A NUL */
12155                 RExC_parse--; /* for vFAIL to print correctly */
12156                 vFAIL("Sequence (? incomplete");
12157                 break;
12158
12159             case ')':
12160                 if (RExC_strict) {  /* [perl #132851] */
12161                     ckWARNreg(RExC_parse, "Empty (?) without any modifiers");
12162                 }
12163                 /* FALLTHROUGH */
12164             case '*': /* If you want to support (?*...), first reconcile with GH #17363 */
12165             /* FALLTHROUGH */
12166             default: /* e.g., (?i) */
12167                 RExC_parse = (char *) seqstart + 1;
12168               parse_flags:
12169                 parse_lparen_question_flags(pRExC_state);
12170                 if (UCHARAT(RExC_parse) != ':') {
12171                     if (RExC_parse < RExC_end)
12172                         nextchar(pRExC_state);
12173                     *flagp = TRYAGAIN;
12174                     return 0;
12175                 }
12176                 paren = ':';
12177                 nextchar(pRExC_state);
12178                 ret = 0;
12179                 goto parse_rest;
12180             } /* end switch */
12181         }
12182         else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) {   /* (...) */
12183           capturing_parens:
12184             parno = RExC_npar;
12185             RExC_npar++;
12186             if (! ALL_PARENS_COUNTED) {
12187                 /* If we are in our first pass through (and maybe only pass),
12188                  * we  need to allocate memory for the capturing parentheses
12189                  * data structures.
12190                  */
12191
12192                 if (!RExC_parens_buf_size) {
12193                     /* first guess at number of parens we might encounter */
12194                     RExC_parens_buf_size = 10;
12195
12196                     /* setup RExC_open_parens, which holds the address of each
12197                      * OPEN tag, and to make things simpler for the 0 index the
12198                      * start of the program - this is used later for offsets */
12199                     Newxz(RExC_open_parens, RExC_parens_buf_size,
12200                             regnode_offset);
12201                     RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
12202
12203                     /* setup RExC_close_parens, which holds the address of each
12204                      * CLOSE tag, and to make things simpler for the 0 index
12205                      * the end of the program - this is used later for offsets
12206                      * */
12207                     Newxz(RExC_close_parens, RExC_parens_buf_size,
12208                             regnode_offset);
12209                     /* we dont know where end op starts yet, so we dont need to
12210                      * set RExC_close_parens[0] like we do RExC_open_parens[0]
12211                      * above */
12212                 }
12213                 else if (RExC_npar > RExC_parens_buf_size) {
12214                     I32 old_size = RExC_parens_buf_size;
12215
12216                     RExC_parens_buf_size *= 2;
12217
12218                     Renew(RExC_open_parens, RExC_parens_buf_size,
12219                             regnode_offset);
12220                     Zero(RExC_open_parens + old_size,
12221                             RExC_parens_buf_size - old_size, regnode_offset);
12222
12223                     Renew(RExC_close_parens, RExC_parens_buf_size,
12224                             regnode_offset);
12225                     Zero(RExC_close_parens + old_size,
12226                             RExC_parens_buf_size - old_size, regnode_offset);
12227                 }
12228             }
12229
12230             ret = reganode(pRExC_state, OPEN, parno);
12231             if (!RExC_nestroot)
12232                 RExC_nestroot = parno;
12233             if (RExC_open_parens && !RExC_open_parens[parno])
12234             {
12235                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12236                     "%*s%*s Setting open paren #%" IVdf " to %zu\n",
12237                     22, "|    |", (int)(depth * 2 + 1), "",
12238                     (IV)parno, ret));
12239                 RExC_open_parens[parno]= ret;
12240             }
12241
12242             Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
12243             Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
12244             is_open = 1;
12245         } else {
12246             /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
12247             paren = ':';
12248             ret = 0;
12249         }
12250     }
12251     else                        /* ! paren */
12252         ret = 0;
12253
12254    parse_rest:
12255     /* Pick up the branches, linking them together. */
12256     parse_start = RExC_parse;   /* MJD */
12257     br = regbranch(pRExC_state, &flags, 1, depth+1);
12258
12259     /*     branch_len = (paren != 0); */
12260
12261     if (br == 0) {
12262         RETURN_FAIL_ON_RESTART(flags, flagp);
12263         FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12264     }
12265     if (*RExC_parse == '|') {
12266         if (RExC_use_BRANCHJ) {
12267             reginsert(pRExC_state, BRANCHJ, br, depth+1);
12268         }
12269         else {                  /* MJD */
12270             reginsert(pRExC_state, BRANCH, br, depth+1);
12271             Set_Node_Length(REGNODE_p(br), paren != 0);
12272             Set_Node_Offset_To_R(br, parse_start-RExC_start);
12273         }
12274         have_branch = 1;
12275     }
12276     else if (paren == ':') {
12277         *flagp |= flags&SIMPLE;
12278     }
12279     if (is_open) {                              /* Starts with OPEN. */
12280         if (! REGTAIL(pRExC_state, ret, br)) {  /* OPEN -> first. */
12281             REQUIRE_BRANCHJ(flagp, 0);
12282         }
12283     }
12284     else if (paren != '?')              /* Not Conditional */
12285         ret = br;
12286     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12287     lastbr = br;
12288     while (*RExC_parse == '|') {
12289         if (RExC_use_BRANCHJ) {
12290             bool shut_gcc_up;
12291
12292             ender = reganode(pRExC_state, LONGJMP, 0);
12293
12294             /* Append to the previous. */
12295             shut_gcc_up = REGTAIL(pRExC_state,
12296                          REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
12297                          ender);
12298             PERL_UNUSED_VAR(shut_gcc_up);
12299         }
12300         nextchar(pRExC_state);
12301         if (freeze_paren) {
12302             if (RExC_npar > after_freeze)
12303                 after_freeze = RExC_npar;
12304             RExC_npar = freeze_paren;
12305         }
12306         br = regbranch(pRExC_state, &flags, 0, depth+1);
12307
12308         if (br == 0) {
12309             RETURN_FAIL_ON_RESTART(flags, flagp);
12310             FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12311         }
12312         if (!  REGTAIL(pRExC_state, lastbr, br)) {  /* BRANCH -> BRANCH. */
12313             REQUIRE_BRANCHJ(flagp, 0);
12314         }
12315         lastbr = br;
12316         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12317     }
12318
12319     if (have_branch || paren != ':') {
12320         regnode * br;
12321
12322         /* Make a closing node, and hook it on the end. */
12323         switch (paren) {
12324         case ':':
12325             ender = reg_node(pRExC_state, TAIL);
12326             break;
12327         case 1: case 2:
12328             ender = reganode(pRExC_state, CLOSE, parno);
12329             if ( RExC_close_parens ) {
12330                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12331                         "%*s%*s Setting close paren #%" IVdf " to %zu\n",
12332                         22, "|    |", (int)(depth * 2 + 1), "",
12333                         (IV)parno, ender));
12334                 RExC_close_parens[parno]= ender;
12335                 if (RExC_nestroot == parno)
12336                     RExC_nestroot = 0;
12337             }
12338             Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
12339             Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
12340             break;
12341         case 's':
12342             ender = reg_node(pRExC_state, SRCLOSE);
12343             RExC_in_script_run = 0;
12344             break;
12345         case '<':
12346         case 'a':
12347         case 'A':
12348         case 'b':
12349         case 'B':
12350         case ',':
12351         case '=':
12352         case '!':
12353             *flagp &= ~HASWIDTH;
12354             /* FALLTHROUGH */
12355         case 't':   /* aTomic */
12356         case '>':
12357             ender = reg_node(pRExC_state, SUCCEED);
12358             break;
12359         case 0:
12360             ender = reg_node(pRExC_state, END);
12361             assert(!RExC_end_op); /* there can only be one! */
12362             RExC_end_op = REGNODE_p(ender);
12363             if (RExC_close_parens) {
12364                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12365                     "%*s%*s Setting close paren #0 (END) to %zu\n",
12366                     22, "|    |", (int)(depth * 2 + 1), "",
12367                     ender));
12368
12369                 RExC_close_parens[0]= ender;
12370             }
12371             break;
12372         }
12373         DEBUG_PARSE_r({
12374             DEBUG_PARSE_MSG("lsbr");
12375             regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
12376             regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
12377             Perl_re_printf( aTHX_  "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12378                           SvPV_nolen_const(RExC_mysv1),
12379                           (IV)lastbr,
12380                           SvPV_nolen_const(RExC_mysv2),
12381                           (IV)ender,
12382                           (IV)(ender - lastbr)
12383             );
12384         });
12385         if (! REGTAIL(pRExC_state, lastbr, ender)) {
12386             REQUIRE_BRANCHJ(flagp, 0);
12387         }
12388
12389         if (have_branch) {
12390             char is_nothing= 1;
12391             if (depth==1)
12392                 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
12393
12394             /* Hook the tails of the branches to the closing node. */
12395             for (br = REGNODE_p(ret); br; br = regnext(br)) {
12396                 const U8 op = PL_regkind[OP(br)];
12397                 if (op == BRANCH) {
12398                     if (! REGTAIL_STUDY(pRExC_state,
12399                                         REGNODE_OFFSET(NEXTOPER(br)),
12400                                         ender))
12401                     {
12402                         REQUIRE_BRANCHJ(flagp, 0);
12403                     }
12404                     if ( OP(NEXTOPER(br)) != NOTHING
12405                          || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12406                         is_nothing= 0;
12407                 }
12408                 else if (op == BRANCHJ) {
12409                     bool shut_gcc_up = REGTAIL_STUDY(pRExC_state,
12410                                         REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12411                                         ender);
12412                     PERL_UNUSED_VAR(shut_gcc_up);
12413                     /* for now we always disable this optimisation * /
12414                     if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12415                          || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12416                     */
12417                         is_nothing= 0;
12418                 }
12419             }
12420             if (is_nothing) {
12421                 regnode * ret_as_regnode = REGNODE_p(ret);
12422                 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12423                                ? regnext(ret_as_regnode)
12424                                : ret_as_regnode;
12425                 DEBUG_PARSE_r({
12426                     DEBUG_PARSE_MSG("NADA");
12427                     regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12428                                      NULL, pRExC_state);
12429                     regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12430                                      NULL, pRExC_state);
12431                     Perl_re_printf( aTHX_  "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12432                                   SvPV_nolen_const(RExC_mysv1),
12433                                   (IV)REG_NODE_NUM(ret_as_regnode),
12434                                   SvPV_nolen_const(RExC_mysv2),
12435                                   (IV)ender,
12436                                   (IV)(ender - ret)
12437                     );
12438                 });
12439                 OP(br)= NOTHING;
12440                 if (OP(REGNODE_p(ender)) == TAIL) {
12441                     NEXT_OFF(br)= 0;
12442                     RExC_emit= REGNODE_OFFSET(br) + 1;
12443                 } else {
12444                     regnode *opt;
12445                     for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12446                         OP(opt)= OPTIMIZED;
12447                     NEXT_OFF(br)= REGNODE_p(ender) - br;
12448                 }
12449             }
12450         }
12451     }
12452
12453     {
12454         const char *p;
12455          /* Even/odd or x=don't care: 010101x10x */
12456         static const char parens[] = "=!aA<,>Bbt";
12457          /* flag below is set to 0 up through 'A'; 1 for larger */
12458
12459         if (paren && (p = strchr(parens, paren))) {
12460             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12461             int flag = (p - parens) > 3;
12462
12463             if (paren == '>' || paren == 't') {
12464                 node = SUSPEND, flag = 0;
12465             }
12466
12467             reginsert(pRExC_state, node, ret, depth+1);
12468             Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12469             Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12470             FLAGS(REGNODE_p(ret)) = flag;
12471             if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL)))
12472             {
12473                 REQUIRE_BRANCHJ(flagp, 0);
12474             }
12475         }
12476     }
12477
12478     /* Check for proper termination. */
12479     if (paren) {
12480         /* restore original flags, but keep (?p) and, if we've encountered
12481          * something in the parse that changes /d rules into /u, keep the /u */
12482         RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12483         if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12484             set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12485         }
12486         if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12487             RExC_parse = oregcomp_parse;
12488             vFAIL("Unmatched (");
12489         }
12490         nextchar(pRExC_state);
12491     }
12492     else if (!paren && RExC_parse < RExC_end) {
12493         if (*RExC_parse == ')') {
12494             RExC_parse++;
12495             vFAIL("Unmatched )");
12496         }
12497         else
12498             FAIL("Junk on end of regexp");      /* "Can't happen". */
12499         NOT_REACHED; /* NOTREACHED */
12500     }
12501
12502     if (RExC_in_lookbehind) {
12503         RExC_in_lookbehind--;
12504     }
12505     if (RExC_in_lookahead) {
12506         RExC_in_lookahead--;
12507     }
12508     if (after_freeze > RExC_npar)
12509         RExC_npar = after_freeze;
12510     return(ret);
12511 }
12512
12513 /*
12514  - regbranch - one alternative of an | operator
12515  *
12516  * Implements the concatenation operator.
12517  *
12518  * On success, returns the offset at which any next node should be placed into
12519  * the regex engine program being compiled.
12520  *
12521  * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12522  * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12523  * UTF-8
12524  */
12525 STATIC regnode_offset
12526 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12527 {
12528     regnode_offset ret;
12529     regnode_offset chain = 0;
12530     regnode_offset latest;
12531     I32 flags = 0, c = 0;
12532     DECLARE_AND_GET_RE_DEBUG_FLAGS;
12533
12534     PERL_ARGS_ASSERT_REGBRANCH;
12535
12536     DEBUG_PARSE("brnc");
12537
12538     if (first)
12539         ret = 0;
12540     else {
12541         if (RExC_use_BRANCHJ)
12542             ret = reganode(pRExC_state, BRANCHJ, 0);
12543         else {
12544             ret = reg_node(pRExC_state, BRANCH);
12545             Set_Node_Length(REGNODE_p(ret), 1);
12546         }
12547     }
12548
12549     *flagp = WORST;                     /* Tentatively. */
12550
12551     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12552                             FALSE /* Don't force to /x */ );
12553     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12554         flags &= ~TRYAGAIN;
12555         latest = regpiece(pRExC_state, &flags, depth+1);
12556         if (latest == 0) {
12557             if (flags & TRYAGAIN)
12558                 continue;
12559             RETURN_FAIL_ON_RESTART(flags, flagp);
12560             FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12561         }
12562         else if (ret == 0)
12563             ret = latest;
12564         *flagp |= flags&(HASWIDTH|POSTPONED);
12565         if (chain == 0)         /* First piece. */
12566             *flagp |= flags&SPSTART;
12567         else {
12568             /* FIXME adding one for every branch after the first is probably
12569              * excessive now we have TRIE support. (hv) */
12570             MARK_NAUGHTY(1);
12571             if (! REGTAIL(pRExC_state, chain, latest)) {
12572                 /* XXX We could just redo this branch, but figuring out what
12573                  * bookkeeping needs to be reset is a pain, and it's likely
12574                  * that other branches that goto END will also be too large */
12575                 REQUIRE_BRANCHJ(flagp, 0);
12576             }
12577         }
12578         chain = latest;
12579         c++;
12580     }
12581     if (chain == 0) {   /* Loop ran zero times. */
12582         chain = reg_node(pRExC_state, NOTHING);
12583         if (ret == 0)
12584             ret = chain;
12585     }
12586     if (c == 1) {
12587         *flagp |= flags&SIMPLE;
12588     }
12589
12590     return ret;
12591 }
12592
12593 /*
12594  - regpiece - something followed by possible quantifier * + ? {n,m}
12595  *
12596  * Note that the branching code sequences used for ? and the general cases
12597  * of * and + are somewhat optimized:  they use the same NOTHING node as
12598  * both the endmarker for their branch list and the body of the last branch.
12599  * It might seem that this node could be dispensed with entirely, but the
12600  * endmarker role is not redundant.
12601  *
12602  * On success, returns the offset at which any next node should be placed into
12603  * the regex engine program being compiled.
12604  *
12605  * Returns 0 otherwise, with *flagp set to indicate why:
12606  *  TRYAGAIN        if regatom() returns 0 with TRYAGAIN.
12607  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
12608  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12609  */
12610 STATIC regnode_offset
12611 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12612 {
12613     regnode_offset ret;
12614     char op;
12615     char *next;
12616     I32 flags;
12617     const char * const origparse = RExC_parse;
12618     I32 min;
12619     I32 max = REG_INFTY;
12620 #ifdef RE_TRACK_PATTERN_OFFSETS
12621     char *parse_start;
12622 #endif
12623     const char *maxpos = NULL;
12624     UV uv;
12625
12626     /* Save the original in case we change the emitted regop to a FAIL. */
12627     const regnode_offset orig_emit = RExC_emit;
12628
12629     DECLARE_AND_GET_RE_DEBUG_FLAGS;
12630
12631     PERL_ARGS_ASSERT_REGPIECE;
12632
12633     DEBUG_PARSE("piec");
12634
12635     ret = regatom(pRExC_state, &flags, depth+1);
12636     if (ret == 0) {
12637         RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12638         FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12639     }
12640
12641     op = *RExC_parse;
12642
12643     if (op == '{' && regcurly(RExC_parse)) {
12644         maxpos = NULL;
12645 #ifdef RE_TRACK_PATTERN_OFFSETS
12646         parse_start = RExC_parse; /* MJD */
12647 #endif
12648         next = RExC_parse + 1;
12649         while (isDIGIT(*next) || *next == ',') {
12650             if (*next == ',') {
12651                 if (maxpos)
12652                     break;
12653                 else
12654                     maxpos = next;
12655             }
12656             next++;
12657         }
12658         if (*next == '}') {             /* got one */
12659             const char* endptr;
12660             if (!maxpos)
12661                 maxpos = next;
12662             RExC_parse++;
12663             if (isDIGIT(*RExC_parse)) {
12664                 endptr = RExC_end;
12665                 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12666                     vFAIL("Invalid quantifier in {,}");
12667                 if (uv >= REG_INFTY)
12668                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12669                 min = (I32)uv;
12670             } else {
12671                 min = 0;
12672             }
12673             if (*maxpos == ',')
12674                 maxpos++;
12675             else
12676                 maxpos = RExC_parse;
12677             if (isDIGIT(*maxpos)) {
12678                 endptr = RExC_end;
12679                 if (!grok_atoUV(maxpos, &uv, &endptr))
12680                     vFAIL("Invalid quantifier in {,}");
12681                 if (uv >= REG_INFTY)
12682                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12683                 max = (I32)uv;
12684             } else {
12685                 max = REG_INFTY;                /* meaning "infinity" */
12686             }
12687             RExC_parse = next;
12688             nextchar(pRExC_state);
12689             if (max < min) {    /* If can't match, warn and optimize to fail
12690                                    unconditionally */
12691                 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12692                 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12693                 NEXT_OFF(REGNODE_p(orig_emit)) =
12694                                     regarglen[OPFAIL] + NODE_STEP_REGNODE;
12695                 return ret;
12696             }
12697             else if (min == max && *RExC_parse == '?')
12698             {
12699                 ckWARN2reg(RExC_parse + 1,
12700                            "Useless use of greediness modifier '%c'",
12701                            *RExC_parse);
12702             }
12703
12704           do_curly:
12705             if ((flags&SIMPLE)) {
12706                 if (min == 0 && max == REG_INFTY) {
12707
12708                     /* Going from 0..inf is currently forbidden in wildcard
12709                      * subpatterns.  The only reason is to make it harder to
12710                      * write patterns that take a long long time to halt, and
12711                      * because the use of this construct isn't necessary in
12712                      * matching Unicode property values */
12713                     if (RExC_pm_flags & PMf_WILDCARD) {
12714                         RExC_parse++;
12715                         /* diag_listed_as: Use of %s is not allowed in Unicode
12716                            property wildcard subpatterns in regex; marked by
12717                            <-- HERE in m/%s/ */
12718                         vFAIL("Use of quantifier '*' is not allowed in"
12719                               " Unicode property wildcard subpatterns");
12720                         /* Note, don't need to worry about {0,}, as a '}' isn't
12721                          * legal at all in wildcards, so wouldn't get this far
12722                          * */
12723                     }
12724                     reginsert(pRExC_state, STAR, ret, depth+1);
12725                     MARK_NAUGHTY(4);
12726                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12727                     goto nest_check;
12728                 }
12729                 if (min == 1 && max == REG_INFTY) {
12730                     reginsert(pRExC_state, PLUS, ret, depth+1);
12731                     MARK_NAUGHTY(3);
12732                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12733                     goto nest_check;
12734                 }
12735                 MARK_NAUGHTY_EXP(2, 2);
12736                 reginsert(pRExC_state, CURLY, ret, depth+1);
12737                 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12738                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12739             }
12740             else {
12741                 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12742
12743                 FLAGS(REGNODE_p(w)) = 0;
12744                 if (!  REGTAIL(pRExC_state, ret, w)) {
12745                     REQUIRE_BRANCHJ(flagp, 0);
12746                 }
12747                 if (RExC_use_BRANCHJ) {
12748                     reginsert(pRExC_state, LONGJMP, ret, depth+1);
12749                     reginsert(pRExC_state, NOTHING, ret, depth+1);
12750                     NEXT_OFF(REGNODE_p(ret)) = 3;       /* Go over LONGJMP. */
12751                 }
12752                 reginsert(pRExC_state, CURLYX, ret, depth+1);
12753                                 /* MJD hk */
12754                 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12755                 Set_Node_Length(REGNODE_p(ret),
12756                                 op == '{' ? (RExC_parse - parse_start) : 1);
12757
12758                 if (RExC_use_BRANCHJ)
12759                     NEXT_OFF(REGNODE_p(ret)) = 3;   /* Go over NOTHING to
12760                                                        LONGJMP. */
12761                 if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state,
12762                                                           NOTHING)))
12763                 {
12764                     REQUIRE_BRANCHJ(flagp, 0);
12765                 }
12766                 RExC_whilem_seen++;
12767                 MARK_NAUGHTY_EXP(1, 4);     /* compound interest */
12768             }
12769             FLAGS(REGNODE_p(ret)) = 0;
12770
12771             if (min > 0)
12772                 *flagp = WORST;
12773             if (max > 0)
12774                 *flagp |= HASWIDTH;
12775             ARG1_SET(REGNODE_p(ret), (U16)min);
12776             ARG2_SET(REGNODE_p(ret), (U16)max);
12777             if (max == REG_INFTY)
12778                 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12779
12780             goto nest_check;
12781         }
12782     }
12783
12784     if (!ISMULT1(op)) {
12785         *flagp = flags;
12786         return(ret);
12787     }
12788
12789 #if 0                           /* Now runtime fix should be reliable. */
12790
12791     /* if this is reinstated, don't forget to put this back into perldiag:
12792
12793             =item Regexp *+ operand could be empty at {#} in regex m/%s/
12794
12795            (F) The part of the regexp subject to either the * or + quantifier
12796            could match an empty string. The {#} shows in the regular
12797            expression about where the problem was discovered.
12798
12799     */
12800
12801     if (!(flags&HASWIDTH) && op != '?')
12802       vFAIL("Regexp *+ operand could be empty");
12803 #endif
12804
12805 #ifdef RE_TRACK_PATTERN_OFFSETS
12806     parse_start = RExC_parse;
12807 #endif
12808     nextchar(pRExC_state);
12809
12810     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12811
12812     if (op == '*') {
12813         min = 0;
12814         goto do_curly;
12815     }
12816     else if (op == '+') {
12817         min = 1;
12818         goto do_curly;
12819     }
12820     else if (op == '?') {
12821         min = 0; max = 1;
12822         goto do_curly;
12823     }
12824   nest_check:
12825     if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12826         if (origparse[0] == '\\' && origparse[1] == 'K') {
12827             vFAIL2utf8f(
12828                        "%" UTF8f " is forbidden - matches null string many times",
12829                        UTF8fARG(UTF, (RExC_parse >= origparse
12830                                      ? RExC_parse - origparse
12831                                      : 0),
12832                        origparse));
12833             /* NOT-REACHED */
12834         } else {
12835             ckWARN2reg(RExC_parse,
12836                        "%" UTF8f " matches null string many times",
12837                        UTF8fARG(UTF, (RExC_parse >= origparse
12838                                      ? RExC_parse - origparse
12839                                      : 0),
12840                        origparse));
12841         }
12842     }
12843
12844     if (*RExC_parse == '?') {
12845         nextchar(pRExC_state);
12846         reginsert(pRExC_state, MINMOD, ret, depth+1);
12847         if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) {
12848             REQUIRE_BRANCHJ(flagp, 0);
12849         }
12850     }
12851     else if (*RExC_parse == '+') {
12852         regnode_offset ender;
12853         nextchar(pRExC_state);
12854         ender = reg_node(pRExC_state, SUCCEED);
12855         if (! REGTAIL(pRExC_state, ret, ender)) {
12856             REQUIRE_BRANCHJ(flagp, 0);
12857         }
12858         reginsert(pRExC_state, SUSPEND, ret, depth+1);
12859         ender = reg_node(pRExC_state, TAIL);
12860         if (! REGTAIL(pRExC_state, ret, ender)) {
12861             REQUIRE_BRANCHJ(flagp, 0);
12862         }
12863     }
12864
12865     if (ISMULT2(RExC_parse)) {
12866         RExC_parse++;
12867         vFAIL("Nested quantifiers");
12868     }
12869
12870     return(ret);
12871 }
12872
12873 STATIC bool
12874 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12875                 regnode_offset * node_p,
12876                 UV * code_point_p,
12877                 int * cp_count,
12878                 I32 * flagp,
12879                 const bool strict,
12880                 const U32 depth
12881     )
12882 {
12883  /* This routine teases apart the various meanings of \N and returns
12884   * accordingly.  The input parameters constrain which meaning(s) is/are valid
12885   * in the current context.
12886   *
12887   * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12888   *
12889   * If <code_point_p> is not NULL, the context is expecting the result to be a
12890   * single code point.  If this \N instance turns out to a single code point,
12891   * the function returns TRUE and sets *code_point_p to that code point.
12892   *
12893   * If <node_p> is not NULL, the context is expecting the result to be one of
12894   * the things representable by a regnode.  If this \N instance turns out to be
12895   * one such, the function generates the regnode, returns TRUE and sets *node_p
12896   * to point to the offset of that regnode into the regex engine program being
12897   * compiled.
12898   *
12899   * If this instance of \N isn't legal in any context, this function will
12900   * generate a fatal error and not return.
12901   *
12902   * On input, RExC_parse should point to the first char following the \N at the
12903   * time of the call.  On successful return, RExC_parse will have been updated
12904   * to point to just after the sequence identified by this routine.  Also
12905   * *flagp has been updated as needed.
12906   *
12907   * When there is some problem with the current context and this \N instance,
12908   * the function returns FALSE, without advancing RExC_parse, nor setting
12909   * *node_p, nor *code_point_p, nor *flagp.
12910   *
12911   * If <cp_count> is not NULL, the caller wants to know the length (in code
12912   * points) that this \N sequence matches.  This is set, and the input is
12913   * parsed for errors, even if the function returns FALSE, as detailed below.
12914   *
12915   * There are 6 possibilities here, as detailed in the next 6 paragraphs.
12916   *
12917   * Probably the most common case is for the \N to specify a single code point.
12918   * *cp_count will be set to 1, and *code_point_p will be set to that code
12919   * point.
12920   *
12921   * Another possibility is for the input to be an empty \N{}.  This is no
12922   * longer accepted, and will generate a fatal error.
12923   *
12924   * Another possibility is for a custom charnames handler to be in effect which
12925   * translates the input name to an empty string.  *cp_count will be set to 0.
12926   * *node_p will be set to a generated NOTHING node.
12927   *
12928   * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12929   * set to 0. *node_p will be set to a generated REG_ANY node.
12930   *
12931   * The fifth possibility is that \N resolves to a sequence of more than one
12932   * code points.  *cp_count will be set to the number of code points in the
12933   * sequence. *node_p will be set to a generated node returned by this
12934   * function calling S_reg().
12935   *
12936   * The final possibility is that it is premature to be calling this function;
12937   * the parse needs to be restarted.  This can happen when this changes from
12938   * /d to /u rules, or when the pattern needs to be upgraded to UTF-8.  The
12939   * latter occurs only when the fifth possibility would otherwise be in
12940   * effect, and is because one of those code points requires the pattern to be
12941   * recompiled as UTF-8.  The function returns FALSE, and sets the
12942   * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate.  When this
12943   * happens, the caller needs to desist from continuing parsing, and return
12944   * this information to its caller.  This is not set for when there is only one
12945   * code point, as this can be called as part of an ANYOF node, and they can
12946   * store above-Latin1 code points without the pattern having to be in UTF-8.
12947   *
12948   * For non-single-quoted regexes, the tokenizer has resolved character and
12949   * sequence names inside \N{...} into their Unicode values, normalizing the
12950   * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12951   * hex-represented code points in the sequence.  This is done there because
12952   * the names can vary based on what charnames pragma is in scope at the time,
12953   * so we need a way to take a snapshot of what they resolve to at the time of
12954   * the original parse. [perl #56444].
12955   *
12956   * That parsing is skipped for single-quoted regexes, so here we may get
12957   * '\N{NAME}', which is parsed now.  If the single-quoted regex is something
12958   * like '\N{U+41}', that code point is Unicode, and has to be translated into
12959   * the native character set for non-ASCII platforms.  The other possibilities
12960   * are already native, so no translation is done. */
12961
12962     char * endbrace;    /* points to '}' following the name */
12963     char* p = RExC_parse; /* Temporary */
12964
12965     SV * substitute_parse = NULL;
12966     char *orig_end;
12967     char *save_start;
12968     I32 flags;
12969
12970     DECLARE_AND_GET_RE_DEBUG_FLAGS;
12971
12972     PERL_ARGS_ASSERT_GROK_BSLASH_N;
12973
12974     assert(cBOOL(node_p) ^ cBOOL(code_point_p));  /* Exactly one should be set */
12975     assert(! (node_p && cp_count));               /* At most 1 should be set */
12976
12977     if (cp_count) {     /* Initialize return for the most common case */
12978         *cp_count = 1;
12979     }
12980
12981     /* The [^\n] meaning of \N ignores spaces and comments under the /x
12982      * modifier.  The other meanings do not, so use a temporary until we find
12983      * out which we are being called with */
12984     skip_to_be_ignored_text(pRExC_state, &p,
12985                             FALSE /* Don't force to /x */ );
12986
12987     /* Disambiguate between \N meaning a named character versus \N meaning
12988      * [^\n].  The latter is assumed when the {...} following the \N is a legal
12989      * quantifier, or if there is no '{' at all */
12990     if (*p != '{' || regcurly(p)) {
12991         RExC_parse = p;
12992         if (cp_count) {
12993             *cp_count = -1;
12994         }
12995
12996         if (! node_p) {
12997             return FALSE;
12998         }
12999
13000         *node_p = reg_node(pRExC_state, REG_ANY);
13001         *flagp |= HASWIDTH|SIMPLE;
13002         MARK_NAUGHTY(1);
13003         Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
13004         return TRUE;
13005     }
13006
13007     /* The test above made sure that the next real character is a '{', but
13008      * under the /x modifier, it could be separated by space (or a comment and
13009      * \n) and this is not allowed (for consistency with \x{...} and the
13010      * tokenizer handling of \N{NAME}). */
13011     if (*RExC_parse != '{') {
13012         vFAIL("Missing braces on \\N{}");
13013     }
13014
13015     RExC_parse++;       /* Skip past the '{' */
13016
13017     endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13018     if (! endbrace) { /* no trailing brace */
13019         vFAIL2("Missing right brace on \\%c{}", 'N');
13020     }
13021
13022     /* Here, we have decided it should be a named character or sequence.  These
13023      * imply Unicode semantics */
13024     REQUIRE_UNI_RULES(flagp, FALSE);
13025
13026     /* \N{_} is what toke.c returns to us to indicate a name that evaluates to
13027      * nothing at all (not allowed under strict) */
13028     if (endbrace - RExC_parse == 1 && *RExC_parse == '_') {
13029         RExC_parse = endbrace;
13030         if (strict) {
13031             RExC_parse++;   /* Position after the "}" */
13032             vFAIL("Zero length \\N{}");
13033         }
13034
13035         if (cp_count) {
13036             *cp_count = 0;
13037         }
13038         nextchar(pRExC_state);
13039         if (! node_p) {
13040             return FALSE;
13041         }
13042
13043         *node_p = reg_node(pRExC_state, NOTHING);
13044         return TRUE;
13045     }
13046
13047     if (endbrace - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) {
13048
13049         /* Here, the name isn't of the form  U+....  This can happen if the
13050          * pattern is single-quoted, so didn't get evaluated in toke.c.  Now
13051          * is the time to find out what the name means */
13052
13053         const STRLEN name_len = endbrace - RExC_parse;
13054         SV *  value_sv;     /* What does this name evaluate to */
13055         SV ** value_svp;
13056         const U8 * value;   /* string of name's value */
13057         STRLEN value_len;   /* and its length */
13058
13059         /*  RExC_unlexed_names is a hash of names that weren't evaluated by
13060          *  toke.c, and their values. Make sure is initialized */
13061         if (! RExC_unlexed_names) {
13062             RExC_unlexed_names = newHV();
13063         }
13064
13065         /* If we have already seen this name in this pattern, use that.  This
13066          * allows us to only call the charnames handler once per name per
13067          * pattern.  A broken or malicious handler could return something
13068          * different each time, which could cause the results to vary depending
13069          * on if something gets added or subtracted from the pattern that
13070          * causes the number of passes to change, for example */
13071         if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse,
13072                                                       name_len, 0)))
13073         {
13074             value_sv = *value_svp;
13075         }
13076         else { /* Otherwise we have to go out and get the name */
13077             const char * error_msg = NULL;
13078             value_sv = get_and_check_backslash_N_name(RExC_parse, endbrace,
13079                                                       UTF,
13080                                                       &error_msg);
13081             if (error_msg) {
13082                 RExC_parse = endbrace;
13083                 vFAIL(error_msg);
13084             }
13085
13086             /* If no error message, should have gotten a valid return */
13087             assert (value_sv);
13088
13089             /* Save the name's meaning for later use */
13090             if (! hv_store(RExC_unlexed_names, RExC_parse, name_len,
13091                            value_sv, 0))
13092             {
13093                 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
13094             }
13095         }
13096
13097         /* Here, we have the value the name evaluates to in 'value_sv' */
13098         value = (U8 *) SvPV(value_sv, value_len);
13099
13100         /* See if the result is one code point vs 0 or multiple */
13101         if (inRANGE(value_len, 1, ((UV) SvUTF8(value_sv)
13102                                   ? UTF8SKIP(value)
13103                                   : 1)))
13104         {
13105             /* Here, exactly one code point.  If that isn't what is wanted,
13106              * fail */
13107             if (! code_point_p) {
13108                 RExC_parse = p;
13109                 return FALSE;
13110             }
13111
13112             /* Convert from string to numeric code point */
13113             *code_point_p = (SvUTF8(value_sv))
13114                             ? valid_utf8_to_uvchr(value, NULL)
13115                             : *value;
13116
13117             /* Have parsed this entire single code point \N{...}.  *cp_count
13118              * has already been set to 1, so don't do it again. */
13119             RExC_parse = endbrace;
13120             nextchar(pRExC_state);
13121             return TRUE;
13122         } /* End of is a single code point */
13123
13124         /* Count the code points, if caller desires.  The API says to do this
13125          * even if we will later return FALSE */
13126         if (cp_count) {
13127             *cp_count = 0;
13128
13129             *cp_count = (SvUTF8(value_sv))
13130                         ? utf8_length(value, value + value_len)
13131                         : value_len;
13132         }
13133
13134         /* Fail if caller doesn't want to handle a multi-code-point sequence.
13135          * But don't back the pointer up if the caller wants to know how many
13136          * code points there are (they need to handle it themselves in this
13137          * case).  */
13138         if (! node_p) {
13139             if (! cp_count) {
13140                 RExC_parse = p;
13141             }
13142             return FALSE;
13143         }
13144
13145         /* Convert this to a sub-pattern of the form "(?: ... )", and then call
13146          * reg recursively to parse it.  That way, it retains its atomicness,
13147          * while not having to worry about any special handling that some code
13148          * points may have. */
13149
13150         substitute_parse = newSVpvs("?:");
13151         sv_catsv(substitute_parse, value_sv);
13152         sv_catpv(substitute_parse, ")");
13153
13154         /* The value should already be native, so no need to convert on EBCDIC
13155          * platforms.*/
13156         assert(! RExC_recode_x_to_native);
13157
13158     }
13159     else {   /* \N{U+...} */
13160         Size_t count = 0;   /* code point count kept internally */
13161
13162         /* We can get to here when the input is \N{U+...} or when toke.c has
13163          * converted a name to the \N{U+...} form.  This include changing a
13164          * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
13165
13166         RExC_parse += 2;    /* Skip past the 'U+' */
13167
13168         /* Code points are separated by dots.  The '}' terminates the whole
13169          * thing. */
13170
13171         do {    /* Loop until the ending brace */
13172             I32 flags = PERL_SCAN_SILENT_OVERFLOW
13173                       | PERL_SCAN_SILENT_ILLDIGIT
13174                       | PERL_SCAN_NOTIFY_ILLDIGIT
13175                       | PERL_SCAN_ALLOW_MEDIAL_UNDERSCORES
13176                       | PERL_SCAN_DISALLOW_PREFIX;
13177             STRLEN len = endbrace - RExC_parse;
13178             NV overflow_value;
13179             char * start_digit = RExC_parse;
13180             UV cp = grok_hex(RExC_parse, &len, &flags, &overflow_value);
13181
13182             if (len == 0) {
13183                 RExC_parse++;
13184               bad_NU:
13185                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
13186             }
13187
13188             RExC_parse += len;
13189
13190             if (cp > MAX_LEGAL_CP) {
13191                 vFAIL(form_cp_too_large_msg(16, start_digit, len, 0));
13192             }
13193
13194             if (RExC_parse >= endbrace) { /* Got to the closing '}' */
13195                 if (count) {
13196                     goto do_concat;
13197                 }
13198
13199                 /* Here, is a single code point; fail if doesn't want that */
13200                 if (! code_point_p) {
13201                     RExC_parse = p;
13202                     return FALSE;
13203                 }
13204
13205                 /* A single code point is easy to handle; just return it */
13206                 *code_point_p = UNI_TO_NATIVE(cp);
13207                 RExC_parse = endbrace;
13208                 nextchar(pRExC_state);
13209                 return TRUE;
13210             }
13211
13212             /* Here, the parse stopped bfore the ending brace.  This is legal
13213              * only if that character is a dot separating code points, like a
13214              * multiple character sequence (of the form "\N{U+c1.c2. ... }".
13215              * So the next character must be a dot (and the one after that
13216              * can't be the endbrace, or we'd have something like \N{U+100.} )
13217              * */
13218             if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
13219                 RExC_parse += (RExC_orig_utf8)  /* point to after 1st invalid */
13220                               ? UTF8SKIP(RExC_parse)
13221                               : 1;
13222                 RExC_parse = MIN(endbrace, RExC_parse);/* Guard against
13223                                                           malformed utf8 */
13224                 goto bad_NU;
13225             }
13226
13227             /* Here, looks like its really a multiple character sequence.  Fail
13228              * if that's not what the caller wants.  But continue with counting
13229              * and error checking if they still want a count */
13230             if (! node_p && ! cp_count) {
13231                 return FALSE;
13232             }
13233
13234             /* What is done here is to convert this to a sub-pattern of the
13235              * form \x{char1}\x{char2}...  and then call reg recursively to
13236              * parse it (enclosing in "(?: ... )" ).  That way, it retains its
13237              * atomicness, while not having to worry about special handling
13238              * that some code points may have.  We don't create a subpattern,
13239              * but go through the motions of code point counting and error
13240              * checking, if the caller doesn't want a node returned. */
13241
13242             if (node_p && ! substitute_parse) {
13243                 substitute_parse = newSVpvs("?:");
13244             }
13245
13246           do_concat:
13247
13248             if (node_p) {
13249                 /* Convert to notation the rest of the code understands */
13250                 sv_catpvs(substitute_parse, "\\x{");
13251                 sv_catpvn(substitute_parse, start_digit,
13252                                             RExC_parse - start_digit);
13253                 sv_catpvs(substitute_parse, "}");
13254             }
13255
13256             /* Move to after the dot (or ending brace the final time through.)
13257              * */
13258             RExC_parse++;
13259             count++;
13260
13261         } while (RExC_parse < endbrace);
13262
13263         if (! node_p) { /* Doesn't want the node */
13264             assert (cp_count);
13265
13266             *cp_count = count;
13267             return FALSE;
13268         }
13269
13270         sv_catpvs(substitute_parse, ")");
13271
13272         /* The values are Unicode, and therefore have to be converted to native
13273          * on a non-Unicode (meaning non-ASCII) platform. */
13274         SET_recode_x_to_native(1);
13275     }
13276
13277     /* Here, we have the string the name evaluates to, ready to be parsed,
13278      * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
13279      * constructs.  This can be called from within a substitute parse already.
13280      * The error reporting mechanism doesn't work for 2 levels of this, but the
13281      * code above has validated this new construct, so there should be no
13282      * errors generated by the below.  And this isn' an exact copy, so the
13283      * mechanism to seamlessly deal with this won't work, so turn off warnings
13284      * during it */
13285     save_start = RExC_start;
13286     orig_end = RExC_end;
13287
13288     RExC_parse = RExC_start = SvPVX(substitute_parse);
13289     RExC_end = RExC_parse + SvCUR(substitute_parse);
13290     TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
13291
13292     *node_p = reg(pRExC_state, 1, &flags, depth+1);
13293
13294     /* Restore the saved values */
13295     RESTORE_WARNINGS;
13296     RExC_start = save_start;
13297     RExC_parse = endbrace;
13298     RExC_end = orig_end;
13299     SET_recode_x_to_native(0);
13300
13301     SvREFCNT_dec_NN(substitute_parse);
13302
13303     if (! *node_p) {
13304         RETURN_FAIL_ON_RESTART(flags, flagp);
13305         FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
13306             (UV) flags);
13307     }
13308     *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13309
13310     nextchar(pRExC_state);
13311
13312     return TRUE;
13313 }
13314
13315
13316 STATIC U8
13317 S_compute_EXACTish(RExC_state_t *pRExC_state)
13318 {
13319     U8 op;
13320
13321     PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
13322
13323     if (! FOLD) {
13324         return (LOC)
13325                 ? EXACTL
13326                 : EXACT;
13327     }
13328
13329     op = get_regex_charset(RExC_flags);
13330     if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
13331         op--; /* /a is same as /u, and map /aa's offset to what /a's would have
13332                  been, so there is no hole */
13333     }
13334
13335     return op + EXACTF;
13336 }
13337
13338 STATIC bool
13339 S_new_regcurly(const char *s, const char *e)
13340 {
13341     /* This is a temporary function designed to match the most lenient form of
13342      * a {m,n} quantifier we ever envision, with either number omitted, and
13343      * spaces anywhere between/before/after them.
13344      *
13345      * If this function fails, then the string it matches is very unlikely to
13346      * ever be considered a valid quantifier, so we can allow the '{' that
13347      * begins it to be considered as a literal */
13348
13349     bool has_min = FALSE;
13350     bool has_max = FALSE;
13351
13352     PERL_ARGS_ASSERT_NEW_REGCURLY;
13353
13354     if (s >= e || *s++ != '{')
13355         return FALSE;
13356
13357     while (s < e && isSPACE(*s)) {
13358         s++;
13359     }
13360     while (s < e && isDIGIT(*s)) {
13361         has_min = TRUE;
13362         s++;
13363     }
13364     while (s < e && isSPACE(*s)) {
13365         s++;
13366     }
13367
13368     if (*s == ',') {
13369         s++;
13370         while (s < e && isSPACE(*s)) {
13371             s++;
13372         }
13373         while (s < e && isDIGIT(*s)) {
13374             has_max = TRUE;
13375             s++;
13376         }
13377         while (s < e && isSPACE(*s)) {
13378             s++;
13379         }
13380     }
13381
13382     return s < e && *s == '}' && (has_min || has_max);
13383 }
13384
13385 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
13386  * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
13387
13388 static I32
13389 S_backref_value(char *p, char *e)
13390 {
13391     const char* endptr = e;
13392     UV val;
13393     if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13394         return (I32)val;
13395     return I32_MAX;
13396 }
13397
13398
13399 /*
13400  - regatom - the lowest level
13401
13402    Try to identify anything special at the start of the current parse position.
13403    If there is, then handle it as required. This may involve generating a
13404    single regop, such as for an assertion; or it may involve recursing, such as
13405    to handle a () structure.
13406
13407    If the string doesn't start with something special then we gobble up
13408    as much literal text as we can.  If we encounter a quantifier, we have to
13409    back off the final literal character, as that quantifier applies to just it
13410    and not to the whole string of literals.
13411
13412    Once we have been able to handle whatever type of thing started the
13413    sequence, we return the offset into the regex engine program being compiled
13414    at which any  next regnode should be placed.
13415
13416    Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13417    Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13418    restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13419    Otherwise does not return 0.
13420
13421    Note: we have to be careful with escapes, as they can be both literal
13422    and special, and in the case of \10 and friends, context determines which.
13423
13424    A summary of the code structure is:
13425
13426    switch (first_byte) {
13427         cases for each special:
13428             handle this special;
13429             break;
13430         case '\\':
13431             switch (2nd byte) {
13432                 cases for each unambiguous special:
13433                     handle this special;
13434                     break;
13435                 cases for each ambigous special/literal:
13436                     disambiguate;
13437                     if (special)  handle here
13438                     else goto defchar;
13439                 default: // unambiguously literal:
13440                     goto defchar;
13441             }
13442         default:  // is a literal char
13443             // FALL THROUGH
13444         defchar:
13445             create EXACTish node for literal;
13446             while (more input and node isn't full) {
13447                 switch (input_byte) {
13448                    cases for each special;
13449                        make sure parse pointer is set so that the next call to
13450                            regatom will see this special first
13451                        goto loopdone; // EXACTish node terminated by prev. char
13452                    default:
13453                        append char to EXACTISH node;
13454                 }
13455                 get next input byte;
13456             }
13457         loopdone:
13458    }
13459    return the generated node;
13460
13461    Specifically there are two separate switches for handling
13462    escape sequences, with the one for handling literal escapes requiring
13463    a dummy entry for all of the special escapes that are actually handled
13464    by the other.
13465
13466 */
13467
13468 STATIC regnode_offset
13469 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13470 {
13471     dVAR;
13472     regnode_offset ret = 0;
13473     I32 flags = 0;
13474     char *parse_start;
13475     U8 op;
13476     int invert = 0;
13477
13478     DECLARE_AND_GET_RE_DEBUG_FLAGS;
13479
13480     *flagp = WORST;             /* Tentatively. */
13481
13482     DEBUG_PARSE("atom");
13483
13484     PERL_ARGS_ASSERT_REGATOM;
13485
13486   tryagain:
13487     parse_start = RExC_parse;
13488     assert(RExC_parse < RExC_end);
13489     switch ((U8)*RExC_parse) {
13490     case '^':
13491         RExC_seen_zerolen++;
13492         nextchar(pRExC_state);
13493         if (RExC_flags & RXf_PMf_MULTILINE)
13494             ret = reg_node(pRExC_state, MBOL);
13495         else
13496             ret = reg_node(pRExC_state, SBOL);
13497         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13498         break;
13499     case '$':
13500         nextchar(pRExC_state);
13501         if (*RExC_parse)
13502             RExC_seen_zerolen++;
13503         if (RExC_flags & RXf_PMf_MULTILINE)
13504             ret = reg_node(pRExC_state, MEOL);
13505         else
13506             ret = reg_node(pRExC_state, SEOL);
13507         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13508         break;
13509     case '.':
13510         nextchar(pRExC_state);
13511         if (RExC_flags & RXf_PMf_SINGLELINE)
13512             ret = reg_node(pRExC_state, SANY);
13513         else
13514             ret = reg_node(pRExC_state, REG_ANY);
13515         *flagp |= HASWIDTH|SIMPLE;
13516         MARK_NAUGHTY(1);
13517         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13518         break;
13519     case '[':
13520     {
13521         char * const oregcomp_parse = ++RExC_parse;
13522         ret = regclass(pRExC_state, flagp, depth+1,
13523                        FALSE, /* means parse the whole char class */
13524                        TRUE, /* allow multi-char folds */
13525                        FALSE, /* don't silence non-portable warnings. */
13526                        (bool) RExC_strict,
13527                        TRUE, /* Allow an optimized regnode result */
13528                        NULL);
13529         if (ret == 0) {
13530             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13531             FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13532                   (UV) *flagp);
13533         }
13534         if (*RExC_parse != ']') {
13535             RExC_parse = oregcomp_parse;
13536             vFAIL("Unmatched [");
13537         }
13538         nextchar(pRExC_state);
13539         Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13540         break;
13541     }
13542     case '(':
13543         nextchar(pRExC_state);
13544         ret = reg(pRExC_state, 2, &flags, depth+1);
13545         if (ret == 0) {
13546                 if (flags & TRYAGAIN) {
13547                     if (RExC_parse >= RExC_end) {
13548                          /* Make parent create an empty node if needed. */
13549                         *flagp |= TRYAGAIN;
13550                         return(0);
13551                     }
13552                     goto tryagain;
13553                 }
13554                 RETURN_FAIL_ON_RESTART(flags, flagp);
13555                 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13556                                                                  (UV) flags);
13557         }
13558         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13559         break;
13560     case '|':
13561     case ')':
13562         if (flags & TRYAGAIN) {
13563             *flagp |= TRYAGAIN;
13564             return 0;
13565         }
13566         vFAIL("Internal urp");
13567                                 /* Supposed to be caught earlier. */
13568         break;
13569     case '?':
13570     case '+':
13571     case '*':
13572         RExC_parse++;
13573         vFAIL("Quantifier follows nothing");
13574         break;
13575     case '\\':
13576         /* Special Escapes
13577
13578            This switch handles escape sequences that resolve to some kind
13579            of special regop and not to literal text. Escape sequences that
13580            resolve to literal text are handled below in the switch marked
13581            "Literal Escapes".
13582
13583            Every entry in this switch *must* have a corresponding entry
13584            in the literal escape switch. However, the opposite is not
13585            required, as the default for this switch is to jump to the
13586            literal text handling code.
13587         */
13588         RExC_parse++;
13589         switch ((U8)*RExC_parse) {
13590         /* Special Escapes */
13591         case 'A':
13592             RExC_seen_zerolen++;
13593             /* Under wildcards, this is changed to match \n; should be
13594              * invisible to the user, as they have to compile under /m */
13595             if (RExC_pm_flags & PMf_WILDCARD) {
13596                 ret = reg_node(pRExC_state, MBOL);
13597             }
13598             else {
13599                 ret = reg_node(pRExC_state, SBOL);
13600                 /* SBOL is shared with /^/ so we set the flags so we can tell
13601                  * /\A/ from /^/ in split. */
13602                 FLAGS(REGNODE_p(ret)) = 1;
13603                 *flagp |= SIMPLE;   /* Wrong, but too late to fix for 5.32 */
13604             }
13605             goto finish_meta_pat;
13606         case 'G':
13607             if (RExC_pm_flags & PMf_WILDCARD) {
13608                 RExC_parse++;
13609                 /* diag_listed_as: Use of %s is not allowed in Unicode property
13610                    wildcard subpatterns in regex; marked by <-- HERE in m/%s/
13611                  */
13612                 vFAIL("Use of '\\G' is not allowed in Unicode property"
13613                       " wildcard subpatterns");
13614             }
13615             ret = reg_node(pRExC_state, GPOS);
13616             RExC_seen |= REG_GPOS_SEEN;
13617             *flagp |= SIMPLE;
13618             goto finish_meta_pat;
13619         case 'K':
13620             if (!RExC_in_lookbehind && !RExC_in_lookahead) {
13621                 RExC_seen_zerolen++;
13622                 ret = reg_node(pRExC_state, KEEPS);
13623                 *flagp |= SIMPLE;
13624                 /* XXX:dmq : disabling in-place substitution seems to
13625                  * be necessary here to avoid cases of memory corruption, as
13626                  * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13627                  */
13628                 RExC_seen |= REG_LOOKBEHIND_SEEN;
13629                 goto finish_meta_pat;
13630             }
13631             else {
13632                 ++RExC_parse; /* advance past the 'K' */
13633                 vFAIL("\\K not permitted in lookahead/lookbehind");
13634             }
13635         case 'Z':
13636             if (RExC_pm_flags & PMf_WILDCARD) {
13637                 /* See comment under \A above */
13638                 ret = reg_node(pRExC_state, MEOL);
13639             }
13640             else {
13641                 ret = reg_node(pRExC_state, SEOL);
13642                 *flagp |= SIMPLE;   /* Wrong, but too late to fix for 5.32 */
13643             }
13644             RExC_seen_zerolen++;                /* Do not optimize RE away */
13645             goto finish_meta_pat;
13646         case 'z':
13647             if (RExC_pm_flags & PMf_WILDCARD) {
13648                 /* See comment under \A above */
13649                 ret = reg_node(pRExC_state, MEOL);
13650             }
13651             else {
13652                 ret = reg_node(pRExC_state, EOS);
13653                 *flagp |= SIMPLE;   /* Wrong, but too late to fix for 5.32 */
13654             }
13655             RExC_seen_zerolen++;                /* Do not optimize RE away */
13656             goto finish_meta_pat;
13657         case 'C':
13658             vFAIL("\\C no longer supported");
13659         case 'X':
13660             ret = reg_node(pRExC_state, CLUMP);
13661             *flagp |= HASWIDTH;
13662             goto finish_meta_pat;
13663
13664         case 'B':
13665             invert = 1;
13666             /* FALLTHROUGH */
13667         case 'b':
13668           {
13669             U8 flags = 0;
13670             regex_charset charset = get_regex_charset(RExC_flags);
13671
13672             RExC_seen_zerolen++;
13673             RExC_seen |= REG_LOOKBEHIND_SEEN;
13674             op = BOUND + charset;
13675
13676             if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13677                 flags = TRADITIONAL_BOUND;
13678                 if (op > BOUNDA) {  /* /aa is same as /a */
13679                     op = BOUNDA;
13680                 }
13681             }
13682             else {
13683                 STRLEN length;
13684                 char name = *RExC_parse;
13685                 char * endbrace = NULL;
13686                 RExC_parse += 2;
13687                 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13688
13689                 if (! endbrace) {
13690                     vFAIL2("Missing right brace on \\%c{}", name);
13691                 }
13692                 /* XXX Need to decide whether to take spaces or not.  Should be
13693                  * consistent with \p{}, but that currently is SPACE, which
13694                  * means vertical too, which seems wrong
13695                  * while (isBLANK(*RExC_parse)) {
13696                     RExC_parse++;
13697                 }*/
13698                 if (endbrace == RExC_parse) {
13699                     RExC_parse++;  /* After the '}' */
13700                     vFAIL2("Empty \\%c{}", name);
13701                 }
13702                 length = endbrace - RExC_parse;
13703                 /*while (isBLANK(*(RExC_parse + length - 1))) {
13704                     length--;
13705                 }*/
13706                 switch (*RExC_parse) {
13707                     case 'g':
13708                         if (    length != 1
13709                             && (memNEs(RExC_parse + 1, length - 1, "cb")))
13710                         {
13711                             goto bad_bound_type;
13712                         }
13713                         flags = GCB_BOUND;
13714                         break;
13715                     case 'l':
13716                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13717                             goto bad_bound_type;
13718                         }
13719                         flags = LB_BOUND;
13720                         break;
13721                     case 's':
13722                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13723                             goto bad_bound_type;
13724                         }
13725                         flags = SB_BOUND;
13726                         break;
13727                     case 'w':
13728                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13729                             goto bad_bound_type;
13730                         }
13731                         flags = WB_BOUND;
13732                         break;
13733                     default:
13734                       bad_bound_type:
13735                         RExC_parse = endbrace;
13736                         vFAIL2utf8f(
13737                             "'%" UTF8f "' is an unknown bound type",
13738                             UTF8fARG(UTF, length, endbrace - length));
13739                         NOT_REACHED; /*NOTREACHED*/
13740                 }
13741                 RExC_parse = endbrace;
13742                 REQUIRE_UNI_RULES(flagp, 0);
13743
13744                 if (op == BOUND) {
13745                     op = BOUNDU;
13746                 }
13747                 else if (op >= BOUNDA) {  /* /aa is same as /a */
13748                     op = BOUNDU;
13749                     length += 4;
13750
13751                     /* Don't have to worry about UTF-8, in this message because
13752                      * to get here the contents of the \b must be ASCII */
13753                     ckWARN4reg(RExC_parse + 1,  /* Include the '}' in msg */
13754                               "Using /u for '%.*s' instead of /%s",
13755                               (unsigned) length,
13756                               endbrace - length + 1,
13757                               (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13758                               ? ASCII_RESTRICT_PAT_MODS
13759                               : ASCII_MORE_RESTRICT_PAT_MODS);
13760                 }
13761             }
13762
13763             if (op == BOUND) {
13764                 RExC_seen_d_op = TRUE;
13765             }
13766             else if (op == BOUNDL) {
13767                 RExC_contains_locale = 1;
13768             }
13769
13770             if (invert) {
13771                 op += NBOUND - BOUND;
13772             }
13773
13774             ret = reg_node(pRExC_state, op);
13775             FLAGS(REGNODE_p(ret)) = flags;
13776
13777             *flagp |= SIMPLE;
13778
13779             goto finish_meta_pat;
13780           }
13781
13782         case 'R':
13783             ret = reg_node(pRExC_state, LNBREAK);
13784             *flagp |= HASWIDTH|SIMPLE;
13785             goto finish_meta_pat;
13786
13787         case 'd':
13788         case 'D':
13789         case 'h':
13790         case 'H':
13791         case 'p':
13792         case 'P':
13793         case 's':
13794         case 'S':
13795         case 'v':
13796         case 'V':
13797         case 'w':
13798         case 'W':
13799             /* These all have the same meaning inside [brackets], and it knows
13800              * how to do the best optimizations for them.  So, pretend we found
13801              * these within brackets, and let it do the work */
13802             RExC_parse--;
13803
13804             ret = regclass(pRExC_state, flagp, depth+1,
13805                            TRUE, /* means just parse this element */
13806                            FALSE, /* don't allow multi-char folds */
13807                            FALSE, /* don't silence non-portable warnings.  It
13808                                      would be a bug if these returned
13809                                      non-portables */
13810                            (bool) RExC_strict,
13811                            TRUE, /* Allow an optimized regnode result */
13812                            NULL);
13813             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13814             /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13815              * multi-char folds are allowed.  */
13816             if (!ret)
13817                 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13818                       (UV) *flagp);
13819
13820             RExC_parse--;   /* regclass() leaves this one too far ahead */
13821
13822           finish_meta_pat:
13823                    /* The escapes above that don't take a parameter can't be
13824                     * followed by a '{'.  But 'pX', 'p{foo}' and
13825                     * correspondingly 'P' can be */
13826             if (   RExC_parse - parse_start == 1
13827                 && UCHARAT(RExC_parse + 1) == '{'
13828                 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13829             {
13830                 RExC_parse += 2;
13831                 vFAIL("Unescaped left brace in regex is illegal here");
13832             }
13833             Set_Node_Offset(REGNODE_p(ret), parse_start);
13834             Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1); /* MJD */
13835             nextchar(pRExC_state);
13836             break;
13837         case 'N':
13838             /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13839              * \N{...} evaluates to a sequence of more than one code points).
13840              * The function call below returns a regnode, which is our result.
13841              * The parameters cause it to fail if the \N{} evaluates to a
13842              * single code point; we handle those like any other literal.  The
13843              * reason that the multicharacter case is handled here and not as
13844              * part of the EXACtish code is because of quantifiers.  In
13845              * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13846              * this way makes that Just Happen. dmq.
13847              * join_exact() will join this up with adjacent EXACTish nodes
13848              * later on, if appropriate. */
13849             ++RExC_parse;
13850             if (grok_bslash_N(pRExC_state,
13851                               &ret,     /* Want a regnode returned */
13852                               NULL,     /* Fail if evaluates to a single code
13853                                            point */
13854                               NULL,     /* Don't need a count of how many code
13855                                            points */
13856                               flagp,
13857                               RExC_strict,
13858                               depth)
13859             ) {
13860                 break;
13861             }
13862
13863             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13864
13865             /* Here, evaluates to a single code point.  Go get that */
13866             RExC_parse = parse_start;
13867             goto defchar;
13868
13869         case 'k':    /* Handle \k<NAME> and \k'NAME' */
13870       parse_named_seq:
13871         {
13872             char ch;
13873             if (   RExC_parse >= RExC_end - 1
13874                 || ((   ch = RExC_parse[1]) != '<'
13875                                       && ch != '\''
13876                                       && ch != '{'))
13877             {
13878                 RExC_parse++;
13879                 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13880                 vFAIL2("Sequence %.2s... not terminated", parse_start);
13881             } else {
13882                 RExC_parse += 2;
13883                 ret = handle_named_backref(pRExC_state,
13884                                            flagp,
13885                                            parse_start,
13886                                            (ch == '<')
13887                                            ? '>'
13888                                            : (ch == '{')
13889                                              ? '}'
13890                                              : '\'');
13891             }
13892             break;
13893         }
13894         case 'g':
13895         case '1': case '2': case '3': case '4':
13896         case '5': case '6': case '7': case '8': case '9':
13897             {
13898                 I32 num;
13899                 bool hasbrace = 0;
13900
13901                 if (*RExC_parse == 'g') {
13902                     bool isrel = 0;
13903
13904                     RExC_parse++;
13905                     if (*RExC_parse == '{') {
13906                         RExC_parse++;
13907                         hasbrace = 1;
13908                     }
13909                     if (*RExC_parse == '-') {
13910                         RExC_parse++;
13911                         isrel = 1;
13912                     }
13913                     if (hasbrace && !isDIGIT(*RExC_parse)) {
13914                         if (isrel) RExC_parse--;
13915                         RExC_parse -= 2;
13916                         goto parse_named_seq;
13917                     }
13918
13919                     if (RExC_parse >= RExC_end) {
13920                         goto unterminated_g;
13921                     }
13922                     num = S_backref_value(RExC_parse, RExC_end);
13923                     if (num == 0)
13924                         vFAIL("Reference to invalid group 0");
13925                     else if (num == I32_MAX) {
13926                          if (isDIGIT(*RExC_parse))
13927                             vFAIL("Reference to nonexistent group");
13928                         else
13929                           unterminated_g:
13930                             vFAIL("Unterminated \\g... pattern");
13931                     }
13932
13933                     if (isrel) {
13934                         num = RExC_npar - num;
13935                         if (num < 1)
13936                             vFAIL("Reference to nonexistent or unclosed group");
13937                     }
13938                 }
13939                 else {
13940                     num = S_backref_value(RExC_parse, RExC_end);
13941                     /* bare \NNN might be backref or octal - if it is larger
13942                      * than or equal RExC_npar then it is assumed to be an
13943                      * octal escape. Note RExC_npar is +1 from the actual
13944                      * number of parens. */
13945                     /* Note we do NOT check if num == I32_MAX here, as that is
13946                      * handled by the RExC_npar check */
13947
13948                     if (
13949                         /* any numeric escape < 10 is always a backref */
13950                         num > 9
13951                         /* any numeric escape < RExC_npar is a backref */
13952                         && num >= RExC_npar
13953                         /* cannot be an octal escape if it starts with 8 */
13954                         && *RExC_parse != '8'
13955                         /* cannot be an octal escape if it starts with 9 */
13956                         && *RExC_parse != '9'
13957                     ) {
13958                         /* Probably not meant to be a backref, instead likely
13959                          * to be an octal character escape, e.g. \35 or \777.
13960                          * The above logic should make it obvious why using
13961                          * octal escapes in patterns is problematic. - Yves */
13962                         RExC_parse = parse_start;
13963                         goto defchar;
13964                     }
13965                 }
13966
13967                 /* At this point RExC_parse points at a numeric escape like
13968                  * \12 or \88 or something similar, which we should NOT treat
13969                  * as an octal escape. It may or may not be a valid backref
13970                  * escape. For instance \88888888 is unlikely to be a valid
13971                  * backref. */
13972                 while (isDIGIT(*RExC_parse))
13973                     RExC_parse++;
13974                 if (hasbrace) {
13975                     if (*RExC_parse != '}')
13976                         vFAIL("Unterminated \\g{...} pattern");
13977                     RExC_parse++;
13978                 }
13979                 if (num >= (I32)RExC_npar) {
13980
13981                     /* It might be a forward reference; we can't fail until we
13982                      * know, by completing the parse to get all the groups, and
13983                      * then reparsing */
13984                     if (ALL_PARENS_COUNTED)  {
13985                         if (num >= RExC_total_parens)  {
13986                             vFAIL("Reference to nonexistent group");
13987                         }
13988                     }
13989                     else {
13990                         REQUIRE_PARENS_PASS;
13991                     }
13992                 }
13993                 RExC_sawback = 1;
13994                 ret = reganode(pRExC_state,
13995                                ((! FOLD)
13996                                  ? REF
13997                                  : (ASCII_FOLD_RESTRICTED)
13998                                    ? REFFA
13999                                    : (AT_LEAST_UNI_SEMANTICS)
14000                                      ? REFFU
14001                                      : (LOC)
14002                                        ? REFFL
14003                                        : REFF),
14004                                 num);
14005                 if (OP(REGNODE_p(ret)) == REFF) {
14006                     RExC_seen_d_op = TRUE;
14007                 }
14008                 *flagp |= HASWIDTH;
14009
14010                 /* override incorrect value set in reganode MJD */
14011                 Set_Node_Offset(REGNODE_p(ret), parse_start);
14012                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
14013                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14014                                         FALSE /* Don't force to /x */ );
14015             }
14016             break;
14017         case '\0':
14018             if (RExC_parse >= RExC_end)
14019                 FAIL("Trailing \\");
14020             /* FALLTHROUGH */
14021         default:
14022             /* Do not generate "unrecognized" warnings here, we fall
14023                back into the quick-grab loop below */
14024             RExC_parse = parse_start;
14025             goto defchar;
14026         } /* end of switch on a \foo sequence */
14027         break;
14028
14029     case '#':
14030
14031         /* '#' comments should have been spaced over before this function was
14032          * called */
14033         assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
14034         /*
14035         if (RExC_flags & RXf_PMf_EXTENDED) {
14036             RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
14037             if (RExC_parse < RExC_end)
14038                 goto tryagain;
14039         }
14040         */
14041
14042         /* FALLTHROUGH */
14043
14044     default:
14045           defchar: {
14046
14047             /* Here, we have determined that the next thing is probably a
14048              * literal character.  RExC_parse points to the first byte of its
14049              * definition.  (It still may be an escape sequence that evaluates
14050              * to a single character) */
14051
14052             STRLEN len = 0;
14053             UV ender = 0;
14054             char *p;
14055             char *s, *old_s = NULL, *old_old_s = NULL;
14056             char *s0;
14057             U32 max_string_len = 255;
14058
14059             /* We may have to reparse the node, artificially stopping filling
14060              * it early, based on info gleaned in the first parse.  This
14061              * variable gives where we stop.  Make it above the normal stopping
14062              * place first time through; otherwise it would stop too early */
14063             U32 upper_fill = max_string_len + 1;
14064
14065             /* We start out as an EXACT node, even if under /i, until we find a
14066              * character which is in a fold.  The algorithm now segregates into
14067              * separate nodes, characters that fold from those that don't under
14068              * /i.  (This hopefully will create nodes that are fixed strings
14069              * even under /i, giving the optimizer something to grab on to.)
14070              * So, if a node has something in it and the next character is in
14071              * the opposite category, that node is closed up, and the function
14072              * returns.  Then regatom is called again, and a new node is
14073              * created for the new category. */
14074             U8 node_type = EXACT;
14075
14076             /* Assume the node will be fully used; the excess is given back at
14077              * the end.  Under /i, we may need to temporarily add the fold of
14078              * an extra character or two at the end to check for splitting
14079              * multi-char folds, so allocate extra space for that.   We can't
14080              * make any other length assumptions, as a byte input sequence
14081              * could shrink down. */
14082             Ptrdiff_t current_string_nodes = STR_SZ(max_string_len
14083                                                  + ((! FOLD)
14084                                                     ? 0
14085                                                     : 2 * ((UTF)
14086                                                            ? UTF8_MAXBYTES_CASE
14087                         /* Max non-UTF-8 expansion is 2 */ : 2)));
14088
14089             bool next_is_quantifier;
14090             char * oldp = NULL;
14091
14092             /* We can convert EXACTF nodes to EXACTFU if they contain only
14093              * characters that match identically regardless of the target
14094              * string's UTF8ness.  The reason to do this is that EXACTF is not
14095              * trie-able, EXACTFU is, and EXACTFU requires fewer operations at
14096              * runtime.
14097              *
14098              * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
14099              * contain only above-Latin1 characters (hence must be in UTF8),
14100              * which don't participate in folds with Latin1-range characters,
14101              * as the latter's folds aren't known until runtime. */
14102             bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
14103
14104             /* Single-character EXACTish nodes are almost always SIMPLE.  This
14105              * allows us to override this as encountered */
14106             U8 maybe_SIMPLE = SIMPLE;
14107
14108             /* Does this node contain something that can't match unless the
14109              * target string is (also) in UTF-8 */
14110             bool requires_utf8_target = FALSE;
14111
14112             /* The sequence 'ss' is problematic in non-UTF-8 patterns. */
14113             bool has_ss = FALSE;
14114
14115             /* So is the MICRO SIGN */
14116             bool has_micro_sign = FALSE;
14117
14118             /* Set when we fill up the current node and there is still more
14119              * text to process */
14120             bool overflowed;
14121
14122             /* Allocate an EXACT node.  The node_type may change below to
14123              * another EXACTish node, but since the size of the node doesn't
14124              * change, it works */
14125             ret = regnode_guts(pRExC_state, node_type, current_string_nodes,
14126                                                                     "exact");
14127             FILL_NODE(ret, node_type);
14128             RExC_emit++;
14129
14130             s = STRING(REGNODE_p(ret));
14131
14132             s0 = s;
14133
14134           reparse:
14135
14136             p = RExC_parse;
14137             len = 0;
14138             s = s0;
14139             node_type = EXACT;
14140             oldp = NULL;
14141             maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
14142             maybe_SIMPLE = SIMPLE;
14143             requires_utf8_target = FALSE;
14144             has_ss = FALSE;
14145             has_micro_sign = FALSE;
14146
14147           continue_parse:
14148
14149             /* This breaks under rare circumstances.  If folding, we do not
14150              * want to split a node at a character that is a non-final in a
14151              * multi-char fold, as an input string could just happen to want to
14152              * match across the node boundary.  The code at the end of the loop
14153              * looks for this, and backs off until it finds not such a
14154              * character, but it is possible (though extremely, extremely
14155              * unlikely) for all characters in the node to be non-final fold
14156              * ones, in which case we just leave the node fully filled, and
14157              * hope that it doesn't match the string in just the wrong place */
14158
14159             assert( ! UTF     /* Is at the beginning of a character */
14160                    || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
14161                    || UTF8_IS_START(UCHARAT(RExC_parse)));
14162
14163             overflowed = FALSE;
14164
14165             /* Here, we have a literal character.  Find the maximal string of
14166              * them in the input that we can fit into a single EXACTish node.
14167              * We quit at the first non-literal or when the node gets full, or
14168              * under /i the categorization of folding/non-folding character
14169              * changes */
14170             while (p < RExC_end && len < upper_fill) {
14171
14172                 /* In most cases each iteration adds one byte to the output.
14173                  * The exceptions override this */
14174                 Size_t added_len = 1;
14175
14176                 oldp = p;
14177                 old_old_s = old_s;
14178                 old_s = s;
14179
14180                 /* White space has already been ignored */
14181                 assert(   (RExC_flags & RXf_PMf_EXTENDED) == 0
14182                        || ! is_PATWS_safe((p), RExC_end, UTF));
14183
14184                 switch ((U8)*p) {
14185                   const char* message;
14186                   U32 packed_warn;
14187                   U8 grok_c_char;
14188
14189                 case '^':
14190                 case '$':
14191                 case '.':
14192                 case '[':
14193                 case '(':
14194                 case ')':
14195                 case '|':
14196                     goto loopdone;
14197                 case '\\':
14198                     /* Literal Escapes Switch
14199
14200                        This switch is meant to handle escape sequences that
14201                        resolve to a literal character.
14202
14203                        Every escape sequence that represents something
14204                        else, like an assertion or a char class, is handled
14205                        in the switch marked 'Special Escapes' above in this
14206                        routine, but also has an entry here as anything that
14207                        isn't explicitly mentioned here will be treated as
14208                        an unescaped equivalent literal.
14209                     */
14210
14211                     switch ((U8)*++p) {
14212
14213                     /* These are all the special escapes. */
14214                     case 'A':             /* Start assertion */
14215                     case 'b': case 'B':   /* Word-boundary assertion*/
14216                     case 'C':             /* Single char !DANGEROUS! */
14217                     case 'd': case 'D':   /* digit class */
14218                     case 'g': case 'G':   /* generic-backref, pos assertion */
14219                     case 'h': case 'H':   /* HORIZWS */
14220                     case 'k': case 'K':   /* named backref, keep marker */
14221                     case 'p': case 'P':   /* Unicode property */
14222                               case 'R':   /* LNBREAK */
14223                     case 's': case 'S':   /* space class */
14224                     case 'v': case 'V':   /* VERTWS */
14225                     case 'w': case 'W':   /* word class */
14226                     case 'X':             /* eXtended Unicode "combining
14227                                              character sequence" */
14228                     case 'z': case 'Z':   /* End of line/string assertion */
14229                         --p;
14230                         goto loopdone;
14231
14232                     /* Anything after here is an escape that resolves to a
14233                        literal. (Except digits, which may or may not)
14234                      */
14235                     case 'n':
14236                         ender = '\n';
14237                         p++;
14238                         break;
14239                     case 'N': /* Handle a single-code point named character. */
14240                         RExC_parse = p + 1;
14241                         if (! grok_bslash_N(pRExC_state,
14242                                             NULL,   /* Fail if evaluates to
14243                                                        anything other than a
14244                                                        single code point */
14245                                             &ender, /* The returned single code
14246                                                        point */
14247                                             NULL,   /* Don't need a count of
14248                                                        how many code points */
14249                                             flagp,
14250                                             RExC_strict,
14251                                             depth)
14252                         ) {
14253                             if (*flagp & NEED_UTF8)
14254                                 FAIL("panic: grok_bslash_N set NEED_UTF8");
14255                             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
14256
14257                             /* Here, it wasn't a single code point.  Go close
14258                              * up this EXACTish node.  The switch() prior to
14259                              * this switch handles the other cases */
14260                             RExC_parse = p = oldp;
14261                             goto loopdone;
14262                         }
14263                         p = RExC_parse;
14264                         RExC_parse = parse_start;
14265
14266                         /* The \N{} means the pattern, if previously /d,
14267                          * becomes /u.  That means it can't be an EXACTF node,
14268                          * but an EXACTFU */
14269                         if (node_type == EXACTF) {
14270                             node_type = EXACTFU;
14271
14272                             /* If the node already contains something that
14273                              * differs between EXACTF and EXACTFU, reparse it
14274                              * as EXACTFU */
14275                             if (! maybe_exactfu) {
14276                                 len = 0;
14277                                 s = s0;
14278                                 goto reparse;
14279                             }
14280                         }
14281
14282                         break;
14283                     case 'r':
14284                         ender = '\r';
14285                         p++;
14286                         break;
14287                     case 't':
14288                         ender = '\t';
14289                         p++;
14290                         break;
14291                     case 'f':
14292                         ender = '\f';
14293                         p++;
14294                         break;
14295                     case 'e':
14296                         ender = ESC_NATIVE;
14297                         p++;
14298                         break;
14299                     case 'a':
14300                         ender = '\a';
14301                         p++;
14302                         break;
14303                     case 'o':
14304                         if (! grok_bslash_o(&p,
14305                                             RExC_end,
14306                                             &ender,
14307                                             &message,
14308                                             &packed_warn,
14309                                             (bool) RExC_strict,
14310                                             FALSE, /* No illegal cp's */
14311                                             UTF))
14312                         {
14313                             RExC_parse = p; /* going to die anyway; point to
14314                                                exact spot of failure */
14315                             vFAIL(message);
14316                         }
14317
14318                         if (message && TO_OUTPUT_WARNINGS(p)) {
14319                             warn_non_literal_string(p, packed_warn, message);
14320                         }
14321                         break;
14322                     case 'x':
14323                         if (! grok_bslash_x(&p,
14324                                             RExC_end,
14325                                             &ender,
14326                                             &message,
14327                                             &packed_warn,
14328                                             (bool) RExC_strict,
14329                                             FALSE, /* No illegal cp's */
14330                                             UTF))
14331                         {
14332                             RExC_parse = p;     /* going to die anyway; point
14333                                                    to exact spot of failure */
14334                             vFAIL(message);
14335                         }
14336
14337                         if (message && TO_OUTPUT_WARNINGS(p)) {
14338                             warn_non_literal_string(p, packed_warn, message);
14339                         }
14340
14341 #ifdef EBCDIC
14342                         if (ender < 0x100) {
14343                             if (RExC_recode_x_to_native) {
14344                                 ender = LATIN1_TO_NATIVE(ender);
14345                             }
14346                         }
14347 #endif
14348                         break;
14349                     case 'c':
14350                         p++;
14351                         if (! grok_bslash_c(*p, &grok_c_char,
14352                                             &message, &packed_warn))
14353                         {
14354                             /* going to die anyway; point to exact spot of
14355                              * failure */
14356                             RExC_parse = p + ((UTF)
14357                                               ? UTF8_SAFE_SKIP(p, RExC_end)
14358                                               : 1);
14359                             vFAIL(message);
14360                         }
14361
14362                         ender = grok_c_char;
14363                         p++;
14364                         if (message && TO_OUTPUT_WARNINGS(p)) {
14365                             warn_non_literal_string(p, packed_warn, message);
14366                         }
14367
14368                         break;
14369                     case '8': case '9': /* must be a backreference */
14370                         --p;
14371                         /* we have an escape like \8 which cannot be an octal escape
14372                          * so we exit the loop, and let the outer loop handle this
14373                          * escape which may or may not be a legitimate backref. */
14374                         goto loopdone;
14375                     case '1': case '2': case '3':case '4':
14376                     case '5': case '6': case '7':
14377                         /* When we parse backslash escapes there is ambiguity
14378                          * between backreferences and octal escapes. Any escape
14379                          * from \1 - \9 is a backreference, any multi-digit
14380                          * escape which does not start with 0 and which when
14381                          * evaluated as decimal could refer to an already
14382                          * parsed capture buffer is a back reference. Anything
14383                          * else is octal.
14384                          *
14385                          * Note this implies that \118 could be interpreted as
14386                          * 118 OR as "\11" . "8" depending on whether there
14387                          * were 118 capture buffers defined already in the
14388                          * pattern.  */
14389
14390                         /* NOTE, RExC_npar is 1 more than the actual number of
14391                          * parens we have seen so far, hence the "<" as opposed
14392                          * to "<=" */
14393                         if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
14394                         {  /* Not to be treated as an octal constant, go
14395                                    find backref */
14396                             --p;
14397                             goto loopdone;
14398                         }
14399                         /* FALLTHROUGH */
14400                     case '0':
14401                         {
14402                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT
14403                                       | PERL_SCAN_NOTIFY_ILLDIGIT;
14404                             STRLEN numlen = 3;
14405                             ender = grok_oct(p, &numlen, &flags, NULL);
14406                             p += numlen;
14407                             if (  (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
14408                                 && isDIGIT(*p)  /* like \08, \178 */
14409                                 && ckWARN(WARN_REGEXP))
14410                             {
14411                                 reg_warn_non_literal_string(
14412                                      p + 1,
14413                                      form_alien_digit_msg(8, numlen, p,
14414                                                         RExC_end, UTF, FALSE));
14415                             }
14416                         }
14417                         break;
14418                     case '\0':
14419                         if (p >= RExC_end)
14420                             FAIL("Trailing \\");
14421                         /* FALLTHROUGH */
14422                     default:
14423                         if (isALPHANUMERIC(*p)) {
14424                             /* An alpha followed by '{' is going to fail next
14425                              * iteration, so don't output this warning in that
14426                              * case */
14427                             if (! isALPHA(*p) || *(p + 1) != '{') {
14428                                 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14429                                                   " passed through", p);
14430                             }
14431                         }
14432                         goto normal_default;
14433                     } /* End of switch on '\' */
14434                     break;
14435                 case '{':
14436                     /* Trying to gain new uses for '{' without breaking too
14437                      * much existing code is hard.  The solution currently
14438                      * adopted is:
14439                      *  1)  If there is no ambiguity that a '{' should always
14440                      *      be taken literally, at the start of a construct, we
14441                      *      just do so.
14442                      *  2)  If the literal '{' conflicts with our desired use
14443                      *      of it as a metacharacter, we die.  The deprecation
14444                      *      cycles for this have come and gone.
14445                      *  3)  If there is ambiguity, we raise a simple warning.
14446                      *      This could happen, for example, if the user
14447                      *      intended it to introduce a quantifier, but slightly
14448                      *      misspelled the quantifier.  Without this warning,
14449                      *      the quantifier would silently be taken as a literal
14450                      *      string of characters instead of a meta construct */
14451                     if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14452                         if (      RExC_strict
14453                             || (  p > parse_start + 1
14454                                 && isALPHA_A(*(p - 1))
14455                                 && *(p - 2) == '\\')
14456                             || new_regcurly(p, RExC_end))
14457                         {
14458                             RExC_parse = p + 1;
14459                             vFAIL("Unescaped left brace in regex is "
14460                                   "illegal here");
14461                         }
14462                         ckWARNreg(p + 1, "Unescaped left brace in regex is"
14463                                          " passed through");
14464                     }
14465                     goto normal_default;
14466                 case '}':
14467                 case ']':
14468                     if (p > RExC_parse && RExC_strict) {
14469                         ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14470                     }
14471                     /*FALLTHROUGH*/
14472                 default:    /* A literal character */
14473                   normal_default:
14474                     if (! UTF8_IS_INVARIANT(*p) && UTF) {
14475                         STRLEN numlen;
14476                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14477                                                &numlen, UTF8_ALLOW_DEFAULT);
14478                         p += numlen;
14479                     }
14480                     else
14481                         ender = (U8) *p++;
14482                     break;
14483                 } /* End of switch on the literal */
14484
14485                 /* Here, have looked at the literal character, and <ender>
14486                  * contains its ordinal; <p> points to the character after it.
14487                  * */
14488
14489                 if (ender > 255) {
14490                     REQUIRE_UTF8(flagp);
14491                     if (   UNICODE_IS_PERL_EXTENDED(ender)
14492                         && TO_OUTPUT_WARNINGS(p))
14493                     {
14494                         ckWARN2_non_literal_string(p,
14495                                                    packWARN(WARN_PORTABLE),
14496                                                    PL_extended_cp_format,
14497                                                    ender);
14498                     }
14499                 }
14500
14501                 /* We need to check if the next non-ignored thing is a
14502                  * quantifier.  Move <p> to after anything that should be
14503                  * ignored, which, as a side effect, positions <p> for the next
14504                  * loop iteration */
14505                 skip_to_be_ignored_text(pRExC_state, &p,
14506                                         FALSE /* Don't force to /x */ );
14507
14508                 /* If the next thing is a quantifier, it applies to this
14509                  * character only, which means that this character has to be in
14510                  * its own node and can't just be appended to the string in an
14511                  * existing node, so if there are already other characters in
14512                  * the node, close the node with just them, and set up to do
14513                  * this character again next time through, when it will be the
14514                  * only thing in its new node */
14515
14516                 next_is_quantifier =    LIKELY(p < RExC_end)
14517                                      && UNLIKELY(ISMULT2(p));
14518
14519                 if (next_is_quantifier && LIKELY(len)) {
14520                     p = oldp;
14521                     goto loopdone;
14522                 }
14523
14524                 /* Ready to add 'ender' to the node */
14525
14526                 if (! FOLD) {  /* The simple case, just append the literal */
14527                   not_fold_common:
14528
14529                     /* Don't output if it would overflow */
14530                     if (UNLIKELY(len > max_string_len - ((UTF)
14531                                                       ? UVCHR_SKIP(ender)
14532                                                       : 1)))
14533                     {
14534                         overflowed = TRUE;
14535                         break;
14536                     }
14537
14538                     if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14539                         *(s++) = (char) ender;
14540                     }
14541                     else {
14542                         U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14543                         added_len = (char *) new_s - s;
14544                         s = (char *) new_s;
14545
14546                         if (ender > 255)  {
14547                             requires_utf8_target = TRUE;
14548                         }
14549                     }
14550                 }
14551                 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14552
14553                     /* Here are folding under /l, and the code point is
14554                      * problematic.  If this is the first character in the
14555                      * node, change the node type to folding.   Otherwise, if
14556                      * this is the first problematic character, close up the
14557                      * existing node, so can start a new node with this one */
14558                     if (! len) {
14559                         node_type = EXACTFL;
14560                         RExC_contains_locale = 1;
14561                     }
14562                     else if (node_type == EXACT) {
14563                         p = oldp;
14564                         goto loopdone;
14565                     }
14566
14567                     /* This problematic code point means we can't simplify
14568                      * things */
14569                     maybe_exactfu = FALSE;
14570
14571                     /* Here, we are adding a problematic fold character.
14572                      * "Problematic" in this context means that its fold isn't
14573                      * known until runtime.  (The non-problematic code points
14574                      * are the above-Latin1 ones that fold to also all
14575                      * above-Latin1.  Their folds don't vary no matter what the
14576                      * locale is.) But here we have characters whose fold
14577                      * depends on the locale.  We just add in the unfolded
14578                      * character, and wait until runtime to fold it */
14579                     goto not_fold_common;
14580                 }
14581                 else /* regular fold; see if actually is in a fold */
14582                      if (   (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14583                          || (ender > 255
14584                             && ! _invlist_contains_cp(PL_in_some_fold, ender)))
14585                 {
14586                     /* Here, folding, but the character isn't in a fold.
14587                      *
14588                      * Start a new node if previous characters in the node were
14589                      * folded */
14590                     if (len && node_type != EXACT) {
14591                         p = oldp;
14592                         goto loopdone;
14593                     }
14594
14595                     /* Here, continuing a node with non-folded characters.  Add
14596                      * this one */
14597                     goto not_fold_common;
14598                 }
14599                 else {  /* Here, does participate in some fold */
14600
14601                     /* If this is the first character in the node, change its
14602                      * type to folding.  Otherwise, if this is the first
14603                      * folding character in the node, close up the existing
14604                      * node, so can start a new node with this one.  */
14605                     if (! len) {
14606                         node_type = compute_EXACTish(pRExC_state);
14607                     }
14608                     else if (node_type == EXACT) {
14609                         p = oldp;
14610                         goto loopdone;
14611                     }
14612
14613                     if (UTF) {  /* Alway use the folded value for UTF-8
14614                                    patterns */
14615                         if (UVCHR_IS_INVARIANT(ender)) {
14616                             if (UNLIKELY(len + 1 > max_string_len)) {
14617                                 overflowed = TRUE;
14618                                 break;
14619                             }
14620
14621                             *(s)++ = (U8) toFOLD(ender);
14622                         }
14623                         else {
14624                             UV folded = _to_uni_fold_flags(
14625                                     ender,
14626                                     (U8 *) s,  /* We have allocated extra space
14627                                                   in 's' so can't run off the
14628                                                   end */
14629                                     &added_len,
14630                                     FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14631                                                     ? FOLD_FLAGS_NOMIX_ASCII
14632                                                     : 0));
14633                             if (UNLIKELY(len + added_len > max_string_len)) {
14634                                 overflowed = TRUE;
14635                                 break;
14636                             }
14637
14638                             s += added_len;
14639
14640                             if (   folded > 255
14641                                 && LIKELY(folded != GREEK_SMALL_LETTER_MU))
14642                             {
14643                                 /* U+B5 folds to the MU, so its possible for a
14644                                  * non-UTF-8 target to match it */
14645                                 requires_utf8_target = TRUE;
14646                             }
14647                         }
14648                     }
14649                     else { /* Here is non-UTF8. */
14650
14651                         /* The fold will be one or (rarely) two characters.
14652                          * Check that there's room for at least a single one
14653                          * before setting any flags, etc.  Because otherwise an
14654                          * overflowing character could cause a flag to be set
14655                          * even though it doesn't end up in this node.  (For
14656                          * the two character fold, we check again, before
14657                          * setting any flags) */
14658                         if (UNLIKELY(len + 1 > max_string_len)) {
14659                             overflowed = TRUE;
14660                             break;
14661                         }
14662
14663 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
14664    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
14665                                       || UNICODE_DOT_DOT_VERSION > 0)
14666
14667                         /* On non-ancient Unicodes, check for the only possible
14668                          * multi-char fold  */
14669                         if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14670
14671                             /* This potential multi-char fold means the node
14672                              * can't be simple (because it could match more
14673                              * than a single char).  And in some cases it will
14674                              * match 'ss', so set that flag */
14675                             maybe_SIMPLE = 0;
14676                             has_ss = TRUE;
14677
14678                             /* It can't change to be an EXACTFU (unless already
14679                              * is one).  We fold it iff under /u rules. */
14680                             if (node_type != EXACTFU) {
14681                                 maybe_exactfu = FALSE;
14682                             }
14683                             else {
14684                                 if (UNLIKELY(len + 2 > max_string_len)) {
14685                                     overflowed = TRUE;
14686                                     break;
14687                                 }
14688
14689                                 *(s++) = 's';
14690                                 *(s++) = 's';
14691                                 added_len = 2;
14692
14693                                 goto done_with_this_char;
14694                             }
14695                         }
14696                         else if (   UNLIKELY(isALPHA_FOLD_EQ(ender, 's'))
14697                                  && LIKELY(len > 0)
14698                                  && UNLIKELY(isALPHA_FOLD_EQ(*(s-1), 's')))
14699                         {
14700                             /* Also, the sequence 'ss' is special when not
14701                              * under /u.  If the target string is UTF-8, it
14702                              * should match SHARP S; otherwise it won't.  So,
14703                              * here we have to exclude the possibility of this
14704                              * node moving to /u.*/
14705                             has_ss = TRUE;
14706                             maybe_exactfu = FALSE;
14707                         }
14708 #endif
14709                         /* Here, the fold will be a single character */
14710
14711                         if (UNLIKELY(ender == MICRO_SIGN)) {
14712                             has_micro_sign = TRUE;
14713                         }
14714                         else if (PL_fold[ender] != PL_fold_latin1[ender]) {
14715
14716                             /* If the character's fold differs between /d and
14717                              * /u, this can't change to be an EXACTFU node */
14718                             maybe_exactfu = FALSE;
14719                         }
14720
14721                         *(s++) = (DEPENDS_SEMANTICS)
14722                                  ? (char) toFOLD(ender)
14723
14724                                    /* Under /u, the fold of any character in
14725                                     * the 0-255 range happens to be its
14726                                     * lowercase equivalent, except for LATIN
14727                                     * SMALL LETTER SHARP S, which was handled
14728                                     * above, and the MICRO SIGN, whose fold
14729                                     * requires UTF-8 to represent.  */
14730                                  : (char) toLOWER_L1(ender);
14731                     }
14732                 } /* End of adding current character to the node */
14733
14734               done_with_this_char:
14735
14736                 len += added_len;
14737
14738                 if (next_is_quantifier) {
14739
14740                     /* Here, the next input is a quantifier, and to get here,
14741                      * the current character is the only one in the node. */
14742                     goto loopdone;
14743                 }
14744
14745             } /* End of loop through literal characters */
14746
14747             /* Here we have either exhausted the input or run out of room in
14748              * the node.  If the former, we are done.  (If we encountered a
14749              * character that can't be in the node, transfer is made directly
14750              * to <loopdone>, and so we wouldn't have fallen off the end of the
14751              * loop.)  */
14752             if (LIKELY(! overflowed)) {
14753                 goto loopdone;
14754             }
14755
14756             /* Here we have run out of room.  We can grow plain EXACT and
14757              * LEXACT nodes.  If the pattern is gigantic enough, though,
14758              * eventually we'll have to artificially chunk the pattern into
14759              * multiple nodes. */
14760             if (! LOC && (node_type == EXACT || node_type == LEXACT)) {
14761                 Size_t overhead = 1 + regarglen[OP(REGNODE_p(ret))];
14762                 Size_t overhead_expansion = 0;
14763                 char temp[256];
14764                 Size_t max_nodes_for_string;
14765                 Size_t achievable;
14766                 SSize_t delta;
14767
14768                 /* Here we couldn't fit the final character in the current
14769                  * node, so it will have to be reparsed, no matter what else we
14770                  * do */
14771                 p = oldp;
14772
14773                 /* If would have overflowed a regular EXACT node, switch
14774                  * instead to an LEXACT.  The code below is structured so that
14775                  * the actual growing code is common to changing from an EXACT
14776                  * or just increasing the LEXACT size.  This means that we have
14777                  * to save the string in the EXACT case before growing, and
14778                  * then copy it afterwards to its new location */
14779                 if (node_type == EXACT) {
14780                     overhead_expansion = regarglen[LEXACT] - regarglen[EXACT];
14781                     RExC_emit += overhead_expansion;
14782                     Copy(s0, temp, len, char);
14783                 }
14784
14785                 /* Ready to grow.  If it was a plain EXACT, the string was
14786                  * saved, and the first few bytes of it overwritten by adding
14787                  * an argument field.  We assume, as we do elsewhere in this
14788                  * file, that one byte of remaining input will translate into
14789                  * one byte of output, and if that's too small, we grow again,
14790                  * if too large the excess memory is freed at the end */
14791
14792                 max_nodes_for_string = U16_MAX - overhead - overhead_expansion;
14793                 achievable = MIN(max_nodes_for_string,
14794                                  current_string_nodes + STR_SZ(RExC_end - p));
14795                 delta = achievable - current_string_nodes;
14796
14797                 /* If there is just no more room, go finish up this chunk of
14798                  * the pattern. */
14799                 if (delta <= 0) {
14800                     goto loopdone;
14801                 }
14802
14803                 change_engine_size(pRExC_state, delta + overhead_expansion);
14804                 current_string_nodes += delta;
14805                 max_string_len
14806                            = sizeof(struct regnode) * current_string_nodes;
14807                 upper_fill = max_string_len + 1;
14808
14809                 /* If the length was small, we know this was originally an
14810                  * EXACT node now converted to LEXACT, and the string has to be
14811                  * restored.  Otherwise the string was untouched.  260 is just
14812                  * a number safely above 255 so don't have to worry about
14813                  * getting it precise */
14814                 if (len < 260) {
14815                     node_type = LEXACT;
14816                     FILL_NODE(ret, node_type);
14817                     s0 = STRING(REGNODE_p(ret));
14818                     Copy(temp, s0, len, char);
14819                     s = s0 + len;
14820                 }
14821
14822                 goto continue_parse;
14823             }
14824             else if (FOLD) {
14825                 bool splittable = FALSE;
14826                 bool backed_up = FALSE;
14827                 char * e;       /* should this be U8? */
14828                 char * s_start; /* should this be U8? */
14829
14830                 /* Here is /i.  Running out of room creates a problem if we are
14831                  * folding, and the split happens in the middle of a
14832                  * multi-character fold, as a match that should have occurred,
14833                  * won't, due to the way nodes are matched, and our artificial
14834                  * boundary.  So back off until we aren't splitting such a
14835                  * fold.  If there is no such place to back off to, we end up
14836                  * taking the entire node as-is.  This can happen if the node
14837                  * consists entirely of 'f' or entirely of 's' characters (or
14838                  * things that fold to them) as 'ff' and 'ss' are
14839                  * multi-character folds.
14840                  *
14841                  * The Unicode standard says that multi character folds consist
14842                  * of either two or three characters.  That means we would be
14843                  * splitting one if the final character in the node is at the
14844                  * beginning of either type, or is the second of a three
14845                  * character fold.
14846                  *
14847                  * At this point:
14848                  *  ender     is the code point of the character that won't fit
14849                  *            in the node
14850                  *  s         points to just beyond the final byte in the node.
14851                  *            It's where we would place ender if there were
14852                  *            room, and where in fact we do place ender's fold
14853                  *            in the code below, as we've over-allocated space
14854                  *            for s0 (hence s) to allow for this
14855                  *  e         starts at 's' and advances as we append things.
14856                  *  old_s     is the same as 's'.  (If ender had fit, 's' would
14857                  *            have been advanced to beyond it).
14858                  *  old_old_s points to the beginning byte of the final
14859                  *            character in the node
14860                  *  p         points to the beginning byte in the input of the
14861                  *            character beyond 'ender'.
14862                  *  oldp      points to the beginning byte in the input of
14863                  *            'ender'.
14864                  *
14865                  * In the case of /il, we haven't folded anything that could be
14866                  * affected by the locale.  That means only above-Latin1
14867                  * characters that fold to other above-latin1 characters get
14868                  * folded at compile time.  To check where a good place to
14869                  * split nodes is, everything in it will have to be folded.
14870                  * The boolean 'maybe_exactfu' keeps track in /il if there are
14871                  * any unfolded characters in the node. */
14872                 bool need_to_fold_loc = LOC && ! maybe_exactfu;
14873
14874                 /* If we do need to fold the node, we need a place to store the
14875                  * folded copy, and a way to map back to the unfolded original
14876                  * */
14877                 char * locfold_buf = NULL;
14878                 Size_t * loc_correspondence = NULL;
14879
14880                 if (! need_to_fold_loc) {   /* The normal case.  Just
14881                                                initialize to the actual node */
14882                     e = s;
14883                     s_start = s0;
14884                     s = old_old_s;  /* Point to the beginning of the final char
14885                                        that fits in the node */
14886                 }
14887                 else {
14888
14889                     /* Here, we have filled a /il node, and there are unfolded
14890                      * characters in it.  If the runtime locale turns out to be
14891                      * UTF-8, there are possible multi-character folds, just
14892                      * like when not under /l.  The node hence can't terminate
14893                      * in the middle of such a fold.  To determine this, we
14894                      * have to create a folded copy of this node.  That means
14895                      * reparsing the node, folding everything assuming a UTF-8
14896                      * locale.  (If at runtime it isn't such a locale, the
14897                      * actions here wouldn't have been necessary, but we have
14898                      * to assume the worst case.)  If we find we need to back
14899                      * off the folded string, we do so, and then map that
14900                      * position back to the original unfolded node, which then
14901                      * gets output, truncated at that spot */
14902
14903                     char * redo_p = RExC_parse;
14904                     char * redo_e;
14905                     char * old_redo_e;
14906
14907                     /* Allow enough space assuming a single byte input folds to
14908                      * a single byte output, plus assume that the two unparsed
14909                      * characters (that we may need) fold to the largest number
14910                      * of bytes possible, plus extra for one more worst case
14911                      * scenario.  In the loop below, if we start eating into
14912                      * that final spare space, we enlarge this initial space */
14913                     Size_t size = max_string_len + (3 * UTF8_MAXBYTES_CASE) + 1;
14914
14915                     Newxz(locfold_buf, size, char);
14916                     Newxz(loc_correspondence, size, Size_t);
14917
14918                     /* Redo this node's parse, folding into 'locfold_buf' */
14919                     redo_p = RExC_parse;
14920                     old_redo_e = redo_e = locfold_buf;
14921                     while (redo_p <= oldp) {
14922
14923                         old_redo_e = redo_e;
14924                         loc_correspondence[redo_e - locfold_buf]
14925                                                         = redo_p - RExC_parse;
14926
14927                         if (UTF) {
14928                             Size_t added_len;
14929
14930                             (void) _to_utf8_fold_flags((U8 *) redo_p,
14931                                                        (U8 *) RExC_end,
14932                                                        (U8 *) redo_e,
14933                                                        &added_len,
14934                                                        FOLD_FLAGS_FULL);
14935                             redo_e += added_len;
14936                             redo_p += UTF8SKIP(redo_p);
14937                         }
14938                         else {
14939
14940                             /* Note that if this code is run on some ancient
14941                              * Unicode versions, SHARP S doesn't fold to 'ss',
14942                              * but rather than clutter the code with #ifdef's,
14943                              * as is done above, we ignore that possibility.
14944                              * This is ok because this code doesn't affect what
14945                              * gets matched, but merely where the node gets
14946                              * split */
14947                             if (UCHARAT(redo_p) != LATIN_SMALL_LETTER_SHARP_S) {
14948                                 *redo_e++ = toLOWER_L1(UCHARAT(redo_p));
14949                             }
14950                             else {
14951                                 *redo_e++ = 's';
14952                                 *redo_e++ = 's';
14953                             }
14954                             redo_p++;
14955                         }
14956
14957
14958                         /* If we're getting so close to the end that a
14959                          * worst-case fold in the next character would cause us
14960                          * to overflow, increase, assuming one byte output byte
14961                          * per one byte input one, plus room for another worst
14962                          * case fold */
14963                         if (   redo_p <= oldp
14964                             && redo_e > locfold_buf + size
14965                                                     - (UTF8_MAXBYTES_CASE + 1))
14966                         {
14967                             Size_t new_size = size
14968                                             + (oldp - redo_p)
14969                                             + UTF8_MAXBYTES_CASE + 1;
14970                             Ptrdiff_t e_offset = redo_e - locfold_buf;
14971
14972                             Renew(locfold_buf, new_size, char);
14973                             Renew(loc_correspondence, new_size, Size_t);
14974                             size = new_size;
14975
14976                             redo_e = locfold_buf + e_offset;
14977                         }
14978                     }
14979
14980                     /* Set so that things are in terms of the folded, temporary
14981                      * string */
14982                     s = old_redo_e;
14983                     s_start = locfold_buf;
14984                     e = redo_e;
14985
14986                 }
14987
14988                 /* Here, we have 's', 's_start' and 'e' set up to point to the
14989                  * input that goes into the node, folded.
14990                  *
14991                  * If the final character of the node and the fold of ender
14992                  * form the first two characters of a three character fold, we
14993                  * need to peek ahead at the next (unparsed) character in the
14994                  * input to determine if the three actually do form such a
14995                  * fold.  Just looking at that character is not generally
14996                  * sufficient, as it could be, for example, an escape sequence
14997                  * that evaluates to something else, and it needs to be folded.
14998                  *
14999                  * khw originally thought to just go through the parse loop one
15000                  * extra time, but that doesn't work easily as that iteration
15001                  * could cause things to think that the parse is over and to
15002                  * goto loopdone.  The character could be a '$' for example, or
15003                  * the character beyond could be a quantifier, and other
15004                  * glitches as well.
15005                  *
15006                  * The solution used here for peeking ahead is to look at that
15007                  * next character.  If it isn't ASCII punctuation, then it will
15008                  * be something that continues in an EXACTish node if there
15009                  * were space.  We append the fold of it to s, having reserved
15010                  * enough room in s0 for the purpose.  If we can't reasonably
15011                  * peek ahead, we instead assume the worst case: that it is
15012                  * something that would form the completion of a multi-char
15013                  * fold.
15014                  *
15015                  * If we can't split between s and ender, we work backwards
15016                  * character-by-character down to s0.  At each current point
15017                  * see if we are at the beginning of a multi-char fold.  If so,
15018                  * that means we would be splitting the fold across nodes, and
15019                  * so we back up one and try again.
15020                  *
15021                  * If we're not at the beginning, we still could be at the
15022                  * final two characters of a (rare) three character fold.  We
15023                  * check if the sequence starting at the character before the
15024                  * current position (and including the current and next
15025                  * characters) is a three character fold.  If not, the node can
15026                  * be split here.  If it is, we have to backup two characters
15027                  * and try again.
15028                  *
15029                  * Otherwise, the node can be split at the current position.
15030                  *
15031                  * The same logic is used for UTF-8 patterns and not */
15032                 if (UTF) {
15033                     Size_t added_len;
15034
15035                     /* Append the fold of ender */
15036                     (void) _to_uni_fold_flags(
15037                         ender,
15038                         (U8 *) e,
15039                         &added_len,
15040                         FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
15041                                         ? FOLD_FLAGS_NOMIX_ASCII
15042                                         : 0));
15043                     e += added_len;
15044
15045                     /* 's' and the character folded to by ender may be the
15046                      * first two of a three-character fold, in which case the
15047                      * node should not be split here.  That may mean examining
15048                      * the so-far unparsed character starting at 'p'.  But if
15049                      * ender folded to more than one character, we already have
15050                      * three characters to look at.  Also, we first check if
15051                      * the sequence consisting of s and the next character form
15052                      * the first two of some three character fold.  If not,
15053                      * there's no need to peek ahead. */
15054                     if (   added_len <= UTF8SKIP(e - added_len)
15055                         && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_utf8_safe(s, e)))
15056                     {
15057                         /* Here, the two do form the beginning of a potential
15058                          * three character fold.  The unexamined character may
15059                          * or may not complete it.  Peek at it.  It might be
15060                          * something that ends the node or an escape sequence,
15061                          * in which case we don't know without a lot of work
15062                          * what it evaluates to, so we have to assume the worst
15063                          * case: that it does complete the fold, and so we
15064                          * can't split here.  All such instances  will have
15065                          * that character be an ASCII punctuation character,
15066                          * like a backslash.  So, for that case, backup one and
15067                          * drop down to try at that position */
15068                         if (isPUNCT(*p)) {
15069                             s = (char *) utf8_hop_back((U8 *) s, -1,
15070                                        (U8 *) s_start);
15071                             backed_up = TRUE;
15072                         }
15073                         else {
15074                             /* Here, since it's not punctuation, it must be a
15075                              * real character, and we can append its fold to
15076                              * 'e' (having deliberately reserved enough space
15077                              * for this eventuality) and drop down to check if
15078                              * the three actually do form a folded sequence */
15079                             (void) _to_utf8_fold_flags(
15080                                 (U8 *) p, (U8 *) RExC_end,
15081                                 (U8 *) e,
15082                                 &added_len,
15083                                 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
15084                                                 ? FOLD_FLAGS_NOMIX_ASCII
15085                                                 : 0));
15086                             e += added_len;
15087                         }
15088                     }
15089
15090                     /* Here, we either have three characters available in
15091                      * sequence starting at 's', or we have two characters and
15092                      * know that the following one can't possibly be part of a
15093                      * three character fold.  We go through the node backwards
15094                      * until we find a place where we can split it without
15095                      * breaking apart a multi-character fold.  At any given
15096                      * point we have to worry about if such a fold begins at
15097                      * the current 's', and also if a three-character fold
15098                      * begins at s-1, (containing s and s+1).  Splitting in
15099                      * either case would break apart a fold */
15100                     do {
15101                         char *prev_s = (char *) utf8_hop_back((U8 *) s, -1,
15102                                                             (U8 *) s_start);
15103
15104                         /* If is a multi-char fold, can't split here.  Backup
15105                          * one char and try again */
15106                         if (UNLIKELY(is_MULTI_CHAR_FOLD_utf8_safe(s, e))) {
15107                             s = prev_s;
15108                             backed_up = TRUE;
15109                             continue;
15110                         }
15111
15112                         /* If the two characters beginning at 's' are part of a
15113                          * three character fold starting at the character
15114                          * before s, we can't split either before or after s.
15115                          * Backup two chars and try again */
15116                         if (   LIKELY(s > s_start)
15117                             && UNLIKELY(is_THREE_CHAR_FOLD_utf8_safe(prev_s, e)))
15118                         {
15119                             s = prev_s;
15120                             s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s_start);
15121                             backed_up = TRUE;
15122                             continue;
15123                         }
15124
15125                         /* Here there's no multi-char fold between s and the
15126                          * next character following it.  We can split */
15127                         splittable = TRUE;
15128                         break;
15129
15130                     } while (s > s_start); /* End of loops backing up through the node */
15131
15132                     /* Here we either couldn't find a place to split the node,
15133                      * or else we broke out of the loop setting 'splittable' to
15134                      * true.  In the latter case, the place to split is between
15135                      * the first and second characters in the sequence starting
15136                      * at 's' */
15137                     if (splittable) {
15138                         s += UTF8SKIP(s);
15139                     }
15140                 }
15141                 else {  /* Pattern not UTF-8 */
15142                     if (   ender != LATIN_SMALL_LETTER_SHARP_S
15143                         || ASCII_FOLD_RESTRICTED)
15144                     {
15145                         assert( toLOWER_L1(ender) < 256 );
15146                         *e++ = (char)(toLOWER_L1(ender)); /* should e and the cast be U8? */
15147                     }
15148                     else {
15149                         *e++ = 's';
15150                         *e++ = 's';
15151                     }
15152
15153                     if (   e - s  <= 1
15154                         && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_latin1_safe(s, e)))
15155                     {
15156                         if (isPUNCT(*p)) {
15157                             s--;
15158                             backed_up = TRUE;
15159                         }
15160                         else {
15161                             if (   UCHARAT(p) != LATIN_SMALL_LETTER_SHARP_S
15162                                 || ASCII_FOLD_RESTRICTED)
15163                             {
15164                                 assert( toLOWER_L1(ender) < 256 );
15165                                 *e++ = (char)(toLOWER_L1(ender)); /* should e and the cast be U8? */
15166                             }
15167                             else {
15168                                 *e++ = 's';
15169                                 *e++ = 's';
15170                             }
15171                         }
15172                     }
15173
15174                     do {
15175                         if (UNLIKELY(is_MULTI_CHAR_FOLD_latin1_safe(s, e))) {
15176                             s--;
15177                             backed_up = TRUE;
15178                             continue;
15179                         }
15180
15181                         if (   LIKELY(s > s_start)
15182                             && UNLIKELY(is_THREE_CHAR_FOLD_latin1_safe(s - 1, e)))
15183                         {
15184                             s -= 2;
15185                             backed_up = TRUE;
15186                             continue;
15187                         }
15188
15189                         splittable = TRUE;
15190                         break;
15191
15192                     } while (s > s_start);
15193
15194                     if (splittable) {
15195                         s++;
15196                     }
15197                 }
15198
15199                 /* Here, we are done backing up.  If we didn't backup at all
15200                  * (the likely case), just proceed */
15201                 if (backed_up) {
15202
15203                    /* If we did find a place to split, reparse the entire node
15204                     * stopping where we have calculated. */
15205                     if (splittable) {
15206
15207                        /* If we created a temporary folded string under /l, we
15208                         * have to map that back to the original */
15209                         if (need_to_fold_loc) {
15210                             upper_fill = loc_correspondence[s - s_start];
15211                             if (upper_fill == 0) {
15212                                 FAIL2("panic: loc_correspondence[%d] is 0",
15213                                       (int) (s - s_start));
15214                             }
15215                         }
15216                         else {
15217                             upper_fill = s - s0;
15218                         }
15219                         goto reparse;
15220                     }
15221
15222                     /* Here the node consists entirely of non-final multi-char
15223                      * folds.  (Likely it is all 'f's or all 's's.)  There's no
15224                      * decent place to split it, so give up and just take the
15225                      * whole thing */
15226                     len = old_s - s0;
15227                 }
15228
15229                 if (need_to_fold_loc) {
15230                     Safefree(locfold_buf);
15231                     Safefree(loc_correspondence);
15232                 }
15233             }   /* End of verifying node ends with an appropriate char */
15234
15235             /* We need to start the next node at the character that didn't fit
15236              * in this one */
15237             p = oldp;
15238
15239           loopdone:   /* Jumped to when encounters something that shouldn't be
15240                          in the node */
15241
15242             /* Free up any over-allocated space; cast is to silence bogus
15243              * warning in MS VC */
15244             change_engine_size(pRExC_state,
15245                         - (Ptrdiff_t) (current_string_nodes - STR_SZ(len)));
15246
15247             /* I (khw) don't know if you can get here with zero length, but the
15248              * old code handled this situation by creating a zero-length EXACT
15249              * node.  Might as well be NOTHING instead */
15250             if (len == 0) {
15251                 OP(REGNODE_p(ret)) = NOTHING;
15252             }
15253             else {
15254
15255                 /* If the node type is EXACT here, check to see if it
15256                  * should be EXACTL, or EXACT_REQ8. */
15257                 if (node_type == EXACT) {
15258                     if (LOC) {
15259                         node_type = EXACTL;
15260                     }
15261                     else if (requires_utf8_target) {
15262                         node_type = EXACT_REQ8;
15263                     }
15264                 }
15265                 else if (node_type == LEXACT) {
15266                     if (requires_utf8_target) {
15267                         node_type = LEXACT_REQ8;
15268                     }
15269                 }
15270                 else if (FOLD) {
15271                     if (    UNLIKELY(has_micro_sign || has_ss)
15272                         && (node_type == EXACTFU || (   node_type == EXACTF
15273                                                      && maybe_exactfu)))
15274                     {   /* These two conditions are problematic in non-UTF-8
15275                            EXACTFU nodes. */
15276                         assert(! UTF);
15277                         node_type = EXACTFUP;
15278                     }
15279                     else if (node_type == EXACTFL) {
15280
15281                         /* 'maybe_exactfu' is deliberately set above to
15282                          * indicate this node type, where all code points in it
15283                          * are above 255 */
15284                         if (maybe_exactfu) {
15285                             node_type = EXACTFLU8;
15286                         }
15287                         else if (UNLIKELY(
15288                              _invlist_contains_cp(PL_HasMultiCharFold, ender)))
15289                         {
15290                             /* A character that folds to more than one will
15291                              * match multiple characters, so can't be SIMPLE.
15292                              * We don't have to worry about this with EXACTFLU8
15293                              * nodes just above, as they have already been
15294                              * folded (since the fold doesn't vary at run
15295                              * time).  Here, if the final character in the node
15296                              * folds to multiple, it can't be simple.  (This
15297                              * only has an effect if the node has only a single
15298                              * character, hence the final one, as elsewhere we
15299                              * turn off simple for nodes whose length > 1 */
15300                             maybe_SIMPLE = 0;
15301                         }
15302                     }
15303                     else if (node_type == EXACTF) {  /* Means is /di */
15304
15305                         /* This intermediate variable is needed solely because
15306                          * the asserts in the macro where used exceed Win32's
15307                          * literal string capacity */
15308                         char first_char = * STRING(REGNODE_p(ret));
15309
15310                         /* If 'maybe_exactfu' is clear, then we need to stay
15311                          * /di.  If it is set, it means there are no code
15312                          * points that match differently depending on UTF8ness
15313                          * of the target string, so it can become an EXACTFU
15314                          * node */
15315                         if (! maybe_exactfu) {
15316                             RExC_seen_d_op = TRUE;
15317                         }
15318                         else if (   isALPHA_FOLD_EQ(first_char, 's')
15319                                  || isALPHA_FOLD_EQ(ender, 's'))
15320                         {
15321                             /* But, if the node begins or ends in an 's' we
15322                              * have to defer changing it into an EXACTFU, as
15323                              * the node could later get joined with another one
15324                              * that ends or begins with 's' creating an 'ss'
15325                              * sequence which would then wrongly match the
15326                              * sharp s without the target being UTF-8.  We
15327                              * create a special node that we resolve later when
15328                              * we join nodes together */
15329
15330                             node_type = EXACTFU_S_EDGE;
15331                         }
15332                         else {
15333                             node_type = EXACTFU;
15334                         }
15335                     }
15336
15337                     if (requires_utf8_target && node_type == EXACTFU) {
15338                         node_type = EXACTFU_REQ8;
15339                     }
15340                 }
15341
15342                 OP(REGNODE_p(ret)) = node_type;
15343                 setSTR_LEN(REGNODE_p(ret), len);
15344                 RExC_emit += STR_SZ(len);
15345
15346                 /* If the node isn't a single character, it can't be SIMPLE */
15347                 if (len > (Size_t) ((UTF) ? UTF8SKIP(STRING(REGNODE_p(ret))) : 1)) {
15348                     maybe_SIMPLE = 0;
15349                 }
15350
15351                 *flagp |= HASWIDTH | maybe_SIMPLE;
15352             }
15353
15354             Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
15355             RExC_parse = p;
15356
15357             {
15358                 /* len is STRLEN which is unsigned, need to copy to signed */
15359                 IV iv = len;
15360                 if (iv < 0)
15361                     vFAIL("Internal disaster");
15362             }
15363
15364         } /* End of label 'defchar:' */
15365         break;
15366     } /* End of giant switch on input character */
15367
15368     /* Position parse to next real character */
15369     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15370                                             FALSE /* Don't force to /x */ );
15371     if (   *RExC_parse == '{'
15372         && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
15373     {
15374         if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
15375             RExC_parse++;
15376             vFAIL("Unescaped left brace in regex is illegal here");
15377         }
15378         ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
15379                                   " passed through");
15380     }
15381
15382     return(ret);
15383 }
15384
15385
15386 STATIC void
15387 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
15388 {
15389     /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'.  It
15390      * sets up the bitmap and any flags, removing those code points from the
15391      * inversion list, setting it to NULL should it become completely empty */
15392
15393     dVAR;
15394
15395     PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
15396     assert(PL_regkind[OP(node)] == ANYOF);
15397
15398     /* There is no bitmap for this node type */
15399     if (inRANGE(OP(node), ANYOFH, ANYOFRb)) {
15400         return;
15401     }
15402
15403     ANYOF_BITMAP_ZERO(node);
15404     if (*invlist_ptr) {
15405
15406         /* This gets set if we actually need to modify things */
15407         bool change_invlist = FALSE;
15408
15409         UV start, end;
15410
15411         /* Start looking through *invlist_ptr */
15412         invlist_iterinit(*invlist_ptr);
15413         while (invlist_iternext(*invlist_ptr, &start, &end)) {
15414             UV high;
15415             int i;
15416
15417             if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
15418                 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
15419             }
15420
15421             /* Quit if are above what we should change */
15422             if (start >= NUM_ANYOF_CODE_POINTS) {
15423                 break;
15424             }
15425
15426             change_invlist = TRUE;
15427
15428             /* Set all the bits in the range, up to the max that we are doing */
15429             high = (end < NUM_ANYOF_CODE_POINTS - 1)
15430                    ? end
15431                    : NUM_ANYOF_CODE_POINTS - 1;
15432             for (i = start; i <= (int) high; i++) {
15433                 if (! ANYOF_BITMAP_TEST(node, i)) {
15434                     ANYOF_BITMAP_SET(node, i);
15435                 }
15436             }
15437         }
15438         invlist_iterfinish(*invlist_ptr);
15439
15440         /* Done with loop; remove any code points that are in the bitmap from
15441          * *invlist_ptr; similarly for code points above the bitmap if we have
15442          * a flag to match all of them anyways */
15443         if (change_invlist) {
15444             _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
15445         }
15446         if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
15447             _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
15448         }
15449
15450         /* If have completely emptied it, remove it completely */
15451         if (_invlist_len(*invlist_ptr) == 0) {
15452             SvREFCNT_dec_NN(*invlist_ptr);
15453             *invlist_ptr = NULL;
15454         }
15455     }
15456 }
15457
15458 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
15459    Character classes ([:foo:]) can also be negated ([:^foo:]).
15460    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
15461    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
15462    but trigger failures because they are currently unimplemented. */
15463
15464 #define POSIXCC_DONE(c)   ((c) == ':')
15465 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
15466 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
15467 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
15468
15469 #define WARNING_PREFIX              "Assuming NOT a POSIX class since "
15470 #define NO_BLANKS_POSIX_WARNING     "no blanks are allowed in one"
15471 #define SEMI_COLON_POSIX_WARNING    "a semi-colon was found instead of a colon"
15472
15473 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
15474
15475 /* 'posix_warnings' and 'warn_text' are names of variables in the following
15476  * routine. q.v. */
15477 #define ADD_POSIX_WARNING(p, text)  STMT_START {                            \
15478         if (posix_warnings) {                                               \
15479             if (! RExC_warn_text ) RExC_warn_text =                         \
15480                                          (AV *) sv_2mortal((SV *) newAV()); \
15481             av_push(RExC_warn_text, Perl_newSVpvf(aTHX_                     \
15482                                              WARNING_PREFIX                 \
15483                                              text                           \
15484                                              REPORT_LOCATION,               \
15485                                              REPORT_LOCATION_ARGS(p)));     \
15486         }                                                                   \
15487     } STMT_END
15488 #define CLEAR_POSIX_WARNINGS()                                              \
15489     STMT_START {                                                            \
15490         if (posix_warnings && RExC_warn_text)                               \
15491             av_clear(RExC_warn_text);                                       \
15492     } STMT_END
15493
15494 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret)                                \
15495     STMT_START {                                                            \
15496         CLEAR_POSIX_WARNINGS();                                             \
15497         return ret;                                                         \
15498     } STMT_END
15499
15500 STATIC int
15501 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
15502
15503     const char * const s,      /* Where the putative posix class begins.
15504                                   Normally, this is one past the '['.  This
15505                                   parameter exists so it can be somewhere
15506                                   besides RExC_parse. */
15507     char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
15508                                   NULL */
15509     AV ** posix_warnings,      /* Where to place any generated warnings, or
15510                                   NULL */
15511     const bool check_only      /* Don't die if error */
15512 )
15513 {
15514     /* This parses what the caller thinks may be one of the three POSIX
15515      * constructs:
15516      *  1) a character class, like [:blank:]
15517      *  2) a collating symbol, like [. .]
15518      *  3) an equivalence class, like [= =]
15519      * In the latter two cases, it croaks if it finds a syntactically legal
15520      * one, as these are not handled by Perl.
15521      *
15522      * The main purpose is to look for a POSIX character class.  It returns:
15523      *  a) the class number
15524      *      if it is a completely syntactically and semantically legal class.
15525      *      'updated_parse_ptr', if not NULL, is set to point to just after the
15526      *      closing ']' of the class
15527      *  b) OOB_NAMEDCLASS
15528      *      if it appears that one of the three POSIX constructs was meant, but
15529      *      its specification was somehow defective.  'updated_parse_ptr', if
15530      *      not NULL, is set to point to the character just after the end
15531      *      character of the class.  See below for handling of warnings.
15532      *  c) NOT_MEANT_TO_BE_A_POSIX_CLASS
15533      *      if it  doesn't appear that a POSIX construct was intended.
15534      *      'updated_parse_ptr' is not changed.  No warnings nor errors are
15535      *      raised.
15536      *
15537      * In b) there may be errors or warnings generated.  If 'check_only' is
15538      * TRUE, then any errors are discarded.  Warnings are returned to the
15539      * caller via an AV* created into '*posix_warnings' if it is not NULL.  If
15540      * instead it is NULL, warnings are suppressed.
15541      *
15542      * The reason for this function, and its complexity is that a bracketed
15543      * character class can contain just about anything.  But it's easy to
15544      * mistype the very specific posix class syntax but yielding a valid
15545      * regular bracketed class, so it silently gets compiled into something
15546      * quite unintended.
15547      *
15548      * The solution adopted here maintains backward compatibility except that
15549      * it adds a warning if it looks like a posix class was intended but
15550      * improperly specified.  The warning is not raised unless what is input
15551      * very closely resembles one of the 14 legal posix classes.  To do this,
15552      * it uses fuzzy parsing.  It calculates how many single-character edits it
15553      * would take to transform what was input into a legal posix class.  Only
15554      * if that number is quite small does it think that the intention was a
15555      * posix class.  Obviously these are heuristics, and there will be cases
15556      * where it errs on one side or another, and they can be tweaked as
15557      * experience informs.
15558      *
15559      * The syntax for a legal posix class is:
15560      *
15561      * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
15562      *
15563      * What this routine considers syntactically to be an intended posix class
15564      * is this (the comments indicate some restrictions that the pattern
15565      * doesn't show):
15566      *
15567      *  qr/(?x: \[?                         # The left bracket, possibly
15568      *                                      # omitted
15569      *          \h*                         # possibly followed by blanks
15570      *          (?: \^ \h* )?               # possibly a misplaced caret
15571      *          [:;]?                       # The opening class character,
15572      *                                      # possibly omitted.  A typo
15573      *                                      # semi-colon can also be used.
15574      *          \h*
15575      *          \^?                         # possibly a correctly placed
15576      *                                      # caret, but not if there was also
15577      *                                      # a misplaced one
15578      *          \h*
15579      *          .{3,15}                     # The class name.  If there are
15580      *                                      # deviations from the legal syntax,
15581      *                                      # its edit distance must be close
15582      *                                      # to a real class name in order
15583      *                                      # for it to be considered to be
15584      *                                      # an intended posix class.
15585      *          \h*
15586      *          [[:punct:]]?                # The closing class character,
15587      *                                      # possibly omitted.  If not a colon
15588      *                                      # nor semi colon, the class name
15589      *                                      # must be even closer to a valid
15590      *                                      # one
15591      *          \h*
15592      *          \]?                         # The right bracket, possibly
15593      *                                      # omitted.
15594      *     )/
15595      *
15596      * In the above, \h must be ASCII-only.
15597      *
15598      * These are heuristics, and can be tweaked as field experience dictates.
15599      * There will be cases when someone didn't intend to specify a posix class
15600      * that this warns as being so.  The goal is to minimize these, while
15601      * maximizing the catching of things intended to be a posix class that
15602      * aren't parsed as such.
15603      */
15604
15605     const char* p             = s;
15606     const char * const e      = RExC_end;
15607     unsigned complement       = 0;      /* If to complement the class */
15608     bool found_problem        = FALSE;  /* Assume OK until proven otherwise */
15609     bool has_opening_bracket  = FALSE;
15610     bool has_opening_colon    = FALSE;
15611     int class_number          = OOB_NAMEDCLASS; /* Out-of-bounds until find
15612                                                    valid class */
15613     const char * possible_end = NULL;   /* used for a 2nd parse pass */
15614     const char* name_start;             /* ptr to class name first char */
15615
15616     /* If the number of single-character typos the input name is away from a
15617      * legal name is no more than this number, it is considered to have meant
15618      * the legal name */
15619     int max_distance          = 2;
15620
15621     /* to store the name.  The size determines the maximum length before we
15622      * decide that no posix class was intended.  Should be at least
15623      * sizeof("alphanumeric") */
15624     UV input_text[15];
15625     STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
15626
15627     PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
15628
15629     CLEAR_POSIX_WARNINGS();
15630
15631     if (p >= e) {
15632         return NOT_MEANT_TO_BE_A_POSIX_CLASS;
15633     }
15634
15635     if (*(p - 1) != '[') {
15636         ADD_POSIX_WARNING(p, "it doesn't start with a '['");
15637         found_problem = TRUE;
15638     }
15639     else {
15640         has_opening_bracket = TRUE;
15641     }
15642
15643     /* They could be confused and think you can put spaces between the
15644      * components */
15645     if (isBLANK(*p)) {
15646         found_problem = TRUE;
15647
15648         do {
15649             p++;
15650         } while (p < e && isBLANK(*p));
15651
15652         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15653     }
15654
15655     /* For [. .] and [= =].  These are quite different internally from [: :],
15656      * so they are handled separately.  */
15657     if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
15658                                             and 1 for at least one char in it
15659                                           */
15660     {
15661         const char open_char  = *p;
15662         const char * temp_ptr = p + 1;
15663
15664         /* These two constructs are not handled by perl, and if we find a
15665          * syntactically valid one, we croak.  khw, who wrote this code, finds
15666          * this explanation of them very unclear:
15667          * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
15668          * And searching the rest of the internet wasn't very helpful either.
15669          * It looks like just about any byte can be in these constructs,
15670          * depending on the locale.  But unless the pattern is being compiled
15671          * under /l, which is very rare, Perl runs under the C or POSIX locale.
15672          * In that case, it looks like [= =] isn't allowed at all, and that
15673          * [. .] could be any single code point, but for longer strings the
15674          * constituent characters would have to be the ASCII alphabetics plus
15675          * the minus-hyphen.  Any sensible locale definition would limit itself
15676          * to these.  And any portable one definitely should.  Trying to parse
15677          * the general case is a nightmare (see [perl #127604]).  So, this code
15678          * looks only for interiors of these constructs that match:
15679          *      qr/.|[-\w]{2,}/
15680          * Using \w relaxes the apparent rules a little, without adding much
15681          * danger of mistaking something else for one of these constructs.
15682          *
15683          * [. .] in some implementations described on the internet is usable to
15684          * escape a character that otherwise is special in bracketed character
15685          * classes.  For example [.].] means a literal right bracket instead of
15686          * the ending of the class
15687          *
15688          * [= =] can legitimately contain a [. .] construct, but we don't
15689          * handle this case, as that [. .] construct will later get parsed
15690          * itself and croak then.  And [= =] is checked for even when not under
15691          * /l, as Perl has long done so.
15692          *
15693          * The code below relies on there being a trailing NUL, so it doesn't
15694          * have to keep checking if the parse ptr < e.
15695          */
15696         if (temp_ptr[1] == open_char) {
15697             temp_ptr++;
15698         }
15699         else while (    temp_ptr < e
15700                     && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
15701         {
15702             temp_ptr++;
15703         }
15704
15705         if (*temp_ptr == open_char) {
15706             temp_ptr++;
15707             if (*temp_ptr == ']') {
15708                 temp_ptr++;
15709                 if (! found_problem && ! check_only) {
15710                     RExC_parse = (char *) temp_ptr;
15711                     vFAIL3("POSIX syntax [%c %c] is reserved for future "
15712                             "extensions", open_char, open_char);
15713                 }
15714
15715                 /* Here, the syntax wasn't completely valid, or else the call
15716                  * is to check-only */
15717                 if (updated_parse_ptr) {
15718                     *updated_parse_ptr = (char *) temp_ptr;
15719                 }
15720
15721                 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
15722             }
15723         }
15724
15725         /* If we find something that started out to look like one of these
15726          * constructs, but isn't, we continue below so that it can be checked
15727          * for being a class name with a typo of '.' or '=' instead of a colon.
15728          * */
15729     }
15730
15731     /* Here, we think there is a possibility that a [: :] class was meant, and
15732      * we have the first real character.  It could be they think the '^' comes
15733      * first */
15734     if (*p == '^') {
15735         found_problem = TRUE;
15736         ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
15737         complement = 1;
15738         p++;
15739
15740         if (isBLANK(*p)) {
15741             found_problem = TRUE;
15742
15743             do {
15744                 p++;
15745             } while (p < e && isBLANK(*p));
15746
15747             ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15748         }
15749     }
15750
15751     /* But the first character should be a colon, which they could have easily
15752      * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
15753      * distinguish from a colon, so treat that as a colon).  */
15754     if (*p == ':') {
15755         p++;
15756         has_opening_colon = TRUE;
15757     }
15758     else if (*p == ';') {
15759         found_problem = TRUE;
15760         p++;
15761         ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15762         has_opening_colon = TRUE;
15763     }
15764     else {
15765         found_problem = TRUE;
15766         ADD_POSIX_WARNING(p, "there must be a starting ':'");
15767
15768         /* Consider an initial punctuation (not one of the recognized ones) to
15769          * be a left terminator */
15770         if (*p != '^' && *p != ']' && isPUNCT(*p)) {
15771             p++;
15772         }
15773     }
15774
15775     /* They may think that you can put spaces between the components */
15776     if (isBLANK(*p)) {
15777         found_problem = TRUE;
15778
15779         do {
15780             p++;
15781         } while (p < e && isBLANK(*p));
15782
15783         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15784     }
15785
15786     if (*p == '^') {
15787
15788         /* We consider something like [^:^alnum:]] to not have been intended to
15789          * be a posix class, but XXX maybe we should */
15790         if (complement) {
15791             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15792         }
15793
15794         complement = 1;
15795         p++;
15796     }
15797
15798     /* Again, they may think that you can put spaces between the components */
15799     if (isBLANK(*p)) {
15800         found_problem = TRUE;
15801
15802         do {
15803             p++;
15804         } while (p < e && isBLANK(*p));
15805
15806         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15807     }
15808
15809     if (*p == ']') {
15810
15811         /* XXX This ']' may be a typo, and something else was meant.  But
15812          * treating it as such creates enough complications, that that
15813          * possibility isn't currently considered here.  So we assume that the
15814          * ']' is what is intended, and if we've already found an initial '[',
15815          * this leaves this construct looking like [:] or [:^], which almost
15816          * certainly weren't intended to be posix classes */
15817         if (has_opening_bracket) {
15818             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15819         }
15820
15821         /* But this function can be called when we parse the colon for
15822          * something like qr/[alpha:]]/, so we back up to look for the
15823          * beginning */
15824         p--;
15825
15826         if (*p == ';') {
15827             found_problem = TRUE;
15828             ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15829         }
15830         else if (*p != ':') {
15831
15832             /* XXX We are currently very restrictive here, so this code doesn't
15833              * consider the possibility that, say, /[alpha.]]/ was intended to
15834              * be a posix class. */
15835             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15836         }
15837
15838         /* Here we have something like 'foo:]'.  There was no initial colon,
15839          * and we back up over 'foo.  XXX Unlike the going forward case, we
15840          * don't handle typos of non-word chars in the middle */
15841         has_opening_colon = FALSE;
15842         p--;
15843
15844         while (p > RExC_start && isWORDCHAR(*p)) {
15845             p--;
15846         }
15847         p++;
15848
15849         /* Here, we have positioned ourselves to where we think the first
15850          * character in the potential class is */
15851     }
15852
15853     /* Now the interior really starts.  There are certain key characters that
15854      * can end the interior, or these could just be typos.  To catch both
15855      * cases, we may have to do two passes.  In the first pass, we keep on
15856      * going unless we come to a sequence that matches
15857      *      qr/ [[:punct:]] [[:blank:]]* \] /xa
15858      * This means it takes a sequence to end the pass, so two typos in a row if
15859      * that wasn't what was intended.  If the class is perfectly formed, just
15860      * this one pass is needed.  We also stop if there are too many characters
15861      * being accumulated, but this number is deliberately set higher than any
15862      * real class.  It is set high enough so that someone who thinks that
15863      * 'alphanumeric' is a correct name would get warned that it wasn't.
15864      * While doing the pass, we keep track of where the key characters were in
15865      * it.  If we don't find an end to the class, and one of the key characters
15866      * was found, we redo the pass, but stop when we get to that character.
15867      * Thus the key character was considered a typo in the first pass, but a
15868      * terminator in the second.  If two key characters are found, we stop at
15869      * the second one in the first pass.  Again this can miss two typos, but
15870      * catches a single one
15871      *
15872      * In the first pass, 'possible_end' starts as NULL, and then gets set to
15873      * point to the first key character.  For the second pass, it starts as -1.
15874      * */
15875
15876     name_start = p;
15877   parse_name:
15878     {
15879         bool has_blank               = FALSE;
15880         bool has_upper               = FALSE;
15881         bool has_terminating_colon   = FALSE;
15882         bool has_terminating_bracket = FALSE;
15883         bool has_semi_colon          = FALSE;
15884         unsigned int name_len        = 0;
15885         int punct_count              = 0;
15886
15887         while (p < e) {
15888
15889             /* Squeeze out blanks when looking up the class name below */
15890             if (isBLANK(*p) ) {
15891                 has_blank = TRUE;
15892                 found_problem = TRUE;
15893                 p++;
15894                 continue;
15895             }
15896
15897             /* The name will end with a punctuation */
15898             if (isPUNCT(*p)) {
15899                 const char * peek = p + 1;
15900
15901                 /* Treat any non-']' punctuation followed by a ']' (possibly
15902                  * with intervening blanks) as trying to terminate the class.
15903                  * ']]' is very likely to mean a class was intended (but
15904                  * missing the colon), but the warning message that gets
15905                  * generated shows the error position better if we exit the
15906                  * loop at the bottom (eventually), so skip it here. */
15907                 if (*p != ']') {
15908                     if (peek < e && isBLANK(*peek)) {
15909                         has_blank = TRUE;
15910                         found_problem = TRUE;
15911                         do {
15912                             peek++;
15913                         } while (peek < e && isBLANK(*peek));
15914                     }
15915
15916                     if (peek < e && *peek == ']') {
15917                         has_terminating_bracket = TRUE;
15918                         if (*p == ':') {
15919                             has_terminating_colon = TRUE;
15920                         }
15921                         else if (*p == ';') {
15922                             has_semi_colon = TRUE;
15923                             has_terminating_colon = TRUE;
15924                         }
15925                         else {
15926                             found_problem = TRUE;
15927                         }
15928                         p = peek + 1;
15929                         goto try_posix;
15930                     }
15931                 }
15932
15933                 /* Here we have punctuation we thought didn't end the class.
15934                  * Keep track of the position of the key characters that are
15935                  * more likely to have been class-enders */
15936                 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15937
15938                     /* Allow just one such possible class-ender not actually
15939                      * ending the class. */
15940                     if (possible_end) {
15941                         break;
15942                     }
15943                     possible_end = p;
15944                 }
15945
15946                 /* If we have too many punctuation characters, no use in
15947                  * keeping going */
15948                 if (++punct_count > max_distance) {
15949                     break;
15950                 }
15951
15952                 /* Treat the punctuation as a typo. */
15953                 input_text[name_len++] = *p;
15954                 p++;
15955             }
15956             else if (isUPPER(*p)) { /* Use lowercase for lookup */
15957                 input_text[name_len++] = toLOWER(*p);
15958                 has_upper = TRUE;
15959                 found_problem = TRUE;
15960                 p++;
15961             } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15962                 input_text[name_len++] = *p;
15963                 p++;
15964             }
15965             else {
15966                 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15967                 p+= UTF8SKIP(p);
15968             }
15969
15970             /* The declaration of 'input_text' is how long we allow a potential
15971              * class name to be, before saying they didn't mean a class name at
15972              * all */
15973             if (name_len >= C_ARRAY_LENGTH(input_text)) {
15974                 break;
15975             }
15976         }
15977
15978         /* We get to here when the possible class name hasn't been properly
15979          * terminated before:
15980          *   1) we ran off the end of the pattern; or
15981          *   2) found two characters, each of which might have been intended to
15982          *      be the name's terminator
15983          *   3) found so many punctuation characters in the purported name,
15984          *      that the edit distance to a valid one is exceeded
15985          *   4) we decided it was more characters than anyone could have
15986          *      intended to be one. */
15987
15988         found_problem = TRUE;
15989
15990         /* In the final two cases, we know that looking up what we've
15991          * accumulated won't lead to a match, even a fuzzy one. */
15992         if (   name_len >= C_ARRAY_LENGTH(input_text)
15993             || punct_count > max_distance)
15994         {
15995             /* If there was an intermediate key character that could have been
15996              * an intended end, redo the parse, but stop there */
15997             if (possible_end && possible_end != (char *) -1) {
15998                 possible_end = (char *) -1; /* Special signal value to say
15999                                                we've done a first pass */
16000                 p = name_start;
16001                 goto parse_name;
16002             }
16003
16004             /* Otherwise, it can't have meant to have been a class */
16005             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16006         }
16007
16008         /* If we ran off the end, and the final character was a punctuation
16009          * one, back up one, to look at that final one just below.  Later, we
16010          * will restore the parse pointer if appropriate */
16011         if (name_len && p == e && isPUNCT(*(p-1))) {
16012             p--;
16013             name_len--;
16014         }
16015
16016         if (p < e && isPUNCT(*p)) {
16017             if (*p == ']') {
16018                 has_terminating_bracket = TRUE;
16019
16020                 /* If this is a 2nd ']', and the first one is just below this
16021                  * one, consider that to be the real terminator.  This gives a
16022                  * uniform and better positioning for the warning message  */
16023                 if (   possible_end
16024                     && possible_end != (char *) -1
16025                     && *possible_end == ']'
16026                     && name_len && input_text[name_len - 1] == ']')
16027                 {
16028                     name_len--;
16029                     p = possible_end;
16030
16031                     /* And this is actually equivalent to having done the 2nd
16032                      * pass now, so set it to not try again */
16033                     possible_end = (char *) -1;
16034                 }
16035             }
16036             else {
16037                 if (*p == ':') {
16038                     has_terminating_colon = TRUE;
16039                 }
16040                 else if (*p == ';') {
16041                     has_semi_colon = TRUE;
16042                     has_terminating_colon = TRUE;
16043                 }
16044                 p++;
16045             }
16046         }
16047
16048     try_posix:
16049
16050         /* Here, we have a class name to look up.  We can short circuit the
16051          * stuff below for short names that can't possibly be meant to be a
16052          * class name.  (We can do this on the first pass, as any second pass
16053          * will yield an even shorter name) */
16054         if (name_len < 3) {
16055             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16056         }
16057
16058         /* Find which class it is.  Initially switch on the length of the name.
16059          * */
16060         switch (name_len) {
16061             case 4:
16062                 if (memEQs(name_start, 4, "word")) {
16063                     /* this is not POSIX, this is the Perl \w */
16064                     class_number = ANYOF_WORDCHAR;
16065                 }
16066                 break;
16067             case 5:
16068                 /* Names all of length 5: alnum alpha ascii blank cntrl digit
16069                  *                        graph lower print punct space upper
16070                  * Offset 4 gives the best switch position.  */
16071                 switch (name_start[4]) {
16072                     case 'a':
16073                         if (memBEGINs(name_start, 5, "alph")) /* alpha */
16074                             class_number = ANYOF_ALPHA;
16075                         break;
16076                     case 'e':
16077                         if (memBEGINs(name_start, 5, "spac")) /* space */
16078                             class_number = ANYOF_SPACE;
16079                         break;
16080                     case 'h':
16081                         if (memBEGINs(name_start, 5, "grap")) /* graph */
16082                             class_number = ANYOF_GRAPH;
16083                         break;
16084                     case 'i':
16085                         if (memBEGINs(name_start, 5, "asci")) /* ascii */
16086                             class_number = ANYOF_ASCII;
16087                         break;
16088                     case 'k':
16089                         if (memBEGINs(name_start, 5, "blan")) /* blank */
16090                             class_number = ANYOF_BLANK;
16091                         break;
16092                     case 'l':
16093                         if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
16094                             class_number = ANYOF_CNTRL;
16095                         break;
16096                     case 'm':
16097                         if (memBEGINs(name_start, 5, "alnu")) /* alnum */
16098                             class_number = ANYOF_ALPHANUMERIC;
16099                         break;
16100                     case 'r':
16101                         if (memBEGINs(name_start, 5, "lowe")) /* lower */
16102                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
16103                         else if (memBEGINs(name_start, 5, "uppe")) /* upper */
16104                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
16105                         break;
16106                     case 't':
16107                         if (memBEGINs(name_start, 5, "digi")) /* digit */
16108                             class_number = ANYOF_DIGIT;
16109                         else if (memBEGINs(name_start, 5, "prin")) /* print */
16110                             class_number = ANYOF_PRINT;
16111                         else if (memBEGINs(name_start, 5, "punc")) /* punct */
16112                             class_number = ANYOF_PUNCT;
16113                         break;
16114                 }
16115                 break;
16116             case 6:
16117                 if (memEQs(name_start, 6, "xdigit"))
16118                     class_number = ANYOF_XDIGIT;
16119                 break;
16120         }
16121
16122         /* If the name exactly matches a posix class name the class number will
16123          * here be set to it, and the input almost certainly was meant to be a
16124          * posix class, so we can skip further checking.  If instead the syntax
16125          * is exactly correct, but the name isn't one of the legal ones, we
16126          * will return that as an error below.  But if neither of these apply,
16127          * it could be that no posix class was intended at all, or that one
16128          * was, but there was a typo.  We tease these apart by doing fuzzy
16129          * matching on the name */
16130         if (class_number == OOB_NAMEDCLASS && found_problem) {
16131             const UV posix_names[][6] = {
16132                                                 { 'a', 'l', 'n', 'u', 'm' },
16133                                                 { 'a', 'l', 'p', 'h', 'a' },
16134                                                 { 'a', 's', 'c', 'i', 'i' },
16135                                                 { 'b', 'l', 'a', 'n', 'k' },
16136                                                 { 'c', 'n', 't', 'r', 'l' },
16137                                                 { 'd', 'i', 'g', 'i', 't' },
16138                                                 { 'g', 'r', 'a', 'p', 'h' },
16139                                                 { 'l', 'o', 'w', 'e', 'r' },
16140                                                 { 'p', 'r', 'i', 'n', 't' },
16141                                                 { 'p', 'u', 'n', 'c', 't' },
16142                                                 { 's', 'p', 'a', 'c', 'e' },
16143                                                 { 'u', 'p', 'p', 'e', 'r' },
16144                                                 { 'w', 'o', 'r', 'd' },
16145                                                 { 'x', 'd', 'i', 'g', 'i', 't' }
16146                                             };
16147             /* The names of the above all have added NULs to make them the same
16148              * size, so we need to also have the real lengths */
16149             const UV posix_name_lengths[] = {
16150                                                 sizeof("alnum") - 1,
16151                                                 sizeof("alpha") - 1,
16152                                                 sizeof("ascii") - 1,
16153                                                 sizeof("blank") - 1,
16154                                                 sizeof("cntrl") - 1,
16155                                                 sizeof("digit") - 1,
16156                                                 sizeof("graph") - 1,
16157                                                 sizeof("lower") - 1,
16158                                                 sizeof("print") - 1,
16159                                                 sizeof("punct") - 1,
16160                                                 sizeof("space") - 1,
16161                                                 sizeof("upper") - 1,
16162                                                 sizeof("word")  - 1,
16163                                                 sizeof("xdigit")- 1
16164                                             };
16165             unsigned int i;
16166             int temp_max = max_distance;    /* Use a temporary, so if we
16167                                                reparse, we haven't changed the
16168                                                outer one */
16169
16170             /* Use a smaller max edit distance if we are missing one of the
16171              * delimiters */
16172             if (   has_opening_bracket + has_opening_colon < 2
16173                 || has_terminating_bracket + has_terminating_colon < 2)
16174             {
16175                 temp_max--;
16176             }
16177
16178             /* See if the input name is close to a legal one */
16179             for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
16180
16181                 /* Short circuit call if the lengths are too far apart to be
16182                  * able to match */
16183                 if (abs( (int) (name_len - posix_name_lengths[i]))
16184                     > temp_max)
16185                 {
16186                     continue;
16187                 }
16188
16189                 if (edit_distance(input_text,
16190                                   posix_names[i],
16191                                   name_len,
16192                                   posix_name_lengths[i],
16193                                   temp_max
16194                                  )
16195                     > -1)
16196                 { /* If it is close, it probably was intended to be a class */
16197                     goto probably_meant_to_be;
16198                 }
16199             }
16200
16201             /* Here the input name is not close enough to a valid class name
16202              * for us to consider it to be intended to be a posix class.  If
16203              * we haven't already done so, and the parse found a character that
16204              * could have been terminators for the name, but which we absorbed
16205              * as typos during the first pass, repeat the parse, signalling it
16206              * to stop at that character */
16207             if (possible_end && possible_end != (char *) -1) {
16208                 possible_end = (char *) -1;
16209                 p = name_start;
16210                 goto parse_name;
16211             }
16212
16213             /* Here neither pass found a close-enough class name */
16214             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
16215         }
16216
16217     probably_meant_to_be:
16218
16219         /* Here we think that a posix specification was intended.  Update any
16220          * parse pointer */
16221         if (updated_parse_ptr) {
16222             *updated_parse_ptr = (char *) p;
16223         }
16224
16225         /* If a posix class name was intended but incorrectly specified, we
16226          * output or return the warnings */
16227         if (found_problem) {
16228
16229             /* We set flags for these issues in the parse loop above instead of
16230              * adding them to the list of warnings, because we can parse it
16231              * twice, and we only want one warning instance */
16232             if (has_upper) {
16233                 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
16234             }
16235             if (has_blank) {
16236                 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
16237             }
16238             if (has_semi_colon) {
16239                 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
16240             }
16241             else if (! has_terminating_colon) {
16242                 ADD_POSIX_WARNING(p, "there is no terminating ':'");
16243             }
16244             if (! has_terminating_bracket) {
16245                 ADD_POSIX_WARNING(p, "there is no terminating ']'");
16246             }
16247
16248             if (   posix_warnings
16249                 && RExC_warn_text
16250                 && av_top_index(RExC_warn_text) > -1)
16251             {
16252                 *posix_warnings = RExC_warn_text;
16253             }
16254         }
16255         else if (class_number != OOB_NAMEDCLASS) {
16256             /* If it is a known class, return the class.  The class number
16257              * #defines are structured so each complement is +1 to the normal
16258              * one */
16259             CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
16260         }
16261         else if (! check_only) {
16262
16263             /* Here, it is an unrecognized class.  This is an error (unless the
16264             * call is to check only, which we've already handled above) */
16265             const char * const complement_string = (complement)
16266                                                    ? "^"
16267                                                    : "";
16268             RExC_parse = (char *) p;
16269             vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
16270                         complement_string,
16271                         UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
16272         }
16273     }
16274
16275     return OOB_NAMEDCLASS;
16276 }
16277 #undef ADD_POSIX_WARNING
16278
16279 STATIC unsigned  int
16280 S_regex_set_precedence(const U8 my_operator) {
16281
16282     /* Returns the precedence in the (?[...]) construct of the input operator,
16283      * specified by its character representation.  The precedence follows
16284      * general Perl rules, but it extends this so that ')' and ']' have (low)
16285      * precedence even though they aren't really operators */
16286
16287     switch (my_operator) {
16288         case '!':
16289             return 5;
16290         case '&':
16291             return 4;
16292         case '^':
16293         case '|':
16294         case '+':
16295         case '-':
16296             return 3;
16297         case ')':
16298             return 2;
16299         case ']':
16300             return 1;
16301     }
16302
16303     NOT_REACHED; /* NOTREACHED */
16304     return 0;   /* Silence compiler warning */
16305 }
16306
16307 STATIC regnode_offset
16308 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
16309                     I32 *flagp, U32 depth,
16310                     char * const oregcomp_parse)
16311 {
16312     /* Handle the (?[...]) construct to do set operations */
16313
16314     U8 curchar;                     /* Current character being parsed */
16315     UV start, end;                  /* End points of code point ranges */
16316     SV* final = NULL;               /* The end result inversion list */
16317     SV* result_string;              /* 'final' stringified */
16318     AV* stack;                      /* stack of operators and operands not yet
16319                                        resolved */
16320     AV* fence_stack = NULL;         /* A stack containing the positions in
16321                                        'stack' of where the undealt-with left
16322                                        parens would be if they were actually
16323                                        put there */
16324     /* The 'volatile' is a workaround for an optimiser bug
16325      * in Solaris Studio 12.3. See RT #127455 */
16326     volatile IV fence = 0;          /* Position of where most recent undealt-
16327                                        with left paren in stack is; -1 if none.
16328                                      */
16329     STRLEN len;                     /* Temporary */
16330     regnode_offset node;            /* Temporary, and final regnode returned by
16331                                        this function */
16332     const bool save_fold = FOLD;    /* Temporary */
16333     char *save_end, *save_parse;    /* Temporaries */
16334     const bool in_locale = LOC;     /* we turn off /l during processing */
16335
16336     DECLARE_AND_GET_RE_DEBUG_FLAGS;
16337
16338     PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
16339     PERL_UNUSED_ARG(oregcomp_parse); /* Only for Set_Node_Length */
16340
16341     DEBUG_PARSE("xcls");
16342
16343     if (in_locale) {
16344         set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
16345     }
16346
16347     /* The use of this operator implies /u.  This is required so that the
16348      * compile time values are valid in all runtime cases */
16349     REQUIRE_UNI_RULES(flagp, 0);
16350
16351     ckWARNexperimental(RExC_parse,
16352                        WARN_EXPERIMENTAL__REGEX_SETS,
16353                        "The regex_sets feature is experimental");
16354
16355     /* Everything in this construct is a metacharacter.  Operands begin with
16356      * either a '\' (for an escape sequence), or a '[' for a bracketed
16357      * character class.  Any other character should be an operator, or
16358      * parenthesis for grouping.  Both types of operands are handled by calling
16359      * regclass() to parse them.  It is called with a parameter to indicate to
16360      * return the computed inversion list.  The parsing here is implemented via
16361      * a stack.  Each entry on the stack is a single character representing one
16362      * of the operators; or else a pointer to an operand inversion list. */
16363
16364 #define IS_OPERATOR(a) SvIOK(a)
16365 #define IS_OPERAND(a)  (! IS_OPERATOR(a))
16366
16367     /* The stack is kept in Łukasiewicz order.  (That's pronounced similar
16368      * to luke-a-shave-itch (or -itz), but people who didn't want to bother
16369      * with pronouncing it called it Reverse Polish instead, but now that YOU
16370      * know how to pronounce it you can use the correct term, thus giving due
16371      * credit to the person who invented it, and impressing your geek friends.
16372      * Wikipedia says that the pronounciation of "Ł" has been changing so that
16373      * it is now more like an English initial W (as in wonk) than an L.)
16374      *
16375      * This means that, for example, 'a | b & c' is stored on the stack as
16376      *
16377      * c  [4]
16378      * b  [3]
16379      * &  [2]
16380      * a  [1]
16381      * |  [0]
16382      *
16383      * where the numbers in brackets give the stack [array] element number.
16384      * In this implementation, parentheses are not stored on the stack.
16385      * Instead a '(' creates a "fence" so that the part of the stack below the
16386      * fence is invisible except to the corresponding ')' (this allows us to
16387      * replace testing for parens, by using instead subtraction of the fence
16388      * position).  As new operands are processed they are pushed onto the stack
16389      * (except as noted in the next paragraph).  New operators of higher
16390      * precedence than the current final one are inserted on the stack before
16391      * the lhs operand (so that when the rhs is pushed next, everything will be
16392      * in the correct positions shown above.  When an operator of equal or
16393      * lower precedence is encountered in parsing, all the stacked operations
16394      * of equal or higher precedence are evaluated, leaving the result as the
16395      * top entry on the stack.  This makes higher precedence operations
16396      * evaluate before lower precedence ones, and causes operations of equal
16397      * precedence to left associate.
16398      *
16399      * The only unary operator '!' is immediately pushed onto the stack when
16400      * encountered.  When an operand is encountered, if the top of the stack is
16401      * a '!", the complement is immediately performed, and the '!' popped.  The
16402      * resulting value is treated as a new operand, and the logic in the
16403      * previous paragraph is executed.  Thus in the expression
16404      *      [a] + ! [b]
16405      * the stack looks like
16406      *
16407      * !
16408      * a
16409      * +
16410      *
16411      * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
16412      * becomes
16413      *
16414      * !b
16415      * a
16416      * +
16417      *
16418      * A ')' is treated as an operator with lower precedence than all the
16419      * aforementioned ones, which causes all operations on the stack above the
16420      * corresponding '(' to be evaluated down to a single resultant operand.
16421      * Then the fence for the '(' is removed, and the operand goes through the
16422      * algorithm above, without the fence.
16423      *
16424      * A separate stack is kept of the fence positions, so that the position of
16425      * the latest so-far unbalanced '(' is at the top of it.
16426      *
16427      * The ']' ending the construct is treated as the lowest operator of all,
16428      * so that everything gets evaluated down to a single operand, which is the
16429      * result */
16430
16431     sv_2mortal((SV *)(stack = newAV()));
16432     sv_2mortal((SV *)(fence_stack = newAV()));
16433
16434     while (RExC_parse < RExC_end) {
16435         I32 top_index;              /* Index of top-most element in 'stack' */
16436         SV** top_ptr;               /* Pointer to top 'stack' element */
16437         SV* current = NULL;         /* To contain the current inversion list
16438                                        operand */
16439         SV* only_to_avoid_leaks;
16440
16441         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
16442                                 TRUE /* Force /x */ );
16443         if (RExC_parse >= RExC_end) {   /* Fail */
16444             break;
16445         }
16446
16447         curchar = UCHARAT(RExC_parse);
16448
16449 redo_curchar:
16450
16451 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16452                     /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
16453         DEBUG_U(dump_regex_sets_structures(pRExC_state,
16454                                            stack, fence, fence_stack));
16455 #endif
16456
16457         top_index = av_tindex_skip_len_mg(stack);
16458
16459         switch (curchar) {
16460             SV** stacked_ptr;       /* Ptr to something already on 'stack' */
16461             char stacked_operator;  /* The topmost operator on the 'stack'. */
16462             SV* lhs;                /* Operand to the left of the operator */
16463             SV* rhs;                /* Operand to the right of the operator */
16464             SV* fence_ptr;          /* Pointer to top element of the fence
16465                                        stack */
16466             case '(':
16467
16468                 if (   RExC_parse < RExC_end - 2
16469                     && UCHARAT(RExC_parse + 1) == '?'
16470                     && UCHARAT(RExC_parse + 2) == '^')
16471                 {
16472                     const regnode_offset orig_emit = RExC_emit;
16473                     SV * resultant_invlist;
16474
16475                     /* If is a '(?^', could be an embedded '(?^flags:(?[...])'.
16476                      * This happens when we have some thing like
16477                      *
16478                      *   my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
16479                      *   ...
16480                      *   qr/(?[ \p{Digit} & $thai_or_lao ])/;
16481                      *
16482                      * Here we would be handling the interpolated
16483                      * '$thai_or_lao'.  We handle this by a recursive call to
16484                      * reg which returns the inversion list the
16485                      * interpolated expression evaluates to.  Actually, the
16486                      * return is a special regnode containing a pointer to that
16487                      * inversion list.  If the return isn't that regnode alone,
16488                      * we know that this wasn't such an interpolation, which is
16489                      * an error: we need to get a single inversion list back
16490                      * from the recursion */
16491
16492                     RExC_parse++;
16493                     RExC_sets_depth++;
16494
16495                     node = reg(pRExC_state, 2, flagp, depth+1);
16496                     RETURN_FAIL_ON_RESTART(*flagp, flagp);
16497
16498                     if (   OP(REGNODE_p(node)) != REGEX_SET
16499                            /* If more than a single node returned, the nested
16500                             * parens evaluated to more than just a (?[...]),
16501                             * which isn't legal */
16502                         || RExC_emit != orig_emit
16503                                       + NODE_STEP_REGNODE
16504                                       + regarglen[REGEX_SET])
16505                     {
16506                         vFAIL("Expecting interpolated extended charclass");
16507                     }
16508                     resultant_invlist = (SV *) ARGp(REGNODE_p(node));
16509                     current = invlist_clone(resultant_invlist, NULL);
16510                     SvREFCNT_dec(resultant_invlist);
16511
16512                     RExC_sets_depth--;
16513                     RExC_emit = orig_emit;
16514                     goto handle_operand;
16515                 }
16516
16517                 /* A regular '('.  Look behind for illegal syntax */
16518                 if (top_index - fence >= 0) {
16519                     /* If the top entry on the stack is an operator, it had
16520                      * better be a '!', otherwise the entry below the top
16521                      * operand should be an operator */
16522                     if (   ! (top_ptr = av_fetch(stack, top_index, FALSE))
16523                         || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
16524                         || (   IS_OPERAND(*top_ptr)
16525                             && (   top_index - fence < 1
16526                                 || ! (stacked_ptr = av_fetch(stack,
16527                                                              top_index - 1,
16528                                                              FALSE))
16529                                 || ! IS_OPERATOR(*stacked_ptr))))
16530                     {
16531                         RExC_parse++;
16532                         vFAIL("Unexpected '(' with no preceding operator");
16533                     }
16534                 }
16535
16536                 /* Stack the position of this undealt-with left paren */
16537                 av_push(fence_stack, newSViv(fence));
16538                 fence = top_index + 1;
16539                 break;
16540
16541             case '\\':
16542                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16543                  * multi-char folds are allowed.  */
16544                 if (!regclass(pRExC_state, flagp, depth+1,
16545                               TRUE, /* means parse just the next thing */
16546                               FALSE, /* don't allow multi-char folds */
16547                               FALSE, /* don't silence non-portable warnings.  */
16548                               TRUE,  /* strict */
16549                               FALSE, /* Require return to be an ANYOF */
16550                               &current))
16551                 {
16552                     RETURN_FAIL_ON_RESTART(*flagp, flagp);
16553                     goto regclass_failed;
16554                 }
16555
16556                 assert(current);
16557
16558                 /* regclass() will return with parsing just the \ sequence,
16559                  * leaving the parse pointer at the next thing to parse */
16560                 RExC_parse--;
16561                 goto handle_operand;
16562
16563             case '[':   /* Is a bracketed character class */
16564             {
16565                 /* See if this is a [:posix:] class. */
16566                 bool is_posix_class = (OOB_NAMEDCLASS
16567                             < handle_possible_posix(pRExC_state,
16568                                                 RExC_parse + 1,
16569                                                 NULL,
16570                                                 NULL,
16571                                                 TRUE /* checking only */));
16572                 /* If it is a posix class, leave the parse pointer at the '['
16573                  * to fool regclass() into thinking it is part of a
16574                  * '[[:posix:]]'. */
16575                 if (! is_posix_class) {
16576                     RExC_parse++;
16577                 }
16578
16579                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16580                  * multi-char folds are allowed.  */
16581                 if (!regclass(pRExC_state, flagp, depth+1,
16582                                 is_posix_class, /* parse the whole char
16583                                                     class only if not a
16584                                                     posix class */
16585                                 FALSE, /* don't allow multi-char folds */
16586                                 TRUE, /* silence non-portable warnings. */
16587                                 TRUE, /* strict */
16588                                 FALSE, /* Require return to be an ANYOF */
16589                                 &current))
16590                 {
16591                     RETURN_FAIL_ON_RESTART(*flagp, flagp);
16592                     goto regclass_failed;
16593                 }
16594
16595                 assert(current);
16596
16597                 /* function call leaves parse pointing to the ']', except if we
16598                  * faked it */
16599                 if (is_posix_class) {
16600                     RExC_parse--;
16601                 }
16602
16603                 goto handle_operand;
16604             }
16605
16606             case ']':
16607                 if (top_index >= 1) {
16608                     goto join_operators;
16609                 }
16610
16611                 /* Only a single operand on the stack: are done */
16612                 goto done;
16613
16614             case ')':
16615                 if (av_tindex_skip_len_mg(fence_stack) < 0) {
16616                     if (UCHARAT(RExC_parse - 1) == ']')  {
16617                         break;
16618                     }
16619                     RExC_parse++;
16620                     vFAIL("Unexpected ')'");
16621                 }
16622
16623                 /* If nothing after the fence, is missing an operand */
16624                 if (top_index - fence < 0) {
16625                     RExC_parse++;
16626                     goto bad_syntax;
16627                 }
16628                 /* If at least two things on the stack, treat this as an
16629                   * operator */
16630                 if (top_index - fence >= 1) {
16631                     goto join_operators;
16632                 }
16633
16634                 /* Here only a single thing on the fenced stack, and there is a
16635                  * fence.  Get rid of it */
16636                 fence_ptr = av_pop(fence_stack);
16637                 assert(fence_ptr);
16638                 fence = SvIV(fence_ptr);
16639                 SvREFCNT_dec_NN(fence_ptr);
16640                 fence_ptr = NULL;
16641
16642                 if (fence < 0) {
16643                     fence = 0;
16644                 }
16645
16646                 /* Having gotten rid of the fence, we pop the operand at the
16647                  * stack top and process it as a newly encountered operand */
16648                 current = av_pop(stack);
16649                 if (IS_OPERAND(current)) {
16650                     goto handle_operand;
16651                 }
16652
16653                 RExC_parse++;
16654                 goto bad_syntax;
16655
16656             case '&':
16657             case '|':
16658             case '+':
16659             case '-':
16660             case '^':
16661
16662                 /* These binary operators should have a left operand already
16663                  * parsed */
16664                 if (   top_index - fence < 0
16665                     || top_index - fence == 1
16666                     || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
16667                     || ! IS_OPERAND(*top_ptr))
16668                 {
16669                     goto unexpected_binary;
16670                 }
16671
16672                 /* If only the one operand is on the part of the stack visible
16673                  * to us, we just place this operator in the proper position */
16674                 if (top_index - fence < 2) {
16675
16676                     /* Place the operator before the operand */
16677
16678                     SV* lhs = av_pop(stack);
16679                     av_push(stack, newSVuv(curchar));
16680                     av_push(stack, lhs);
16681                     break;
16682                 }
16683
16684                 /* But if there is something else on the stack, we need to
16685                  * process it before this new operator if and only if the
16686                  * stacked operation has equal or higher precedence than the
16687                  * new one */
16688
16689              join_operators:
16690
16691                 /* The operator on the stack is supposed to be below both its
16692                  * operands */
16693                 if (   ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
16694                     || IS_OPERAND(*stacked_ptr))
16695                 {
16696                     /* But if not, it's legal and indicates we are completely
16697                      * done if and only if we're currently processing a ']',
16698                      * which should be the final thing in the expression */
16699                     if (curchar == ']') {
16700                         goto done;
16701                     }
16702
16703                   unexpected_binary:
16704                     RExC_parse++;
16705                     vFAIL2("Unexpected binary operator '%c' with no "
16706                            "preceding operand", curchar);
16707                 }
16708                 stacked_operator = (char) SvUV(*stacked_ptr);
16709
16710                 if (regex_set_precedence(curchar)
16711                     > regex_set_precedence(stacked_operator))
16712                 {
16713                     /* Here, the new operator has higher precedence than the
16714                      * stacked one.  This means we need to add the new one to
16715                      * the stack to await its rhs operand (and maybe more
16716                      * stuff).  We put it before the lhs operand, leaving
16717                      * untouched the stacked operator and everything below it
16718                      * */
16719                     lhs = av_pop(stack);
16720                     assert(IS_OPERAND(lhs));
16721
16722                     av_push(stack, newSVuv(curchar));
16723                     av_push(stack, lhs);
16724                     break;
16725                 }
16726
16727                 /* Here, the new operator has equal or lower precedence than
16728                  * what's already there.  This means the operation already
16729                  * there should be performed now, before the new one. */
16730
16731                 rhs = av_pop(stack);
16732                 if (! IS_OPERAND(rhs)) {
16733
16734                     /* This can happen when a ! is not followed by an operand,
16735                      * like in /(?[\t &!])/ */
16736                     goto bad_syntax;
16737                 }
16738
16739                 lhs = av_pop(stack);
16740
16741                 if (! IS_OPERAND(lhs)) {
16742
16743                     /* This can happen when there is an empty (), like in
16744                      * /(?[[0]+()+])/ */
16745                     goto bad_syntax;
16746                 }
16747
16748                 switch (stacked_operator) {
16749                     case '&':
16750                         _invlist_intersection(lhs, rhs, &rhs);
16751                         break;
16752
16753                     case '|':
16754                     case '+':
16755                         _invlist_union(lhs, rhs, &rhs);
16756                         break;
16757
16758                     case '-':
16759                         _invlist_subtract(lhs, rhs, &rhs);
16760                         break;
16761
16762                     case '^':   /* The union minus the intersection */
16763                     {
16764                         SV* i = NULL;
16765                         SV* u = NULL;
16766
16767                         _invlist_union(lhs, rhs, &u);
16768                         _invlist_intersection(lhs, rhs, &i);
16769                         _invlist_subtract(u, i, &rhs);
16770                         SvREFCNT_dec_NN(i);
16771                         SvREFCNT_dec_NN(u);
16772                         break;
16773                     }
16774                 }
16775                 SvREFCNT_dec(lhs);
16776
16777                 /* Here, the higher precedence operation has been done, and the
16778                  * result is in 'rhs'.  We overwrite the stacked operator with
16779                  * the result.  Then we redo this code to either push the new
16780                  * operator onto the stack or perform any higher precedence
16781                  * stacked operation */
16782                 only_to_avoid_leaks = av_pop(stack);
16783                 SvREFCNT_dec(only_to_avoid_leaks);
16784                 av_push(stack, rhs);
16785                 goto redo_curchar;
16786
16787             case '!':   /* Highest priority, right associative */
16788
16789                 /* If what's already at the top of the stack is another '!",
16790                  * they just cancel each other out */
16791                 if (   (top_ptr = av_fetch(stack, top_index, FALSE))
16792                     && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
16793                 {
16794                     only_to_avoid_leaks = av_pop(stack);
16795                     SvREFCNT_dec(only_to_avoid_leaks);
16796                 }
16797                 else { /* Otherwise, since it's right associative, just push
16798                           onto the stack */
16799                     av_push(stack, newSVuv(curchar));
16800                 }
16801                 break;
16802
16803             default:
16804                 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16805                 if (RExC_parse >= RExC_end) {
16806                     break;
16807                 }
16808                 vFAIL("Unexpected character");
16809
16810           handle_operand:
16811
16812             /* Here 'current' is the operand.  If something is already on the
16813              * stack, we have to check if it is a !.  But first, the code above
16814              * may have altered the stack in the time since we earlier set
16815              * 'top_index'.  */
16816
16817             top_index = av_tindex_skip_len_mg(stack);
16818             if (top_index - fence >= 0) {
16819                 /* If the top entry on the stack is an operator, it had better
16820                  * be a '!', otherwise the entry below the top operand should
16821                  * be an operator */
16822                 top_ptr = av_fetch(stack, top_index, FALSE);
16823                 assert(top_ptr);
16824                 if (IS_OPERATOR(*top_ptr)) {
16825
16826                     /* The only permissible operator at the top of the stack is
16827                      * '!', which is applied immediately to this operand. */
16828                     curchar = (char) SvUV(*top_ptr);
16829                     if (curchar != '!') {
16830                         SvREFCNT_dec(current);
16831                         vFAIL2("Unexpected binary operator '%c' with no "
16832                                 "preceding operand", curchar);
16833                     }
16834
16835                     _invlist_invert(current);
16836
16837                     only_to_avoid_leaks = av_pop(stack);
16838                     SvREFCNT_dec(only_to_avoid_leaks);
16839
16840                     /* And we redo with the inverted operand.  This allows
16841                      * handling multiple ! in a row */
16842                     goto handle_operand;
16843                 }
16844                           /* Single operand is ok only for the non-binary ')'
16845                            * operator */
16846                 else if ((top_index - fence == 0 && curchar != ')')
16847                          || (top_index - fence > 0
16848                              && (! (stacked_ptr = av_fetch(stack,
16849                                                            top_index - 1,
16850                                                            FALSE))
16851                                  || IS_OPERAND(*stacked_ptr))))
16852                 {
16853                     SvREFCNT_dec(current);
16854                     vFAIL("Operand with no preceding operator");
16855                 }
16856             }
16857
16858             /* Here there was nothing on the stack or the top element was
16859              * another operand.  Just add this new one */
16860             av_push(stack, current);
16861
16862         } /* End of switch on next parse token */
16863
16864         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16865     } /* End of loop parsing through the construct */
16866
16867     vFAIL("Syntax error in (?[...])");
16868
16869   done:
16870
16871     if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16872         if (RExC_parse < RExC_end) {
16873             RExC_parse++;
16874         }
16875
16876         vFAIL("Unexpected ']' with no following ')' in (?[...");
16877     }
16878
16879     if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16880         vFAIL("Unmatched (");
16881     }
16882
16883     if (av_tindex_skip_len_mg(stack) < 0   /* Was empty */
16884         || ((final = av_pop(stack)) == NULL)
16885         || ! IS_OPERAND(final)
16886         || ! is_invlist(final)
16887         || av_tindex_skip_len_mg(stack) >= 0)  /* More left on stack */
16888     {
16889       bad_syntax:
16890         SvREFCNT_dec(final);
16891         vFAIL("Incomplete expression within '(?[ ])'");
16892     }
16893
16894     /* Here, 'final' is the resultant inversion list from evaluating the
16895      * expression.  Return it if so requested */
16896     if (return_invlist) {
16897         *return_invlist = final;
16898         return END;
16899     }
16900
16901     if (RExC_sets_depth) {  /* If within a recursive call, return in a special
16902                                regnode */
16903         RExC_parse++;
16904         node = regpnode(pRExC_state, REGEX_SET, final);
16905     }
16906     else {
16907
16908         /* Otherwise generate a resultant node, based on 'final'.  regclass()
16909          * is expecting a string of ranges and individual code points */
16910         invlist_iterinit(final);
16911         result_string = newSVpvs("");
16912         while (invlist_iternext(final, &start, &end)) {
16913             if (start == end) {
16914                 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16915             }
16916             else {
16917                 Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%"
16918                                                         UVXf "}", start, end);
16919             }
16920         }
16921
16922         /* About to generate an ANYOF (or similar) node from the inversion list
16923          * we have calculated */
16924         save_parse = RExC_parse;
16925         RExC_parse = SvPV(result_string, len);
16926         save_end = RExC_end;
16927         RExC_end = RExC_parse + len;
16928         TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16929
16930         /* We turn off folding around the call, as the class we have
16931          * constructed already has all folding taken into consideration, and we
16932          * don't want regclass() to add to that */
16933         RExC_flags &= ~RXf_PMf_FOLD;
16934         /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16935          * folds are allowed.  */
16936         node = regclass(pRExC_state, flagp, depth+1,
16937                         FALSE, /* means parse the whole char class */
16938                         FALSE, /* don't allow multi-char folds */
16939                         TRUE, /* silence non-portable warnings.  The above may
16940                                  very well have generated non-portable code
16941                                  points, but they're valid on this machine */
16942                         FALSE, /* similarly, no need for strict */
16943
16944                         /* We can optimize into something besides an ANYOF,
16945                          * except under /l, which needs to be ANYOF because of
16946                          * runtime checks for locale sanity, etc */
16947                     ! in_locale,
16948                         NULL
16949                     );
16950
16951         RESTORE_WARNINGS;
16952         RExC_parse = save_parse + 1;
16953         RExC_end = save_end;
16954         SvREFCNT_dec_NN(final);
16955         SvREFCNT_dec_NN(result_string);
16956
16957         if (save_fold) {
16958             RExC_flags |= RXf_PMf_FOLD;
16959         }
16960
16961         if (!node) {
16962             RETURN_FAIL_ON_RESTART(*flagp, flagp);
16963             goto regclass_failed;
16964         }
16965
16966         /* Fix up the node type if we are in locale.  (We have pretended we are
16967          * under /u for the purposes of regclass(), as this construct will only
16968          * work under UTF-8 locales.  But now we change the opcode to be ANYOFL
16969          * (so as to cause any warnings about bad locales to be output in
16970          * regexec.c), and add the flag that indicates to check if not in a
16971          * UTF-8 locale.  The reason we above forbid optimization into
16972          * something other than an ANYOF node is simply to minimize the number
16973          * of code changes in regexec.c.  Otherwise we would have to create new
16974          * EXACTish node types and deal with them.  This decision could be
16975          * revisited should this construct become popular.
16976          *
16977          * (One might think we could look at the resulting ANYOF node and
16978          * suppress the flag if everything is above 255, as those would be
16979          * UTF-8 only, but this isn't true, as the components that led to that
16980          * result could have been locale-affected, and just happen to cancel
16981          * each other out under UTF-8 locales.) */
16982         if (in_locale) {
16983             set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16984
16985             assert(OP(REGNODE_p(node)) == ANYOF);
16986
16987             OP(REGNODE_p(node)) = ANYOFL;
16988             ANYOF_FLAGS(REGNODE_p(node))
16989                     |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16990         }
16991     }
16992
16993     nextchar(pRExC_state);
16994     Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16995     return node;
16996
16997   regclass_failed:
16998     FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf,
16999                                                                 (UV) *flagp);
17000 }
17001
17002 #ifdef ENABLE_REGEX_SETS_DEBUGGING
17003
17004 STATIC void
17005 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
17006                              AV * stack, const IV fence, AV * fence_stack)
17007 {   /* Dumps the stacks in handle_regex_sets() */
17008
17009     const SSize_t stack_top = av_tindex_skip_len_mg(stack);
17010     const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
17011     SSize_t i;
17012
17013     PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
17014
17015     PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
17016
17017     if (stack_top < 0) {
17018         PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
17019     }
17020     else {
17021         PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
17022         for (i = stack_top; i >= 0; i--) {
17023             SV ** element_ptr = av_fetch(stack, i, FALSE);
17024             if (! element_ptr) {
17025             }
17026
17027             if (IS_OPERATOR(*element_ptr)) {
17028                 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
17029                                             (int) i, (int) SvIV(*element_ptr));
17030             }
17031             else {
17032                 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
17033                 sv_dump(*element_ptr);
17034             }
17035         }
17036     }
17037
17038     if (fence_stack_top < 0) {
17039         PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
17040     }
17041     else {
17042         PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
17043         for (i = fence_stack_top; i >= 0; i--) {
17044             SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
17045             if (! element_ptr) {
17046             }
17047
17048             PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
17049                                             (int) i, (int) SvIV(*element_ptr));
17050         }
17051     }
17052 }
17053
17054 #endif
17055
17056 #undef IS_OPERATOR
17057 #undef IS_OPERAND
17058
17059 STATIC void
17060 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
17061 {
17062     /* This adds the Latin1/above-Latin1 folding rules.
17063      *
17064      * This should be called only for a Latin1-range code points, cp, which is
17065      * known to be involved in a simple fold with other code points above
17066      * Latin1.  It would give false results if /aa has been specified.
17067      * Multi-char folds are outside the scope of this, and must be handled
17068      * specially. */
17069
17070     PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
17071
17072     assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
17073
17074     /* The rules that are valid for all Unicode versions are hard-coded in */
17075     switch (cp) {
17076         case 'k':
17077         case 'K':
17078           *invlist =
17079              add_cp_to_invlist(*invlist, KELVIN_SIGN);
17080             break;
17081         case 's':
17082         case 'S':
17083           *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
17084             break;
17085         case MICRO_SIGN:
17086           *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
17087           *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
17088             break;
17089         case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
17090         case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
17091           *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
17092             break;
17093         case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
17094           *invlist = add_cp_to_invlist(*invlist,
17095                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
17096             break;
17097
17098         default:    /* Other code points are checked against the data for the
17099                        current Unicode version */
17100           {
17101             Size_t folds_count;
17102             U32 first_fold;
17103             const U32 * remaining_folds;
17104             UV folded_cp;
17105
17106             if (isASCII(cp)) {
17107                 folded_cp = toFOLD(cp);
17108             }
17109             else {
17110                 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
17111                 Size_t dummy_len;
17112                 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
17113             }
17114
17115             if (folded_cp > 255) {
17116                 *invlist = add_cp_to_invlist(*invlist, folded_cp);
17117             }
17118
17119             folds_count = _inverse_folds(folded_cp, &first_fold,
17120                                                     &remaining_folds);
17121             if (folds_count == 0) {
17122
17123                 /* Use deprecated warning to increase the chances of this being
17124                  * output */
17125                 ckWARN2reg_d(RExC_parse,
17126                         "Perl folding rules are not up-to-date for 0x%02X;"
17127                         " please use the perlbug utility to report;", cp);
17128             }
17129             else {
17130                 unsigned int i;
17131
17132                 if (first_fold > 255) {
17133                     *invlist = add_cp_to_invlist(*invlist, first_fold);
17134                 }
17135                 for (i = 0; i < folds_count - 1; i++) {
17136                     if (remaining_folds[i] > 255) {
17137                         *invlist = add_cp_to_invlist(*invlist,
17138                                                     remaining_folds[i]);
17139                     }
17140                 }
17141             }
17142             break;
17143          }
17144     }
17145 }
17146
17147 STATIC void
17148 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
17149 {
17150     /* Output the elements of the array given by '*posix_warnings' as REGEXP
17151      * warnings. */
17152
17153     SV * msg;
17154     const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
17155
17156     PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
17157
17158     if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
17159         CLEAR_POSIX_WARNINGS();
17160         return;
17161     }
17162
17163     while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
17164         if (first_is_fatal) {           /* Avoid leaking this */
17165             av_undef(posix_warnings);   /* This isn't necessary if the
17166                                             array is mortal, but is a
17167                                             fail-safe */
17168             (void) sv_2mortal(msg);
17169             PREPARE_TO_DIE;
17170         }
17171         Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
17172         SvREFCNT_dec_NN(msg);
17173     }
17174
17175     UPDATE_WARNINGS_LOC(RExC_parse);
17176 }
17177
17178 PERL_STATIC_INLINE Size_t
17179 S_find_first_differing_byte_pos(const U8 * s1, const U8 * s2, const Size_t max)
17180 {
17181     const U8 * const start = s1;
17182     const U8 * const send = start + max;
17183
17184     PERL_ARGS_ASSERT_FIND_FIRST_DIFFERING_BYTE_POS;
17185
17186     while (s1 < send && *s1  == *s2) {
17187         s1++; s2++;
17188     }
17189
17190     return s1 - start;
17191 }
17192
17193
17194 STATIC AV *
17195 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
17196 {
17197     /* This adds the string scalar <multi_string> to the array
17198      * <multi_char_matches>.  <multi_string> is known to have exactly
17199      * <cp_count> code points in it.  This is used when constructing a
17200      * bracketed character class and we find something that needs to match more
17201      * than a single character.
17202      *
17203      * <multi_char_matches> is actually an array of arrays.  Each top-level
17204      * element is an array that contains all the strings known so far that are
17205      * the same length.  And that length (in number of code points) is the same
17206      * as the index of the top-level array.  Hence, the [2] element is an
17207      * array, each element thereof is a string containing TWO code points;
17208      * while element [3] is for strings of THREE characters, and so on.  Since
17209      * this is for multi-char strings there can never be a [0] nor [1] element.
17210      *
17211      * When we rewrite the character class below, we will do so such that the
17212      * longest strings are written first, so that it prefers the longest
17213      * matching strings first.  This is done even if it turns out that any
17214      * quantifier is non-greedy, out of this programmer's (khw) laziness.  Tom
17215      * Christiansen has agreed that this is ok.  This makes the test for the
17216      * ligature 'ffi' come before the test for 'ff', for example */
17217
17218     AV* this_array;
17219     AV** this_array_ptr;
17220
17221     PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
17222
17223     if (! multi_char_matches) {
17224         multi_char_matches = newAV();
17225     }
17226
17227     if (av_exists(multi_char_matches, cp_count)) {
17228         this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
17229         this_array = *this_array_ptr;
17230     }
17231     else {
17232         this_array = newAV();
17233         av_store(multi_char_matches, cp_count,
17234                  (SV*) this_array);
17235     }
17236     av_push(this_array, multi_string);
17237
17238     return multi_char_matches;
17239 }
17240
17241 /* The names of properties whose definitions are not known at compile time are
17242  * stored in this SV, after a constant heading.  So if the length has been
17243  * changed since initialization, then there is a run-time definition. */
17244 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION                            \
17245                                         (SvCUR(listsv) != initial_listsv_len)
17246
17247 /* There is a restricted set of white space characters that are legal when
17248  * ignoring white space in a bracketed character class.  This generates the
17249  * code to skip them.
17250  *
17251  * There is a line below that uses the same white space criteria but is outside
17252  * this macro.  Both here and there must use the same definition */
17253 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p)                          \
17254     STMT_START {                                                        \
17255         if (do_skip) {                                                  \
17256             while (isBLANK_A(UCHARAT(p)))                               \
17257             {                                                           \
17258                 p++;                                                    \
17259             }                                                           \
17260         }                                                               \
17261     } STMT_END
17262
17263 STATIC regnode_offset
17264 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
17265                  const bool stop_at_1,  /* Just parse the next thing, don't
17266                                            look for a full character class */
17267                  bool allow_mutiple_chars,
17268                  const bool silence_non_portable,   /* Don't output warnings
17269                                                        about too large
17270                                                        characters */
17271                  const bool strict,
17272                  bool optimizable,                  /* ? Allow a non-ANYOF return
17273                                                        node */
17274                  SV** ret_invlist  /* Return an inversion list, not a node */
17275           )
17276 {
17277     /* parse a bracketed class specification.  Most of these will produce an
17278      * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
17279      * EXACTFish node; [[:ascii:]], a POSIXA node; etc.  It is more complex
17280      * under /i with multi-character folds: it will be rewritten following the
17281      * paradigm of this example, where the <multi-fold>s are characters which
17282      * fold to multiple character sequences:
17283      *      /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
17284      * gets effectively rewritten as:
17285      *      /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
17286      * reg() gets called (recursively) on the rewritten version, and this
17287      * function will return what it constructs.  (Actually the <multi-fold>s
17288      * aren't physically removed from the [abcdefghi], it's just that they are
17289      * ignored in the recursion by means of a flag:
17290      * <RExC_in_multi_char_class>.)
17291      *
17292      * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
17293      * characters, with the corresponding bit set if that character is in the
17294      * list.  For characters above this, an inversion list is used.  There
17295      * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
17296      * determinable at compile time
17297      *
17298      * On success, returns the offset at which any next node should be placed
17299      * into the regex engine program being compiled.
17300      *
17301      * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
17302      * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
17303      * UTF-8
17304      */
17305
17306     dVAR;
17307     UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
17308     IV range = 0;
17309     UV value = OOB_UNICODE, save_value = OOB_UNICODE;
17310     regnode_offset ret = -1;    /* Initialized to an illegal value */
17311     STRLEN numlen;
17312     int namedclass = OOB_NAMEDCLASS;
17313     char *rangebegin = NULL;
17314     SV *listsv = NULL;      /* List of \p{user-defined} whose definitions
17315                                aren't available at the time this was called */
17316     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
17317                                       than just initialized.  */
17318     SV* properties = NULL;    /* Code points that match \p{} \P{} */
17319     SV* posixes = NULL;     /* Code points that match classes like [:word:],
17320                                extended beyond the Latin1 range.  These have to
17321                                be kept separate from other code points for much
17322                                of this function because their handling  is
17323                                different under /i, and for most classes under
17324                                /d as well */
17325     SV* nposixes = NULL;    /* Similarly for [:^word:].  These are kept
17326                                separate for a while from the non-complemented
17327                                versions because of complications with /d
17328                                matching */
17329     SV* simple_posixes = NULL; /* But under some conditions, the classes can be
17330                                   treated more simply than the general case,
17331                                   leading to less compilation and execution
17332                                   work */
17333     UV element_count = 0;   /* Number of distinct elements in the class.
17334                                Optimizations may be possible if this is tiny */
17335     AV * multi_char_matches = NULL; /* Code points that fold to more than one
17336                                        character; used under /i */
17337     UV n;
17338     char * stop_ptr = RExC_end;    /* where to stop parsing */
17339
17340     /* ignore unescaped whitespace? */
17341     const bool skip_white = cBOOL(   ret_invlist
17342                                   || (RExC_flags & RXf_PMf_EXTENDED_MORE));
17343
17344     /* inversion list of code points this node matches only when the target
17345      * string is in UTF-8.  These are all non-ASCII, < 256.  (Because is under
17346      * /d) */
17347     SV* upper_latin1_only_utf8_matches = NULL;
17348
17349     /* Inversion list of code points this node matches regardless of things
17350      * like locale, folding, utf8ness of the target string */
17351     SV* cp_list = NULL;
17352
17353     /* Like cp_list, but code points on this list need to be checked for things
17354      * that fold to/from them under /i */
17355     SV* cp_foldable_list = NULL;
17356
17357     /* Like cp_list, but code points on this list are valid only when the
17358      * runtime locale is UTF-8 */
17359     SV* only_utf8_locale_list = NULL;
17360
17361     /* In a range, if one of the endpoints is non-character-set portable,
17362      * meaning that it hard-codes a code point that may mean a different
17363      * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
17364      * mnemonic '\t' which each mean the same character no matter which
17365      * character set the platform is on. */
17366     unsigned int non_portable_endpoint = 0;
17367
17368     /* Is the range unicode? which means on a platform that isn't 1-1 native
17369      * to Unicode (i.e. non-ASCII), each code point in it should be considered
17370      * to be a Unicode value.  */
17371     bool unicode_range = FALSE;
17372     bool invert = FALSE;    /* Is this class to be complemented */
17373
17374     bool warn_super = ALWAYS_WARN_SUPER;
17375
17376     const char * orig_parse = RExC_parse;
17377
17378     /* This variable is used to mark where the end in the input is of something
17379      * that looks like a POSIX construct but isn't.  During the parse, when
17380      * something looks like it could be such a construct is encountered, it is
17381      * checked for being one, but not if we've already checked this area of the
17382      * input.  Only after this position is reached do we check again */
17383     char *not_posix_region_end = RExC_parse - 1;
17384
17385     AV* posix_warnings = NULL;
17386     const bool do_posix_warnings = ckWARN(WARN_REGEXP);
17387     U8 op = END;    /* The returned node-type, initialized to an impossible
17388                        one.  */
17389     U8 anyof_flags = 0;   /* flag bits if the node is an ANYOF-type */
17390     U32 posixl = 0;       /* bit field of posix classes matched under /l */
17391
17392
17393 /* Flags as to what things aren't knowable until runtime.  (Note that these are
17394  * mutually exclusive.) */
17395 #define HAS_USER_DEFINED_PROPERTY 0x01   /* /u any user-defined properties that
17396                                             haven't been defined as of yet */
17397 #define HAS_D_RUNTIME_DEPENDENCY  0x02   /* /d if the target being matched is
17398                                             UTF-8 or not */
17399 #define HAS_L_RUNTIME_DEPENDENCY   0x04 /* /l what the posix classes match and
17400                                             what gets folded */
17401     U32 has_runtime_dependency = 0;     /* OR of the above flags */
17402
17403     DECLARE_AND_GET_RE_DEBUG_FLAGS;
17404
17405     PERL_ARGS_ASSERT_REGCLASS;
17406 #ifndef DEBUGGING
17407     PERL_UNUSED_ARG(depth);
17408 #endif
17409
17410     assert(! (ret_invlist && allow_mutiple_chars));
17411
17412     /* If wants an inversion list returned, we can't optimize to something
17413      * else. */
17414     if (ret_invlist) {
17415         optimizable = FALSE;
17416     }
17417
17418     DEBUG_PARSE("clas");
17419
17420 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */      \
17421     || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0          \
17422                                    && UNICODE_DOT_DOT_VERSION == 0)
17423     allow_mutiple_chars = FALSE;
17424 #endif
17425
17426     /* We include the /i status at the beginning of this so that we can
17427      * know it at runtime */
17428     listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
17429     initial_listsv_len = SvCUR(listsv);
17430     SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated.  */
17431
17432     SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17433
17434     assert(RExC_parse <= RExC_end);
17435
17436     if (UCHARAT(RExC_parse) == '^') {   /* Complement the class */
17437         RExC_parse++;
17438         invert = TRUE;
17439         allow_mutiple_chars = FALSE;
17440         MARK_NAUGHTY(1);
17441         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17442     }
17443
17444     /* Check that they didn't say [:posix:] instead of [[:posix:]] */
17445     if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
17446         int maybe_class = handle_possible_posix(pRExC_state,
17447                                                 RExC_parse,
17448                                                 &not_posix_region_end,
17449                                                 NULL,
17450                                                 TRUE /* checking only */);
17451         if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
17452             ckWARN4reg(not_posix_region_end,
17453                     "POSIX syntax [%c %c] belongs inside character classes%s",
17454                     *RExC_parse, *RExC_parse,
17455                     (maybe_class == OOB_NAMEDCLASS)
17456                     ? ((POSIXCC_NOTYET(*RExC_parse))
17457                         ? " (but this one isn't implemented)"
17458                         : " (but this one isn't fully valid)")
17459                     : ""
17460                     );
17461         }
17462     }
17463
17464     /* If the caller wants us to just parse a single element, accomplish this
17465      * by faking the loop ending condition */
17466     if (stop_at_1 && RExC_end > RExC_parse) {
17467         stop_ptr = RExC_parse + 1;
17468     }
17469
17470     /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
17471     if (UCHARAT(RExC_parse) == ']')
17472         goto charclassloop;
17473
17474     while (1) {
17475
17476         if (   posix_warnings
17477             && av_tindex_skip_len_mg(posix_warnings) >= 0
17478             && RExC_parse > not_posix_region_end)
17479         {
17480             /* Warnings about posix class issues are considered tentative until
17481              * we are far enough along in the parse that we can no longer
17482              * change our mind, at which point we output them.  This is done
17483              * each time through the loop so that a later class won't zap them
17484              * before they have been dealt with. */
17485             output_posix_warnings(pRExC_state, posix_warnings);
17486         }
17487
17488         if  (RExC_parse >= stop_ptr) {
17489             break;
17490         }
17491
17492         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17493
17494         if  (UCHARAT(RExC_parse) == ']') {
17495             break;
17496         }
17497
17498       charclassloop:
17499
17500         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
17501         save_value = value;
17502         save_prevvalue = prevvalue;
17503
17504         if (!range) {
17505             rangebegin = RExC_parse;
17506             element_count++;
17507             non_portable_endpoint = 0;
17508         }
17509         if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
17510             value = utf8n_to_uvchr((U8*)RExC_parse,
17511                                    RExC_end - RExC_parse,
17512                                    &numlen, UTF8_ALLOW_DEFAULT);
17513             RExC_parse += numlen;
17514         }
17515         else
17516             value = UCHARAT(RExC_parse++);
17517
17518         if (value == '[') {
17519             char * posix_class_end;
17520             namedclass = handle_possible_posix(pRExC_state,
17521                                                RExC_parse,
17522                                                &posix_class_end,
17523                                                do_posix_warnings ? &posix_warnings : NULL,
17524                                                FALSE    /* die if error */);
17525             if (namedclass > OOB_NAMEDCLASS) {
17526
17527                 /* If there was an earlier attempt to parse this particular
17528                  * posix class, and it failed, it was a false alarm, as this
17529                  * successful one proves */
17530                 if (   posix_warnings
17531                     && av_tindex_skip_len_mg(posix_warnings) >= 0
17532                     && not_posix_region_end >= RExC_parse
17533                     && not_posix_region_end <= posix_class_end)
17534                 {
17535                     av_undef(posix_warnings);
17536                 }
17537
17538                 RExC_parse = posix_class_end;
17539             }
17540             else if (namedclass == OOB_NAMEDCLASS) {
17541                 not_posix_region_end = posix_class_end;
17542             }
17543             else {
17544                 namedclass = OOB_NAMEDCLASS;
17545             }
17546         }
17547         else if (   RExC_parse - 1 > not_posix_region_end
17548                  && MAYBE_POSIXCC(value))
17549         {
17550             (void) handle_possible_posix(
17551                         pRExC_state,
17552                         RExC_parse - 1,  /* -1 because parse has already been
17553                                             advanced */
17554                         &not_posix_region_end,
17555                         do_posix_warnings ? &posix_warnings : NULL,
17556                         TRUE /* checking only */);
17557         }
17558         else if (  strict && ! skip_white
17559                  && (   _generic_isCC(value, _CC_VERTSPACE)
17560                      || is_VERTWS_cp_high(value)))
17561         {
17562             vFAIL("Literal vertical space in [] is illegal except under /x");
17563         }
17564         else if (value == '\\') {
17565             /* Is a backslash; get the code point of the char after it */
17566
17567             if (RExC_parse >= RExC_end) {
17568                 vFAIL("Unmatched [");
17569             }
17570
17571             if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
17572                 value = utf8n_to_uvchr((U8*)RExC_parse,
17573                                    RExC_end - RExC_parse,
17574                                    &numlen, UTF8_ALLOW_DEFAULT);
17575                 RExC_parse += numlen;
17576             }
17577             else
17578                 value = UCHARAT(RExC_parse++);
17579
17580             /* Some compilers cannot handle switching on 64-bit integer
17581              * values, therefore value cannot be an UV.  Yes, this will
17582              * be a problem later if we want switch on Unicode.
17583              * A similar issue a little bit later when switching on
17584              * namedclass. --jhi */
17585
17586             /* If the \ is escaping white space when white space is being
17587              * skipped, it means that that white space is wanted literally, and
17588              * is already in 'value'.  Otherwise, need to translate the escape
17589              * into what it signifies. */
17590             if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
17591                 const char * message;
17592                 U32 packed_warn;
17593                 U8 grok_c_char;
17594
17595             case 'w':   namedclass = ANYOF_WORDCHAR;    break;
17596             case 'W':   namedclass = ANYOF_NWORDCHAR;   break;
17597             case 's':   namedclass = ANYOF_SPACE;       break;
17598             case 'S':   namedclass = ANYOF_NSPACE;      break;
17599             case 'd':   namedclass = ANYOF_DIGIT;       break;
17600             case 'D':   namedclass = ANYOF_NDIGIT;      break;
17601             case 'v':   namedclass = ANYOF_VERTWS;      break;
17602             case 'V':   namedclass = ANYOF_NVERTWS;     break;
17603             case 'h':   namedclass = ANYOF_HORIZWS;     break;
17604             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
17605             case 'N':  /* Handle \N{NAME} in class */
17606                 {
17607                     const char * const backslash_N_beg = RExC_parse - 2;
17608                     int cp_count;
17609
17610                     if (! grok_bslash_N(pRExC_state,
17611                                         NULL,      /* No regnode */
17612                                         &value,    /* Yes single value */
17613                                         &cp_count, /* Multiple code pt count */
17614                                         flagp,
17615                                         strict,
17616                                         depth)
17617                     ) {
17618
17619                         if (*flagp & NEED_UTF8)
17620                             FAIL("panic: grok_bslash_N set NEED_UTF8");
17621
17622                         RETURN_FAIL_ON_RESTART_FLAGP(flagp);
17623
17624                         if (cp_count < 0) {
17625                             vFAIL("\\N in a character class must be a named character: \\N{...}");
17626                         }
17627                         else if (cp_count == 0) {
17628                             ckWARNreg(RExC_parse,
17629                               "Ignoring zero length \\N{} in character class");
17630                         }
17631                         else { /* cp_count > 1 */
17632                             assert(cp_count > 1);
17633                             if (! RExC_in_multi_char_class) {
17634                                 if ( ! allow_mutiple_chars
17635                                     || invert
17636                                     || range
17637                                     || *RExC_parse == '-')
17638                                 {
17639                                     if (strict) {
17640                                         RExC_parse--;
17641                                         vFAIL("\\N{} here is restricted to one character");
17642                                     }
17643                                     ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
17644                                     break; /* <value> contains the first code
17645                                               point. Drop out of the switch to
17646                                               process it */
17647                                 }
17648                                 else {
17649                                     SV * multi_char_N = newSVpvn(backslash_N_beg,
17650                                                  RExC_parse - backslash_N_beg);
17651                                     multi_char_matches
17652                                         = add_multi_match(multi_char_matches,
17653                                                           multi_char_N,
17654                                                           cp_count);
17655                                 }
17656                             }
17657                         } /* End of cp_count != 1 */
17658
17659                         /* This element should not be processed further in this
17660                          * class */
17661                         element_count--;
17662                         value = save_value;
17663                         prevvalue = save_prevvalue;
17664                         continue;   /* Back to top of loop to get next char */
17665                     }
17666
17667                     /* Here, is a single code point, and <value> contains it */
17668                     unicode_range = TRUE;   /* \N{} are Unicode */
17669                 }
17670                 break;
17671             case 'p':
17672             case 'P':
17673                 {
17674                 char *e;
17675
17676                 if (RExC_pm_flags & PMf_WILDCARD) {
17677                     RExC_parse++;
17678                     /* diag_listed_as: Use of %s is not allowed in Unicode
17679                        property wildcard subpatterns in regex; marked by <--
17680                        HERE in m/%s/ */
17681                     vFAIL3("Use of '\\%c%c' is not allowed in Unicode property"
17682                            " wildcard subpatterns", (char) value, *(RExC_parse - 1));
17683                 }
17684
17685                 /* \p means they want Unicode semantics */
17686                 REQUIRE_UNI_RULES(flagp, 0);
17687
17688                 if (RExC_parse >= RExC_end)
17689                     vFAIL2("Empty \\%c", (U8)value);
17690                 if (*RExC_parse == '{') {
17691                     const U8 c = (U8)value;
17692                     e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
17693                     if (!e) {
17694                         RExC_parse++;
17695                         vFAIL2("Missing right brace on \\%c{}", c);
17696                     }
17697
17698                     RExC_parse++;
17699
17700                     /* White space is allowed adjacent to the braces and after
17701                      * any '^', even when not under /x */
17702                     while (isSPACE(*RExC_parse)) {
17703                          RExC_parse++;
17704                     }
17705
17706                     if (UCHARAT(RExC_parse) == '^') {
17707
17708                         /* toggle.  (The rhs xor gets the single bit that
17709                          * differs between P and p; the other xor inverts just
17710                          * that bit) */
17711                         value ^= 'P' ^ 'p';
17712
17713                         RExC_parse++;
17714                         while (isSPACE(*RExC_parse)) {
17715                             RExC_parse++;
17716                         }
17717                     }
17718
17719                     if (e == RExC_parse)
17720                         vFAIL2("Empty \\%c{}", c);
17721
17722                     n = e - RExC_parse;
17723                     while (isSPACE(*(RExC_parse + n - 1)))
17724                         n--;
17725
17726                 }   /* The \p isn't immediately followed by a '{' */
17727                 else if (! isALPHA(*RExC_parse)) {
17728                     RExC_parse += (UTF)
17729                                   ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17730                                   : 1;
17731                     vFAIL2("Character following \\%c must be '{' or a "
17732                            "single-character Unicode property name",
17733                            (U8) value);
17734                 }
17735                 else {
17736                     e = RExC_parse;
17737                     n = 1;
17738                 }
17739                 {
17740                     char* name = RExC_parse;
17741
17742                     /* Any message returned about expanding the definition */
17743                     SV* msg = newSVpvs_flags("", SVs_TEMP);
17744
17745                     /* If set TRUE, the property is user-defined as opposed to
17746                      * official Unicode */
17747                     bool user_defined = FALSE;
17748                     AV * strings = NULL;
17749
17750                     SV * prop_definition = parse_uniprop_string(
17751                                             name, n, UTF, FOLD,
17752                                             FALSE, /* This is compile-time */
17753
17754                                             /* We can't defer this defn when
17755                                              * the full result is required in
17756                                              * this call */
17757                                             ! cBOOL(ret_invlist),
17758
17759                                             &strings,
17760                                             &user_defined,
17761                                             msg,
17762                                             0 /* Base level */
17763                                            );
17764                     if (SvCUR(msg)) {   /* Assumes any error causes a msg */
17765                         assert(prop_definition == NULL);
17766                         RExC_parse = e + 1;
17767                         if (SvUTF8(msg)) {  /* msg being UTF-8 makes the whole
17768                                                thing so, or else the display is
17769                                                mojibake */
17770                             RExC_utf8 = TRUE;
17771                         }
17772                         /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
17773                         vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
17774                                     SvCUR(msg), SvPVX(msg)));
17775                     }
17776
17777                     assert(prop_definition || strings);
17778
17779                     if (strings) {
17780                         if (ret_invlist) {
17781                             if (! prop_definition) {
17782                                 RExC_parse = e + 1;
17783                                 vFAIL("Unicode string properties are not implemented in (?[...])");
17784                             }
17785                             else {
17786                                 ckWARNreg(e + 1,
17787                                     "Using just the single character results"
17788                                     " returned by \\p{} in (?[...])");
17789                             }
17790                         }
17791                         else if (! RExC_in_multi_char_class) {
17792                             if (invert ^ (value == 'P')) {
17793                                 RExC_parse = e + 1;
17794                                 vFAIL("Inverting a character class which contains"
17795                                     " a multi-character sequence is illegal");
17796                             }
17797
17798                             /* For each multi-character string ... */
17799                             while (av_tindex(strings) >= 0) {
17800                                 /* ... Each entry is itself an array of code
17801                                 * points. */
17802                                 AV * this_string = (AV *) av_shift( strings);
17803                                 STRLEN cp_count = av_tindex(this_string) + 1;
17804                                 SV * final = newSV(cp_count * 4);
17805                                 SvPVCLEAR(final);
17806
17807                                 /* Create another string of sequences of \x{...} */
17808                                 while (av_tindex(this_string) >= 0) {
17809                                     SV * character = av_shift(this_string);
17810                                     UV cp = SvUV(character);
17811
17812                                     if (cp > 255) {
17813                                         REQUIRE_UTF8(flagp);
17814                                     }
17815                                     Perl_sv_catpvf(aTHX_ final, "\\x{%" UVXf "}",
17816                                                                         cp);
17817                                     SvREFCNT_dec_NN(character);
17818                                 }
17819                                 SvREFCNT_dec_NN(this_string);
17820
17821                                 /* And add that to the list of such things */
17822                                 multi_char_matches
17823                                             = add_multi_match(multi_char_matches,
17824                                                             final,
17825                                                             cp_count);
17826                             }
17827                         }
17828                         SvREFCNT_dec_NN(strings);
17829                     }
17830
17831                     if (! prop_definition) {    /* If we got only a string,
17832                                                    this iteration didn't really
17833                                                    find a character */
17834                         element_count--;
17835                     }
17836                     else if (! is_invlist(prop_definition)) {
17837
17838                         /* Here, the definition isn't known, so we have gotten
17839                          * returned a string that will be evaluated if and when
17840                          * encountered at runtime.  We add it to the list of
17841                          * such properties, along with whether it should be
17842                          * complemented or not */
17843                         if (value == 'P') {
17844                             sv_catpvs(listsv, "!");
17845                         }
17846                         else {
17847                             sv_catpvs(listsv, "+");
17848                         }
17849                         sv_catsv(listsv, prop_definition);
17850
17851                         has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
17852
17853                         /* We don't know yet what this matches, so have to flag
17854                          * it */
17855                         anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
17856                     }
17857                     else {
17858                         assert (prop_definition && is_invlist(prop_definition));
17859
17860                         /* Here we do have the complete property definition
17861                          *
17862                          * Temporary workaround for [perl #133136].  For this
17863                          * precise input that is in the .t that is failing,
17864                          * load utf8.pm, which is what the test wants, so that
17865                          * that .t passes */
17866                         if (     memEQs(RExC_start, e + 1 - RExC_start,
17867                                         "foo\\p{Alnum}")
17868                             && ! hv_common(GvHVn(PL_incgv),
17869                                            NULL,
17870                                            "utf8.pm", sizeof("utf8.pm") - 1,
17871                                            0, HV_FETCH_ISEXISTS, NULL, 0))
17872                         {
17873                             require_pv("utf8.pm");
17874                         }
17875
17876                         if (! user_defined &&
17877                             /* We warn on matching an above-Unicode code point
17878                              * if the match would return true, except don't
17879                              * warn for \p{All}, which has exactly one element
17880                              * = 0 */
17881                             (_invlist_contains_cp(prop_definition, 0x110000)
17882                                 && (! (_invlist_len(prop_definition) == 1
17883                                        && *invlist_array(prop_definition) == 0))))
17884                         {
17885                             warn_super = TRUE;
17886                         }
17887
17888                         /* Invert if asking for the complement */
17889                         if (value == 'P') {
17890                             _invlist_union_complement_2nd(properties,
17891                                                           prop_definition,
17892                                                           &properties);
17893                         }
17894                         else {
17895                             _invlist_union(properties, prop_definition, &properties);
17896                         }
17897                     }
17898                 }
17899
17900                 RExC_parse = e + 1;
17901                 namedclass = ANYOF_UNIPROP;  /* no official name, but it's
17902                                                 named */
17903                 }
17904                 break;
17905             case 'n':   value = '\n';                   break;
17906             case 'r':   value = '\r';                   break;
17907             case 't':   value = '\t';                   break;
17908             case 'f':   value = '\f';                   break;
17909             case 'b':   value = '\b';                   break;
17910             case 'e':   value = ESC_NATIVE;             break;
17911             case 'a':   value = '\a';                   break;
17912             case 'o':
17913                 RExC_parse--;   /* function expects to be pointed at the 'o' */
17914                 if (! grok_bslash_o(&RExC_parse,
17915                                             RExC_end,
17916                                             &value,
17917                                             &message,
17918                                             &packed_warn,
17919                                             strict,
17920                                             cBOOL(range), /* MAX_UV allowed for range
17921                                                       upper limit */
17922                                             UTF))
17923                 {
17924                     vFAIL(message);
17925                 }
17926                 else if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17927                     warn_non_literal_string(RExC_parse, packed_warn, message);
17928                 }
17929
17930                 if (value < 256) {
17931                     non_portable_endpoint++;
17932                 }
17933                 break;
17934             case 'x':
17935                 RExC_parse--;   /* function expects to be pointed at the 'x' */
17936                 if (!  grok_bslash_x(&RExC_parse,
17937                                             RExC_end,
17938                                             &value,
17939                                             &message,
17940                                             &packed_warn,
17941                                             strict,
17942                                             cBOOL(range), /* MAX_UV allowed for range
17943                                                       upper limit */
17944                                             UTF))
17945                 {
17946                     vFAIL(message);
17947                 }
17948                 else if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17949                     warn_non_literal_string(RExC_parse, packed_warn, message);
17950                 }
17951
17952                 if (value < 256) {
17953                     non_portable_endpoint++;
17954                 }
17955                 break;
17956             case 'c':
17957                 if (! grok_bslash_c(*RExC_parse, &grok_c_char, &message,
17958                                                                 &packed_warn))
17959                 {
17960                     /* going to die anyway; point to exact spot of
17961                         * failure */
17962                     RExC_parse += (UTF)
17963                                   ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17964                                   : 1;
17965                     vFAIL(message);
17966                 }
17967
17968                 value = grok_c_char;
17969                 RExC_parse++;
17970                 if (message && TO_OUTPUT_WARNINGS(RExC_parse)) {
17971                     warn_non_literal_string(RExC_parse, packed_warn, message);
17972                 }
17973
17974                 non_portable_endpoint++;
17975                 break;
17976             case '0': case '1': case '2': case '3': case '4':
17977             case '5': case '6': case '7':
17978                 {
17979                     /* Take 1-3 octal digits */
17980                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT
17981                               | PERL_SCAN_NOTIFY_ILLDIGIT;
17982                     numlen = (strict) ? 4 : 3;
17983                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17984                     RExC_parse += numlen;
17985                     if (numlen != 3) {
17986                         if (strict) {
17987                             RExC_parse += (UTF)
17988                                           ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17989                                           : 1;
17990                             vFAIL("Need exactly 3 octal digits");
17991                         }
17992                         else if (  (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
17993                                  && RExC_parse < RExC_end
17994                                  && isDIGIT(*RExC_parse)
17995                                  && ckWARN(WARN_REGEXP))
17996                         {
17997                             reg_warn_non_literal_string(
17998                                  RExC_parse + 1,
17999                                  form_alien_digit_msg(8, numlen, RExC_parse,
18000                                                         RExC_end, UTF, FALSE));
18001                         }
18002                     }
18003                     if (value < 256) {
18004                         non_portable_endpoint++;
18005                     }
18006                     break;
18007                 }
18008             default:
18009                 /* Allow \_ to not give an error */
18010                 if (isWORDCHAR(value) && value != '_') {
18011                     if (strict) {
18012                         vFAIL2("Unrecognized escape \\%c in character class",
18013                                (int)value);
18014                     }
18015                     else {
18016                         ckWARN2reg(RExC_parse,
18017                             "Unrecognized escape \\%c in character class passed through",
18018                             (int)value);
18019                     }
18020                 }
18021                 break;
18022             }   /* End of switch on char following backslash */
18023         } /* end of handling backslash escape sequences */
18024
18025         /* Here, we have the current token in 'value' */
18026
18027         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
18028             U8 classnum;
18029
18030             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
18031              * literal, as is the character that began the false range, i.e.
18032              * the 'a' in the examples */
18033             if (range) {
18034                 const int w = (RExC_parse >= rangebegin)
18035                                 ? RExC_parse - rangebegin
18036                                 : 0;
18037                 if (strict) {
18038                     vFAIL2utf8f(
18039                         "False [] range \"%" UTF8f "\"",
18040                         UTF8fARG(UTF, w, rangebegin));
18041                 }
18042                 else {
18043                     ckWARN2reg(RExC_parse,
18044                         "False [] range \"%" UTF8f "\"",
18045                         UTF8fARG(UTF, w, rangebegin));
18046                     cp_list = add_cp_to_invlist(cp_list, '-');
18047                     cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
18048                                                             prevvalue);
18049                 }
18050
18051                 range = 0; /* this was not a true range */
18052                 element_count += 2; /* So counts for three values */
18053             }
18054
18055             classnum = namedclass_to_classnum(namedclass);
18056
18057             if (LOC && namedclass < ANYOF_POSIXL_MAX
18058 #ifndef HAS_ISASCII
18059                 && classnum != _CC_ASCII
18060 #endif
18061             ) {
18062                 SV* scratch_list = NULL;
18063
18064                 /* What the Posix classes (like \w, [:space:]) match isn't
18065                  * generally knowable under locale until actual match time.  A
18066                  * special node is used for these which has extra space for a
18067                  * bitmap, with a bit reserved for each named class that is to
18068                  * be matched against.  (This isn't needed for \p{} and
18069                  * pseudo-classes, as they are not affected by locale, and
18070                  * hence are dealt with separately.)  However, if a named class
18071                  * and its complement are both present, then it matches
18072                  * everything, and there is no runtime dependency.  Odd numbers
18073                  * are the complements of the next lower number, so xor works.
18074                  * (Note that something like [\w\D] should match everything,
18075                  * because \d should be a proper subset of \w.  But rather than
18076                  * trust that the locale is well behaved, we leave this to
18077                  * runtime to sort out) */
18078                 if (POSIXL_TEST(posixl, namedclass ^ 1)) {
18079                     cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX);
18080                     POSIXL_ZERO(posixl);
18081                     has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY;
18082                     anyof_flags &= ~ANYOF_MATCHES_POSIXL;
18083                     continue;   /* We could ignore the rest of the class, but
18084                                    best to parse it for any errors */
18085                 }
18086                 else { /* Here, isn't the complement of any already parsed
18087                           class */
18088                     POSIXL_SET(posixl, namedclass);
18089                     has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18090                     anyof_flags |= ANYOF_MATCHES_POSIXL;
18091
18092                     /* The above-Latin1 characters are not subject to locale
18093                      * rules.  Just add them to the unconditionally-matched
18094                      * list */
18095
18096                     /* Get the list of the above-Latin1 code points this
18097                      * matches */
18098                     _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
18099                                             PL_XPosix_ptrs[classnum],
18100
18101                                             /* Odd numbers are complements,
18102                                              * like NDIGIT, NASCII, ... */
18103                                             namedclass % 2 != 0,
18104                                             &scratch_list);
18105                     /* Checking if 'cp_list' is NULL first saves an extra
18106                      * clone.  Its reference count will be decremented at the
18107                      * next union, etc, or if this is the only instance, at the
18108                      * end of the routine */
18109                     if (! cp_list) {
18110                         cp_list = scratch_list;
18111                     }
18112                     else {
18113                         _invlist_union(cp_list, scratch_list, &cp_list);
18114                         SvREFCNT_dec_NN(scratch_list);
18115                     }
18116                     continue;   /* Go get next character */
18117                 }
18118             }
18119             else {
18120
18121                 /* Here, is not /l, or is a POSIX class for which /l doesn't
18122                  * matter (or is a Unicode property, which is skipped here). */
18123                 if (namedclass >= ANYOF_POSIXL_MAX) {  /* If a special class */
18124                     if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
18125
18126                         /* Here, should be \h, \H, \v, or \V.  None of /d, /i
18127                          * nor /l make a difference in what these match,
18128                          * therefore we just add what they match to cp_list. */
18129                         if (classnum != _CC_VERTSPACE) {
18130                             assert(   namedclass == ANYOF_HORIZWS
18131                                    || namedclass == ANYOF_NHORIZWS);
18132
18133                             /* It turns out that \h is just a synonym for
18134                              * XPosixBlank */
18135                             classnum = _CC_BLANK;
18136                         }
18137
18138                         _invlist_union_maybe_complement_2nd(
18139                                 cp_list,
18140                                 PL_XPosix_ptrs[classnum],
18141                                 namedclass % 2 != 0,    /* Complement if odd
18142                                                           (NHORIZWS, NVERTWS)
18143                                                         */
18144                                 &cp_list);
18145                     }
18146                 }
18147                 else if (   AT_LEAST_UNI_SEMANTICS
18148                          || classnum == _CC_ASCII
18149                          || (DEPENDS_SEMANTICS && (   classnum == _CC_DIGIT
18150                                                    || classnum == _CC_XDIGIT)))
18151                 {
18152                     /* We usually have to worry about /d affecting what POSIX
18153                      * classes match, with special code needed because we won't
18154                      * know until runtime what all matches.  But there is no
18155                      * extra work needed under /u and /a; and [:ascii:] is
18156                      * unaffected by /d; and :digit: and :xdigit: don't have
18157                      * runtime differences under /d.  So we can special case
18158                      * these, and avoid some extra work below, and at runtime.
18159                      * */
18160                     _invlist_union_maybe_complement_2nd(
18161                                                      simple_posixes,
18162                                                       ((AT_LEAST_ASCII_RESTRICTED)
18163                                                        ? PL_Posix_ptrs[classnum]
18164                                                        : PL_XPosix_ptrs[classnum]),
18165                                                      namedclass % 2 != 0,
18166                                                      &simple_posixes);
18167                 }
18168                 else {  /* Garden variety class.  If is NUPPER, NALPHA, ...
18169                            complement and use nposixes */
18170                     SV** posixes_ptr = namedclass % 2 == 0
18171                                        ? &posixes
18172                                        : &nposixes;
18173                     _invlist_union_maybe_complement_2nd(
18174                                                      *posixes_ptr,
18175                                                      PL_XPosix_ptrs[classnum],
18176                                                      namedclass % 2 != 0,
18177                                                      posixes_ptr);
18178                 }
18179             }
18180         } /* end of namedclass \blah */
18181
18182         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
18183
18184         /* If 'range' is set, 'value' is the ending of a range--check its
18185          * validity.  (If value isn't a single code point in the case of a
18186          * range, we should have figured that out above in the code that
18187          * catches false ranges).  Later, we will handle each individual code
18188          * point in the range.  If 'range' isn't set, this could be the
18189          * beginning of a range, so check for that by looking ahead to see if
18190          * the next real character to be processed is the range indicator--the
18191          * minus sign */
18192
18193         if (range) {
18194 #ifdef EBCDIC
18195             /* For unicode ranges, we have to test that the Unicode as opposed
18196              * to the native values are not decreasing.  (Above 255, there is
18197              * no difference between native and Unicode) */
18198             if (unicode_range && prevvalue < 255 && value < 255) {
18199                 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
18200                     goto backwards_range;
18201                 }
18202             }
18203             else
18204 #endif
18205             if (prevvalue > value) /* b-a */ {
18206                 int w;
18207 #ifdef EBCDIC
18208               backwards_range:
18209 #endif
18210                 w = RExC_parse - rangebegin;
18211                 vFAIL2utf8f(
18212                     "Invalid [] range \"%" UTF8f "\"",
18213                     UTF8fARG(UTF, w, rangebegin));
18214                 NOT_REACHED; /* NOTREACHED */
18215             }
18216         }
18217         else {
18218             prevvalue = value; /* save the beginning of the potential range */
18219             if (! stop_at_1     /* Can't be a range if parsing just one thing */
18220                 && *RExC_parse == '-')
18221             {
18222                 char* next_char_ptr = RExC_parse + 1;
18223
18224                 /* Get the next real char after the '-' */
18225                 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
18226
18227                 /* If the '-' is at the end of the class (just before the ']',
18228                  * it is a literal minus; otherwise it is a range */
18229                 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
18230                     RExC_parse = next_char_ptr;
18231
18232                     /* a bad range like \w-, [:word:]- ? */
18233                     if (namedclass > OOB_NAMEDCLASS) {
18234                         if (strict || ckWARN(WARN_REGEXP)) {
18235                             const int w = RExC_parse >= rangebegin
18236                                           ?  RExC_parse - rangebegin
18237                                           : 0;
18238                             if (strict) {
18239                                 vFAIL4("False [] range \"%*.*s\"",
18240                                     w, w, rangebegin);
18241                             }
18242                             else {
18243                                 vWARN4(RExC_parse,
18244                                     "False [] range \"%*.*s\"",
18245                                     w, w, rangebegin);
18246                             }
18247                         }
18248                         cp_list = add_cp_to_invlist(cp_list, '-');
18249                         element_count++;
18250                     } else
18251                         range = 1;      /* yeah, it's a range! */
18252                     continue;   /* but do it the next time */
18253                 }
18254             }
18255         }
18256
18257         if (namedclass > OOB_NAMEDCLASS) {
18258             continue;
18259         }
18260
18261         /* Here, we have a single value this time through the loop, and
18262          * <prevvalue> is the beginning of the range, if any; or <value> if
18263          * not. */
18264
18265         /* non-Latin1 code point implies unicode semantics. */
18266         if (value > 255) {
18267             if (value > MAX_LEGAL_CP && (   value != UV_MAX
18268                                          || prevvalue > MAX_LEGAL_CP))
18269             {
18270                 vFAIL(form_cp_too_large_msg(16, NULL, 0, value));
18271             }
18272             REQUIRE_UNI_RULES(flagp, 0);
18273             if (  ! silence_non_portable
18274                 &&  UNICODE_IS_PERL_EXTENDED(value)
18275                 &&  TO_OUTPUT_WARNINGS(RExC_parse))
18276             {
18277                 ckWARN2_non_literal_string(RExC_parse,
18278                                            packWARN(WARN_PORTABLE),
18279                                            PL_extended_cp_format,
18280                                            value);
18281             }
18282         }
18283
18284         /* Ready to process either the single value, or the completed range.
18285          * For single-valued non-inverted ranges, we consider the possibility
18286          * of multi-char folds.  (We made a conscious decision to not do this
18287          * for the other cases because it can often lead to non-intuitive
18288          * results.  For example, you have the peculiar case that:
18289          *  "s s" =~ /^[^\xDF]+$/i => Y
18290          *  "ss"  =~ /^[^\xDF]+$/i => N
18291          *
18292          * See [perl #89750] */
18293         if (FOLD && allow_mutiple_chars && value == prevvalue) {
18294             if (    value == LATIN_SMALL_LETTER_SHARP_S
18295                 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
18296                                                         value)))
18297             {
18298                 /* Here <value> is indeed a multi-char fold.  Get what it is */
18299
18300                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18301                 STRLEN foldlen;
18302
18303                 UV folded = _to_uni_fold_flags(
18304                                 value,
18305                                 foldbuf,
18306                                 &foldlen,
18307                                 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
18308                                                    ? FOLD_FLAGS_NOMIX_ASCII
18309                                                    : 0)
18310                                 );
18311
18312                 /* Here, <folded> should be the first character of the
18313                  * multi-char fold of <value>, with <foldbuf> containing the
18314                  * whole thing.  But, if this fold is not allowed (because of
18315                  * the flags), <fold> will be the same as <value>, and should
18316                  * be processed like any other character, so skip the special
18317                  * handling */
18318                 if (folded != value) {
18319
18320                     /* Skip if we are recursed, currently parsing the class
18321                      * again.  Otherwise add this character to the list of
18322                      * multi-char folds. */
18323                     if (! RExC_in_multi_char_class) {
18324                         STRLEN cp_count = utf8_length(foldbuf,
18325                                                       foldbuf + foldlen);
18326                         SV* multi_fold = sv_2mortal(newSVpvs(""));
18327
18328                         Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
18329
18330                         multi_char_matches
18331                                         = add_multi_match(multi_char_matches,
18332                                                           multi_fold,
18333                                                           cp_count);
18334
18335                     }
18336
18337                     /* This element should not be processed further in this
18338                      * class */
18339                     element_count--;
18340                     value = save_value;
18341                     prevvalue = save_prevvalue;
18342                     continue;
18343                 }
18344             }
18345         }
18346
18347         if (strict && ckWARN(WARN_REGEXP)) {
18348             if (range) {
18349
18350                 /* If the range starts above 255, everything is portable and
18351                  * likely to be so for any forseeable character set, so don't
18352                  * warn. */
18353                 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
18354                     vWARN(RExC_parse, "Both or neither range ends should be Unicode");
18355                 }
18356                 else if (prevvalue != value) {
18357
18358                     /* Under strict, ranges that stop and/or end in an ASCII
18359                      * printable should have each end point be a portable value
18360                      * for it (preferably like 'A', but we don't warn if it is
18361                      * a (portable) Unicode name or code point), and the range
18362                      * must be all digits or all letters of the same case.
18363                      * Otherwise, the range is non-portable and unclear as to
18364                      * what it contains */
18365                     if (             (isPRINT_A(prevvalue) || isPRINT_A(value))
18366                         && (          non_portable_endpoint
18367                             || ! (   (isDIGIT_A(prevvalue) && isDIGIT_A(value))
18368                                   || (isLOWER_A(prevvalue) && isLOWER_A(value))
18369                                   || (isUPPER_A(prevvalue) && isUPPER_A(value))
18370                     ))) {
18371                         vWARN(RExC_parse, "Ranges of ASCII printables should"
18372                                           " be some subset of \"0-9\","
18373                                           " \"A-Z\", or \"a-z\"");
18374                     }
18375                     else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
18376                         SSize_t index_start;
18377                         SSize_t index_final;
18378
18379                         /* But the nature of Unicode and languages mean we
18380                          * can't do the same checks for above-ASCII ranges,
18381                          * except in the case of digit ones.  These should
18382                          * contain only digits from the same group of 10.  The
18383                          * ASCII case is handled just above.  Hence here, the
18384                          * range could be a range of digits.  First some
18385                          * unlikely special cases.  Grandfather in that a range
18386                          * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
18387                          * if its starting value is one of the 10 digits prior
18388                          * to it.  This is because it is an alternate way of
18389                          * writing 19D1, and some people may expect it to be in
18390                          * that group.  But it is bad, because it won't give
18391                          * the expected results.  In Unicode 5.2 it was
18392                          * considered to be in that group (of 11, hence), but
18393                          * this was fixed in the next version */
18394
18395                         if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
18396                             goto warn_bad_digit_range;
18397                         }
18398                         else if (UNLIKELY(   prevvalue >= 0x1D7CE
18399                                           &&     value <= 0x1D7FF))
18400                         {
18401                             /* This is the only other case currently in Unicode
18402                              * where the algorithm below fails.  The code
18403                              * points just above are the end points of a single
18404                              * range containing only decimal digits.  It is 5
18405                              * different series of 0-9.  All other ranges of
18406                              * digits currently in Unicode are just a single
18407                              * series.  (And mktables will notify us if a later
18408                              * Unicode version breaks this.)
18409                              *
18410                              * If the range being checked is at most 9 long,
18411                              * and the digit values represented are in
18412                              * numerical order, they are from the same series.
18413                              * */
18414                             if (         value - prevvalue > 9
18415                                 ||    (((    value - 0x1D7CE) % 10)
18416                                      <= (prevvalue - 0x1D7CE) % 10))
18417                             {
18418                                 goto warn_bad_digit_range;
18419                             }
18420                         }
18421                         else {
18422
18423                             /* For all other ranges of digits in Unicode, the
18424                              * algorithm is just to check if both end points
18425                              * are in the same series, which is the same range.
18426                              * */
18427                             index_start = _invlist_search(
18428                                                     PL_XPosix_ptrs[_CC_DIGIT],
18429                                                     prevvalue);
18430
18431                             /* Warn if the range starts and ends with a digit,
18432                              * and they are not in the same group of 10. */
18433                             if (   index_start >= 0
18434                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
18435                                 && (index_final =
18436                                     _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
18437                                                     value)) != index_start
18438                                 && index_final >= 0
18439                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
18440                             {
18441                               warn_bad_digit_range:
18442                                 vWARN(RExC_parse, "Ranges of digits should be"
18443                                                   " from the same group of"
18444                                                   " 10");
18445                             }
18446                         }
18447                     }
18448                 }
18449             }
18450             if ((! range || prevvalue == value) && non_portable_endpoint) {
18451                 if (isPRINT_A(value)) {
18452                     char literal[3];
18453                     unsigned d = 0;
18454                     if (isBACKSLASHED_PUNCT(value)) {
18455                         literal[d++] = '\\';
18456                     }
18457                     literal[d++] = (char) value;
18458                     literal[d++] = '\0';
18459
18460                     vWARN4(RExC_parse,
18461                            "\"%.*s\" is more clearly written simply as \"%s\"",
18462                            (int) (RExC_parse - rangebegin),
18463                            rangebegin,
18464                            literal
18465                         );
18466                 }
18467                 else if (isMNEMONIC_CNTRL(value)) {
18468                     vWARN4(RExC_parse,
18469                            "\"%.*s\" is more clearly written simply as \"%s\"",
18470                            (int) (RExC_parse - rangebegin),
18471                            rangebegin,
18472                            cntrl_to_mnemonic((U8) value)
18473                         );
18474                 }
18475             }
18476         }
18477
18478         /* Deal with this element of the class */
18479
18480 #ifndef EBCDIC
18481         cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18482                                                     prevvalue, value);
18483 #else
18484         /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
18485          * that don't require special handling, we can just add the range like
18486          * we do for ASCII platforms */
18487         if ((UNLIKELY(prevvalue == 0) && value >= 255)
18488             || ! (prevvalue < 256
18489                     && (unicode_range
18490                         || (! non_portable_endpoint
18491                             && ((isLOWER_A(prevvalue) && isLOWER_A(value))
18492                                 || (isUPPER_A(prevvalue)
18493                                     && isUPPER_A(value)))))))
18494         {
18495             cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18496                                                         prevvalue, value);
18497         }
18498         else {
18499             /* Here, requires special handling.  This can be because it is a
18500              * range whose code points are considered to be Unicode, and so
18501              * must be individually translated into native, or because its a
18502              * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
18503              * EBCDIC, but we have defined them to include only the "expected"
18504              * upper or lower case ASCII alphabetics.  Subranges above 255 are
18505              * the same in native and Unicode, so can be added as a range */
18506             U8 start = NATIVE_TO_LATIN1(prevvalue);
18507             unsigned j;
18508             U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
18509             for (j = start; j <= end; j++) {
18510                 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
18511             }
18512             if (value > 255) {
18513                 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18514                                                             256, value);
18515             }
18516         }
18517 #endif
18518
18519         range = 0; /* this range (if it was one) is done now */
18520     } /* End of loop through all the text within the brackets */
18521
18522     if (   posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
18523         output_posix_warnings(pRExC_state, posix_warnings);
18524     }
18525
18526     /* If anything in the class expands to more than one character, we have to
18527      * deal with them by building up a substitute parse string, and recursively
18528      * calling reg() on it, instead of proceeding */
18529     if (multi_char_matches) {
18530         SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
18531         I32 cp_count;
18532         STRLEN len;
18533         char *save_end = RExC_end;
18534         char *save_parse = RExC_parse;
18535         char *save_start = RExC_start;
18536         Size_t constructed_prefix_len = 0; /* This gives the length of the
18537                                               constructed portion of the
18538                                               substitute parse. */
18539         bool first_time = TRUE;     /* First multi-char occurrence doesn't get
18540                                        a "|" */
18541         I32 reg_flags;
18542
18543         assert(! invert);
18544         /* Only one level of recursion allowed */
18545         assert(RExC_copy_start_in_constructed == RExC_precomp);
18546
18547 #if 0   /* Have decided not to deal with multi-char folds in inverted classes,
18548            because too confusing */
18549         if (invert) {
18550             sv_catpvs(substitute_parse, "(?:");
18551         }
18552 #endif
18553
18554         /* Look at the longest strings first */
18555         for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
18556                         cp_count > 0;
18557                         cp_count--)
18558         {
18559
18560             if (av_exists(multi_char_matches, cp_count)) {
18561                 AV** this_array_ptr;
18562                 SV* this_sequence;
18563
18564                 this_array_ptr = (AV**) av_fetch(multi_char_matches,
18565                                                  cp_count, FALSE);
18566                 while ((this_sequence = av_pop(*this_array_ptr)) !=
18567                                                                 &PL_sv_undef)
18568                 {
18569                     if (! first_time) {
18570                         sv_catpvs(substitute_parse, "|");
18571                     }
18572                     first_time = FALSE;
18573
18574                     sv_catpv(substitute_parse, SvPVX(this_sequence));
18575                 }
18576             }
18577         }
18578
18579         /* If the character class contains anything else besides these
18580          * multi-character strings, have to include it in recursive parsing */
18581         if (element_count) {
18582             bool has_l_bracket = orig_parse > RExC_start && *(orig_parse - 1) == '[';
18583
18584             sv_catpvs(substitute_parse, "|");
18585             if (has_l_bracket) {    /* Add an [ if the original had one */
18586                 sv_catpvs(substitute_parse, "[");
18587             }
18588             constructed_prefix_len = SvCUR(substitute_parse);
18589             sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
18590
18591             /* Put in a closing ']' to match any opening one, but not if going
18592              * off the end, as otherwise we are adding something that really
18593              * isn't there */
18594             if (has_l_bracket && RExC_parse < RExC_end) {
18595                 sv_catpvs(substitute_parse, "]");
18596             }
18597         }
18598
18599         sv_catpvs(substitute_parse, ")");
18600 #if 0
18601         if (invert) {
18602             /* This is a way to get the parse to skip forward a whole named
18603              * sequence instead of matching the 2nd character when it fails the
18604              * first */
18605             sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
18606         }
18607 #endif
18608
18609         /* Set up the data structure so that any errors will be properly
18610          * reported.  See the comments at the definition of
18611          * REPORT_LOCATION_ARGS for details */
18612         RExC_copy_start_in_input = (char *) orig_parse;
18613         RExC_start = RExC_parse = SvPV(substitute_parse, len);
18614         RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
18615         RExC_end = RExC_parse + len;
18616         RExC_in_multi_char_class = 1;
18617
18618         ret = reg(pRExC_state, 1, &reg_flags, depth+1);
18619
18620         *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
18621
18622         /* And restore so can parse the rest of the pattern */
18623         RExC_parse = save_parse;
18624         RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
18625         RExC_end = save_end;
18626         RExC_in_multi_char_class = 0;
18627         SvREFCNT_dec_NN(multi_char_matches);
18628         return ret;
18629     }
18630
18631     /* If folding, we calculate all characters that could fold to or from the
18632      * ones already on the list */
18633     if (cp_foldable_list) {
18634         if (FOLD) {
18635             UV start, end;      /* End points of code point ranges */
18636
18637             SV* fold_intersection = NULL;
18638             SV** use_list;
18639
18640             /* Our calculated list will be for Unicode rules.  For locale
18641              * matching, we have to keep a separate list that is consulted at
18642              * runtime only when the locale indicates Unicode rules (and we
18643              * don't include potential matches in the ASCII/Latin1 range, as
18644              * any code point could fold to any other, based on the run-time
18645              * locale).   For non-locale, we just use the general list */
18646             if (LOC) {
18647                 use_list = &only_utf8_locale_list;
18648             }
18649             else {
18650                 use_list = &cp_list;
18651             }
18652
18653             /* Only the characters in this class that participate in folds need
18654              * be checked.  Get the intersection of this class and all the
18655              * possible characters that are foldable.  This can quickly narrow
18656              * down a large class */
18657             _invlist_intersection(PL_in_some_fold, cp_foldable_list,
18658                                   &fold_intersection);
18659
18660             /* Now look at the foldable characters in this class individually */
18661             invlist_iterinit(fold_intersection);
18662             while (invlist_iternext(fold_intersection, &start, &end)) {
18663                 UV j;
18664                 UV folded;
18665
18666                 /* Look at every character in the range */
18667                 for (j = start; j <= end; j++) {
18668                     U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18669                     STRLEN foldlen;
18670                     unsigned int k;
18671                     Size_t folds_count;
18672                     U32 first_fold;
18673                     const U32 * remaining_folds;
18674
18675                     if (j < 256) {
18676
18677                         /* Under /l, we don't know what code points below 256
18678                          * fold to, except we do know the MICRO SIGN folds to
18679                          * an above-255 character if the locale is UTF-8, so we
18680                          * add it to the special list (in *use_list)  Otherwise
18681                          * we know now what things can match, though some folds
18682                          * are valid under /d only if the target is UTF-8.
18683                          * Those go in a separate list */
18684                         if (      IS_IN_SOME_FOLD_L1(j)
18685                             && ! (LOC && j != MICRO_SIGN))
18686                         {
18687
18688                             /* ASCII is always matched; non-ASCII is matched
18689                              * only under Unicode rules (which could happen
18690                              * under /l if the locale is a UTF-8 one */
18691                             if (isASCII(j) || ! DEPENDS_SEMANTICS) {
18692                                 *use_list = add_cp_to_invlist(*use_list,
18693                                                             PL_fold_latin1[j]);
18694                             }
18695                             else if (j != PL_fold_latin1[j]) {
18696                                 upper_latin1_only_utf8_matches
18697                                         = add_cp_to_invlist(
18698                                                 upper_latin1_only_utf8_matches,
18699                                                 PL_fold_latin1[j]);
18700                             }
18701                         }
18702
18703                         if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
18704                             && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
18705                         {
18706                             add_above_Latin1_folds(pRExC_state,
18707                                                    (U8) j,
18708                                                    use_list);
18709                         }
18710                         continue;
18711                     }
18712
18713                     /* Here is an above Latin1 character.  We don't have the
18714                      * rules hard-coded for it.  First, get its fold.  This is
18715                      * the simple fold, as the multi-character folds have been
18716                      * handled earlier and separated out */
18717                     folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
18718                                                         (ASCII_FOLD_RESTRICTED)
18719                                                         ? FOLD_FLAGS_NOMIX_ASCII
18720                                                         : 0);
18721
18722                     /* Single character fold of above Latin1.  Add everything
18723                      * in its fold closure to the list that this node should
18724                      * match. */
18725                     folds_count = _inverse_folds(folded, &first_fold,
18726                                                     &remaining_folds);
18727                     for (k = 0; k <= folds_count; k++) {
18728                         UV c = (k == 0)     /* First time through use itself */
18729                                 ? folded
18730                                 : (k == 1)  /* 2nd time use, the first fold */
18731                                    ? first_fold
18732
18733                                      /* Then the remaining ones */
18734                                    : remaining_folds[k-2];
18735
18736                         /* /aa doesn't allow folds between ASCII and non- */
18737                         if ((   ASCII_FOLD_RESTRICTED
18738                             && (isASCII(c) != isASCII(j))))
18739                         {
18740                             continue;
18741                         }
18742
18743                         /* Folds under /l which cross the 255/256 boundary are
18744                          * added to a separate list.  (These are valid only
18745                          * when the locale is UTF-8.) */
18746                         if (c < 256 && LOC) {
18747                             *use_list = add_cp_to_invlist(*use_list, c);
18748                             continue;
18749                         }
18750
18751                         if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
18752                         {
18753                             cp_list = add_cp_to_invlist(cp_list, c);
18754                         }
18755                         else {
18756                             /* Similarly folds involving non-ascii Latin1
18757                              * characters under /d are added to their list */
18758                             upper_latin1_only_utf8_matches
18759                                     = add_cp_to_invlist(
18760                                                 upper_latin1_only_utf8_matches,
18761                                                 c);
18762                         }
18763                     }
18764                 }
18765             }
18766             SvREFCNT_dec_NN(fold_intersection);
18767         }
18768
18769         /* Now that we have finished adding all the folds, there is no reason
18770          * to keep the foldable list separate */
18771         _invlist_union(cp_list, cp_foldable_list, &cp_list);
18772         SvREFCNT_dec_NN(cp_foldable_list);
18773     }
18774
18775     /* And combine the result (if any) with any inversion lists from posix
18776      * classes.  The lists are kept separate up to now because we don't want to
18777      * fold the classes */
18778     if (simple_posixes) {   /* These are the classes known to be unaffected by
18779                                /a, /aa, and /d */
18780         if (cp_list) {
18781             _invlist_union(cp_list, simple_posixes, &cp_list);
18782             SvREFCNT_dec_NN(simple_posixes);
18783         }
18784         else {
18785             cp_list = simple_posixes;
18786         }
18787     }
18788     if (posixes || nposixes) {
18789         if (! DEPENDS_SEMANTICS) {
18790
18791             /* For everything but /d, we can just add the current 'posixes' and
18792              * 'nposixes' to the main list */
18793             if (posixes) {
18794                 if (cp_list) {
18795                     _invlist_union(cp_list, posixes, &cp_list);
18796                     SvREFCNT_dec_NN(posixes);
18797                 }
18798                 else {
18799                     cp_list = posixes;
18800                 }
18801             }
18802             if (nposixes) {
18803                 if (cp_list) {
18804                     _invlist_union(cp_list, nposixes, &cp_list);
18805                     SvREFCNT_dec_NN(nposixes);
18806                 }
18807                 else {
18808                     cp_list = nposixes;
18809                 }
18810             }
18811         }
18812         else {
18813             /* Under /d, things like \w match upper Latin1 characters only if
18814              * the target string is in UTF-8.  But things like \W match all the
18815              * upper Latin1 characters if the target string is not in UTF-8.
18816              *
18817              * Handle the case with something like \W separately */
18818             if (nposixes) {
18819                 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
18820
18821                 /* A complemented posix class matches all upper Latin1
18822                  * characters if not in UTF-8.  And it matches just certain
18823                  * ones when in UTF-8.  That means those certain ones are
18824                  * matched regardless, so can just be added to the
18825                  * unconditional list */
18826                 if (cp_list) {
18827                     _invlist_union(cp_list, nposixes, &cp_list);
18828                     SvREFCNT_dec_NN(nposixes);
18829                     nposixes = NULL;
18830                 }
18831                 else {
18832                     cp_list = nposixes;
18833                 }
18834
18835                 /* Likewise for 'posixes' */
18836                 _invlist_union(posixes, cp_list, &cp_list);
18837                 SvREFCNT_dec(posixes);
18838
18839                 /* Likewise for anything else in the range that matched only
18840                  * under UTF-8 */
18841                 if (upper_latin1_only_utf8_matches) {
18842                     _invlist_union(cp_list,
18843                                    upper_latin1_only_utf8_matches,
18844                                    &cp_list);
18845                     SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18846                     upper_latin1_only_utf8_matches = NULL;
18847                 }
18848
18849                 /* If we don't match all the upper Latin1 characters regardless
18850                  * of UTF-8ness, we have to set a flag to match the rest when
18851                  * not in UTF-8 */
18852                 _invlist_subtract(only_non_utf8_list, cp_list,
18853                                   &only_non_utf8_list);
18854                 if (_invlist_len(only_non_utf8_list) != 0) {
18855                     anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18856                 }
18857                 SvREFCNT_dec_NN(only_non_utf8_list);
18858             }
18859             else {
18860                 /* Here there were no complemented posix classes.  That means
18861                  * the upper Latin1 characters in 'posixes' match only when the
18862                  * target string is in UTF-8.  So we have to add them to the
18863                  * list of those types of code points, while adding the
18864                  * remainder to the unconditional list.
18865                  *
18866                  * First calculate what they are */
18867                 SV* nonascii_but_latin1_properties = NULL;
18868                 _invlist_intersection(posixes, PL_UpperLatin1,
18869                                       &nonascii_but_latin1_properties);
18870
18871                 /* And add them to the final list of such characters. */
18872                 _invlist_union(upper_latin1_only_utf8_matches,
18873                                nonascii_but_latin1_properties,
18874                                &upper_latin1_only_utf8_matches);
18875
18876                 /* Remove them from what now becomes the unconditional list */
18877                 _invlist_subtract(posixes, nonascii_but_latin1_properties,
18878                                   &posixes);
18879
18880                 /* And add those unconditional ones to the final list */
18881                 if (cp_list) {
18882                     _invlist_union(cp_list, posixes, &cp_list);
18883                     SvREFCNT_dec_NN(posixes);
18884                     posixes = NULL;
18885                 }
18886                 else {
18887                     cp_list = posixes;
18888                 }
18889
18890                 SvREFCNT_dec(nonascii_but_latin1_properties);
18891
18892                 /* Get rid of any characters from the conditional list that we
18893                  * now know are matched unconditionally, which may make that
18894                  * list empty */
18895                 _invlist_subtract(upper_latin1_only_utf8_matches,
18896                                   cp_list,
18897                                   &upper_latin1_only_utf8_matches);
18898                 if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
18899                     SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18900                     upper_latin1_only_utf8_matches = NULL;
18901                 }
18902             }
18903         }
18904     }
18905
18906     /* And combine the result (if any) with any inversion list from properties.
18907      * The lists are kept separate up to now so that we can distinguish the two
18908      * in regards to matching above-Unicode.  A run-time warning is generated
18909      * if a Unicode property is matched against a non-Unicode code point. But,
18910      * we allow user-defined properties to match anything, without any warning,
18911      * and we also suppress the warning if there is a portion of the character
18912      * class that isn't a Unicode property, and which matches above Unicode, \W
18913      * or [\x{110000}] for example.
18914      * (Note that in this case, unlike the Posix one above, there is no
18915      * <upper_latin1_only_utf8_matches>, because having a Unicode property
18916      * forces Unicode semantics */
18917     if (properties) {
18918         if (cp_list) {
18919
18920             /* If it matters to the final outcome, see if a non-property
18921              * component of the class matches above Unicode.  If so, the
18922              * warning gets suppressed.  This is true even if just a single
18923              * such code point is specified, as, though not strictly correct if
18924              * another such code point is matched against, the fact that they
18925              * are using above-Unicode code points indicates they should know
18926              * the issues involved */
18927             if (warn_super) {
18928                 warn_super = ! (invert
18929                                ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
18930             }
18931
18932             _invlist_union(properties, cp_list, &cp_list);
18933             SvREFCNT_dec_NN(properties);
18934         }
18935         else {
18936             cp_list = properties;
18937         }
18938
18939         if (warn_super) {
18940             anyof_flags
18941              |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18942
18943             /* Because an ANYOF node is the only one that warns, this node
18944              * can't be optimized into something else */
18945             optimizable = FALSE;
18946         }
18947     }
18948
18949     /* Here, we have calculated what code points should be in the character
18950      * class.
18951      *
18952      * Now we can see about various optimizations.  Fold calculation (which we
18953      * did above) needs to take place before inversion.  Otherwise /[^k]/i
18954      * would invert to include K, which under /i would match k, which it
18955      * shouldn't.  Therefore we can't invert folded locale now, as it won't be
18956      * folded until runtime */
18957
18958     /* If we didn't do folding, it's because some information isn't available
18959      * until runtime; set the run-time fold flag for these  We know to set the
18960      * flag if we have a non-NULL list for UTF-8 locales, or the class matches
18961      * at least one 0-255 range code point */
18962     if (LOC && FOLD) {
18963
18964         /* Some things on the list might be unconditionally included because of
18965          * other components.  Remove them, and clean up the list if it goes to
18966          * 0 elements */
18967         if (only_utf8_locale_list && cp_list) {
18968             _invlist_subtract(only_utf8_locale_list, cp_list,
18969                               &only_utf8_locale_list);
18970
18971             if (_invlist_len(only_utf8_locale_list) == 0) {
18972                 SvREFCNT_dec_NN(only_utf8_locale_list);
18973                 only_utf8_locale_list = NULL;
18974             }
18975         }
18976         if (    only_utf8_locale_list
18977             || (cp_list && (   _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
18978                             || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
18979         {
18980             has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18981             anyof_flags
18982                  |= ANYOFL_FOLD
18983                  |  ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18984         }
18985         else if (cp_list && invlist_lowest(cp_list) < 256) {
18986             /* If nothing is below 256, has no locale dependency; otherwise it
18987              * does */
18988             anyof_flags |= ANYOFL_FOLD;
18989             has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18990         }
18991     }
18992     else if (   DEPENDS_SEMANTICS
18993              && (    upper_latin1_only_utf8_matches
18994                  || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18995     {
18996         RExC_seen_d_op = TRUE;
18997         has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
18998     }
18999
19000     /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
19001      * compile time. */
19002     if (     cp_list
19003         &&   invert
19004         && ! has_runtime_dependency)
19005     {
19006         _invlist_invert(cp_list);
19007
19008         /* Clear the invert flag since have just done it here */
19009         invert = FALSE;
19010     }
19011
19012     /* All possible optimizations below still have these characteristics.
19013      * (Multi-char folds aren't SIMPLE, but they don't get this far in this
19014      * routine) */
19015     *flagp |= HASWIDTH|SIMPLE;
19016
19017     if (ret_invlist) {
19018         *ret_invlist = cp_list;
19019
19020         return (cp_list) ? RExC_emit : 0;
19021     }
19022
19023     if (anyof_flags & ANYOF_LOCALE_FLAGS) {
19024         RExC_contains_locale = 1;
19025     }
19026
19027     /* Some character classes are equivalent to other nodes.  Such nodes take
19028      * up less room, and some nodes require fewer operations to execute, than
19029      * ANYOF nodes.  EXACTish nodes may be joinable with adjacent nodes to
19030      * improve efficiency. */
19031
19032     if (optimizable) {
19033         PERL_UINT_FAST8_T i;
19034         UV partial_cp_count = 0;
19035         UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
19036         UV   end[MAX_FOLD_FROMS+1] = { 0 };
19037         bool single_range = FALSE;
19038
19039         if (cp_list) { /* Count the code points in enough ranges that we would
19040                           see all the ones possible in any fold in this version
19041                           of Unicode */
19042
19043             invlist_iterinit(cp_list);
19044             for (i = 0; i <= MAX_FOLD_FROMS; i++) {
19045                 if (! invlist_iternext(cp_list, &start[i], &end[i])) {
19046                     break;
19047                 }
19048                 partial_cp_count += end[i] - start[i] + 1;
19049             }
19050
19051             if (i == 1) {
19052                 single_range = TRUE;
19053             }
19054             invlist_iterfinish(cp_list);
19055         }
19056
19057         /* If we know at compile time that this matches every possible code
19058          * point, any run-time dependencies don't matter */
19059         if (start[0] == 0 && end[0] == UV_MAX) {
19060             if (invert) {
19061                 ret = reganode(pRExC_state, OPFAIL, 0);
19062             }
19063             else {
19064                 ret = reg_node(pRExC_state, SANY);
19065                 MARK_NAUGHTY(1);
19066             }
19067             goto not_anyof;
19068         }
19069
19070         /* Similarly, for /l posix classes, if both a class and its
19071          * complement match, any run-time dependencies don't matter */
19072         if (posixl) {
19073             for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX;
19074                                                         namedclass += 2)
19075             {
19076                 if (   POSIXL_TEST(posixl, namedclass)      /* class */
19077                     && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
19078                 {
19079                     if (invert) {
19080                         ret = reganode(pRExC_state, OPFAIL, 0);
19081                     }
19082                     else {
19083                         ret = reg_node(pRExC_state, SANY);
19084                         MARK_NAUGHTY(1);
19085                     }
19086                     goto not_anyof;
19087                 }
19088             }
19089
19090             /* For well-behaved locales, some classes are subsets of others,
19091              * so complementing the subset and including the non-complemented
19092              * superset should match everything, like [\D[:alnum:]], and
19093              * [[:^alpha:][:alnum:]], but some implementations of locales are
19094              * buggy, and khw thinks its a bad idea to have optimization change
19095              * behavior, even if it avoids an OS bug in a given case */
19096
19097 #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
19098
19099             /* If is a single posix /l class, can optimize to just that op.
19100              * Such a node will not match anything in the Latin1 range, as that
19101              * is not determinable until runtime, but will match whatever the
19102              * class does outside that range.  (Note that some classes won't
19103              * match anything outside the range, like [:ascii:]) */
19104             if (    isSINGLE_BIT_SET(posixl)
19105                 && (partial_cp_count == 0 || start[0] > 255))
19106             {
19107                 U8 classnum;
19108                 SV * class_above_latin1 = NULL;
19109                 bool already_inverted;
19110                 bool are_equivalent;
19111
19112                 /* Compute which bit is set, which is the same thing as, e.g.,
19113                  * ANYOF_CNTRL.  From
19114                  * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
19115                  * */
19116                 static const int MultiplyDeBruijnBitPosition2[32] =
19117                     {
19118                     0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
19119                     31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
19120                     };
19121
19122                 namedclass = MultiplyDeBruijnBitPosition2[(posixl
19123                                                           * 0x077CB531U) >> 27];
19124                 classnum = namedclass_to_classnum(namedclass);
19125
19126                 /* The named classes are such that the inverted number is one
19127                  * larger than the non-inverted one */
19128                 already_inverted = namedclass
19129                                  - classnum_to_namedclass(classnum);
19130
19131                 /* Create an inversion list of the official property, inverted
19132                  * if the constructed node list is inverted, and restricted to
19133                  * only the above latin1 code points, which are the only ones
19134                  * known at compile time */
19135                 _invlist_intersection_maybe_complement_2nd(
19136                                                     PL_AboveLatin1,
19137                                                     PL_XPosix_ptrs[classnum],
19138                                                     already_inverted,
19139                                                     &class_above_latin1);
19140                 are_equivalent = _invlistEQ(class_above_latin1, cp_list,
19141                                                                         FALSE);
19142                 SvREFCNT_dec_NN(class_above_latin1);
19143
19144                 if (are_equivalent) {
19145
19146                     /* Resolve the run-time inversion flag with this possibly
19147                      * inverted class */
19148                     invert = invert ^ already_inverted;
19149
19150                     ret = reg_node(pRExC_state,
19151                                    POSIXL + invert * (NPOSIXL - POSIXL));
19152                     FLAGS(REGNODE_p(ret)) = classnum;
19153                     goto not_anyof;
19154                 }
19155             }
19156         }
19157
19158         /* khw can't think of any other possible transformation involving
19159          * these. */
19160         if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
19161             goto is_anyof;
19162         }
19163
19164         if (! has_runtime_dependency) {
19165
19166             /* If the list is empty, nothing matches.  This happens, for
19167              * example, when a Unicode property that doesn't match anything is
19168              * the only element in the character class (perluniprops.pod notes
19169              * such properties). */
19170             if (partial_cp_count == 0) {
19171                 if (invert) {
19172                     ret = reg_node(pRExC_state, SANY);
19173                 }
19174                 else {
19175                     ret = reganode(pRExC_state, OPFAIL, 0);
19176                 }
19177
19178                 goto not_anyof;
19179             }
19180
19181             /* If matches everything but \n */
19182             if (   start[0] == 0 && end[0] == '\n' - 1
19183                 && start[1] == '\n' + 1 && end[1] == UV_MAX)
19184             {
19185                 assert (! invert);
19186                 ret = reg_node(pRExC_state, REG_ANY);
19187                 MARK_NAUGHTY(1);
19188                 goto not_anyof;
19189             }
19190         }
19191
19192         /* Next see if can optimize classes that contain just a few code points
19193          * into an EXACTish node.  The reason to do this is to let the
19194          * optimizer join this node with adjacent EXACTish ones, and ANYOF
19195          * nodes require conversion to code point from UTF-8.
19196          *
19197          * An EXACTFish node can be generated even if not under /i, and vice
19198          * versa.  But care must be taken.  An EXACTFish node has to be such
19199          * that it only matches precisely the code points in the class, but we
19200          * want to generate the least restrictive one that does that, to
19201          * increase the odds of being able to join with an adjacent node.  For
19202          * example, if the class contains [kK], we have to make it an EXACTFAA
19203          * node to prevent the KELVIN SIGN from matching.  Whether we are under
19204          * /i or not is irrelevant in this case.  Less obvious is the pattern
19205          * qr/[\x{02BC}]n/i.  U+02BC is MODIFIER LETTER APOSTROPHE. That is
19206          * supposed to match the single character U+0149 LATIN SMALL LETTER N
19207          * PRECEDED BY APOSTROPHE.  And so even though there is no simple fold
19208          * that includes \X{02BC}, there is a multi-char fold that does, and so
19209          * the node generated for it must be an EXACTFish one.  On the other
19210          * hand qr/:/i should generate a plain EXACT node since the colon
19211          * participates in no fold whatsoever, and having it EXACT tells the
19212          * optimizer the target string cannot match unless it has a colon in
19213          * it.
19214          */
19215         if (   ! posixl
19216             && ! invert
19217
19218                 /* Only try if there are no more code points in the class than
19219                  * in the max possible fold */
19220             &&   inRANGE(partial_cp_count, 1, MAX_FOLD_FROMS + 1))
19221         {
19222             if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches)
19223             {
19224                 /* We can always make a single code point class into an
19225                  * EXACTish node. */
19226
19227                 if (LOC) {
19228
19229                     /* Here is /l:  Use EXACTL, except if there is a fold not
19230                      * known until runtime so shows as only a single code point
19231                      * here.  For code points above 255, we know which can
19232                      * cause problems by having a potential fold to the Latin1
19233                      * range. */
19234                     if (  ! FOLD
19235                         || (     start[0] > 255
19236                             && ! is_PROBLEMATIC_LOCALE_FOLD_cp(start[0])))
19237                     {
19238                         op = EXACTL;
19239                     }
19240                     else {
19241                         op = EXACTFL;
19242                     }
19243                 }
19244                 else if (! FOLD) { /* Not /l and not /i */
19245                     op = (start[0] < 256) ? EXACT : EXACT_REQ8;
19246                 }
19247                 else if (start[0] < 256) { /* /i, not /l, and the code point is
19248                                               small */
19249
19250                     /* Under /i, it gets a little tricky.  A code point that
19251                      * doesn't participate in a fold should be an EXACT node.
19252                      * We know this one isn't the result of a simple fold, or
19253                      * there'd be more than one code point in the list, but it
19254                      * could be part of a multi- character fold.  In that case
19255                      * we better not create an EXACT node, as we would wrongly
19256                      * be telling the optimizer that this code point must be in
19257                      * the target string, and that is wrong.  This is because
19258                      * if the sequence around this code point forms a
19259                      * multi-char fold, what needs to be in the string could be
19260                      * the code point that folds to the sequence.
19261                      *
19262                      * This handles the case of below-255 code points, as we
19263                      * have an easy look up for those.  The next clause handles
19264                      * the above-256 one */
19265                     op = IS_IN_SOME_FOLD_L1(start[0])
19266                          ? EXACTFU
19267                          : EXACT;
19268                 }
19269                 else {  /* /i, larger code point.  Since we are under /i, and
19270                            have just this code point, we know that it can't
19271                            fold to something else, so PL_InMultiCharFold
19272                            applies to it */
19273                     op = _invlist_contains_cp(PL_InMultiCharFold,
19274                                               start[0])
19275                          ? EXACTFU_REQ8
19276                          : EXACT_REQ8;
19277                 }
19278
19279                 value = start[0];
19280             }
19281             else if (  ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
19282                      && _invlist_contains_cp(PL_in_some_fold, start[0]))
19283             {
19284                 /* Here, the only runtime dependency, if any, is from /d, and
19285                  * the class matches more than one code point, and the lowest
19286                  * code point participates in some fold.  It might be that the
19287                  * other code points are /i equivalent to this one, and hence
19288                  * they would representable by an EXACTFish node.  Above, we
19289                  * eliminated classes that contain too many code points to be
19290                  * EXACTFish, with the test for MAX_FOLD_FROMS
19291                  *
19292                  * First, special case the ASCII fold pairs, like 'B' and 'b'.
19293                  * We do this because we have EXACTFAA at our disposal for the
19294                  * ASCII range */
19295                 if (partial_cp_count == 2 && isASCII(start[0])) {
19296
19297                     /* The only ASCII characters that participate in folds are
19298                      * alphabetics */
19299                     assert(isALPHA(start[0]));
19300                     if (   end[0] == start[0]   /* First range is a single
19301                                                    character, so 2nd exists */
19302                         && isALPHA_FOLD_EQ(start[0], start[1]))
19303                     {
19304
19305                         /* Here, is part of an ASCII fold pair */
19306
19307                         if (   ASCII_FOLD_RESTRICTED
19308                             || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
19309                         {
19310                             /* If the second clause just above was true, it
19311                              * means we can't be under /i, or else the list
19312                              * would have included more than this fold pair.
19313                              * Therefore we have to exclude the possibility of
19314                              * whatever else it is that folds to these, by
19315                              * using EXACTFAA */
19316                             op = EXACTFAA;
19317                         }
19318                         else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
19319
19320                             /* Here, there's no simple fold that start[0] is part
19321                              * of, but there is a multi-character one.  If we
19322                              * are not under /i, we want to exclude that
19323                              * possibility; if under /i, we want to include it
19324                              * */
19325                             op = (FOLD) ? EXACTFU : EXACTFAA;
19326                         }
19327                         else {
19328
19329                             /* Here, the only possible fold start[0] particpates in
19330                              * is with start[1].  /i or not isn't relevant */
19331                             op = EXACTFU;
19332                         }
19333
19334                         value = toFOLD(start[0]);
19335                     }
19336                 }
19337                 else if (  ! upper_latin1_only_utf8_matches
19338                          || (   _invlist_len(upper_latin1_only_utf8_matches)
19339                                                                           == 2
19340                              && PL_fold_latin1[
19341                                invlist_highest(upper_latin1_only_utf8_matches)]
19342                              == start[0]))
19343                 {
19344                     /* Here, the smallest character is non-ascii or there are
19345                      * more than 2 code points matched by this node.  Also, we
19346                      * either don't have /d UTF-8 dependent matches, or if we
19347                      * do, they look like they could be a single character that
19348                      * is the fold of the lowest one in the always-match list.
19349                      * This test quickly excludes most of the false positives
19350                      * when there are /d UTF-8 depdendent matches.  These are
19351                      * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN
19352                      * SMALL LETTER A WITH GRAVE iff the target string is
19353                      * UTF-8.  (We don't have to worry above about exceeding
19354                      * the array bounds of PL_fold_latin1[] because any code
19355                      * point in 'upper_latin1_only_utf8_matches' is below 256.)
19356                      *
19357                      * EXACTFAA would apply only to pairs (hence exactly 2 code
19358                      * points) in the ASCII range, so we can't use it here to
19359                      * artificially restrict the fold domain, so we check if
19360                      * the class does or does not match some EXACTFish node.
19361                      * Further, if we aren't under /i, and the folded-to
19362                      * character is part of a multi-character fold, we can't do
19363                      * this optimization, as the sequence around it could be
19364                      * that multi-character fold, and we don't here know the
19365                      * context, so we have to assume it is that multi-char
19366                      * fold, to prevent potential bugs.
19367                      *
19368                      * To do the general case, we first find the fold of the
19369                      * lowest code point (which may be higher than the lowest
19370                      * one), then find everything that folds to it.  (The data
19371                      * structure we have only maps from the folded code points,
19372                      * so we have to do the earlier step.) */
19373
19374                     Size_t foldlen;
19375                     U8 foldbuf[UTF8_MAXBYTES_CASE];
19376                     UV folded = _to_uni_fold_flags(start[0],
19377                                                         foldbuf, &foldlen, 0);
19378                     U32 first_fold;
19379                     const U32 * remaining_folds;
19380                     Size_t folds_to_this_cp_count = _inverse_folds(
19381                                                             folded,
19382                                                             &first_fold,
19383                                                             &remaining_folds);
19384                     Size_t folds_count = folds_to_this_cp_count + 1;
19385                     SV * fold_list = _new_invlist(folds_count);
19386                     unsigned int i;
19387
19388                     /* If there are UTF-8 dependent matches, create a temporary
19389                      * list of what this node matches, including them. */
19390                     SV * all_cp_list = NULL;
19391                     SV ** use_this_list = &cp_list;
19392
19393                     if (upper_latin1_only_utf8_matches) {
19394                         all_cp_list = _new_invlist(0);
19395                         use_this_list = &all_cp_list;
19396                         _invlist_union(cp_list,
19397                                        upper_latin1_only_utf8_matches,
19398                                        use_this_list);
19399                     }
19400
19401                     /* Having gotten everything that participates in the fold
19402                      * containing the lowest code point, we turn that into an
19403                      * inversion list, making sure everything is included. */
19404                     fold_list = add_cp_to_invlist(fold_list, start[0]);
19405                     fold_list = add_cp_to_invlist(fold_list, folded);
19406                     if (folds_to_this_cp_count > 0) {
19407                         fold_list = add_cp_to_invlist(fold_list, first_fold);
19408                         for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
19409                             fold_list = add_cp_to_invlist(fold_list,
19410                                                         remaining_folds[i]);
19411                         }
19412                     }
19413
19414                     /* If the fold list is identical to what's in this ANYOF
19415                      * node, the node can be represented by an EXACTFish one
19416                      * instead */
19417                     if (_invlistEQ(*use_this_list, fold_list,
19418                                    0 /* Don't complement */ )
19419                     ) {
19420
19421                         /* But, we have to be careful, as mentioned above.
19422                          * Just the right sequence of characters could match
19423                          * this if it is part of a multi-character fold.  That
19424                          * IS what we want if we are under /i.  But it ISN'T
19425                          * what we want if not under /i, as it could match when
19426                          * it shouldn't.  So, when we aren't under /i and this
19427                          * character participates in a multi-char fold, we
19428                          * don't optimize into an EXACTFish node.  So, for each
19429                          * case below we have to check if we are folding
19430                          * and if not, if it is not part of a multi-char fold.
19431                          * */
19432                         if (start[0] > 255) {    /* Highish code point */
19433                             if (FOLD || ! _invlist_contains_cp(
19434                                             PL_InMultiCharFold, folded))
19435                             {
19436                                 op = (LOC)
19437                                      ? EXACTFLU8
19438                                      : (ASCII_FOLD_RESTRICTED)
19439                                        ? EXACTFAA
19440                                        : EXACTFU_REQ8;
19441                                 value = folded;
19442                             }
19443                         }   /* Below, the lowest code point < 256 */
19444                         else if (    FOLD
19445                                  &&  folded == 's'
19446                                  &&  DEPENDS_SEMANTICS)
19447                         {   /* An EXACTF node containing a single character
19448                                 's', can be an EXACTFU if it doesn't get
19449                                 joined with an adjacent 's' */
19450                             op = EXACTFU_S_EDGE;
19451                             value = folded;
19452                         }
19453                         else if (    FOLD
19454                                 || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
19455                         {
19456                             if (upper_latin1_only_utf8_matches) {
19457                                 op = EXACTF;
19458
19459                                 /* We can't use the fold, as that only matches
19460                                  * under UTF-8 */
19461                                 value = start[0];
19462                             }
19463                             else if (     UNLIKELY(start[0] == MICRO_SIGN)
19464                                      && ! UTF)
19465                             {   /* EXACTFUP is a special node for this
19466                                    character */
19467                                 op = (ASCII_FOLD_RESTRICTED)
19468                                      ? EXACTFAA
19469                                      : EXACTFUP;
19470                                 value = MICRO_SIGN;
19471                             }
19472                             else if (     ASCII_FOLD_RESTRICTED
19473                                      && ! isASCII(start[0]))
19474                             {   /* For ASCII under /iaa, we can use EXACTFU
19475                                    below */
19476                                 op = EXACTFAA;
19477                                 value = folded;
19478                             }
19479                             else {
19480                                 op = EXACTFU;
19481                                 value = folded;
19482                             }
19483                         }
19484                     }
19485
19486                     SvREFCNT_dec_NN(fold_list);
19487                     SvREFCNT_dec(all_cp_list);
19488                 }
19489             }
19490
19491             if (op != END) {
19492                 U8 len;
19493
19494                 /* Here, we have calculated what EXACTish node to use.  Have to
19495                  * convert to UTF-8 if not already there */
19496                 if (value > 255) {
19497                     if (! UTF) {
19498                         SvREFCNT_dec(cp_list);;
19499                         REQUIRE_UTF8(flagp);
19500                     }
19501
19502                     /* This is a kludge to the special casing issues with this
19503                      * ligature under /aa.  FB05 should fold to FB06, but the
19504                      * call above to _to_uni_fold_flags() didn't find this, as
19505                      * it didn't use the /aa restriction in order to not miss
19506                      * other folds that would be affected.  This is the only
19507                      * instance likely to ever be a problem in all of Unicode.
19508                      * So special case it. */
19509                     if (   value == LATIN_SMALL_LIGATURE_LONG_S_T
19510                         && ASCII_FOLD_RESTRICTED)
19511                     {
19512                         value = LATIN_SMALL_LIGATURE_ST;
19513                     }
19514                 }
19515
19516                 len = (UTF) ? UVCHR_SKIP(value) : 1;
19517
19518                 ret = regnode_guts(pRExC_state, op, len, "exact");
19519                 FILL_NODE(ret, op);
19520                 RExC_emit += 1 + STR_SZ(len);
19521                 setSTR_LEN(REGNODE_p(ret), len);
19522                 if (len == 1) {
19523                     *STRINGs(REGNODE_p(ret)) = (U8) value;
19524                 }
19525                 else {
19526                     uvchr_to_utf8((U8 *) STRINGs(REGNODE_p(ret)), value);
19527                 }
19528                 goto not_anyof;
19529             }
19530         }
19531
19532         if (! has_runtime_dependency) {
19533
19534             /* See if this can be turned into an ANYOFM node.  Think about the
19535              * bit patterns in two different bytes.  In some positions, the
19536              * bits in each will be 1; and in other positions both will be 0;
19537              * and in some positions the bit will be 1 in one byte, and 0 in
19538              * the other.  Let 'n' be the number of positions where the bits
19539              * differ.  We create a mask which has exactly 'n' 0 bits, each in
19540              * a position where the two bytes differ.  Now take the set of all
19541              * bytes that when ANDed with the mask yield the same result.  That
19542              * set has 2**n elements, and is representable by just two 8 bit
19543              * numbers: the result and the mask.  Importantly, matching the set
19544              * can be vectorized by creating a word full of the result bytes,
19545              * and a word full of the mask bytes, yielding a significant speed
19546              * up.  Here, see if this node matches such a set.  As a concrete
19547              * example consider [01], and the byte representing '0' which is
19548              * 0x30 on ASCII machines.  It has the bits 0011 0000.  Take the
19549              * mask 1111 1110.  If we AND 0x31 and 0x30 with that mask we get
19550              * 0x30.  Any other bytes ANDed yield something else.  So [01],
19551              * which is a common usage, is optimizable into ANYOFM, and can
19552              * benefit from the speed up.  We can only do this on UTF-8
19553              * invariant bytes, because they have the same bit patterns under
19554              * UTF-8 as not. */
19555             PERL_UINT_FAST8_T inverted = 0;
19556 #ifdef EBCDIC
19557             const PERL_UINT_FAST8_T max_permissible = 0xFF;
19558 #else
19559             const PERL_UINT_FAST8_T max_permissible = 0x7F;
19560 #endif
19561             /* If doesn't fit the criteria for ANYOFM, invert and try again.
19562              * If that works we will instead later generate an NANYOFM, and
19563              * invert back when through */
19564             if (invlist_highest(cp_list) > max_permissible) {
19565                 _invlist_invert(cp_list);
19566                 inverted = 1;
19567             }
19568
19569             if (invlist_highest(cp_list) <= max_permissible) {
19570                 UV this_start, this_end;
19571                 UV lowest_cp = UV_MAX;  /* init'ed to suppress compiler warn */
19572                 U8 bits_differing = 0;
19573                 Size_t full_cp_count = 0;
19574                 bool first_time = TRUE;
19575
19576                 /* Go through the bytes and find the bit positions that differ
19577                  * */
19578                 invlist_iterinit(cp_list);
19579                 while (invlist_iternext(cp_list, &this_start, &this_end)) {
19580                     unsigned int i = this_start;
19581
19582                     if (first_time) {
19583                         if (! UVCHR_IS_INVARIANT(i)) {
19584                             goto done_anyofm;
19585                         }
19586
19587                         first_time = FALSE;
19588                         lowest_cp = this_start;
19589
19590                         /* We have set up the code point to compare with.
19591                          * Don't compare it with itself */
19592                         i++;
19593                     }
19594
19595                     /* Find the bit positions that differ from the lowest code
19596                      * point in the node.  Keep track of all such positions by
19597                      * OR'ing */
19598                     for (; i <= this_end; i++) {
19599                         if (! UVCHR_IS_INVARIANT(i)) {
19600                             goto done_anyofm;
19601                         }
19602
19603                         bits_differing  |= i ^ lowest_cp;
19604                     }
19605
19606                     full_cp_count += this_end - this_start + 1;
19607                 }
19608
19609                 /* At the end of the loop, we count how many bits differ from
19610                  * the bits in lowest code point, call the count 'd'.  If the
19611                  * set we found contains 2**d elements, it is the closure of
19612                  * all code points that differ only in those bit positions.  To
19613                  * convince yourself of that, first note that the number in the
19614                  * closure must be a power of 2, which we test for.  The only
19615                  * way we could have that count and it be some differing set,
19616                  * is if we got some code points that don't differ from the
19617                  * lowest code point in any position, but do differ from each
19618                  * other in some other position.  That means one code point has
19619                  * a 1 in that position, and another has a 0.  But that would
19620                  * mean that one of them differs from the lowest code point in
19621                  * that position, which possibility we've already excluded.  */
19622                 if (  (inverted || full_cp_count > 1)
19623                     && full_cp_count == 1U << PL_bitcount[bits_differing])
19624                 {
19625                     U8 ANYOFM_mask;
19626
19627                     op = ANYOFM + inverted;;
19628
19629                     /* We need to make the bits that differ be 0's */
19630                     ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
19631
19632                     /* The argument is the lowest code point */
19633                     ret = reganode(pRExC_state, op, lowest_cp);
19634                     FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
19635                 }
19636
19637               done_anyofm:
19638                 invlist_iterfinish(cp_list);
19639             }
19640
19641             if (inverted) {
19642                 _invlist_invert(cp_list);
19643             }
19644
19645             if (op != END) {
19646                 goto not_anyof;
19647             }
19648
19649             /* XXX We could create an ANYOFR_LOW node here if we saved above if
19650              * all were invariants, it wasn't inverted, and there is a single
19651              * range.  This would be faster than some of the posix nodes we
19652              * create below like /\d/a, but would be twice the size.  Without
19653              * having actually measured the gain, khw doesn't think the
19654              * tradeoff is really worth it */
19655         }
19656
19657         if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) {
19658             PERL_UINT_FAST8_T type;
19659             SV * intersection = NULL;
19660             SV* d_invlist = NULL;
19661
19662             /* See if this matches any of the POSIX classes.  The POSIXA and
19663              * POSIXD ones are about the same speed as ANYOF ops, but take less
19664              * room; the ones that have above-Latin1 code point matches are
19665              * somewhat faster than ANYOF.  */
19666
19667             for (type = POSIXA; type >= POSIXD; type--) {
19668                 int posix_class;
19669
19670                 if (type == POSIXL) {   /* But not /l posix classes */
19671                     continue;
19672                 }
19673
19674                 for (posix_class = 0;
19675                      posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
19676                      posix_class++)
19677                 {
19678                     SV** our_code_points = &cp_list;
19679                     SV** official_code_points;
19680                     int try_inverted;
19681
19682                     if (type == POSIXA) {
19683                         official_code_points = &PL_Posix_ptrs[posix_class];
19684                     }
19685                     else {
19686                         official_code_points = &PL_XPosix_ptrs[posix_class];
19687                     }
19688
19689                     /* Skip non-existent classes of this type.  e.g. \v only
19690                      * has an entry in PL_XPosix_ptrs */
19691                     if (! *official_code_points) {
19692                         continue;
19693                     }
19694
19695                     /* Try both the regular class, and its inversion */
19696                     for (try_inverted = 0; try_inverted < 2; try_inverted++) {
19697                         bool this_inverted = invert ^ try_inverted;
19698
19699                         if (type != POSIXD) {
19700
19701                             /* This class that isn't /d can't match if we have
19702                              * /d dependencies */
19703                             if (has_runtime_dependency
19704                                                     & HAS_D_RUNTIME_DEPENDENCY)
19705                             {
19706                                 continue;
19707                             }
19708                         }
19709                         else /* is /d */ if (! this_inverted) {
19710
19711                             /* /d classes don't match anything non-ASCII below
19712                              * 256 unconditionally (which cp_list contains) */
19713                             _invlist_intersection(cp_list, PL_UpperLatin1,
19714                                                            &intersection);
19715                             if (_invlist_len(intersection) != 0) {
19716                                 continue;
19717                             }
19718
19719                             SvREFCNT_dec(d_invlist);
19720                             d_invlist = invlist_clone(cp_list, NULL);
19721
19722                             /* But under UTF-8 it turns into using /u rules.
19723                              * Add the things it matches under these conditions
19724                              * so that we check below that these are identical
19725                              * to what the tested class should match */
19726                             if (upper_latin1_only_utf8_matches) {
19727                                 _invlist_union(
19728                                             d_invlist,
19729                                             upper_latin1_only_utf8_matches,
19730                                             &d_invlist);
19731                             }
19732                             our_code_points = &d_invlist;
19733                         }
19734                         else {  /* POSIXD, inverted.  If this doesn't have this
19735                                    flag set, it isn't /d. */
19736                             if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
19737                             {
19738                                 continue;
19739                             }
19740                             our_code_points = &cp_list;
19741                         }
19742
19743                         /* Here, have weeded out some things.  We want to see
19744                          * if the list of characters this node contains
19745                          * ('*our_code_points') precisely matches those of the
19746                          * class we are currently checking against
19747                          * ('*official_code_points'). */
19748                         if (_invlistEQ(*our_code_points,
19749                                        *official_code_points,
19750                                        try_inverted))
19751                         {
19752                             /* Here, they precisely match.  Optimize this ANYOF
19753                              * node into its equivalent POSIX one of the
19754                              * correct type, possibly inverted */
19755                             ret = reg_node(pRExC_state, (try_inverted)
19756                                                         ? type + NPOSIXA
19757                                                                 - POSIXA
19758                                                         : type);
19759                             FLAGS(REGNODE_p(ret)) = posix_class;
19760                             SvREFCNT_dec(d_invlist);
19761                             SvREFCNT_dec(intersection);
19762                             goto not_anyof;
19763                         }
19764                     }
19765                 }
19766             }
19767             SvREFCNT_dec(d_invlist);
19768             SvREFCNT_dec(intersection);
19769         }
19770
19771         /* If it is a single contiguous range, ANYOFR is an efficient regnode,
19772          * both in size and speed.  Currently, a 20 bit range base (smallest
19773          * code point in the range), and a 12 bit maximum delta are packed into
19774          * a 32 bit word.  This allows for using it on all of the Unicode code
19775          * points except for the highest plane, which is only for private use
19776          * code points.  khw doubts that a bigger delta is likely in real world
19777          * applications */
19778         if (     single_range
19779             && ! has_runtime_dependency
19780             &&   anyof_flags == 0
19781             &&   start[0] < (1 << ANYOFR_BASE_BITS)
19782             &&   end[0] - start[0]
19783                     < ((1U << (sizeof(((struct regnode_1 *)NULL)->arg1)
19784                                    * CHARBITS - ANYOFR_BASE_BITS))))
19785
19786         {
19787             U8 low_utf8[UTF8_MAXBYTES+1];
19788             U8 high_utf8[UTF8_MAXBYTES+1];
19789
19790             ret = reganode(pRExC_state, ANYOFR,
19791                         (start[0] | (end[0] - start[0]) << ANYOFR_BASE_BITS));
19792
19793             /* Place the lowest UTF-8 start byte in the flags field, so as to
19794              * allow efficient ruling out at run time of many possible inputs.
19795              * */
19796             (void) uvchr_to_utf8(low_utf8, start[0]);
19797             (void) uvchr_to_utf8(high_utf8, end[0]);
19798
19799             /* If all code points share the same first byte, this can be an
19800              * ANYOFRb.  Otherwise store the lowest UTF-8 start byte which can
19801              * quickly rule out many inputs at run-time without having to
19802              * compute the code point from UTF-8.  For EBCDIC, we use I8, as
19803              * not doing that transformation would not rule out nearly so many
19804              * things */
19805             if (low_utf8[0] == high_utf8[0]) {
19806                 OP(REGNODE_p(ret)) = ANYOFRb;
19807                 ANYOF_FLAGS(REGNODE_p(ret)) = low_utf8[0];
19808             }
19809             else {
19810                 ANYOF_FLAGS(REGNODE_p(ret))
19811                                     = NATIVE_UTF8_TO_I8(low_utf8[0]);
19812             }
19813
19814             goto not_anyof;
19815         }
19816
19817         /* If didn't find an optimization and there is no need for a bitmap,
19818          * optimize to indicate that */
19819         if (     start[0] >= NUM_ANYOF_CODE_POINTS
19820             && ! LOC
19821             && ! upper_latin1_only_utf8_matches
19822             &&   anyof_flags == 0)
19823         {
19824             U8 low_utf8[UTF8_MAXBYTES+1];
19825             UV highest_cp = invlist_highest(cp_list);
19826
19827             /* Currently the maximum allowed code point by the system is
19828              * IV_MAX.  Higher ones are reserved for future internal use.  This
19829              * particular regnode can be used for higher ones, but we can't
19830              * calculate the code point of those.  IV_MAX suffices though, as
19831              * it will be a large first byte */
19832             Size_t low_len = uvchr_to_utf8(low_utf8, MIN(start[0], IV_MAX))
19833                            - low_utf8;
19834
19835             /* We store the lowest possible first byte of the UTF-8
19836              * representation, using the flags field.  This allows for quick
19837              * ruling out of some inputs without having to convert from UTF-8
19838              * to code point.  For EBCDIC, we use I8, as not doing that
19839              * transformation would not rule out nearly so many things */
19840             anyof_flags = NATIVE_UTF8_TO_I8(low_utf8[0]);
19841
19842             op = ANYOFH;
19843
19844             /* If the first UTF-8 start byte for the highest code point in the
19845              * range is suitably small, we may be able to get an upper bound as
19846              * well */
19847             if (highest_cp <= IV_MAX) {
19848                 U8 high_utf8[UTF8_MAXBYTES+1];
19849                 Size_t high_len = uvchr_to_utf8(high_utf8, highest_cp)
19850                                 - high_utf8;
19851
19852                 /* If the lowest and highest are the same, we can get an exact
19853                  * first byte instead of a just minimum or even a sequence of
19854                  * exact leading bytes.  We signal these with different
19855                  * regnodes */
19856                 if (low_utf8[0] == high_utf8[0]) {
19857                     Size_t len = find_first_differing_byte_pos(low_utf8,
19858                                                                high_utf8,
19859                                                        MIN(low_len, high_len));
19860
19861                     if (len == 1) {
19862
19863                         /* No need to convert to I8 for EBCDIC as this is an
19864                          * exact match */
19865                         anyof_flags = low_utf8[0];
19866                         op = ANYOFHb;
19867                     }
19868                     else {
19869                         op = ANYOFHs;
19870                         ret = regnode_guts(pRExC_state, op,
19871                                            regarglen[op] + STR_SZ(len),
19872                                            "anyofhs");
19873                         FILL_NODE(ret, op);
19874                         ((struct regnode_anyofhs *) REGNODE_p(ret))->str_len
19875                                                                         = len;
19876                         Copy(low_utf8,  /* Add the common bytes */
19877                            ((struct regnode_anyofhs *) REGNODE_p(ret))->string,
19878                            len, U8);
19879                         RExC_emit += NODE_SZ_STR(REGNODE_p(ret));
19880                         set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19881                                                   NULL, only_utf8_locale_list);
19882                         goto not_anyof;
19883                     }
19884                 }
19885                 else if (NATIVE_UTF8_TO_I8(high_utf8[0]) <= MAX_ANYOF_HRx_BYTE)
19886                 {
19887
19888                     /* Here, the high byte is not the same as the low, but is
19889                      * small enough that its reasonable to have a loose upper
19890                      * bound, which is packed in with the strict lower bound.
19891                      * See comments at the definition of MAX_ANYOF_HRx_BYTE.
19892                      * On EBCDIC platforms, I8 is used.  On ASCII platforms I8
19893                      * is the same thing as UTF-8 */
19894
19895                     U8 bits = 0;
19896                     U8 max_range_diff = MAX_ANYOF_HRx_BYTE - anyof_flags;
19897                     U8 range_diff = NATIVE_UTF8_TO_I8(high_utf8[0])
19898                                   - anyof_flags;
19899
19900                     if (range_diff <= max_range_diff / 8) {
19901                         bits = 3;
19902                     }
19903                     else if (range_diff <= max_range_diff / 4) {
19904                         bits = 2;
19905                     }
19906                     else if (range_diff <= max_range_diff / 2) {
19907                         bits = 1;
19908                     }
19909                     anyof_flags = (anyof_flags - 0xC0) << 2 | bits;
19910                     op = ANYOFHr;
19911                 }
19912             }
19913
19914             goto done_finding_op;
19915         }
19916     }   /* End of seeing if can optimize it into a different node */
19917
19918   is_anyof: /* It's going to be an ANYOF node. */
19919     op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY)
19920          ? ANYOFD
19921          : ((posixl)
19922             ? ANYOFPOSIXL
19923             : ((LOC)
19924                ? ANYOFL
19925                : ANYOF));
19926
19927   done_finding_op:
19928
19929     ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
19930     FILL_NODE(ret, op);        /* We set the argument later */
19931     RExC_emit += 1 + regarglen[op];
19932     ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
19933
19934     /* Here, <cp_list> contains all the code points we can determine at
19935      * compile time that match under all conditions.  Go through it, and
19936      * for things that belong in the bitmap, put them there, and delete from
19937      * <cp_list>.  While we are at it, see if everything above 255 is in the
19938      * list, and if so, set a flag to speed up execution */
19939
19940     populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
19941
19942     if (posixl) {
19943         ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
19944     }
19945
19946     if (invert) {
19947         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
19948     }
19949
19950     /* Here, the bitmap has been populated with all the Latin1 code points that
19951      * always match.  Can now add to the overall list those that match only
19952      * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
19953      * */
19954     if (upper_latin1_only_utf8_matches) {
19955         if (cp_list) {
19956             _invlist_union(cp_list,
19957                            upper_latin1_only_utf8_matches,
19958                            &cp_list);
19959             SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
19960         }
19961         else {
19962             cp_list = upper_latin1_only_utf8_matches;
19963         }
19964         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
19965     }
19966
19967     set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19968                   (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
19969                    ? listsv
19970                    : NULL,
19971                   only_utf8_locale_list);
19972     SvREFCNT_dec(cp_list);;
19973     SvREFCNT_dec(only_utf8_locale_list);
19974     return ret;
19975
19976   not_anyof:
19977
19978     /* Here, the node is getting optimized into something that's not an ANYOF
19979      * one.  Finish up. */
19980
19981     Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
19982                                            RExC_parse - orig_parse);;
19983     SvREFCNT_dec(cp_list);;
19984     SvREFCNT_dec(only_utf8_locale_list);
19985     return ret;
19986 }
19987
19988 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
19989
19990 STATIC void
19991 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
19992                 regnode* const node,
19993                 SV* const cp_list,
19994                 SV* const runtime_defns,
19995                 SV* const only_utf8_locale_list)
19996 {
19997     /* Sets the arg field of an ANYOF-type node 'node', using information about
19998      * the node passed-in.  If there is nothing outside the node's bitmap, the
19999      * arg is set to ANYOF_ONLY_HAS_BITMAP.  Otherwise, it sets the argument to
20000      * the count returned by add_data(), having allocated and stored an array,
20001      * av, as follows:
20002      *
20003      *  av[0] stores the inversion list defining this class as far as known at
20004      *        this time, or PL_sv_undef if nothing definite is now known.
20005      *  av[1] stores the inversion list of code points that match only if the
20006      *        current locale is UTF-8, or if none, PL_sv_undef if there is an
20007      *        av[2], or no entry otherwise.
20008      *  av[2] stores the list of user-defined properties whose subroutine
20009      *        definitions aren't known at this time, or no entry if none. */
20010
20011     UV n;
20012
20013     PERL_ARGS_ASSERT_SET_ANYOF_ARG;
20014
20015     if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
20016         assert(! (ANYOF_FLAGS(node)
20017                 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
20018         ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
20019     }
20020     else {
20021         AV * const av = newAV();
20022         SV *rv;
20023
20024         if (cp_list) {
20025             av_store(av, INVLIST_INDEX, SvREFCNT_inc_NN(cp_list));
20026         }
20027
20028         /* (Note that if any of this changes, the size calculations in
20029          * S_optimize_regclass() might need to be updated.) */
20030
20031         if (only_utf8_locale_list) {
20032             av_store(av, ONLY_LOCALE_MATCHES_INDEX,
20033                                      SvREFCNT_inc_NN(only_utf8_locale_list));
20034         }
20035
20036         if (runtime_defns) {
20037             av_store(av, DEFERRED_USER_DEFINED_INDEX,
20038                          SvREFCNT_inc_NN(runtime_defns));
20039         }
20040
20041         rv = newRV_noinc(MUTABLE_SV(av));
20042         n = add_data(pRExC_state, STR_WITH_LEN("s"));
20043         RExC_rxi->data->data[n] = (void*)rv;
20044         ARG_SET(node, n);
20045     }
20046 }
20047
20048 SV *
20049
20050 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
20051 Perl_get_regclass_nonbitmap_data(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV** only_utf8_locale_ptr, SV** output_invlist)
20052 #else
20053 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)
20054 #endif
20055
20056 {
20057     /* For internal core use only.
20058      * Returns the inversion list for the input 'node' in the regex 'prog'.
20059      * If <doinit> is 'true', will attempt to create the inversion list if not
20060      *    already done.
20061      * If <listsvp> is non-null, will return the printable contents of the
20062      *    property definition.  This can be used to get debugging information
20063      *    even before the inversion list exists, by calling this function with
20064      *    'doinit' set to false, in which case the components that will be used
20065      *    to eventually create the inversion list are returned  (in a printable
20066      *    form).
20067      * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
20068      *    store an inversion list of code points that should match only if the
20069      *    execution-time locale is a UTF-8 one.
20070      * If <output_invlist> is not NULL, it is where this routine is to store an
20071      *    inversion list of the code points that would be instead returned in
20072      *    <listsvp> if this were NULL.  Thus, what gets output in <listsvp>
20073      *    when this parameter is used, is just the non-code point data that
20074      *    will go into creating the inversion list.  This currently should be just
20075      *    user-defined properties whose definitions were not known at compile
20076      *    time.  Using this parameter allows for easier manipulation of the
20077      *    inversion list's data by the caller.  It is illegal to call this
20078      *    function with this parameter set, but not <listsvp>
20079      *
20080      * Tied intimately to how S_set_ANYOF_arg sets up the data structure.  Note
20081      * that, in spite of this function's name, the inversion list it returns
20082      * may include the bitmap data as well */
20083
20084     SV *si  = NULL;         /* Input initialization string */
20085     SV* invlist = NULL;
20086
20087     RXi_GET_DECL(prog, progi);
20088     const struct reg_data * const data = prog ? progi->data : NULL;
20089
20090 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
20091     PERL_ARGS_ASSERT_GET_REGCLASS_NONBITMAP_DATA;
20092 #else
20093     PERL_ARGS_ASSERT_GET_RE_GCLASS_NONBITMAP_DATA;
20094 #endif
20095     assert(! output_invlist || listsvp);
20096
20097     if (data && data->count) {
20098         const U32 n = ARG(node);
20099
20100         if (data->what[n] == 's') {
20101             SV * const rv = MUTABLE_SV(data->data[n]);
20102             AV * const av = MUTABLE_AV(SvRV(rv));
20103             SV **const ary = AvARRAY(av);
20104
20105             invlist = ary[INVLIST_INDEX];
20106
20107             if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
20108                 *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
20109             }
20110
20111             if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
20112                 si = ary[DEFERRED_USER_DEFINED_INDEX];
20113             }
20114
20115             if (doinit && (si || invlist)) {
20116                 if (si) {
20117                     bool user_defined;
20118                     SV * msg = newSVpvs_flags("", SVs_TEMP);
20119
20120                     SV * prop_definition = handle_user_defined_property(
20121                             "", 0, FALSE,   /* There is no \p{}, \P{} */
20122                             SvPVX_const(si)[1] - '0',   /* /i or not has been
20123                                                            stored here for just
20124                                                            this occasion */
20125                             TRUE,           /* run time */
20126                             FALSE,          /* This call must find the defn */
20127                             si,             /* The property definition  */
20128                             &user_defined,
20129                             msg,
20130                             0               /* base level call */
20131                            );
20132
20133                     if (SvCUR(msg)) {
20134                         assert(prop_definition == NULL);
20135
20136                         Perl_croak(aTHX_ "%" UTF8f,
20137                                 UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
20138                     }
20139
20140                     if (invlist) {
20141                         _invlist_union(invlist, prop_definition, &invlist);
20142                         SvREFCNT_dec_NN(prop_definition);
20143                     }
20144                     else {
20145                         invlist = prop_definition;
20146                     }
20147
20148                     STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
20149                     STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
20150
20151                     ary[INVLIST_INDEX] = invlist;
20152                     av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
20153                                  ? ONLY_LOCALE_MATCHES_INDEX
20154                                  : INVLIST_INDEX);
20155                     si = NULL;
20156                 }
20157             }
20158         }
20159     }
20160
20161     /* If requested, return a printable version of what this ANYOF node matches
20162      * */
20163     if (listsvp) {
20164         SV* matches_string = NULL;
20165
20166         /* This function can be called at compile-time, before everything gets
20167          * resolved, in which case we return the currently best available
20168          * information, which is the string that will eventually be used to do
20169          * that resolving, 'si' */
20170         if (si) {
20171             /* Here, we only have 'si' (and possibly some passed-in data in
20172              * 'invlist', which is handled below)  If the caller only wants
20173              * 'si', use that.  */
20174             if (! output_invlist) {
20175                 matches_string = newSVsv(si);
20176             }
20177             else {
20178                 /* But if the caller wants an inversion list of the node, we
20179                  * need to parse 'si' and place as much as possible in the
20180                  * desired output inversion list, making 'matches_string' only
20181                  * contain the currently unresolvable things */
20182                 const char *si_string = SvPVX(si);
20183                 STRLEN remaining = SvCUR(si);
20184                 UV prev_cp = 0;
20185                 U8 count = 0;
20186
20187                 /* Ignore everything before and including the first new-line */
20188                 si_string = (const char *) memchr(si_string, '\n', SvCUR(si));
20189                 assert (si_string != NULL);
20190                 si_string++;
20191                 remaining = SvPVX(si) + SvCUR(si) - si_string;
20192
20193                 while (remaining > 0) {
20194
20195                     /* The data consists of just strings defining user-defined
20196                      * property names, but in prior incarnations, and perhaps
20197                      * somehow from pluggable regex engines, it could still
20198                      * hold hex code point definitions, all of which should be
20199                      * legal (or it wouldn't have gotten this far).  Each
20200                      * component of a range would be separated by a tab, and
20201                      * each range by a new-line.  If these are found, instead
20202                      * add them to the inversion list */
20203                     I32 grok_flags =  PERL_SCAN_SILENT_ILLDIGIT
20204                                      |PERL_SCAN_SILENT_NON_PORTABLE;
20205                     STRLEN len = remaining;
20206                     UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
20207
20208                     /* If the hex decode routine found something, it should go
20209                      * up to the next \n */
20210                     if (   *(si_string + len) == '\n') {
20211                         if (count) {    /* 2nd code point on line */
20212                             *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
20213                         }
20214                         else {
20215                             *output_invlist = add_cp_to_invlist(*output_invlist, cp);
20216                         }
20217                         count = 0;
20218                         goto prepare_for_next_iteration;
20219                     }
20220
20221                     /* If the hex decode was instead for the lower range limit,
20222                      * save it, and go parse the upper range limit */
20223                     if (*(si_string + len) == '\t') {
20224                         assert(count == 0);
20225
20226                         prev_cp = cp;
20227                         count = 1;
20228                       prepare_for_next_iteration:
20229                         si_string += len + 1;
20230                         remaining -= len + 1;
20231                         continue;
20232                     }
20233
20234                     /* Here, didn't find a legal hex number.  Just add the text
20235                      * from here up to the next \n, omitting any trailing
20236                      * markers. */
20237
20238                     remaining -= len;
20239                     len = strcspn(si_string,
20240                                         DEFERRED_COULD_BE_OFFICIAL_MARKERs "\n");
20241                     remaining -= len;
20242                     if (matches_string) {
20243                         sv_catpvn(matches_string, si_string, len);
20244                     }
20245                     else {
20246                         matches_string = newSVpvn(si_string, len);
20247                     }
20248                     sv_catpvs(matches_string, " ");
20249
20250                     si_string += len;
20251                     if (   remaining
20252                         && UCHARAT(si_string)
20253                                             == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
20254                     {
20255                         si_string++;
20256                         remaining--;
20257                     }
20258                     if (remaining && UCHARAT(si_string) == '\n') {
20259                         si_string++;
20260                         remaining--;
20261                     }
20262                 } /* end of loop through the text */
20263
20264                 assert(matches_string);
20265                 if (SvCUR(matches_string)) {  /* Get rid of trailing blank */
20266                     SvCUR_set(matches_string, SvCUR(matches_string) - 1);
20267                 }
20268             } /* end of has an 'si' */
20269         }
20270
20271         /* Add the stuff that's already known */
20272         if (invlist) {
20273
20274             /* Again, if the caller doesn't want the output inversion list, put
20275              * everything in 'matches-string' */
20276             if (! output_invlist) {
20277                 if ( ! matches_string) {
20278                     matches_string = newSVpvs("\n");
20279                 }
20280                 sv_catsv(matches_string, invlist_contents(invlist,
20281                                                   TRUE /* traditional style */
20282                                                   ));
20283             }
20284             else if (! *output_invlist) {
20285                 *output_invlist = invlist_clone(invlist, NULL);
20286             }
20287             else {
20288                 _invlist_union(*output_invlist, invlist, output_invlist);
20289             }
20290         }
20291
20292         *listsvp = matches_string;
20293     }
20294
20295     return invlist;
20296 }
20297
20298 /* reg_skipcomment()
20299
20300    Absorbs an /x style # comment from the input stream,
20301    returning a pointer to the first character beyond the comment, or if the
20302    comment terminates the pattern without anything following it, this returns
20303    one past the final character of the pattern (in other words, RExC_end) and
20304    sets the REG_RUN_ON_COMMENT_SEEN flag.
20305
20306    Note it's the callers responsibility to ensure that we are
20307    actually in /x mode
20308
20309 */
20310
20311 PERL_STATIC_INLINE char*
20312 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
20313 {
20314     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
20315
20316     assert(*p == '#');
20317
20318     while (p < RExC_end) {
20319         if (*(++p) == '\n') {
20320             return p+1;
20321         }
20322     }
20323
20324     /* we ran off the end of the pattern without ending the comment, so we have
20325      * to add an \n when wrapping */
20326     RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
20327     return p;
20328 }
20329
20330 STATIC void
20331 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
20332                                 char ** p,
20333                                 const bool force_to_xmod
20334                          )
20335 {
20336     /* If the text at the current parse position '*p' is a '(?#...)' comment,
20337      * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
20338      * is /x whitespace, advance '*p' so that on exit it points to the first
20339      * byte past all such white space and comments */
20340
20341     const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
20342
20343     PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
20344
20345     assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
20346
20347     for (;;) {
20348         if (RExC_end - (*p) >= 3
20349             && *(*p)     == '('
20350             && *(*p + 1) == '?'
20351             && *(*p + 2) == '#')
20352         {
20353             while (*(*p) != ')') {
20354                 if ((*p) == RExC_end)
20355                     FAIL("Sequence (?#... not terminated");
20356                 (*p)++;
20357             }
20358             (*p)++;
20359             continue;
20360         }
20361
20362         if (use_xmod) {
20363             const char * save_p = *p;
20364             while ((*p) < RExC_end) {
20365                 STRLEN len;
20366                 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
20367                     (*p) += len;
20368                 }
20369                 else if (*(*p) == '#') {
20370                     (*p) = reg_skipcomment(pRExC_state, (*p));
20371                 }
20372                 else {
20373                     break;
20374                 }
20375             }
20376             if (*p != save_p) {
20377                 continue;
20378             }
20379         }
20380
20381         break;
20382     }
20383
20384     return;
20385 }
20386
20387 /* nextchar()
20388
20389    Advances the parse position by one byte, unless that byte is the beginning
20390    of a '(?#...)' style comment, or is /x whitespace and /x is in effect.  In
20391    those two cases, the parse position is advanced beyond all such comments and
20392    white space.
20393
20394    This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
20395 */
20396
20397 STATIC void
20398 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
20399 {
20400     PERL_ARGS_ASSERT_NEXTCHAR;
20401
20402     if (RExC_parse < RExC_end) {
20403         assert(   ! UTF
20404                || UTF8_IS_INVARIANT(*RExC_parse)
20405                || UTF8_IS_START(*RExC_parse));
20406
20407         RExC_parse += (UTF)
20408                       ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
20409                       : 1;
20410
20411         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
20412                                 FALSE /* Don't force /x */ );
20413     }
20414 }
20415
20416 STATIC void
20417 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
20418 {
20419     /* 'size' is the delta number of smallest regnode equivalents to add or
20420      * subtract from the current memory allocated to the regex engine being
20421      * constructed. */
20422
20423     PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
20424
20425     RExC_size += size;
20426
20427     Renewc(RExC_rxi,
20428            sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
20429                                                 /* +1 for REG_MAGIC */
20430            char,
20431            regexp_internal);
20432     if ( RExC_rxi == NULL )
20433         FAIL("Regexp out of space");
20434     RXi_SET(RExC_rx, RExC_rxi);
20435
20436     RExC_emit_start = RExC_rxi->program;
20437     if (size > 0) {
20438         Zero(REGNODE_p(RExC_emit), size, regnode);
20439     }
20440
20441 #ifdef RE_TRACK_PATTERN_OFFSETS
20442     Renew(RExC_offsets, 2*RExC_size+1, U32);
20443     if (size > 0) {
20444         Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
20445     }
20446     RExC_offsets[0] = RExC_size;
20447 #endif
20448 }
20449
20450 STATIC regnode_offset
20451 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
20452 {
20453     /* Allocate a regnode for 'op', with 'extra_size' extra (smallest) regnode
20454      * equivalents space.  It aligns and increments RExC_size
20455      *
20456      * It returns the regnode's offset into the regex engine program */
20457
20458     const regnode_offset ret = RExC_emit;
20459
20460     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20461
20462     PERL_ARGS_ASSERT_REGNODE_GUTS;
20463
20464     SIZE_ALIGN(RExC_size);
20465     change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
20466     NODE_ALIGN_FILL(REGNODE_p(ret));
20467 #ifndef RE_TRACK_PATTERN_OFFSETS
20468     PERL_UNUSED_ARG(name);
20469     PERL_UNUSED_ARG(op);
20470 #else
20471     assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
20472
20473     if (RExC_offsets) {         /* MJD */
20474         MJD_OFFSET_DEBUG(
20475               ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
20476               name, __LINE__,
20477               PL_reg_name[op],
20478               (UV)(RExC_emit) > RExC_offsets[0]
20479                 ? "Overwriting end of array!\n" : "OK",
20480               (UV)(RExC_emit),
20481               (UV)(RExC_parse - RExC_start),
20482               (UV)RExC_offsets[0]));
20483         Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
20484     }
20485 #endif
20486     return(ret);
20487 }
20488
20489 /*
20490 - reg_node - emit a node
20491 */
20492 STATIC regnode_offset /* Location. */
20493 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
20494 {
20495     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
20496     regnode_offset ptr = ret;
20497
20498     PERL_ARGS_ASSERT_REG_NODE;
20499
20500     assert(regarglen[op] == 0);
20501
20502     FILL_ADVANCE_NODE(ptr, op);
20503     RExC_emit = ptr;
20504     return(ret);
20505 }
20506
20507 /*
20508 - reganode - emit a node with an argument
20509 */
20510 STATIC regnode_offset /* Location. */
20511 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
20512 {
20513     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
20514     regnode_offset ptr = ret;
20515
20516     PERL_ARGS_ASSERT_REGANODE;
20517
20518     /* ANYOF are special cased to allow non-length 1 args */
20519     assert(regarglen[op] == 1);
20520
20521     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
20522     RExC_emit = ptr;
20523     return(ret);
20524 }
20525
20526 /*
20527 - regpnode - emit a temporary node with a SV* argument
20528 */
20529 STATIC regnode_offset /* Location. */
20530 S_regpnode(pTHX_ RExC_state_t *pRExC_state, U8 op, SV * arg)
20531 {
20532     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "regpnode");
20533     regnode_offset ptr = ret;
20534
20535     PERL_ARGS_ASSERT_REGPNODE;
20536
20537     FILL_ADVANCE_NODE_ARGp(ptr, op, arg);
20538     RExC_emit = ptr;
20539     return(ret);
20540 }
20541
20542 STATIC regnode_offset
20543 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
20544 {
20545     /* emit a node with U32 and I32 arguments */
20546
20547     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
20548     regnode_offset ptr = ret;
20549
20550     PERL_ARGS_ASSERT_REG2LANODE;
20551
20552     assert(regarglen[op] == 2);
20553
20554     FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
20555     RExC_emit = ptr;
20556     return(ret);
20557 }
20558
20559 /*
20560 - reginsert - insert an operator in front of already-emitted operand
20561 *
20562 * That means that on exit 'operand' is the offset of the newly inserted
20563 * operator, and the original operand has been relocated.
20564 *
20565 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
20566 * set up NEXT_OFF() of the inserted node if needed. Something like this:
20567 *
20568 *   reginsert(pRExC, OPFAIL, orig_emit, depth+1);
20569 *   NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
20570 *
20571 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
20572 */
20573 STATIC void
20574 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
20575                   const regnode_offset operand, const U32 depth)
20576 {
20577     regnode *src;
20578     regnode *dst;
20579     regnode *place;
20580     const int offset = regarglen[(U8)op];
20581     const int size = NODE_STEP_REGNODE + offset;
20582     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20583
20584     PERL_ARGS_ASSERT_REGINSERT;
20585     PERL_UNUSED_CONTEXT;
20586     PERL_UNUSED_ARG(depth);
20587 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
20588     DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
20589     assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
20590                                     studying. If this is wrong then we need to adjust RExC_recurse
20591                                     below like we do with RExC_open_parens/RExC_close_parens. */
20592     change_engine_size(pRExC_state, (Ptrdiff_t) size);
20593     src = REGNODE_p(RExC_emit);
20594     RExC_emit += size;
20595     dst = REGNODE_p(RExC_emit);
20596
20597     /* If we are in a "count the parentheses" pass, the numbers are unreliable,
20598      * and [perl #133871] shows this can lead to problems, so skip this
20599      * realignment of parens until a later pass when they are reliable */
20600     if (! IN_PARENS_PASS && RExC_open_parens) {
20601         int paren;
20602         /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
20603         /* remember that RExC_npar is rex->nparens + 1,
20604          * iow it is 1 more than the number of parens seen in
20605          * the pattern so far. */
20606         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
20607             /* note, RExC_open_parens[0] is the start of the
20608              * regex, it can't move. RExC_close_parens[0] is the end
20609              * of the regex, it *can* move. */
20610             if ( paren && RExC_open_parens[paren] >= operand ) {
20611                 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
20612                 RExC_open_parens[paren] += size;
20613             } else {
20614                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
20615             }
20616             if ( RExC_close_parens[paren] >= operand ) {
20617                 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
20618                 RExC_close_parens[paren] += size;
20619             } else {
20620                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
20621             }
20622         }
20623     }
20624     if (RExC_end_op)
20625         RExC_end_op += size;
20626
20627     while (src > REGNODE_p(operand)) {
20628         StructCopy(--src, --dst, regnode);
20629 #ifdef RE_TRACK_PATTERN_OFFSETS
20630         if (RExC_offsets) {     /* MJD 20010112 */
20631             MJD_OFFSET_DEBUG(
20632                  ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
20633                   "reginsert",
20634                   __LINE__,
20635                   PL_reg_name[op],
20636                   (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
20637                     ? "Overwriting end of array!\n" : "OK",
20638                   (UV)REGNODE_OFFSET(src),
20639                   (UV)REGNODE_OFFSET(dst),
20640                   (UV)RExC_offsets[0]));
20641             Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
20642             Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
20643         }
20644 #endif
20645     }
20646
20647     place = REGNODE_p(operand); /* Op node, where operand used to be. */
20648 #ifdef RE_TRACK_PATTERN_OFFSETS
20649     if (RExC_offsets) {         /* MJD */
20650         MJD_OFFSET_DEBUG(
20651               ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
20652               "reginsert",
20653               __LINE__,
20654               PL_reg_name[op],
20655               (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
20656               ? "Overwriting end of array!\n" : "OK",
20657               (UV)REGNODE_OFFSET(place),
20658               (UV)(RExC_parse - RExC_start),
20659               (UV)RExC_offsets[0]));
20660         Set_Node_Offset(place, RExC_parse);
20661         Set_Node_Length(place, 1);
20662     }
20663 #endif
20664     src = NEXTOPER(place);
20665     FLAGS(place) = 0;
20666     FILL_NODE(operand, op);
20667
20668     /* Zero out any arguments in the new node */
20669     Zero(src, offset, regnode);
20670 }
20671
20672 /*
20673 - regtail - set the next-pointer at the end of a node chain of p to val.  If
20674             that value won't fit in the space available, instead returns FALSE.
20675             (Except asserts if we can't fit in the largest space the regex
20676             engine is designed for.)
20677 - SEE ALSO: regtail_study
20678 */
20679 STATIC bool
20680 S_regtail(pTHX_ RExC_state_t * pRExC_state,
20681                 const regnode_offset p,
20682                 const regnode_offset val,
20683                 const U32 depth)
20684 {
20685     regnode_offset scan;
20686     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20687
20688     PERL_ARGS_ASSERT_REGTAIL;
20689 #ifndef DEBUGGING
20690     PERL_UNUSED_ARG(depth);
20691 #endif
20692
20693     /* The final node in the chain is the first one with a nonzero next pointer
20694      * */
20695     scan = (regnode_offset) p;
20696     for (;;) {
20697         regnode * const temp = regnext(REGNODE_p(scan));
20698         DEBUG_PARSE_r({
20699             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
20700             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20701             Perl_re_printf( aTHX_  "~ %s (%zu) %s %s\n",
20702                 SvPV_nolen_const(RExC_mysv), scan,
20703                     (temp == NULL ? "->" : ""),
20704                     (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
20705             );
20706         });
20707         if (temp == NULL)
20708             break;
20709         scan = REGNODE_OFFSET(temp);
20710     }
20711
20712     /* Populate this node's next pointer */
20713     assert(val >= scan);
20714     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20715         assert((UV) (val - scan) <= U32_MAX);
20716         ARG_SET(REGNODE_p(scan), val - scan);
20717     }
20718     else {
20719         if (val - scan > U16_MAX) {
20720             /* Populate this with something that won't loop and will likely
20721              * lead to a crash if the caller ignores the failure return, and
20722              * execution continues */
20723             NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20724             return FALSE;
20725         }
20726         NEXT_OFF(REGNODE_p(scan)) = val - scan;
20727     }
20728
20729     return TRUE;
20730 }
20731
20732 #ifdef DEBUGGING
20733 /*
20734 - regtail_study - set the next-pointer at the end of a node chain of p to val.
20735 - Look for optimizable sequences at the same time.
20736 - currently only looks for EXACT chains.
20737
20738 This is experimental code. The idea is to use this routine to perform
20739 in place optimizations on branches and groups as they are constructed,
20740 with the long term intention of removing optimization from study_chunk so
20741 that it is purely analytical.
20742
20743 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
20744 to control which is which.
20745
20746 This used to return a value that was ignored.  It was a problem that it is
20747 #ifdef'd to be another function that didn't return a value.  khw has changed it
20748 so both currently return a pass/fail return.
20749
20750 */
20751 /* TODO: All four parms should be const */
20752
20753 STATIC bool
20754 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
20755                       const regnode_offset val, U32 depth)
20756 {
20757     regnode_offset scan;
20758     U8 exact = PSEUDO;
20759 #ifdef EXPERIMENTAL_INPLACESCAN
20760     I32 min = 0;
20761 #endif
20762     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20763
20764     PERL_ARGS_ASSERT_REGTAIL_STUDY;
20765
20766
20767     /* Find last node. */
20768
20769     scan = p;
20770     for (;;) {
20771         regnode * const temp = regnext(REGNODE_p(scan));
20772 #ifdef EXPERIMENTAL_INPLACESCAN
20773         if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
20774             bool unfolded_multi_char;   /* Unexamined in this routine */
20775             if (join_exact(pRExC_state, scan, &min,
20776                            &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
20777                 return TRUE; /* Was return EXACT */
20778         }
20779 #endif
20780         if ( exact ) {
20781             switch (OP(REGNODE_p(scan))) {
20782                 case LEXACT:
20783                 case EXACT:
20784                 case LEXACT_REQ8:
20785                 case EXACT_REQ8:
20786                 case EXACTL:
20787                 case EXACTF:
20788                 case EXACTFU_S_EDGE:
20789                 case EXACTFAA_NO_TRIE:
20790                 case EXACTFAA:
20791                 case EXACTFU:
20792                 case EXACTFU_REQ8:
20793                 case EXACTFLU8:
20794                 case EXACTFUP:
20795                 case EXACTFL:
20796                         if( exact == PSEUDO )
20797                             exact= OP(REGNODE_p(scan));
20798                         else if ( exact != OP(REGNODE_p(scan)) )
20799                             exact= 0;
20800                 case NOTHING:
20801                     break;
20802                 default:
20803                     exact= 0;
20804             }
20805         }
20806         DEBUG_PARSE_r({
20807             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
20808             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20809             Perl_re_printf( aTHX_  "~ %s (%zu) -> %s\n",
20810                 SvPV_nolen_const(RExC_mysv),
20811                 scan,
20812                 PL_reg_name[exact]);
20813         });
20814         if (temp == NULL)
20815             break;
20816         scan = REGNODE_OFFSET(temp);
20817     }
20818     DEBUG_PARSE_r({
20819         DEBUG_PARSE_MSG("");
20820         regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
20821         Perl_re_printf( aTHX_
20822                       "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
20823                       SvPV_nolen_const(RExC_mysv),
20824                       (IV)val,
20825                       (IV)(val - scan)
20826         );
20827     });
20828     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20829         assert((UV) (val - scan) <= U32_MAX);
20830         ARG_SET(REGNODE_p(scan), val - scan);
20831     }
20832     else {
20833         if (val - scan > U16_MAX) {
20834             /* Populate this with something that won't loop and will likely
20835              * lead to a crash if the caller ignores the failure return, and
20836              * execution continues */
20837             NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20838             return FALSE;
20839         }
20840         NEXT_OFF(REGNODE_p(scan)) = val - scan;
20841     }
20842
20843     return TRUE; /* Was 'return exact' */
20844 }
20845 #endif
20846
20847 STATIC SV*
20848 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
20849
20850     /* Returns an inversion list of all the code points matched by the
20851      * ANYOFM/NANYOFM node 'n' */
20852
20853     SV * cp_list = _new_invlist(-1);
20854     const U8 lowest = (U8) ARG(n);
20855     unsigned int i;
20856     U8 count = 0;
20857     U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
20858
20859     PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
20860
20861     /* Starting with the lowest code point, any code point that ANDed with the
20862      * mask yields the lowest code point is in the set */
20863     for (i = lowest; i <= 0xFF; i++) {
20864         if ((i & FLAGS(n)) == ARG(n)) {
20865             cp_list = add_cp_to_invlist(cp_list, i);
20866             count++;
20867
20868             /* We know how many code points (a power of two) that are in the
20869              * set.  No use looking once we've got that number */
20870             if (count >= needed) break;
20871         }
20872     }
20873
20874     if (OP(n) == NANYOFM) {
20875         _invlist_invert(cp_list);
20876     }
20877     return cp_list;
20878 }
20879
20880 /*
20881  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
20882  */
20883 #ifdef DEBUGGING
20884
20885 static void
20886 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
20887 {
20888     int bit;
20889     int set=0;
20890
20891     ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20892
20893     for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
20894         if (flags & (1<<bit)) {
20895             if (!set++ && lead)
20896                 Perl_re_printf( aTHX_  "%s", lead);
20897             Perl_re_printf( aTHX_  "%s ", PL_reg_intflags_name[bit]);
20898         }
20899     }
20900     if (lead)  {
20901         if (set)
20902             Perl_re_printf( aTHX_  "\n");
20903         else
20904             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
20905     }
20906 }
20907
20908 static void
20909 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
20910 {
20911     int bit;
20912     int set=0;
20913     regex_charset cs;
20914
20915     ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20916
20917     for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
20918         if (flags & (1<<bit)) {
20919             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
20920                 continue;
20921             }
20922             if (!set++ && lead)
20923                 Perl_re_printf( aTHX_  "%s", lead);
20924             Perl_re_printf( aTHX_  "%s ", PL_reg_extflags_name[bit]);
20925         }
20926     }
20927     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
20928             if (!set++ && lead) {
20929                 Perl_re_printf( aTHX_  "%s", lead);
20930             }
20931             switch (cs) {
20932                 case REGEX_UNICODE_CHARSET:
20933                     Perl_re_printf( aTHX_  "UNICODE");
20934                     break;
20935                 case REGEX_LOCALE_CHARSET:
20936                     Perl_re_printf( aTHX_  "LOCALE");
20937                     break;
20938                 case REGEX_ASCII_RESTRICTED_CHARSET:
20939                     Perl_re_printf( aTHX_  "ASCII-RESTRICTED");
20940                     break;
20941                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
20942                     Perl_re_printf( aTHX_  "ASCII-MORE_RESTRICTED");
20943                     break;
20944                 default:
20945                     Perl_re_printf( aTHX_  "UNKNOWN CHARACTER SET");
20946                     break;
20947             }
20948     }
20949     if (lead)  {
20950         if (set)
20951             Perl_re_printf( aTHX_  "\n");
20952         else
20953             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
20954     }
20955 }
20956 #endif
20957
20958 void
20959 Perl_regdump(pTHX_ const regexp *r)
20960 {
20961 #ifdef DEBUGGING
20962     int i;
20963     SV * const sv = sv_newmortal();
20964     SV *dsv= sv_newmortal();
20965     RXi_GET_DECL(r, ri);
20966     DECLARE_AND_GET_RE_DEBUG_FLAGS;
20967
20968     PERL_ARGS_ASSERT_REGDUMP;
20969
20970     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
20971
20972     /* Header fields of interest. */
20973     for (i = 0; i < 2; i++) {
20974         if (r->substrs->data[i].substr) {
20975             RE_PV_QUOTED_DECL(s, 0, dsv,
20976                             SvPVX_const(r->substrs->data[i].substr),
20977                             RE_SV_DUMPLEN(r->substrs->data[i].substr),
20978                             PL_dump_re_max_len);
20979             Perl_re_printf( aTHX_
20980                           "%s %s%s at %" IVdf "..%" UVuf " ",
20981                           i ? "floating" : "anchored",
20982                           s,
20983                           RE_SV_TAIL(r->substrs->data[i].substr),
20984                           (IV)r->substrs->data[i].min_offset,
20985                           (UV)r->substrs->data[i].max_offset);
20986         }
20987         else if (r->substrs->data[i].utf8_substr) {
20988             RE_PV_QUOTED_DECL(s, 1, dsv,
20989                             SvPVX_const(r->substrs->data[i].utf8_substr),
20990                             RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
20991                             30);
20992             Perl_re_printf( aTHX_
20993                           "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
20994                           i ? "floating" : "anchored",
20995                           s,
20996                           RE_SV_TAIL(r->substrs->data[i].utf8_substr),
20997                           (IV)r->substrs->data[i].min_offset,
20998                           (UV)r->substrs->data[i].max_offset);
20999         }
21000     }
21001
21002     if (r->check_substr || r->check_utf8)
21003         Perl_re_printf( aTHX_
21004                       (const char *)
21005                       (   r->check_substr == r->substrs->data[1].substr
21006                        && r->check_utf8   == r->substrs->data[1].utf8_substr
21007                        ? "(checking floating" : "(checking anchored"));
21008     if (r->intflags & PREGf_NOSCAN)
21009         Perl_re_printf( aTHX_  " noscan");
21010     if (r->extflags & RXf_CHECK_ALL)
21011         Perl_re_printf( aTHX_  " isall");
21012     if (r->check_substr || r->check_utf8)
21013         Perl_re_printf( aTHX_  ") ");
21014
21015     if (ri->regstclass) {
21016         regprop(r, sv, ri->regstclass, NULL, NULL);
21017         Perl_re_printf( aTHX_  "stclass %s ", SvPVX_const(sv));
21018     }
21019     if (r->intflags & PREGf_ANCH) {
21020         Perl_re_printf( aTHX_  "anchored");
21021         if (r->intflags & PREGf_ANCH_MBOL)
21022             Perl_re_printf( aTHX_  "(MBOL)");
21023         if (r->intflags & PREGf_ANCH_SBOL)
21024             Perl_re_printf( aTHX_  "(SBOL)");
21025         if (r->intflags & PREGf_ANCH_GPOS)
21026             Perl_re_printf( aTHX_  "(GPOS)");
21027         Perl_re_printf( aTHX_ " ");
21028     }
21029     if (r->intflags & PREGf_GPOS_SEEN)
21030         Perl_re_printf( aTHX_  "GPOS:%" UVuf " ", (UV)r->gofs);
21031     if (r->intflags & PREGf_SKIP)
21032         Perl_re_printf( aTHX_  "plus ");
21033     if (r->intflags & PREGf_IMPLICIT)
21034         Perl_re_printf( aTHX_  "implicit ");
21035     Perl_re_printf( aTHX_  "minlen %" IVdf " ", (IV)r->minlen);
21036     if (r->extflags & RXf_EVAL_SEEN)
21037         Perl_re_printf( aTHX_  "with eval ");
21038     Perl_re_printf( aTHX_  "\n");
21039     DEBUG_FLAGS_r({
21040         regdump_extflags("r->extflags: ", r->extflags);
21041         regdump_intflags("r->intflags: ", r->intflags);
21042     });
21043 #else
21044     PERL_ARGS_ASSERT_REGDUMP;
21045     PERL_UNUSED_CONTEXT;
21046     PERL_UNUSED_ARG(r);
21047 #endif  /* DEBUGGING */
21048 }
21049
21050 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
21051 #ifdef DEBUGGING
21052
21053 #  if   _CC_WORDCHAR != 0 || _CC_DIGIT != 1        || _CC_ALPHA != 2    \
21054      || _CC_LOWER != 3    || _CC_UPPER != 4        || _CC_PUNCT != 5    \
21055      || _CC_PRINT != 6    || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8    \
21056      || _CC_CASED != 9    || _CC_SPACE != 10       || _CC_BLANK != 11   \
21057      || _CC_XDIGIT != 12  || _CC_CNTRL != 13       || _CC_ASCII != 14   \
21058      || _CC_VERTSPACE != 15
21059 #   error Need to adjust order of anyofs[]
21060 #  endif
21061 static const char * const anyofs[] = {
21062     "\\w",
21063     "\\W",
21064     "\\d",
21065     "\\D",
21066     "[:alpha:]",
21067     "[:^alpha:]",
21068     "[:lower:]",
21069     "[:^lower:]",
21070     "[:upper:]",
21071     "[:^upper:]",
21072     "[:punct:]",
21073     "[:^punct:]",
21074     "[:print:]",
21075     "[:^print:]",
21076     "[:alnum:]",
21077     "[:^alnum:]",
21078     "[:graph:]",
21079     "[:^graph:]",
21080     "[:cased:]",
21081     "[:^cased:]",
21082     "\\s",
21083     "\\S",
21084     "[:blank:]",
21085     "[:^blank:]",
21086     "[:xdigit:]",
21087     "[:^xdigit:]",
21088     "[:cntrl:]",
21089     "[:^cntrl:]",
21090     "[:ascii:]",
21091     "[:^ascii:]",
21092     "\\v",
21093     "\\V"
21094 };
21095 #endif
21096
21097 /*
21098 - regprop - printable representation of opcode, with run time support
21099 */
21100
21101 void
21102 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
21103 {
21104 #ifdef DEBUGGING
21105     dVAR;
21106     int k;
21107     RXi_GET_DECL(prog, progi);
21108     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21109
21110     PERL_ARGS_ASSERT_REGPROP;
21111
21112     SvPVCLEAR(sv);
21113
21114     if (OP(o) > REGNODE_MAX) {          /* regnode.type is unsigned */
21115         if (pRExC_state) {  /* This gives more info, if we have it */
21116             FAIL3("panic: corrupted regexp opcode %d > %d",
21117                   (int)OP(o), (int)REGNODE_MAX);
21118         }
21119         else {
21120             Perl_croak(aTHX_ "panic: corrupted regexp opcode %d > %d",
21121                              (int)OP(o), (int)REGNODE_MAX);
21122         }
21123     }
21124     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
21125
21126     k = PL_regkind[OP(o)];
21127
21128     if (k == EXACT) {
21129         sv_catpvs(sv, " ");
21130         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
21131          * is a crude hack but it may be the best for now since
21132          * we have no flag "this EXACTish node was UTF-8"
21133          * --jhi */
21134         pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
21135                   PL_colors[0], PL_colors[1],
21136                   PERL_PV_ESCAPE_UNI_DETECT |
21137                   PERL_PV_ESCAPE_NONASCII   |
21138                   PERL_PV_PRETTY_ELLIPSES   |
21139                   PERL_PV_PRETTY_LTGT       |
21140                   PERL_PV_PRETTY_NOCLEAR
21141                   );
21142     } else if (k == TRIE) {
21143         /* print the details of the trie in dumpuntil instead, as
21144          * progi->data isn't available here */
21145         const char op = OP(o);
21146         const U32 n = ARG(o);
21147         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
21148                (reg_ac_data *)progi->data->data[n] :
21149                NULL;
21150         const reg_trie_data * const trie
21151             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
21152
21153         Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
21154         DEBUG_TRIE_COMPILE_r({
21155           if (trie->jump)
21156             sv_catpvs(sv, "(JUMP)");
21157           Perl_sv_catpvf(aTHX_ sv,
21158             "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
21159             (UV)trie->startstate,
21160             (IV)trie->statecount-1, /* -1 because of the unused 0 element */
21161             (UV)trie->wordcount,
21162             (UV)trie->minlen,
21163             (UV)trie->maxlen,
21164             (UV)TRIE_CHARCOUNT(trie),
21165             (UV)trie->uniquecharcount
21166           );
21167         });
21168         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
21169             sv_catpvs(sv, "[");
21170             (void) put_charclass_bitmap_innards(sv,
21171                                                 ((IS_ANYOF_TRIE(op))
21172                                                  ? ANYOF_BITMAP(o)
21173                                                  : TRIE_BITMAP(trie)),
21174                                                 NULL,
21175                                                 NULL,
21176                                                 NULL,
21177                                                 0,
21178                                                 FALSE
21179                                                );
21180             sv_catpvs(sv, "]");
21181         }
21182     } else if (k == CURLY) {
21183         U32 lo = ARG1(o), hi = ARG2(o);
21184         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
21185             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
21186         Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
21187         if (hi == REG_INFTY)
21188             sv_catpvs(sv, "INFTY");
21189         else
21190             Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
21191         sv_catpvs(sv, "}");
21192     }
21193     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
21194         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
21195     else if (k == REF || k == OPEN || k == CLOSE
21196              || k == GROUPP || OP(o)==ACCEPT)
21197     {
21198         AV *name_list= NULL;
21199         U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
21200         Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno);        /* Parenth number */
21201         if ( RXp_PAREN_NAMES(prog) ) {
21202             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
21203         } else if ( pRExC_state ) {
21204             name_list= RExC_paren_name_list;
21205         }
21206         if (name_list) {
21207             if ( k != REF || (OP(o) < REFN)) {
21208                 SV **name= av_fetch(name_list, parno, 0 );
21209                 if (name)
21210                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21211             }
21212             else {
21213                 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
21214                 I32 *nums=(I32*)SvPVX(sv_dat);
21215                 SV **name= av_fetch(name_list, nums[0], 0 );
21216                 I32 n;
21217                 if (name) {
21218                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
21219                         Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
21220                                     (n ? "," : ""), (IV)nums[n]);
21221                     }
21222                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21223                 }
21224             }
21225         }
21226         if ( k == REF && reginfo) {
21227             U32 n = ARG(o);  /* which paren pair */
21228             I32 ln = prog->offs[n].start;
21229             if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
21230                 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
21231             else if (ln == prog->offs[n].end)
21232                 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
21233             else {
21234                 const char *s = reginfo->strbeg + ln;
21235                 Perl_sv_catpvf(aTHX_ sv, ": ");
21236                 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
21237                     PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
21238             }
21239         }
21240     } else if (k == GOSUB) {
21241         AV *name_list= NULL;
21242         if ( RXp_PAREN_NAMES(prog) ) {
21243             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
21244         } else if ( pRExC_state ) {
21245             name_list= RExC_paren_name_list;
21246         }
21247
21248         /* Paren and offset */
21249         Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
21250                 (int)((o + (int)ARG2L(o)) - progi->program) );
21251         if (name_list) {
21252             SV **name= av_fetch(name_list, ARG(o), 0 );
21253             if (name)
21254                 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
21255         }
21256     }
21257     else if (k == LOGICAL)
21258         /* 2: embedded, otherwise 1 */
21259         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
21260     else if (k == ANYOF || k == ANYOFR) {
21261         U8 flags;
21262         char * bitmap;
21263         U32 arg;
21264         bool do_sep = FALSE;    /* Do we need to separate various components of
21265                                    the output? */
21266         /* Set if there is still an unresolved user-defined property */
21267         SV *unresolved                = NULL;
21268
21269         /* Things that are ignored except when the runtime locale is UTF-8 */
21270         SV *only_utf8_locale_invlist = NULL;
21271
21272         /* Code points that don't fit in the bitmap */
21273         SV *nonbitmap_invlist = NULL;
21274
21275         /* And things that aren't in the bitmap, but are small enough to be */
21276         SV* bitmap_range_not_in_bitmap = NULL;
21277
21278         bool inverted;
21279
21280         if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21281             flags = 0;
21282             bitmap = NULL;
21283             arg = 0;
21284         }
21285         else {
21286             flags = ANYOF_FLAGS(o);
21287             bitmap = ANYOF_BITMAP(o);
21288             arg = ARG(o);
21289         }
21290
21291         if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
21292             if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
21293                 sv_catpvs(sv, "{utf8-locale-reqd}");
21294             }
21295             if (flags & ANYOFL_FOLD) {
21296                 sv_catpvs(sv, "{i}");
21297             }
21298         }
21299
21300         inverted = flags & ANYOF_INVERT;
21301
21302         /* If there is stuff outside the bitmap, get it */
21303         if (arg != ANYOF_ONLY_HAS_BITMAP) {
21304             if (inRANGE(OP(o), ANYOFR, ANYOFRb)) {
21305                 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
21306                                             ANYOFRbase(o),
21307                                             ANYOFRbase(o) + ANYOFRdelta(o));
21308             }
21309             else {
21310 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
21311                 (void) get_regclass_nonbitmap_data(prog, o, FALSE,
21312                                                 &unresolved,
21313                                                 &only_utf8_locale_invlist,
21314                                                 &nonbitmap_invlist);
21315 #else
21316                 (void) get_re_gclass_nonbitmap_data(prog, o, FALSE,
21317                                                 &unresolved,
21318                                                 &only_utf8_locale_invlist,
21319                                                 &nonbitmap_invlist);
21320 #endif
21321             }
21322
21323             /* The non-bitmap data may contain stuff that could fit in the
21324              * bitmap.  This could come from a user-defined property being
21325              * finally resolved when this call was done; or much more likely
21326              * because there are matches that require UTF-8 to be valid, and so
21327              * aren't in the bitmap (or ANYOFR).  This is teased apart later */
21328             _invlist_intersection(nonbitmap_invlist,
21329                                   PL_InBitmap,
21330                                   &bitmap_range_not_in_bitmap);
21331             /* Leave just the things that don't fit into the bitmap */
21332             _invlist_subtract(nonbitmap_invlist,
21333                               PL_InBitmap,
21334                               &nonbitmap_invlist);
21335         }
21336
21337         /* Obey this flag to add all above-the-bitmap code points */
21338         if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
21339             nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
21340                                                       NUM_ANYOF_CODE_POINTS,
21341                                                       UV_MAX);
21342         }
21343
21344         /* Ready to start outputting.  First, the initial left bracket */
21345         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21346
21347         /* ANYOFH by definition doesn't have anything that will fit inside the
21348          * bitmap;  ANYOFR may or may not. */
21349         if (  ! inRANGE(OP(o), ANYOFH, ANYOFHr)
21350             && (   ! inRANGE(OP(o), ANYOFR, ANYOFRb)
21351                 ||   ANYOFRbase(o) < NUM_ANYOF_CODE_POINTS))
21352         {
21353             /* Then all the things that could fit in the bitmap */
21354             do_sep = put_charclass_bitmap_innards(sv,
21355                                                   bitmap,
21356                                                   bitmap_range_not_in_bitmap,
21357                                                   only_utf8_locale_invlist,
21358                                                   o,
21359                                                   flags,
21360
21361                                                   /* Can't try inverting for a
21362                                                    * better display if there
21363                                                    * are things that haven't
21364                                                    * been resolved */
21365                                                   unresolved != NULL
21366                                             || inRANGE(OP(o), ANYOFR, ANYOFRb));
21367             SvREFCNT_dec(bitmap_range_not_in_bitmap);
21368
21369             /* If there are user-defined properties which haven't been defined
21370              * yet, output them.  If the result is not to be inverted, it is
21371              * clearest to output them in a separate [] from the bitmap range
21372              * stuff.  If the result is to be complemented, we have to show
21373              * everything in one [], as the inversion applies to the whole
21374              * thing.  Use {braces} to separate them from anything in the
21375              * bitmap and anything above the bitmap. */
21376             if (unresolved) {
21377                 if (inverted) {
21378                     if (! do_sep) { /* If didn't output anything in the bitmap
21379                                      */
21380                         sv_catpvs(sv, "^");
21381                     }
21382                     sv_catpvs(sv, "{");
21383                 }
21384                 else if (do_sep) {
21385                     Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
21386                                                       PL_colors[0]);
21387                 }
21388                 sv_catsv(sv, unresolved);
21389                 if (inverted) {
21390                     sv_catpvs(sv, "}");
21391                 }
21392                 do_sep = ! inverted;
21393             }
21394         }
21395
21396         /* And, finally, add the above-the-bitmap stuff */
21397         if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
21398             SV* contents;
21399
21400             /* See if truncation size is overridden */
21401             const STRLEN dump_len = (PL_dump_re_max_len > 256)
21402                                     ? PL_dump_re_max_len
21403                                     : 256;
21404
21405             /* This is output in a separate [] */
21406             if (do_sep) {
21407                 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
21408             }
21409
21410             /* And, for easy of understanding, it is shown in the
21411              * uncomplemented form if possible.  The one exception being if
21412              * there are unresolved items, where the inversion has to be
21413              * delayed until runtime */
21414             if (inverted && ! unresolved) {
21415                 _invlist_invert(nonbitmap_invlist);
21416                 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
21417             }
21418
21419             contents = invlist_contents(nonbitmap_invlist,
21420                                         FALSE /* output suitable for catsv */
21421                                        );
21422
21423             /* If the output is shorter than the permissible maximum, just do it. */
21424             if (SvCUR(contents) <= dump_len) {
21425                 sv_catsv(sv, contents);
21426             }
21427             else {
21428                 const char * contents_string = SvPVX(contents);
21429                 STRLEN i = dump_len;
21430
21431                 /* Otherwise, start at the permissible max and work back to the
21432                  * first break possibility */
21433                 while (i > 0 && contents_string[i] != ' ') {
21434                     i--;
21435                 }
21436                 if (i == 0) {       /* Fail-safe.  Use the max if we couldn't
21437                                        find a legal break */
21438                     i = dump_len;
21439                 }
21440
21441                 sv_catpvn(sv, contents_string, i);
21442                 sv_catpvs(sv, "...");
21443             }
21444
21445             SvREFCNT_dec_NN(contents);
21446             SvREFCNT_dec_NN(nonbitmap_invlist);
21447         }
21448
21449         /* And finally the matching, closing ']' */
21450         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21451
21452         if (OP(o) == ANYOFHs) {
21453             Perl_sv_catpvf(aTHX_ sv, " (Leading UTF-8 bytes=%s", _byte_dump_string((U8 *) ((struct regnode_anyofhs *) o)->string, FLAGS(o), 1));
21454         }
21455         else if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21456             U8 lowest = (OP(o) != ANYOFHr)
21457                          ? FLAGS(o)
21458                          : LOWEST_ANYOF_HRx_BYTE(FLAGS(o));
21459             U8 highest = (OP(o) == ANYOFHr)
21460                          ? HIGHEST_ANYOF_HRx_BYTE(FLAGS(o))
21461                          : (OP(o) == ANYOFH || OP(o) == ANYOFR)
21462                            ? 0xFF
21463                            : lowest;
21464 #ifndef EBCDIC
21465             if (OP(o) != ANYOFR || ! isASCII(ANYOFRbase(o) + ANYOFRdelta(o)))
21466 #endif
21467             {
21468                 Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=%02X", lowest);
21469                 if (lowest != highest) {
21470                     Perl_sv_catpvf(aTHX_ sv, "-%02X", highest);
21471                 }
21472                 Perl_sv_catpvf(aTHX_ sv, ")");
21473             }
21474         }
21475
21476         SvREFCNT_dec(unresolved);
21477     }
21478     else if (k == ANYOFM) {
21479         SV * cp_list = get_ANYOFM_contents(o);
21480
21481         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21482         if (OP(o) == NANYOFM) {
21483             _invlist_invert(cp_list);
21484         }
21485
21486         put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, 0, TRUE);
21487         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21488
21489         SvREFCNT_dec(cp_list);
21490     }
21491     else if (k == POSIXD || k == NPOSIXD) {
21492         U8 index = FLAGS(o) * 2;
21493         if (index < C_ARRAY_LENGTH(anyofs)) {
21494             if (*anyofs[index] != '[')  {
21495                 sv_catpvs(sv, "[");
21496             }
21497             sv_catpv(sv, anyofs[index]);
21498             if (*anyofs[index] != '[')  {
21499                 sv_catpvs(sv, "]");
21500             }
21501         }
21502         else {
21503             Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
21504         }
21505     }
21506     else if (k == BOUND || k == NBOUND) {
21507         /* Must be synced with order of 'bound_type' in regcomp.h */
21508         const char * const bounds[] = {
21509             "",      /* Traditional */
21510             "{gcb}",
21511             "{lb}",
21512             "{sb}",
21513             "{wb}"
21514         };
21515         assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
21516         sv_catpv(sv, bounds[FLAGS(o)]);
21517     }
21518     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) {
21519         Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags));
21520         if (o->next_off) {
21521             Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off);
21522         }
21523         Perl_sv_catpvf(aTHX_ sv, "]");
21524     }
21525     else if (OP(o) == SBOL)
21526         Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
21527
21528     /* add on the verb argument if there is one */
21529     if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
21530         if ( ARG(o) )
21531             Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
21532                        SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
21533         else
21534             sv_catpvs(sv, ":NULL");
21535     }
21536 #else
21537     PERL_UNUSED_CONTEXT;
21538     PERL_UNUSED_ARG(sv);
21539     PERL_UNUSED_ARG(o);
21540     PERL_UNUSED_ARG(prog);
21541     PERL_UNUSED_ARG(reginfo);
21542     PERL_UNUSED_ARG(pRExC_state);
21543 #endif  /* DEBUGGING */
21544 }
21545
21546
21547
21548 SV *
21549 Perl_re_intuit_string(pTHX_ REGEXP * const r)
21550 {                               /* Assume that RE_INTUIT is set */
21551     /* Returns an SV containing a string that must appear in the target for it
21552      * to match, or NULL if nothing is known that must match.
21553      *
21554      * CAUTION: the SV can be freed during execution of the regex engine */
21555
21556     struct regexp *const prog = ReANY(r);
21557     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21558
21559     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
21560     PERL_UNUSED_CONTEXT;
21561
21562     DEBUG_COMPILE_r(
21563         {
21564             if (prog->maxlen > 0) {
21565                 const char * const s = SvPV_nolen_const(RX_UTF8(r)
21566                       ? prog->check_utf8 : prog->check_substr);
21567
21568                 if (!PL_colorset) reginitcolors();
21569                 Perl_re_printf( aTHX_
21570                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
21571                       PL_colors[4],
21572                       RX_UTF8(r) ? "utf8 " : "",
21573                       PL_colors[5], PL_colors[0],
21574                       s,
21575                       PL_colors[1],
21576                       (strlen(s) > PL_dump_re_max_len ? "..." : ""));
21577             }
21578         } );
21579
21580     /* use UTF8 check substring if regexp pattern itself is in UTF8 */
21581     return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
21582 }
21583
21584 /*
21585    pregfree()
21586
21587    handles refcounting and freeing the perl core regexp structure. When
21588    it is necessary to actually free the structure the first thing it
21589    does is call the 'free' method of the regexp_engine associated to
21590    the regexp, allowing the handling of the void *pprivate; member
21591    first. (This routine is not overridable by extensions, which is why
21592    the extensions free is called first.)
21593
21594    See regdupe and regdupe_internal if you change anything here.
21595 */
21596 #ifndef PERL_IN_XSUB_RE
21597 void
21598 Perl_pregfree(pTHX_ REGEXP *r)
21599 {
21600     SvREFCNT_dec(r);
21601 }
21602
21603 void
21604 Perl_pregfree2(pTHX_ REGEXP *rx)
21605 {
21606     struct regexp *const r = ReANY(rx);
21607     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21608
21609     PERL_ARGS_ASSERT_PREGFREE2;
21610
21611     if (! r)
21612         return;
21613
21614     if (r->mother_re) {
21615         ReREFCNT_dec(r->mother_re);
21616     } else {
21617         CALLREGFREE_PVT(rx); /* free the private data */
21618         SvREFCNT_dec(RXp_PAREN_NAMES(r));
21619     }
21620     if (r->substrs) {
21621         int i;
21622         for (i = 0; i < 2; i++) {
21623             SvREFCNT_dec(r->substrs->data[i].substr);
21624             SvREFCNT_dec(r->substrs->data[i].utf8_substr);
21625         }
21626         Safefree(r->substrs);
21627     }
21628     RX_MATCH_COPY_FREE(rx);
21629 #ifdef PERL_ANY_COW
21630     SvREFCNT_dec(r->saved_copy);
21631 #endif
21632     Safefree(r->offs);
21633     SvREFCNT_dec(r->qr_anoncv);
21634     if (r->recurse_locinput)
21635         Safefree(r->recurse_locinput);
21636 }
21637
21638
21639 /*  reg_temp_copy()
21640
21641     Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
21642     except that dsv will be created if NULL.
21643
21644     This function is used in two main ways. First to implement
21645         $r = qr/....; $s = $$r;
21646
21647     Secondly, it is used as a hacky workaround to the structural issue of
21648     match results
21649     being stored in the regexp structure which is in turn stored in
21650     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
21651     could be PL_curpm in multiple contexts, and could require multiple
21652     result sets being associated with the pattern simultaneously, such
21653     as when doing a recursive match with (??{$qr})
21654
21655     The solution is to make a lightweight copy of the regexp structure
21656     when a qr// is returned from the code executed by (??{$qr}) this
21657     lightweight copy doesn't actually own any of its data except for
21658     the starp/end and the actual regexp structure itself.
21659
21660 */
21661
21662
21663 REGEXP *
21664 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
21665 {
21666     struct regexp *drx;
21667     struct regexp *const srx = ReANY(ssv);
21668     const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
21669
21670     PERL_ARGS_ASSERT_REG_TEMP_COPY;
21671
21672     if (!dsv)
21673         dsv = (REGEXP*) newSV_type(SVt_REGEXP);
21674     else {
21675         assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV));
21676
21677         /* our only valid caller, sv_setsv_flags(), should have done
21678          * a SV_CHECK_THINKFIRST_COW_DROP() by now */
21679         assert(!SvOOK(dsv));
21680         assert(!SvIsCOW(dsv));
21681         assert(!SvROK(dsv));
21682
21683         if (SvPVX_const(dsv)) {
21684             if (SvLEN(dsv))
21685                 Safefree(SvPVX(dsv));
21686             SvPVX(dsv) = NULL;
21687         }
21688         SvLEN_set(dsv, 0);
21689         SvCUR_set(dsv, 0);
21690         SvOK_off((SV *)dsv);
21691
21692         if (islv) {
21693             /* For PVLVs, the head (sv_any) points to an XPVLV, while
21694              * the LV's xpvlenu_rx will point to a regexp body, which
21695              * we allocate here */
21696             REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
21697             assert(!SvPVX(dsv));
21698             ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
21699             temp->sv_any = NULL;
21700             SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
21701             SvREFCNT_dec_NN(temp);
21702             /* SvCUR still resides in the xpvlv struct, so the regexp copy-
21703                ing below will not set it. */
21704             SvCUR_set(dsv, SvCUR(ssv));
21705         }
21706     }
21707     /* This ensures that SvTHINKFIRST(sv) is true, and hence that
21708        sv_force_normal(sv) is called.  */
21709     SvFAKE_on(dsv);
21710     drx = ReANY(dsv);
21711
21712     SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
21713     SvPV_set(dsv, RX_WRAPPED(ssv));
21714     /* We share the same string buffer as the original regexp, on which we
21715        hold a reference count, incremented when mother_re is set below.
21716        The string pointer is copied here, being part of the regexp struct.
21717      */
21718     memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
21719            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
21720     if (!islv)
21721         SvLEN_set(dsv, 0);
21722     if (srx->offs) {
21723         const I32 npar = srx->nparens+1;
21724         Newx(drx->offs, npar, regexp_paren_pair);
21725         Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
21726     }
21727     if (srx->substrs) {
21728         int i;
21729         Newx(drx->substrs, 1, struct reg_substr_data);
21730         StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
21731
21732         for (i = 0; i < 2; i++) {
21733             SvREFCNT_inc_void(drx->substrs->data[i].substr);
21734             SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
21735         }
21736
21737         /* check_substr and check_utf8, if non-NULL, point to either their
21738            anchored or float namesakes, and don't hold a second reference.  */
21739     }
21740     RX_MATCH_COPIED_off(dsv);
21741 #ifdef PERL_ANY_COW
21742     drx->saved_copy = NULL;
21743 #endif
21744     drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
21745     SvREFCNT_inc_void(drx->qr_anoncv);
21746     if (srx->recurse_locinput)
21747         Newx(drx->recurse_locinput, srx->nparens + 1, char *);
21748
21749     return dsv;
21750 }
21751 #endif
21752
21753
21754 /* regfree_internal()
21755
21756    Free the private data in a regexp. This is overloadable by
21757    extensions. Perl takes care of the regexp structure in pregfree(),
21758    this covers the *pprivate pointer which technically perl doesn't
21759    know about, however of course we have to handle the
21760    regexp_internal structure when no extension is in use.
21761
21762    Note this is called before freeing anything in the regexp
21763    structure.
21764  */
21765
21766 void
21767 Perl_regfree_internal(pTHX_ REGEXP * const rx)
21768 {
21769     struct regexp *const r = ReANY(rx);
21770     RXi_GET_DECL(r, ri);
21771     DECLARE_AND_GET_RE_DEBUG_FLAGS;
21772
21773     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
21774
21775     if (! ri) {
21776         return;
21777     }
21778
21779     DEBUG_COMPILE_r({
21780         if (!PL_colorset)
21781             reginitcolors();
21782         {
21783             SV *dsv= sv_newmortal();
21784             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
21785                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
21786             Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
21787                 PL_colors[4], PL_colors[5], s);
21788         }
21789     });
21790
21791 #ifdef RE_TRACK_PATTERN_OFFSETS
21792     if (ri->u.offsets)
21793         Safefree(ri->u.offsets);             /* 20010421 MJD */
21794 #endif
21795     if (ri->code_blocks)
21796         S_free_codeblocks(aTHX_ ri->code_blocks);
21797
21798     if (ri->data) {
21799         int n = ri->data->count;
21800
21801         while (--n >= 0) {
21802           /* If you add a ->what type here, update the comment in regcomp.h */
21803             switch (ri->data->what[n]) {
21804             case 'a':
21805             case 'r':
21806             case 's':
21807             case 'S':
21808             case 'u':
21809                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
21810                 break;
21811             case 'f':
21812                 Safefree(ri->data->data[n]);
21813                 break;
21814             case 'l':
21815             case 'L':
21816                 break;
21817             case 'T':
21818                 { /* Aho Corasick add-on structure for a trie node.
21819                      Used in stclass optimization only */
21820                     U32 refcount;
21821                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
21822 #ifdef USE_ITHREADS
21823                     dVAR;
21824 #endif
21825                     OP_REFCNT_LOCK;
21826                     refcount = --aho->refcount;
21827                     OP_REFCNT_UNLOCK;
21828                     if ( !refcount ) {
21829                         PerlMemShared_free(aho->states);
21830                         PerlMemShared_free(aho->fail);
21831                          /* do this last!!!! */
21832                         PerlMemShared_free(ri->data->data[n]);
21833                         /* we should only ever get called once, so
21834                          * assert as much, and also guard the free
21835                          * which /might/ happen twice. At the least
21836                          * it will make code anlyzers happy and it
21837                          * doesn't cost much. - Yves */
21838                         assert(ri->regstclass);
21839                         if (ri->regstclass) {
21840                             PerlMemShared_free(ri->regstclass);
21841                             ri->regstclass = 0;
21842                         }
21843                     }
21844                 }
21845                 break;
21846             case 't':
21847                 {
21848                     /* trie structure. */
21849                     U32 refcount;
21850                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
21851 #ifdef USE_ITHREADS
21852                     dVAR;
21853 #endif
21854                     OP_REFCNT_LOCK;
21855                     refcount = --trie->refcount;
21856                     OP_REFCNT_UNLOCK;
21857                     if ( !refcount ) {
21858                         PerlMemShared_free(trie->charmap);
21859                         PerlMemShared_free(trie->states);
21860                         PerlMemShared_free(trie->trans);
21861                         if (trie->bitmap)
21862                             PerlMemShared_free(trie->bitmap);
21863                         if (trie->jump)
21864                             PerlMemShared_free(trie->jump);
21865                         PerlMemShared_free(trie->wordinfo);
21866                         /* do this last!!!! */
21867                         PerlMemShared_free(ri->data->data[n]);
21868                     }
21869                 }
21870                 break;
21871             default:
21872                 Perl_croak(aTHX_ "panic: regfree data code '%c'",
21873                                                     ri->data->what[n]);
21874             }
21875         }
21876         Safefree(ri->data->what);
21877         Safefree(ri->data);
21878     }
21879
21880     Safefree(ri);
21881 }
21882
21883 #define av_dup_inc(s, t)        MUTABLE_AV(sv_dup_inc((const SV *)s, t))
21884 #define hv_dup_inc(s, t)        MUTABLE_HV(sv_dup_inc((const SV *)s, t))
21885 #define SAVEPVN(p, n)   ((p) ? savepvn(p, n) : NULL)
21886
21887 /*
21888    re_dup_guts - duplicate a regexp.
21889
21890    This routine is expected to clone a given regexp structure. It is only
21891    compiled under USE_ITHREADS.
21892
21893    After all of the core data stored in struct regexp is duplicated
21894    the regexp_engine.dupe method is used to copy any private data
21895    stored in the *pprivate pointer. This allows extensions to handle
21896    any duplication it needs to do.
21897
21898    See pregfree() and regfree_internal() if you change anything here.
21899 */
21900 #if defined(USE_ITHREADS)
21901 #ifndef PERL_IN_XSUB_RE
21902 void
21903 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
21904 {
21905     dVAR;
21906     I32 npar;
21907     const struct regexp *r = ReANY(sstr);
21908     struct regexp *ret = ReANY(dstr);
21909
21910     PERL_ARGS_ASSERT_RE_DUP_GUTS;
21911
21912     npar = r->nparens+1;
21913     Newx(ret->offs, npar, regexp_paren_pair);
21914     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
21915
21916     if (ret->substrs) {
21917         /* Do it this way to avoid reading from *r after the StructCopy().
21918            That way, if any of the sv_dup_inc()s dislodge *r from the L1
21919            cache, it doesn't matter.  */
21920         int i;
21921         const bool anchored = r->check_substr
21922             ? r->check_substr == r->substrs->data[0].substr
21923             : r->check_utf8   == r->substrs->data[0].utf8_substr;
21924         Newx(ret->substrs, 1, struct reg_substr_data);
21925         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
21926
21927         for (i = 0; i < 2; i++) {
21928             ret->substrs->data[i].substr =
21929                         sv_dup_inc(ret->substrs->data[i].substr, param);
21930             ret->substrs->data[i].utf8_substr =
21931                         sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
21932         }
21933
21934         /* check_substr and check_utf8, if non-NULL, point to either their
21935            anchored or float namesakes, and don't hold a second reference.  */
21936
21937         if (ret->check_substr) {
21938             if (anchored) {
21939                 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
21940
21941                 ret->check_substr = ret->substrs->data[0].substr;
21942                 ret->check_utf8   = ret->substrs->data[0].utf8_substr;
21943             } else {
21944                 assert(r->check_substr == r->substrs->data[1].substr);
21945                 assert(r->check_utf8   == r->substrs->data[1].utf8_substr);
21946
21947                 ret->check_substr = ret->substrs->data[1].substr;
21948                 ret->check_utf8   = ret->substrs->data[1].utf8_substr;
21949             }
21950         } else if (ret->check_utf8) {
21951             if (anchored) {
21952                 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
21953             } else {
21954                 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
21955             }
21956         }
21957     }
21958
21959     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
21960     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
21961     if (r->recurse_locinput)
21962         Newx(ret->recurse_locinput, r->nparens + 1, char *);
21963
21964     if (ret->pprivate)
21965         RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
21966
21967     if (RX_MATCH_COPIED(dstr))
21968         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
21969     else
21970         ret->subbeg = NULL;
21971 #ifdef PERL_ANY_COW
21972     ret->saved_copy = NULL;
21973 #endif
21974
21975     /* Whether mother_re be set or no, we need to copy the string.  We
21976        cannot refrain from copying it when the storage points directly to
21977        our mother regexp, because that's
21978                1: a buffer in a different thread
21979                2: something we no longer hold a reference on
21980                so we need to copy it locally.  */
21981     RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
21982     /* set malloced length to a non-zero value so it will be freed
21983      * (otherwise in combination with SVf_FAKE it looks like an alien
21984      * buffer). It doesn't have to be the actual malloced size, since it
21985      * should never be grown */
21986     SvLEN_set(dstr, SvCUR(sstr)+1);
21987     ret->mother_re   = NULL;
21988 }
21989 #endif /* PERL_IN_XSUB_RE */
21990
21991 /*
21992    regdupe_internal()
21993
21994    This is the internal complement to regdupe() which is used to copy
21995    the structure pointed to by the *pprivate pointer in the regexp.
21996    This is the core version of the extension overridable cloning hook.
21997    The regexp structure being duplicated will be copied by perl prior
21998    to this and will be provided as the regexp *r argument, however
21999    with the /old/ structures pprivate pointer value. Thus this routine
22000    may override any copying normally done by perl.
22001
22002    It returns a pointer to the new regexp_internal structure.
22003 */
22004
22005 void *
22006 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
22007 {
22008     dVAR;
22009     struct regexp *const r = ReANY(rx);
22010     regexp_internal *reti;
22011     int len;
22012     RXi_GET_DECL(r, ri);
22013
22014     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
22015
22016     len = ProgLen(ri);
22017
22018     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
22019           char, regexp_internal);
22020     Copy(ri->program, reti->program, len+1, regnode);
22021
22022
22023     if (ri->code_blocks) {
22024         int n;
22025         Newx(reti->code_blocks, 1, struct reg_code_blocks);
22026         Newx(reti->code_blocks->cb, ri->code_blocks->count,
22027                     struct reg_code_block);
22028         Copy(ri->code_blocks->cb, reti->code_blocks->cb,
22029              ri->code_blocks->count, struct reg_code_block);
22030         for (n = 0; n < ri->code_blocks->count; n++)
22031              reti->code_blocks->cb[n].src_regex = (REGEXP*)
22032                     sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
22033         reti->code_blocks->count = ri->code_blocks->count;
22034         reti->code_blocks->refcnt = 1;
22035     }
22036     else
22037         reti->code_blocks = NULL;
22038
22039     reti->regstclass = NULL;
22040
22041     if (ri->data) {
22042         struct reg_data *d;
22043         const int count = ri->data->count;
22044         int i;
22045
22046         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
22047                 char, struct reg_data);
22048         Newx(d->what, count, U8);
22049
22050         d->count = count;
22051         for (i = 0; i < count; i++) {
22052             d->what[i] = ri->data->what[i];
22053             switch (d->what[i]) {
22054                 /* see also regcomp.h and regfree_internal() */
22055             case 'a': /* actually an AV, but the dup function is identical.
22056                          values seem to be "plain sv's" generally. */
22057             case 'r': /* a compiled regex (but still just another SV) */
22058             case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
22059                          this use case should go away, the code could have used
22060                          'a' instead - see S_set_ANYOF_arg() for array contents. */
22061             case 'S': /* actually an SV, but the dup function is identical.  */
22062             case 'u': /* actually an HV, but the dup function is identical.
22063                          values are "plain sv's" */
22064                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
22065                 break;
22066             case 'f':
22067                 /* Synthetic Start Class - "Fake" charclass we generate to optimize
22068                  * patterns which could start with several different things. Pre-TRIE
22069                  * this was more important than it is now, however this still helps
22070                  * in some places, for instance /x?a+/ might produce a SSC equivalent
22071                  * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
22072                  * in regexec.c
22073                  */
22074                 /* This is cheating. */
22075                 Newx(d->data[i], 1, regnode_ssc);
22076                 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
22077                 reti->regstclass = (regnode*)d->data[i];
22078                 break;
22079             case 'T':
22080                 /* AHO-CORASICK fail table */
22081                 /* Trie stclasses are readonly and can thus be shared
22082                  * without duplication. We free the stclass in pregfree
22083                  * when the corresponding reg_ac_data struct is freed.
22084                  */
22085                 reti->regstclass= ri->regstclass;
22086                 /* FALLTHROUGH */
22087             case 't':
22088                 /* TRIE transition table */
22089                 OP_REFCNT_LOCK;
22090                 ((reg_trie_data*)ri->data->data[i])->refcount++;
22091                 OP_REFCNT_UNLOCK;
22092                 /* FALLTHROUGH */
22093             case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
22094             case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
22095                          is not from another regexp */
22096                 d->data[i] = ri->data->data[i];
22097                 break;
22098             default:
22099                 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
22100                                                            ri->data->what[i]);
22101             }
22102         }
22103
22104         reti->data = d;
22105     }
22106     else
22107         reti->data = NULL;
22108
22109     reti->name_list_idx = ri->name_list_idx;
22110
22111 #ifdef RE_TRACK_PATTERN_OFFSETS
22112     if (ri->u.offsets) {
22113         Newx(reti->u.offsets, 2*len+1, U32);
22114         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
22115     }
22116 #else
22117     SetProgLen(reti, len);
22118 #endif
22119
22120     return (void*)reti;
22121 }
22122
22123 #endif    /* USE_ITHREADS */
22124
22125 #ifndef PERL_IN_XSUB_RE
22126
22127 /*
22128  - regnext - dig the "next" pointer out of a node
22129  */
22130 regnode *
22131 Perl_regnext(pTHX_ regnode *p)
22132 {
22133     I32 offset;
22134
22135     if (!p)
22136         return(NULL);
22137
22138     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
22139         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
22140                                                 (int)OP(p), (int)REGNODE_MAX);
22141     }
22142
22143     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
22144     if (offset == 0)
22145         return(NULL);
22146
22147     return(p+offset);
22148 }
22149
22150 #endif
22151
22152 STATIC void
22153 S_re_croak(pTHX_ bool utf8, const char* pat,...)
22154 {
22155     va_list args;
22156     STRLEN len = strlen(pat);
22157     char buf[512];
22158     SV *msv;
22159     const char *message;
22160
22161     PERL_ARGS_ASSERT_RE_CROAK;
22162
22163     if (len > 510)
22164         len = 510;
22165     Copy(pat, buf, len , char);
22166     buf[len] = '\n';
22167     buf[len + 1] = '\0';
22168     va_start(args, pat);
22169     msv = vmess(buf, &args);
22170     va_end(args);
22171     message = SvPV_const(msv, len);
22172     if (len > 512)
22173         len = 512;
22174     Copy(message, buf, len , char);
22175     /* len-1 to avoid \n */
22176     Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, len-1, buf));
22177 }
22178
22179 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
22180
22181 #ifndef PERL_IN_XSUB_RE
22182 void
22183 Perl_save_re_context(pTHX)
22184 {
22185     I32 nparens = -1;
22186     I32 i;
22187
22188     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
22189
22190     if (PL_curpm) {
22191         const REGEXP * const rx = PM_GETRE(PL_curpm);
22192         if (rx)
22193             nparens = RX_NPARENS(rx);
22194     }
22195
22196     /* RT #124109. This is a complete hack; in the SWASHNEW case we know
22197      * that PL_curpm will be null, but that utf8.pm and the modules it
22198      * loads will only use $1..$3.
22199      * The t/porting/re_context.t test file checks this assumption.
22200      */
22201     if (nparens == -1)
22202         nparens = 3;
22203
22204     for (i = 1; i <= nparens; i++) {
22205         char digits[TYPE_CHARS(long)];
22206         const STRLEN len = my_snprintf(digits, sizeof(digits),
22207                                        "%lu", (long)i);
22208         GV *const *const gvp
22209             = (GV**)hv_fetch(PL_defstash, digits, len, 0);
22210
22211         if (gvp) {
22212             GV * const gv = *gvp;
22213             if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
22214                 save_scalar(gv);
22215         }
22216     }
22217 }
22218 #endif
22219
22220 #ifdef DEBUGGING
22221
22222 STATIC void
22223 S_put_code_point(pTHX_ SV *sv, UV c)
22224 {
22225     PERL_ARGS_ASSERT_PUT_CODE_POINT;
22226
22227     if (c > 255) {
22228         Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
22229     }
22230     else if (isPRINT(c)) {
22231         const char string = (char) c;
22232
22233         /* We use {phrase} as metanotation in the class, so also escape literal
22234          * braces */
22235         if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
22236             sv_catpvs(sv, "\\");
22237         sv_catpvn(sv, &string, 1);
22238     }
22239     else if (isMNEMONIC_CNTRL(c)) {
22240         Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
22241     }
22242     else {
22243         Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
22244     }
22245 }
22246
22247 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
22248
22249 STATIC void
22250 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
22251 {
22252     /* Appends to 'sv' a displayable version of the range of code points from
22253      * 'start' to 'end'.  Mnemonics (like '\r') are used for the few controls
22254      * that have them, when they occur at the beginning or end of the range.
22255      * It uses hex to output the remaining code points, unless 'allow_literals'
22256      * is true, in which case the printable ASCII ones are output as-is (though
22257      * some of these will be escaped by put_code_point()).
22258      *
22259      * NOTE:  This is designed only for printing ranges of code points that fit
22260      *        inside an ANYOF bitmap.  Higher code points are simply suppressed
22261      */
22262
22263     const unsigned int min_range_count = 3;
22264
22265     assert(start <= end);
22266
22267     PERL_ARGS_ASSERT_PUT_RANGE;
22268
22269     while (start <= end) {
22270         UV this_end;
22271         const char * format;
22272
22273         if (end - start < min_range_count) {
22274
22275             /* Output chars individually when they occur in short ranges */
22276             for (; start <= end; start++) {
22277                 put_code_point(sv, start);
22278             }
22279             break;
22280         }
22281
22282         /* If permitted by the input options, and there is a possibility that
22283          * this range contains a printable literal, look to see if there is
22284          * one. */
22285         if (allow_literals && start <= MAX_PRINT_A) {
22286
22287             /* If the character at the beginning of the range isn't an ASCII
22288              * printable, effectively split the range into two parts:
22289              *  1) the portion before the first such printable,
22290              *  2) the rest
22291              * and output them separately. */
22292             if (! isPRINT_A(start)) {
22293                 UV temp_end = start + 1;
22294
22295                 /* There is no point looking beyond the final possible
22296                  * printable, in MAX_PRINT_A */
22297                 UV max = MIN(end, MAX_PRINT_A);
22298
22299                 while (temp_end <= max && ! isPRINT_A(temp_end)) {
22300                     temp_end++;
22301                 }
22302
22303                 /* Here, temp_end points to one beyond the first printable if
22304                  * found, or to one beyond 'max' if not.  If none found, make
22305                  * sure that we use the entire range */
22306                 if (temp_end > MAX_PRINT_A) {
22307                     temp_end = end + 1;
22308                 }
22309
22310                 /* Output the first part of the split range: the part that
22311                  * doesn't have printables, with the parameter set to not look
22312                  * for literals (otherwise we would infinitely recurse) */
22313                 put_range(sv, start, temp_end - 1, FALSE);
22314
22315                 /* The 2nd part of the range (if any) starts here. */
22316                 start = temp_end;
22317
22318                 /* We do a continue, instead of dropping down, because even if
22319                  * the 2nd part is non-empty, it could be so short that we want
22320                  * to output it as individual characters, as tested for at the
22321                  * top of this loop.  */
22322                 continue;
22323             }
22324
22325             /* Here, 'start' is a printable ASCII.  If it is an alphanumeric,
22326              * output a sub-range of just the digits or letters, then process
22327              * the remaining portion as usual. */
22328             if (isALPHANUMERIC_A(start)) {
22329                 UV mask = (isDIGIT_A(start))
22330                            ? _CC_DIGIT
22331                              : isUPPER_A(start)
22332                                ? _CC_UPPER
22333                                : _CC_LOWER;
22334                 UV temp_end = start + 1;
22335
22336                 /* Find the end of the sub-range that includes just the
22337                  * characters in the same class as the first character in it */
22338                 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
22339                     temp_end++;
22340                 }
22341                 temp_end--;
22342
22343                 /* For short ranges, don't duplicate the code above to output
22344                  * them; just call recursively */
22345                 if (temp_end - start < min_range_count) {
22346                     put_range(sv, start, temp_end, FALSE);
22347                 }
22348                 else {  /* Output as a range */
22349                     put_code_point(sv, start);
22350                     sv_catpvs(sv, "-");
22351                     put_code_point(sv, temp_end);
22352                 }
22353                 start = temp_end + 1;
22354                 continue;
22355             }
22356
22357             /* We output any other printables as individual characters */
22358             if (isPUNCT_A(start) || isSPACE_A(start)) {
22359                 while (start <= end && (isPUNCT_A(start)
22360                                         || isSPACE_A(start)))
22361                 {
22362                     put_code_point(sv, start);
22363                     start++;
22364                 }
22365                 continue;
22366             }
22367         } /* End of looking for literals */
22368
22369         /* Here is not to output as a literal.  Some control characters have
22370          * mnemonic names.  Split off any of those at the beginning and end of
22371          * the range to print mnemonically.  It isn't possible for many of
22372          * these to be in a row, so this won't overwhelm with output */
22373         if (   start <= end
22374             && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
22375         {
22376             while (isMNEMONIC_CNTRL(start) && start <= end) {
22377                 put_code_point(sv, start);
22378                 start++;
22379             }
22380
22381             /* If this didn't take care of the whole range ... */
22382             if (start <= end) {
22383
22384                 /* Look backwards from the end to find the final non-mnemonic
22385                  * */
22386                 UV temp_end = end;
22387                 while (isMNEMONIC_CNTRL(temp_end)) {
22388                     temp_end--;
22389                 }
22390
22391                 /* And separately output the interior range that doesn't start
22392                  * or end with mnemonics */
22393                 put_range(sv, start, temp_end, FALSE);
22394
22395                 /* Then output the mnemonic trailing controls */
22396                 start = temp_end + 1;
22397                 while (start <= end) {
22398                     put_code_point(sv, start);
22399                     start++;
22400                 }
22401                 break;
22402             }
22403         }
22404
22405         /* As a final resort, output the range or subrange as hex. */
22406
22407         if (start >= NUM_ANYOF_CODE_POINTS) {
22408             this_end = end;
22409         }
22410         else {  /* Have to split range at the bitmap boundary */
22411             this_end = (end < NUM_ANYOF_CODE_POINTS)
22412                         ? end
22413                         : NUM_ANYOF_CODE_POINTS - 1;
22414         }
22415 #if NUM_ANYOF_CODE_POINTS > 256
22416         format = (this_end < 256)
22417                  ? "\\x%02" UVXf "-\\x%02" UVXf
22418                  : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
22419 #else
22420         format = "\\x%02" UVXf "-\\x%02" UVXf;
22421 #endif
22422         GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
22423         Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
22424         GCC_DIAG_RESTORE_STMT;
22425         break;
22426     }
22427 }
22428
22429 STATIC void
22430 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
22431 {
22432     /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
22433      * 'invlist' */
22434
22435     UV start, end;
22436     bool allow_literals = TRUE;
22437
22438     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
22439
22440     /* Generally, it is more readable if printable characters are output as
22441      * literals, but if a range (nearly) spans all of them, it's best to output
22442      * it as a single range.  This code will use a single range if all but 2
22443      * ASCII printables are in it */
22444     invlist_iterinit(invlist);
22445     while (invlist_iternext(invlist, &start, &end)) {
22446
22447         /* If the range starts beyond the final printable, it doesn't have any
22448          * in it */
22449         if (start > MAX_PRINT_A) {
22450             break;
22451         }
22452
22453         /* In both ASCII and EBCDIC, a SPACE is the lowest printable.  To span
22454          * all but two, the range must start and end no later than 2 from
22455          * either end */
22456         if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
22457             if (end > MAX_PRINT_A) {
22458                 end = MAX_PRINT_A;
22459             }
22460             if (start < ' ') {
22461                 start = ' ';
22462             }
22463             if (end - start >= MAX_PRINT_A - ' ' - 2) {
22464                 allow_literals = FALSE;
22465             }
22466             break;
22467         }
22468     }
22469     invlist_iterfinish(invlist);
22470
22471     /* Here we have figured things out.  Output each range */
22472     invlist_iterinit(invlist);
22473     while (invlist_iternext(invlist, &start, &end)) {
22474         if (start >= NUM_ANYOF_CODE_POINTS) {
22475             break;
22476         }
22477         put_range(sv, start, end, allow_literals);
22478     }
22479     invlist_iterfinish(invlist);
22480
22481     return;
22482 }
22483
22484 STATIC SV*
22485 S_put_charclass_bitmap_innards_common(pTHX_
22486         SV* invlist,            /* The bitmap */
22487         SV* posixes,            /* Under /l, things like [:word:], \S */
22488         SV* only_utf8,          /* Under /d, matches iff the target is UTF-8 */
22489         SV* not_utf8,           /* /d, matches iff the target isn't UTF-8 */
22490         SV* only_utf8_locale,   /* Under /l, matches if the locale is UTF-8 */
22491         const bool invert       /* Is the result to be inverted? */
22492 )
22493 {
22494     /* Create and return an SV containing a displayable version of the bitmap
22495      * and associated information determined by the input parameters.  If the
22496      * output would have been only the inversion indicator '^', NULL is instead
22497      * returned. */
22498
22499     dVAR;
22500     SV * output;
22501
22502     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
22503
22504     if (invert) {
22505         output = newSVpvs("^");
22506     }
22507     else {
22508         output = newSVpvs("");
22509     }
22510
22511     /* First, the code points in the bitmap that are unconditionally there */
22512     put_charclass_bitmap_innards_invlist(output, invlist);
22513
22514     /* Traditionally, these have been placed after the main code points */
22515     if (posixes) {
22516         sv_catsv(output, posixes);
22517     }
22518
22519     if (only_utf8 && _invlist_len(only_utf8)) {
22520         Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
22521         put_charclass_bitmap_innards_invlist(output, only_utf8);
22522     }
22523
22524     if (not_utf8 && _invlist_len(not_utf8)) {
22525         Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
22526         put_charclass_bitmap_innards_invlist(output, not_utf8);
22527     }
22528
22529     if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
22530         Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
22531         put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
22532
22533         /* This is the only list in this routine that can legally contain code
22534          * points outside the bitmap range.  The call just above to
22535          * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
22536          * output them here.  There's about a half-dozen possible, and none in
22537          * contiguous ranges longer than 2 */
22538         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22539             UV start, end;
22540             SV* above_bitmap = NULL;
22541
22542             _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
22543
22544             invlist_iterinit(above_bitmap);
22545             while (invlist_iternext(above_bitmap, &start, &end)) {
22546                 UV i;
22547
22548                 for (i = start; i <= end; i++) {
22549                     put_code_point(output, i);
22550                 }
22551             }
22552             invlist_iterfinish(above_bitmap);
22553             SvREFCNT_dec_NN(above_bitmap);
22554         }
22555     }
22556
22557     if (invert && SvCUR(output) == 1) {
22558         return NULL;
22559     }
22560
22561     return output;
22562 }
22563
22564 STATIC bool
22565 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
22566                                      char *bitmap,
22567                                      SV *nonbitmap_invlist,
22568                                      SV *only_utf8_locale_invlist,
22569                                      const regnode * const node,
22570                                      const U8 flags,
22571                                      const bool force_as_is_display)
22572 {
22573     /* Appends to 'sv' a displayable version of the innards of the bracketed
22574      * character class defined by the other arguments:
22575      *  'bitmap' points to the bitmap, or NULL if to ignore that.
22576      *  'nonbitmap_invlist' is an inversion list of the code points that are in
22577      *      the bitmap range, but for some reason aren't in the bitmap; NULL if
22578      *      none.  The reasons for this could be that they require some
22579      *      condition such as the target string being or not being in UTF-8
22580      *      (under /d), or because they came from a user-defined property that
22581      *      was not resolved at the time of the regex compilation (under /u)
22582      *  'only_utf8_locale_invlist' is an inversion list of the code points that
22583      *      are valid only if the runtime locale is a UTF-8 one; NULL if none
22584      *  'node' is the regex pattern ANYOF node.  It is needed only when the
22585      *      above two parameters are not null, and is passed so that this
22586      *      routine can tease apart the various reasons for them.
22587      *  'flags' is the flags field of 'node'
22588      *  'force_as_is_display' is TRUE if this routine should definitely NOT try
22589      *      to invert things to see if that leads to a cleaner display.  If
22590      *      FALSE, this routine is free to use its judgment about doing this.
22591      *
22592      * It returns TRUE if there was actually something output.  (It may be that
22593      * the bitmap, etc is empty.)
22594      *
22595      * When called for outputting the bitmap of a non-ANYOF node, just pass the
22596      * bitmap, with the succeeding parameters set to NULL, and the final one to
22597      * FALSE.
22598      */
22599
22600     /* In general, it tries to display the 'cleanest' representation of the
22601      * innards, choosing whether to display them inverted or not, regardless of
22602      * whether the class itself is to be inverted.  However,  there are some
22603      * cases where it can't try inverting, as what actually matches isn't known
22604      * until runtime, and hence the inversion isn't either. */
22605
22606     dVAR;
22607     bool inverting_allowed = ! force_as_is_display;
22608
22609     int i;
22610     STRLEN orig_sv_cur = SvCUR(sv);
22611
22612     SV* invlist;            /* Inversion list we accumulate of code points that
22613                                are unconditionally matched */
22614     SV* only_utf8 = NULL;   /* Under /d, list of matches iff the target is
22615                                UTF-8 */
22616     SV* not_utf8 =  NULL;   /* /d, list of matches iff the target isn't UTF-8
22617                              */
22618     SV* posixes = NULL;     /* Under /l, string of things like [:word:], \D */
22619     SV* only_utf8_locale = NULL;    /* Under /l, list of matches if the locale
22620                                        is UTF-8 */
22621
22622     SV* as_is_display;      /* The output string when we take the inputs
22623                                literally */
22624     SV* inverted_display;   /* The output string when we invert the inputs */
22625
22626     bool invert = cBOOL(flags & ANYOF_INVERT);  /* Is the input to be inverted
22627                                                    to match? */
22628     /* We are biased in favor of displaying things without them being inverted,
22629      * as that is generally easier to understand */
22630     const int bias = 5;
22631
22632     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
22633
22634     /* Start off with whatever code points are passed in.  (We clone, so we
22635      * don't change the caller's list) */
22636     if (nonbitmap_invlist) {
22637         assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
22638         invlist = invlist_clone(nonbitmap_invlist, NULL);
22639     }
22640     else {  /* Worst case size is every other code point is matched */
22641         invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
22642     }
22643
22644     if (flags) {
22645         if (OP(node) == ANYOFD) {
22646
22647             /* This flag indicates that the code points below 0x100 in the
22648              * nonbitmap list are precisely the ones that match only when the
22649              * target is UTF-8 (they should all be non-ASCII). */
22650             if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
22651             {
22652                 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
22653                 _invlist_subtract(invlist, only_utf8, &invlist);
22654             }
22655
22656             /* And this flag for matching all non-ASCII 0xFF and below */
22657             if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
22658             {
22659                 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
22660             }
22661         }
22662         else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
22663
22664             /* If either of these flags are set, what matches isn't
22665              * determinable except during execution, so don't know enough here
22666              * to invert */
22667             if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
22668                 inverting_allowed = FALSE;
22669             }
22670
22671             /* What the posix classes match also varies at runtime, so these
22672              * will be output symbolically. */
22673             if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
22674                 int i;
22675
22676                 posixes = newSVpvs("");
22677                 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
22678                     if (ANYOF_POSIXL_TEST(node, i)) {
22679                         sv_catpv(posixes, anyofs[i]);
22680                     }
22681                 }
22682             }
22683         }
22684     }
22685
22686     /* Accumulate the bit map into the unconditional match list */
22687     if (bitmap) {
22688         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
22689             if (BITMAP_TEST(bitmap, i)) {
22690                 int start = i++;
22691                 for (;
22692                      i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
22693                      i++)
22694                 { /* empty */ }
22695                 invlist = _add_range_to_invlist(invlist, start, i-1);
22696             }
22697         }
22698     }
22699
22700     /* Make sure that the conditional match lists don't have anything in them
22701      * that match unconditionally; otherwise the output is quite confusing.
22702      * This could happen if the code that populates these misses some
22703      * duplication. */
22704     if (only_utf8) {
22705         _invlist_subtract(only_utf8, invlist, &only_utf8);
22706     }
22707     if (not_utf8) {
22708         _invlist_subtract(not_utf8, invlist, &not_utf8);
22709     }
22710
22711     if (only_utf8_locale_invlist) {
22712
22713         /* Since this list is passed in, we have to make a copy before
22714          * modifying it */
22715         only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
22716
22717         _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
22718
22719         /* And, it can get really weird for us to try outputting an inverted
22720          * form of this list when it has things above the bitmap, so don't even
22721          * try */
22722         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22723             inverting_allowed = FALSE;
22724         }
22725     }
22726
22727     /* Calculate what the output would be if we take the input as-is */
22728     as_is_display = put_charclass_bitmap_innards_common(invlist,
22729                                                     posixes,
22730                                                     only_utf8,
22731                                                     not_utf8,
22732                                                     only_utf8_locale,
22733                                                     invert);
22734
22735     /* If have to take the output as-is, just do that */
22736     if (! inverting_allowed) {
22737         if (as_is_display) {
22738             sv_catsv(sv, as_is_display);
22739             SvREFCNT_dec_NN(as_is_display);
22740         }
22741     }
22742     else { /* But otherwise, create the output again on the inverted input, and
22743               use whichever version is shorter */
22744
22745         int inverted_bias, as_is_bias;
22746
22747         /* We will apply our bias to whichever of the results doesn't have
22748          * the '^' */
22749         if (invert) {
22750             invert = FALSE;
22751             as_is_bias = bias;
22752             inverted_bias = 0;
22753         }
22754         else {
22755             invert = TRUE;
22756             as_is_bias = 0;
22757             inverted_bias = bias;
22758         }
22759
22760         /* Now invert each of the lists that contribute to the output,
22761          * excluding from the result things outside the possible range */
22762
22763         /* For the unconditional inversion list, we have to add in all the
22764          * conditional code points, so that when inverted, they will be gone
22765          * from it */
22766         _invlist_union(only_utf8, invlist, &invlist);
22767         _invlist_union(not_utf8, invlist, &invlist);
22768         _invlist_union(only_utf8_locale, invlist, &invlist);
22769         _invlist_invert(invlist);
22770         _invlist_intersection(invlist, PL_InBitmap, &invlist);
22771
22772         if (only_utf8) {
22773             _invlist_invert(only_utf8);
22774             _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
22775         }
22776         else if (not_utf8) {
22777
22778             /* If a code point matches iff the target string is not in UTF-8,
22779              * then complementing the result has it not match iff not in UTF-8,
22780              * which is the same thing as matching iff it is UTF-8. */
22781             only_utf8 = not_utf8;
22782             not_utf8 = NULL;
22783         }
22784
22785         if (only_utf8_locale) {
22786             _invlist_invert(only_utf8_locale);
22787             _invlist_intersection(only_utf8_locale,
22788                                   PL_InBitmap,
22789                                   &only_utf8_locale);
22790         }
22791
22792         inverted_display = put_charclass_bitmap_innards_common(
22793                                             invlist,
22794                                             posixes,
22795                                             only_utf8,
22796                                             not_utf8,
22797                                             only_utf8_locale, invert);
22798
22799         /* Use the shortest representation, taking into account our bias
22800          * against showing it inverted */
22801         if (   inverted_display
22802             && (   ! as_is_display
22803                 || (  SvCUR(inverted_display) + inverted_bias
22804                     < SvCUR(as_is_display)    + as_is_bias)))
22805         {
22806             sv_catsv(sv, inverted_display);
22807         }
22808         else if (as_is_display) {
22809             sv_catsv(sv, as_is_display);
22810         }
22811
22812         SvREFCNT_dec(as_is_display);
22813         SvREFCNT_dec(inverted_display);
22814     }
22815
22816     SvREFCNT_dec_NN(invlist);
22817     SvREFCNT_dec(only_utf8);
22818     SvREFCNT_dec(not_utf8);
22819     SvREFCNT_dec(posixes);
22820     SvREFCNT_dec(only_utf8_locale);
22821
22822     return SvCUR(sv) > orig_sv_cur;
22823 }
22824
22825 #define CLEAR_OPTSTART                                                       \
22826     if (optstart) STMT_START {                                               \
22827         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_                                           \
22828                               " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
22829         optstart=NULL;                                                       \
22830     } STMT_END
22831
22832 #define DUMPUNTIL(b,e)                                                       \
22833                     CLEAR_OPTSTART;                                          \
22834                     node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
22835
22836 STATIC const regnode *
22837 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
22838             const regnode *last, const regnode *plast,
22839             SV* sv, I32 indent, U32 depth)
22840 {
22841     U8 op = PSEUDO;     /* Arbitrary non-END op. */
22842     const regnode *next;
22843     const regnode *optstart= NULL;
22844
22845     RXi_GET_DECL(r, ri);
22846     DECLARE_AND_GET_RE_DEBUG_FLAGS;
22847
22848     PERL_ARGS_ASSERT_DUMPUNTIL;
22849
22850 #ifdef DEBUG_DUMPUNTIL
22851     Perl_re_printf( aTHX_  "--- %d : %d - %d - %d\n", indent, node-start,
22852         last ? last-start : 0, plast ? plast-start : 0);
22853 #endif
22854
22855     if (plast && plast < last)
22856         last= plast;
22857
22858     while (PL_regkind[op] != END && (!last || node < last)) {
22859         assert(node);
22860         /* While that wasn't END last time... */
22861         NODE_ALIGN(node);
22862         op = OP(node);
22863         if (op == CLOSE || op == SRCLOSE || op == WHILEM)
22864             indent--;
22865         next = regnext((regnode *)node);
22866
22867         /* Where, what. */
22868         if (OP(node) == OPTIMIZED) {
22869             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
22870                 optstart = node;
22871             else
22872                 goto after_print;
22873         } else
22874             CLEAR_OPTSTART;
22875
22876         regprop(r, sv, node, NULL, NULL);
22877         Perl_re_printf( aTHX_  "%4" IVdf ":%*s%s", (IV)(node - start),
22878                       (int)(2*indent + 1), "", SvPVX_const(sv));
22879
22880         if (OP(node) != OPTIMIZED) {
22881             if (next == NULL)           /* Next ptr. */
22882                 Perl_re_printf( aTHX_  " (0)");
22883             else if (PL_regkind[(U8)op] == BRANCH
22884                      && PL_regkind[OP(next)] != BRANCH )
22885                 Perl_re_printf( aTHX_  " (FAIL)");
22886             else
22887                 Perl_re_printf( aTHX_  " (%" IVdf ")", (IV)(next - start));
22888             Perl_re_printf( aTHX_ "\n");
22889         }
22890
22891       after_print:
22892         if (PL_regkind[(U8)op] == BRANCHJ) {
22893             assert(next);
22894             {
22895                 const regnode *nnode = (OP(next) == LONGJMP
22896                                        ? regnext((regnode *)next)
22897                                        : next);
22898                 if (last && nnode > last)
22899                     nnode = last;
22900                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
22901             }
22902         }
22903         else if (PL_regkind[(U8)op] == BRANCH) {
22904             assert(next);
22905             DUMPUNTIL(NEXTOPER(node), next);
22906         }
22907         else if ( PL_regkind[(U8)op]  == TRIE ) {
22908             const regnode *this_trie = node;
22909             const char op = OP(node);
22910             const U32 n = ARG(node);
22911             const reg_ac_data * const ac = op>=AHOCORASICK ?
22912                (reg_ac_data *)ri->data->data[n] :
22913                NULL;
22914             const reg_trie_data * const trie =
22915                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
22916 #ifdef DEBUGGING
22917             AV *const trie_words
22918                            = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
22919 #endif
22920             const regnode *nextbranch= NULL;
22921             I32 word_idx;
22922             SvPVCLEAR(sv);
22923             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
22924                 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
22925
22926                 Perl_re_indentf( aTHX_  "%s ",
22927                     indent+3,
22928                     elem_ptr
22929                     ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
22930                                 SvCUR(*elem_ptr), PL_dump_re_max_len,
22931                                 PL_colors[0], PL_colors[1],
22932                                 (SvUTF8(*elem_ptr)
22933                                  ? PERL_PV_ESCAPE_UNI
22934                                  : 0)
22935                                 | PERL_PV_PRETTY_ELLIPSES
22936                                 | PERL_PV_PRETTY_LTGT
22937                             )
22938                     : "???"
22939                 );
22940                 if (trie->jump) {
22941                     U16 dist= trie->jump[word_idx+1];
22942                     Perl_re_printf( aTHX_  "(%" UVuf ")\n",
22943                                (UV)((dist ? this_trie + dist : next) - start));
22944                     if (dist) {
22945                         if (!nextbranch)
22946                             nextbranch= this_trie + trie->jump[0];
22947                         DUMPUNTIL(this_trie + dist, nextbranch);
22948                     }
22949                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
22950                         nextbranch= regnext((regnode *)nextbranch);
22951                 } else {
22952                     Perl_re_printf( aTHX_  "\n");
22953                 }
22954             }
22955             if (last && next > last)
22956                 node= last;
22957             else
22958                 node= next;
22959         }
22960         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
22961             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
22962                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
22963         }
22964         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
22965             assert(next);
22966             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
22967         }
22968         else if ( op == PLUS || op == STAR) {
22969             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
22970         }
22971         else if (PL_regkind[(U8)op] == EXACT || op == ANYOFHs) {
22972             /* Literal string, where present. */
22973             node += NODE_SZ_STR(node) - 1;
22974             node = NEXTOPER(node);
22975         }
22976         else {
22977             node = NEXTOPER(node);
22978             node += regarglen[(U8)op];
22979         }
22980         if (op == CURLYX || op == OPEN || op == SROPEN)
22981             indent++;
22982     }
22983     CLEAR_OPTSTART;
22984 #ifdef DEBUG_DUMPUNTIL
22985     Perl_re_printf( aTHX_  "--- %d\n", (int)indent);
22986 #endif
22987     return node;
22988 }
22989
22990 #endif  /* DEBUGGING */
22991
22992 #ifndef PERL_IN_XSUB_RE
22993
22994 #  include "uni_keywords.h"
22995
22996 void
22997 Perl_init_uniprops(pTHX)
22998 {
22999     dVAR;
23000
23001 #  ifdef DEBUGGING
23002     char * dump_len_string;
23003
23004     dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
23005     if (   ! dump_len_string
23006         || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
23007     {
23008         PL_dump_re_max_len = 60;    /* A reasonable default */
23009     }
23010 #  endif
23011
23012     PL_user_def_props = newHV();
23013
23014 #  ifdef USE_ITHREADS
23015
23016     HvSHAREKEYS_off(PL_user_def_props);
23017     PL_user_def_props_aTHX = aTHX;
23018
23019 #  endif
23020
23021     /* Set up the inversion list interpreter-level variables */
23022
23023     PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
23024     PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
23025     PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
23026     PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
23027     PL_XPosix_ptrs[_CC_CASED] =  _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
23028     PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
23029     PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
23030     PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
23031     PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
23032     PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
23033     PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
23034     PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
23035     PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
23036     PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
23037     PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
23038     PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
23039
23040     PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
23041     PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
23042     PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
23043     PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
23044     PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
23045     PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
23046     PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
23047     PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
23048     PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
23049     PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
23050     PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
23051     PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
23052     PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
23053     PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
23054     PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
23055     PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
23056
23057     PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
23058     PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
23059     PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
23060     PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
23061     PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
23062
23063     PL_InBitmap = _new_invlist_C_array(InBitmap_invlist);
23064     PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
23065     PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
23066     PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
23067
23068     PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
23069
23070     PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
23071     PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
23072
23073     PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
23074     PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
23075
23076     PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
23077     PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
23078                                             UNI__PERL_FOLDS_TO_MULTI_CHAR]);
23079     PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
23080                                             UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
23081     PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
23082     PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
23083     PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
23084     PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
23085     PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
23086     PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
23087     PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
23088     PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
23089     PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]);
23090
23091 #  ifdef UNI_XIDC
23092     /* The below are used only by deprecated functions.  They could be removed */
23093     PL_utf8_xidcont  = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
23094     PL_utf8_idcont   = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
23095     PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
23096 #  endif
23097 }
23098
23099 /* These four functions are compiled only in regcomp.c, where they have access
23100  * to the data they return.  They are a way for re_comp.c to get access to that
23101  * data without having to compile the whole data structures. */
23102
23103 I16
23104 Perl_do_uniprop_match(const char * const key, const U16 key_len)
23105 {
23106     PERL_ARGS_ASSERT_DO_UNIPROP_MATCH;
23107
23108     return match_uniprop((U8 *) key, key_len);
23109 }
23110
23111 SV *
23112 Perl_get_prop_definition(pTHX_ const int table_index)
23113 {
23114     PERL_ARGS_ASSERT_GET_PROP_DEFINITION;
23115
23116     /* Create and return the inversion list */
23117     return _new_invlist_C_array(uni_prop_ptrs[table_index]);
23118 }
23119
23120 const char * const *
23121 Perl_get_prop_values(const int table_index)
23122 {
23123     PERL_ARGS_ASSERT_GET_PROP_VALUES;
23124
23125     return UNI_prop_value_ptrs[table_index];
23126 }
23127
23128 const char *
23129 Perl_get_deprecated_property_msg(const Size_t warning_offset)
23130 {
23131     PERL_ARGS_ASSERT_GET_DEPRECATED_PROPERTY_MSG;
23132
23133     return deprecated_property_msgs[warning_offset];
23134 }
23135
23136 #  if 0
23137
23138 This code was mainly added for backcompat to give a warning for non-portable
23139 code points in user-defined properties.  But experiments showed that the
23140 warning in earlier perls were only omitted on overflow, which should be an
23141 error, so there really isnt a backcompat issue, and actually adding the
23142 warning when none was present before might cause breakage, for little gain.  So
23143 khw left this code in, but not enabled.  Tests were never added.
23144
23145 embed.fnc entry:
23146 Ei      |const char *|get_extended_utf8_msg|const UV cp
23147
23148 PERL_STATIC_INLINE const char *
23149 S_get_extended_utf8_msg(pTHX_ const UV cp)
23150 {
23151     U8 dummy[UTF8_MAXBYTES + 1];
23152     HV *msgs;
23153     SV **msg;
23154
23155     uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
23156                              &msgs);
23157
23158     msg = hv_fetchs(msgs, "text", 0);
23159     assert(msg);
23160
23161     (void) sv_2mortal((SV *) msgs);
23162
23163     return SvPVX(*msg);
23164 }
23165
23166 #  endif
23167 #endif /* end of ! PERL_IN_XSUB_RE */
23168
23169 STATIC REGEXP *
23170 S_compile_wildcard(pTHX_ const char * subpattern, const STRLEN len,
23171                          const bool ignore_case)
23172 {
23173     /* Pretends that the input subpattern is qr/subpattern/aam, compiling it
23174      * possibly with /i if the 'ignore_case' parameter is true.  Use /aa
23175      * because nothing outside of ASCII will match.  Use /m because the input
23176      * string may be a bunch of lines strung together.
23177      *
23178      * Also sets up the debugging info */
23179
23180     U32 flags = PMf_MULTILINE|PMf_WILDCARD;
23181     U32 rx_flags;
23182     SV * subpattern_sv = sv_2mortal(newSVpvn(subpattern, len));
23183     REGEXP * subpattern_re;
23184     DECLARE_AND_GET_RE_DEBUG_FLAGS;
23185
23186     PERL_ARGS_ASSERT_COMPILE_WILDCARD;
23187
23188     if (ignore_case) {
23189         flags |= PMf_FOLD;
23190     }
23191     set_regex_charset(&flags, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
23192
23193     /* Like in op.c, we copy the compile time pm flags to the rx ones */
23194     rx_flags = flags & RXf_PMf_COMPILETIME;
23195
23196 #ifndef PERL_IN_XSUB_RE
23197     /* Use the core engine if this file is regcomp.c.  That means no
23198      * 'use re "Debug ..." is in effect, so the core engine is sufficient */
23199     subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23200                                              &PL_core_reg_engine,
23201                                              NULL, NULL,
23202                                              rx_flags, flags);
23203 #else
23204     if (isDEBUG_WILDCARD) {
23205         /* Use the special debugging engine if this file is re_comp.c and wants
23206          * to output the wildcard matching.  This uses whatever
23207          * 'use re "Debug ..." is in effect */
23208         subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23209                                                  &my_reg_engine,
23210                                                  NULL, NULL,
23211                                                  rx_flags, flags);
23212     }
23213     else {
23214         /* Use the special wildcard engine if this file is re_comp.c and
23215          * doesn't want to output the wildcard matching.  This uses whatever
23216          * 'use re "Debug ..." is in effect for compilation, but this engine
23217          * structure has been set up so that it uses the core engine for
23218          * execution, so no execution debugging as a result of re.pm will be
23219          * displayed. */
23220         subpattern_re = Perl_re_op_compile(aTHX_ &subpattern_sv, 1, NULL,
23221                                                  &wild_reg_engine,
23222                                                  NULL, NULL,
23223                                                  rx_flags, flags);
23224         /* XXX The above has the effect that any user-supplied regex engine
23225          * won't be called for matching wildcards.  That might be good, or bad.
23226          * It could be changed in several ways.  The reason it is done the
23227          * current way is to avoid having to save and restore
23228          * ^{^RE_DEBUG_FLAGS} around the execution.  save_scalar() perhaps
23229          * could be used.  Another suggestion is to keep the authoritative
23230          * value of the debug flags in a thread-local variable and add set/get
23231          * magic to ${^RE_DEBUG_FLAGS} to keep the C level variable up to date.
23232          * Still another is to pass a flag, say in the engine's intflags that
23233          * would be checked each time before doing the debug output */
23234     }
23235 #endif
23236
23237     assert(subpattern_re);  /* Should have died if didn't compile successfully */
23238     return subpattern_re;
23239 }
23240
23241 STATIC I32
23242 S_execute_wildcard(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
23243          char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
23244 {
23245     I32 result;
23246     DECLARE_AND_GET_RE_DEBUG_FLAGS;
23247
23248     PERL_ARGS_ASSERT_EXECUTE_WILDCARD;
23249
23250     ENTER;
23251
23252     /* The compilation has set things up so that if the program doesn't want to
23253      * see the wildcard matching procedure, it will get the core execution
23254      * engine, which is subject only to -Dr.  So we have to turn that off
23255      * around this procedure */
23256     if (! isDEBUG_WILDCARD) {
23257         /* Note! Casts away 'volatile' */
23258         SAVEI32(PL_debug);
23259         PL_debug &= ~ DEBUG_r_FLAG;
23260     }
23261
23262     result = CALLREGEXEC(prog, stringarg, strend, strbeg, minend, screamer,
23263                          NULL, nosave);
23264     LEAVE;
23265
23266     return result;
23267 }
23268
23269 SV *
23270 S_handle_user_defined_property(pTHX_
23271
23272     /* Parses the contents of a user-defined property definition; returning the
23273      * expanded definition if possible.  If so, the return is an inversion
23274      * list.
23275      *
23276      * If there are subroutines that are part of the expansion and which aren't
23277      * known at the time of the call to this function, this returns what
23278      * parse_uniprop_string() returned for the first one encountered.
23279      *
23280      * If an error was found, NULL is returned, and 'msg' gets a suitable
23281      * message appended to it.  (Appending allows the back trace of how we got
23282      * to the faulty definition to be displayed through nested calls of
23283      * user-defined subs.)
23284      *
23285      * The caller IS responsible for freeing any returned SV.
23286      *
23287      * The syntax of the contents is pretty much described in perlunicode.pod,
23288      * but we also allow comments on each line */
23289
23290     const char * name,          /* Name of property */
23291     const STRLEN name_len,      /* The name's length in bytes */
23292     const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
23293     const bool to_fold,         /* ? Is this under /i */
23294     const bool runtime,         /* ? Are we in compile- or run-time */
23295     const bool deferrable,      /* Is it ok for this property's full definition
23296                                    to be deferred until later? */
23297     SV* contents,               /* The property's definition */
23298     bool *user_defined_ptr,     /* This will be set TRUE as we wouldn't be
23299                                    getting called unless this is thought to be
23300                                    a user-defined property */
23301     SV * msg,                   /* Any error or warning msg(s) are appended to
23302                                    this */
23303     const STRLEN level)         /* Recursion level of this call */
23304 {
23305     STRLEN len;
23306     const char * string         = SvPV_const(contents, len);
23307     const char * const e        = string + len;
23308     const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
23309     const STRLEN msgs_length_on_entry = SvCUR(msg);
23310
23311     const char * s0 = string;   /* Points to first byte in the current line
23312                                    being parsed in 'string' */
23313     const char overflow_msg[] = "Code point too large in \"";
23314     SV* running_definition = NULL;
23315
23316     PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
23317
23318     *user_defined_ptr = TRUE;
23319
23320     /* Look at each line */
23321     while (s0 < e) {
23322         const char * s;     /* Current byte */
23323         char op = '+';      /* Default operation is 'union' */
23324         IV   min = 0;       /* range begin code point */
23325         IV   max = -1;      /* and range end */
23326         SV* this_definition;
23327
23328         /* Skip comment lines */
23329         if (*s0 == '#') {
23330             s0 = strchr(s0, '\n');
23331             if (s0 == NULL) {
23332                 break;
23333             }
23334             s0++;
23335             continue;
23336         }
23337
23338         /* For backcompat, allow an empty first line */
23339         if (*s0 == '\n') {
23340             s0++;
23341             continue;
23342         }
23343
23344         /* First character in the line may optionally be the operation */
23345         if (   *s0 == '+'
23346             || *s0 == '!'
23347             || *s0 == '-'
23348             || *s0 == '&')
23349         {
23350             op = *s0++;
23351         }
23352
23353         /* If the line is one or two hex digits separated by blank space, its
23354          * a range; otherwise it is either another user-defined property or an
23355          * error */
23356
23357         s = s0;
23358
23359         if (! isXDIGIT(*s)) {
23360             goto check_if_property;
23361         }
23362
23363         do { /* Each new hex digit will add 4 bits. */
23364             if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
23365                 s = strchr(s, '\n');
23366                 if (s == NULL) {
23367                     s = e;
23368                 }
23369                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23370                 sv_catpv(msg, overflow_msg);
23371                 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23372                                      UTF8fARG(is_contents_utf8, s - s0, s0));
23373                 sv_catpvs(msg, "\"");
23374                 goto return_failure;
23375             }
23376
23377             /* Accumulate this digit into the value */
23378             min = (min << 4) + READ_XDIGIT(s);
23379         } while (isXDIGIT(*s));
23380
23381         while (isBLANK(*s)) { s++; }
23382
23383         /* We allow comments at the end of the line */
23384         if (*s == '#') {
23385             s = strchr(s, '\n');
23386             if (s == NULL) {
23387                 s = e;
23388             }
23389             s++;
23390         }
23391         else if (s < e && *s != '\n') {
23392             if (! isXDIGIT(*s)) {
23393                 goto check_if_property;
23394             }
23395
23396             /* Look for the high point of the range */
23397             max = 0;
23398             do {
23399                 if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
23400                     s = strchr(s, '\n');
23401                     if (s == NULL) {
23402                         s = e;
23403                     }
23404                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23405                     sv_catpv(msg, overflow_msg);
23406                     Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23407                                       UTF8fARG(is_contents_utf8, s - s0, s0));
23408                     sv_catpvs(msg, "\"");
23409                     goto return_failure;
23410                 }
23411
23412                 max = (max << 4) + READ_XDIGIT(s);
23413             } while (isXDIGIT(*s));
23414
23415             while (isBLANK(*s)) { s++; }
23416
23417             if (*s == '#') {
23418                 s = strchr(s, '\n');
23419                 if (s == NULL) {
23420                     s = e;
23421                 }
23422             }
23423             else if (s < e && *s != '\n') {
23424                 goto check_if_property;
23425             }
23426         }
23427
23428         if (max == -1) {    /* The line only had one entry */
23429             max = min;
23430         }
23431         else if (max < min) {
23432             if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23433             sv_catpvs(msg, "Illegal range in \"");
23434             Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23435                                 UTF8fARG(is_contents_utf8, s - s0, s0));
23436             sv_catpvs(msg, "\"");
23437             goto return_failure;
23438         }
23439
23440 #  if 0   /* See explanation at definition above of get_extended_utf8_msg() */
23441
23442         if (   UNICODE_IS_PERL_EXTENDED(min)
23443             || UNICODE_IS_PERL_EXTENDED(max))
23444         {
23445             if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23446
23447             /* If both code points are non-portable, warn only on the lower
23448              * one. */
23449             sv_catpv(msg, get_extended_utf8_msg(
23450                                             (UNICODE_IS_PERL_EXTENDED(min))
23451                                             ? min : max));
23452             sv_catpvs(msg, " in \"");
23453             Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
23454                                  UTF8fARG(is_contents_utf8, s - s0, s0));
23455             sv_catpvs(msg, "\"");
23456         }
23457
23458 #  endif
23459
23460         /* Here, this line contains a legal range */
23461         this_definition = sv_2mortal(_new_invlist(2));
23462         this_definition = _add_range_to_invlist(this_definition, min, max);
23463         goto calculate;
23464
23465       check_if_property:
23466
23467         /* Here it isn't a legal range line.  See if it is a legal property
23468          * line.  First find the end of the meat of the line */
23469         s = strpbrk(s, "#\n");
23470         if (s == NULL) {
23471             s = e;
23472         }
23473
23474         /* Ignore trailing blanks in keeping with the requirements of
23475          * parse_uniprop_string() */
23476         s--;
23477         while (s > s0 && isBLANK_A(*s)) {
23478             s--;
23479         }
23480         s++;
23481
23482         this_definition = parse_uniprop_string(s0, s - s0,
23483                                                is_utf8, to_fold, runtime,
23484                                                deferrable,
23485                                                NULL,
23486                                                user_defined_ptr, msg,
23487                                                (name_len == 0)
23488                                                 ? level /* Don't increase level
23489                                                            if input is empty */
23490                                                 : level + 1
23491                                               );
23492         if (this_definition == NULL) {
23493             goto return_failure;    /* 'msg' should have had the reason
23494                                        appended to it by the above call */
23495         }
23496
23497         if (! is_invlist(this_definition)) {    /* Unknown at this time */
23498             return newSVsv(this_definition);
23499         }
23500
23501         if (*s != '\n') {
23502             s = strchr(s, '\n');
23503             if (s == NULL) {
23504                 s = e;
23505             }
23506         }
23507
23508       calculate:
23509
23510         switch (op) {
23511             case '+':
23512                 _invlist_union(running_definition, this_definition,
23513                                                         &running_definition);
23514                 break;
23515             case '-':
23516                 _invlist_subtract(running_definition, this_definition,
23517                                                         &running_definition);
23518                 break;
23519             case '&':
23520                 _invlist_intersection(running_definition, this_definition,
23521                                                         &running_definition);
23522                 break;
23523             case '!':
23524                 _invlist_union_complement_2nd(running_definition,
23525                                         this_definition, &running_definition);
23526                 break;
23527             default:
23528                 Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
23529                                  __FILE__, __LINE__, op);
23530                 break;
23531         }
23532
23533         /* Position past the '\n' */
23534         s0 = s + 1;
23535     }   /* End of loop through the lines of 'contents' */
23536
23537     /* Here, we processed all the lines in 'contents' without error.  If we
23538      * didn't add any warnings, simply return success */
23539     if (msgs_length_on_entry == SvCUR(msg)) {
23540
23541         /* If the expansion was empty, the answer isn't nothing: its an empty
23542          * inversion list */
23543         if (running_definition == NULL) {
23544             running_definition = _new_invlist(1);
23545         }
23546
23547         return running_definition;
23548     }
23549
23550     /* Otherwise, add some explanatory text, but we will return success */
23551     goto return_msg;
23552
23553   return_failure:
23554     running_definition = NULL;
23555
23556   return_msg:
23557
23558     if (name_len > 0) {
23559         sv_catpvs(msg, " in expansion of ");
23560         Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
23561     }
23562
23563     return running_definition;
23564 }
23565
23566 /* As explained below, certain operations need to take place in the first
23567  * thread created.  These macros switch contexts */
23568 #  ifdef USE_ITHREADS
23569 #    define DECLARATION_FOR_GLOBAL_CONTEXT                                  \
23570                                         PerlInterpreter * save_aTHX = aTHX;
23571 #    define SWITCH_TO_GLOBAL_CONTEXT                                        \
23572                            PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
23573 #    define RESTORE_CONTEXT  PERL_SET_CONTEXT((aTHX = save_aTHX));
23574 #    define CUR_CONTEXT      aTHX
23575 #    define ORIGINAL_CONTEXT save_aTHX
23576 #  else
23577 #    define DECLARATION_FOR_GLOBAL_CONTEXT    dNOOP
23578 #    define SWITCH_TO_GLOBAL_CONTEXT          NOOP
23579 #    define RESTORE_CONTEXT                   NOOP
23580 #    define CUR_CONTEXT                       NULL
23581 #    define ORIGINAL_CONTEXT                  NULL
23582 #  endif
23583
23584 STATIC void
23585 S_delete_recursion_entry(pTHX_ void *key)
23586 {
23587     /* Deletes the entry used to detect recursion when expanding user-defined
23588      * properties.  This is a function so it can be set up to be called even if
23589      * the program unexpectedly quits */
23590
23591     dVAR;
23592     SV ** current_entry;
23593     const STRLEN key_len = strlen((const char *) key);
23594     DECLARATION_FOR_GLOBAL_CONTEXT;
23595
23596     SWITCH_TO_GLOBAL_CONTEXT;
23597
23598     /* If the entry is one of these types, it is a permanent entry, and not the
23599      * one used to detect recursions.  This function should delete only the
23600      * recursion entry */
23601     current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
23602     if (     current_entry
23603         && ! is_invlist(*current_entry)
23604         && ! SvPOK(*current_entry))
23605     {
23606         (void) hv_delete(PL_user_def_props, (const char *) key, key_len,
23607                                                                     G_DISCARD);
23608     }
23609
23610     RESTORE_CONTEXT;
23611 }
23612
23613 STATIC SV *
23614 S_get_fq_name(pTHX_
23615               const char * const name,    /* The first non-blank in the \p{}, \P{} */
23616               const Size_t name_len,      /* Its length in bytes, not including any trailing space */
23617               const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
23618               const bool has_colon_colon
23619              )
23620 {
23621     /* Returns a mortal SV containing the fully qualified version of the input
23622      * name */
23623
23624     SV * fq_name;
23625
23626     fq_name = newSVpvs_flags("", SVs_TEMP);
23627
23628     /* Use the current package if it wasn't included in our input */
23629     if (! has_colon_colon) {
23630         const HV * pkg = (IN_PERL_COMPILETIME)
23631                          ? PL_curstash
23632                          : CopSTASH(PL_curcop);
23633         const char* pkgname = HvNAME(pkg);
23634
23635         Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23636                       UTF8fARG(is_utf8, strlen(pkgname), pkgname));
23637         sv_catpvs(fq_name, "::");
23638     }
23639
23640     Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23641                          UTF8fARG(is_utf8, name_len, name));
23642     return fq_name;
23643 }
23644
23645 STATIC SV *
23646 S_parse_uniprop_string(pTHX_
23647
23648     /* Parse the interior of a \p{}, \P{}.  Returns its definition if knowable
23649      * now.  If so, the return is an inversion list.
23650      *
23651      * If the property is user-defined, it is a subroutine, which in turn
23652      * may call other subroutines.  This function will call the whole nest of
23653      * them to get the definition they return; if some aren't known at the time
23654      * of the call to this function, the fully qualified name of the highest
23655      * level sub is returned.  It is an error to call this function at runtime
23656      * without every sub defined.
23657      *
23658      * If an error was found, NULL is returned, and 'msg' gets a suitable
23659      * message appended to it.  (Appending allows the back trace of how we got
23660      * to the faulty definition to be displayed through nested calls of
23661      * user-defined subs.)
23662      *
23663      * The caller should NOT try to free any returned inversion list.
23664      *
23665      * Other parameters will be set on return as described below */
23666
23667     const char * const name,    /* The first non-blank in the \p{}, \P{} */
23668     Size_t name_len,            /* Its length in bytes, not including any
23669                                    trailing space */
23670     const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
23671     const bool to_fold,         /* ? Is this under /i */
23672     const bool runtime,         /* TRUE if this is being called at run time */
23673     const bool deferrable,      /* TRUE if it's ok for the definition to not be
23674                                    known at this call */
23675     AV ** strings,              /* To return string property values, like named
23676                                    sequences */
23677     bool *user_defined_ptr,     /* Upon return from this function it will be
23678                                    set to TRUE if any component is a
23679                                    user-defined property */
23680     SV * msg,                   /* Any error or warning msg(s) are appended to
23681                                    this */
23682     const STRLEN level)         /* Recursion level of this call */
23683 {
23684     dVAR;
23685     char* lookup_name;          /* normalized name for lookup in our tables */
23686     unsigned lookup_len;        /* Its length */
23687     enum { Not_Strict = 0,      /* Some properties have stricter name */
23688            Strict,              /* normalization rules, which we decide */
23689            As_Is                /* upon based on parsing */
23690          } stricter = Not_Strict;
23691
23692     /* nv= or numeric_value=, or possibly one of the cjk numeric properties
23693      * (though it requires extra effort to download them from Unicode and
23694      * compile perl to know about them) */
23695     bool is_nv_type = FALSE;
23696
23697     unsigned int i, j = 0;
23698     int equals_pos = -1;    /* Where the '=' is found, or negative if none */
23699     int slash_pos  = -1;    /* Where the '/' is found, or negative if none */
23700     int table_index = 0;    /* The entry number for this property in the table
23701                                of all Unicode property names */
23702     bool starts_with_Is = FALSE;  /* ? Does the name start with 'Is' */
23703     Size_t lookup_offset = 0;   /* Used to ignore the first few characters of
23704                                    the normalized name in certain situations */
23705     Size_t non_pkg_begin = 0;   /* Offset of first byte in 'name' that isn't
23706                                    part of a package name */
23707     Size_t lun_non_pkg_begin = 0;   /* Similarly for 'lookup_name' */
23708     bool could_be_user_defined = TRUE;  /* ? Could this be a user-defined
23709                                              property rather than a Unicode
23710                                              one. */
23711     SV * prop_definition = NULL;  /* The returned definition of 'name' or NULL
23712                                      if an error.  If it is an inversion list,
23713                                      it is the definition.  Otherwise it is a
23714                                      string containing the fully qualified sub
23715                                      name of 'name' */
23716     SV * fq_name = NULL;        /* For user-defined properties, the fully
23717                                    qualified name */
23718     bool invert_return = FALSE; /* ? Do we need to complement the result before
23719                                      returning it */
23720     bool stripped_utf8_pkg = FALSE; /* Set TRUE if the input includes an
23721                                        explicit utf8:: package that we strip
23722                                        off  */
23723     /* The expansion of properties that could be either user-defined or
23724      * official unicode ones is deferred until runtime, including a marker for
23725      * those that might be in the latter category.  This boolean indicates if
23726      * we've seen that marker.  If not, what we're parsing can't be such an
23727      * official Unicode property whose expansion was deferred */
23728     bool could_be_deferred_official = FALSE;
23729
23730     PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
23731
23732     /* The input will be normalized into 'lookup_name' */
23733     Newx(lookup_name, name_len, char);
23734     SAVEFREEPV(lookup_name);
23735
23736     /* Parse the input. */
23737     for (i = 0; i < name_len; i++) {
23738         char cur = name[i];
23739
23740         /* Most of the characters in the input will be of this ilk, being parts
23741          * of a name */
23742         if (isIDCONT_A(cur)) {
23743
23744             /* Case differences are ignored.  Our lookup routine assumes
23745              * everything is lowercase, so normalize to that */
23746             if (isUPPER_A(cur)) {
23747                 lookup_name[j++] = toLOWER_A(cur);
23748                 continue;
23749             }
23750
23751             if (cur == '_') { /* Don't include these in the normalized name */
23752                 continue;
23753             }
23754
23755             lookup_name[j++] = cur;
23756
23757             /* The first character in a user-defined name must be of this type.
23758              * */
23759             if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
23760                 could_be_user_defined = FALSE;
23761             }
23762
23763             continue;
23764         }
23765
23766         /* Here, the character is not something typically in a name,  But these
23767          * two types of characters (and the '_' above) can be freely ignored in
23768          * most situations.  Later it may turn out we shouldn't have ignored
23769          * them, and we have to reparse, but we don't have enough information
23770          * yet to make that decision */
23771         if (cur == '-' || isSPACE_A(cur)) {
23772             could_be_user_defined = FALSE;
23773             continue;
23774         }
23775
23776         /* An equals sign or single colon mark the end of the first part of
23777          * the property name */
23778         if (    cur == '='
23779             || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
23780         {
23781             lookup_name[j++] = '='; /* Treat the colon as an '=' */
23782             equals_pos = j; /* Note where it occurred in the input */
23783             could_be_user_defined = FALSE;
23784             break;
23785         }
23786
23787         /* If this looks like it is a marker we inserted at compile time,
23788          * set a flag and otherwise ignore it.  If it isn't in the final
23789          * position, keep it as it would have been user input. */
23790         if (     UNLIKELY(cur == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
23791             && ! deferrable
23792             &&   could_be_user_defined
23793             &&   i == name_len - 1)
23794         {
23795             name_len--;
23796             could_be_deferred_official = TRUE;
23797             continue;
23798         }
23799
23800         /* Otherwise, this character is part of the name. */
23801         lookup_name[j++] = cur;
23802
23803         /* Here it isn't a single colon, so if it is a colon, it must be a
23804          * double colon */
23805         if (cur == ':') {
23806
23807             /* A double colon should be a package qualifier.  We note its
23808              * position and continue.  Note that one could have
23809              *      pkg1::pkg2::...::foo
23810              * so that the position at the end of the loop will be just after
23811              * the final qualifier */
23812
23813             i++;
23814             non_pkg_begin = i + 1;
23815             lookup_name[j++] = ':';
23816             lun_non_pkg_begin = j;
23817         }
23818         else { /* Only word chars (and '::') can be in a user-defined name */
23819             could_be_user_defined = FALSE;
23820         }
23821     } /* End of parsing through the lhs of the property name (or all of it if
23822          no rhs) */
23823
23824 #  define STRLENs(s)  (sizeof("" s "") - 1)
23825
23826     /* If there is a single package name 'utf8::', it is ambiguous.  It could
23827      * be for a user-defined property, or it could be a Unicode property, as
23828      * all of them are considered to be for that package.  For the purposes of
23829      * parsing the rest of the property, strip it off */
23830     if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
23831         lookup_name +=  STRLENs("utf8::");
23832         j -=  STRLENs("utf8::");
23833         equals_pos -=  STRLENs("utf8::");
23834         stripped_utf8_pkg = TRUE;
23835     }
23836
23837     /* Here, we are either done with the whole property name, if it was simple;
23838      * or are positioned just after the '=' if it is compound. */
23839
23840     if (equals_pos >= 0) {
23841         assert(stricter == Not_Strict); /* We shouldn't have set this yet */
23842
23843         /* Space immediately after the '=' is ignored */
23844         i++;
23845         for (; i < name_len; i++) {
23846             if (! isSPACE_A(name[i])) {
23847                 break;
23848             }
23849         }
23850
23851         /* Most punctuation after the equals indicates a subpattern, like
23852          * \p{foo=/bar/} */
23853         if (   isPUNCT_A(name[i])
23854             &&  name[i] != '-'
23855             &&  name[i] != '+'
23856             &&  name[i] != '_'
23857             &&  name[i] != '{'
23858                 /* A backslash means the real delimitter is the next character,
23859                  * but it must be punctuation */
23860             && (name[i] != '\\' || (i < name_len && isPUNCT_A(name[i+1]))))
23861         {
23862             bool special_property = memEQs(lookup_name, j - 1, "name")
23863                                  || memEQs(lookup_name, j - 1, "na");
23864             if (! special_property) {
23865                 /* Find the property.  The table includes the equals sign, so
23866                  * we use 'j' as-is */
23867                 table_index = do_uniprop_match(lookup_name, j);
23868             }
23869             if (special_property || table_index) {
23870                 REGEXP * subpattern_re;
23871                 char open = name[i++];
23872                 char close;
23873                 const char * pos_in_brackets;
23874                 const char * const * prop_values;
23875                 bool escaped = 0;
23876
23877                 /* Backslash => delimitter is the character following.  We
23878                  * already checked that it is punctuation */
23879                 if (open == '\\') {
23880                     open = name[i++];
23881                     escaped = 1;
23882                 }
23883
23884                 /* This data structure is constructed so that the matching
23885                  * closing bracket is 3 past its matching opening.  The second
23886                  * set of closing is so that if the opening is something like
23887                  * ']', the closing will be that as well.  Something similar is
23888                  * done in toke.c */
23889                 pos_in_brackets = memCHRs("([<)]>)]>", open);
23890                 close = (pos_in_brackets) ? pos_in_brackets[3] : open;
23891
23892                 if (    i >= name_len
23893                     ||  name[name_len-1] != close
23894                     || (escaped && name[name_len-2] != '\\')
23895                         /* Also make sure that there are enough characters.
23896                          * e.g., '\\\' would show up incorrectly as legal even
23897                          * though it is too short */
23898                     || (SSize_t) (name_len - i - 1 - escaped) < 0)
23899                 {
23900                     sv_catpvs(msg, "Unicode property wildcard not terminated");
23901                     goto append_name_to_msg;
23902                 }
23903
23904                 Perl_ck_warner_d(aTHX_
23905                     packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS),
23906                     "The Unicode property wildcards feature is experimental");
23907
23908                 if (special_property) {
23909                     const char * error_msg;
23910                     const char * revised_name = name + i;
23911                     Size_t revised_name_len = name_len - (i + 1 + escaped);
23912
23913                     /* Currently, the only 'special_property' is name, which we
23914                      * lookup in _charnames.pm */
23915
23916                     if (! load_charnames(newSVpvs("placeholder"),
23917                                          revised_name, revised_name_len,
23918                                          &error_msg))
23919                     {
23920                         sv_catpv(msg, error_msg);
23921                         goto append_name_to_msg;
23922                     }
23923
23924                     /* Farm this out to a function just to make the current
23925                      * function less unwieldy */
23926                     if (handle_names_wildcard(revised_name, revised_name_len,
23927                                               &prop_definition,
23928                                               strings))
23929                     {
23930                         return prop_definition;
23931                     }
23932
23933                     goto failed;
23934                 }
23935
23936                 prop_values = get_prop_values(table_index);
23937
23938                 /* Now create and compile the wildcard subpattern.  Use /i
23939                  * because the property values are supposed to match with case
23940                  * ignored. */
23941                 subpattern_re = compile_wildcard(name + i,
23942                                                  name_len - i - 1 - escaped,
23943                                                  TRUE /* /i */
23944                                                 );
23945
23946                 /* For each legal property value, see if the supplied pattern
23947                  * matches it. */
23948                 while (*prop_values) {
23949                     const char * const entry = *prop_values;
23950                     const Size_t len = strlen(entry);
23951                     SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP);
23952
23953                     if (execute_wildcard(subpattern_re,
23954                                  (char *) entry,
23955                                  (char *) entry + len,
23956                                  (char *) entry, 0,
23957                                  entry_sv,
23958                                  0))
23959                     { /* Here, matched.  Add to the returned list */
23960                         Size_t total_len = j + len;
23961                         SV * sub_invlist = NULL;
23962                         char * this_string;
23963
23964                         /* We know this is a legal \p{property=value}.  Call
23965                          * the function to return the list of code points that
23966                          * match it */
23967                         Newxz(this_string, total_len + 1, char);
23968                         Copy(lookup_name, this_string, j, char);
23969                         my_strlcat(this_string, entry, total_len + 1);
23970                         SAVEFREEPV(this_string);
23971                         sub_invlist = parse_uniprop_string(this_string,
23972                                                            total_len,
23973                                                            is_utf8,
23974                                                            to_fold,
23975                                                            runtime,
23976                                                            deferrable,
23977                                                            NULL,
23978                                                            user_defined_ptr,
23979                                                            msg,
23980                                                            level + 1);
23981                         _invlist_union(prop_definition, sub_invlist,
23982                                        &prop_definition);
23983                     }
23984
23985                     prop_values++;  /* Next iteration, look at next propvalue */
23986                 } /* End of looking through property values; (the data
23987                      structure is terminated by a NULL ptr) */
23988
23989                 SvREFCNT_dec_NN(subpattern_re);
23990
23991                 if (prop_definition) {
23992                     return prop_definition;
23993                 }
23994
23995                 sv_catpvs(msg, "No Unicode property value wildcard matches:");
23996                 goto append_name_to_msg;
23997             }
23998
23999             /* Here's how khw thinks we should proceed to handle the properties
24000              * not yet done:    Bidi Mirroring Glyph        can map to ""
24001                                 Bidi Paired Bracket         can map to ""
24002                                 Case Folding  (both full and simple)
24003                                             Shouldn't /i be good enough for Full
24004                                 Decomposition Mapping
24005                                 Equivalent Unified Ideograph    can map to ""
24006                                 Lowercase Mapping  (both full and simple)
24007                                 NFKC Case Fold                  can map to ""
24008                                 Titlecase Mapping  (both full and simple)
24009                                 Uppercase Mapping  (both full and simple)
24010              * Handle these the same way Name is done, using say, _wild.pm, but
24011              * having both loose and full, like in charclass_invlists.h.
24012              * Perhaps move block and script to that as they are somewhat large
24013              * in charclass_invlists.h.
24014              * For properties where the default is the code point itself, such
24015              * as any of the case changing mappings, the string would otherwise
24016              * consist of all Unicode code points in UTF-8 strung together.
24017              * This would be impractical.  So instead, examine their compiled
24018              * pattern, looking at the ssc.  If none, reject the pattern as an
24019              * error.  Otherwise run the pattern against every code point in
24020              * the ssc.  The ssc is kind of like tr18's 3.9 Possible Match Sets
24021              * And it might be good to create an API to return the ssc.
24022              * Or handle them like the algorithmic names are done
24023              */
24024         } /* End of is a wildcard subppattern */
24025
24026         /* \p{name=...} is handled specially.  Instead of using the normal
24027          * mechanism involving charclass_invlists.h, it uses _charnames.pm
24028          * which has the necessary (huge) data accessible to it, and which
24029          * doesn't get loaded unless necessary.  The legal syntax for names is
24030          * somewhat different than other properties due both to the vagaries of
24031          * a few outlier official names, and the fact that only a few ASCII
24032          * characters are permitted in them */
24033         if (   memEQs(lookup_name, j - 1, "name")
24034             || memEQs(lookup_name, j - 1, "na"))
24035         {
24036             dSP;
24037             HV * table;
24038             SV * character;
24039             const char * error_msg;
24040             CV* lookup_loose;
24041             SV * character_name;
24042             STRLEN character_len;
24043             UV cp;
24044
24045             stricter = As_Is;
24046
24047             /* Since the RHS (after skipping initial space) is passed unchanged
24048              * to charnames, and there are different criteria for what are
24049              * legal characters in the name, just parse it here.  A character
24050              * name must begin with an ASCII alphabetic */
24051             if (! isALPHA(name[i])) {
24052                 goto failed;
24053             }
24054             lookup_name[j++] = name[i];
24055
24056             for (++i; i < name_len; i++) {
24057                 /* Official names can only be in the ASCII range, and only
24058                  * certain characters */
24059                 if (! isASCII(name[i]) || ! isCHARNAME_CONT(name[i])) {
24060                     goto failed;
24061                 }
24062                 lookup_name[j++] = name[i];
24063             }
24064
24065             /* Finished parsing, save the name into an SV */
24066             character_name = newSVpvn(lookup_name + equals_pos, j - equals_pos);
24067
24068             /* Make sure _charnames is loaded.  (The parameters give context
24069              * for any errors generated */
24070             table = load_charnames(character_name, name, name_len, &error_msg);
24071             if (table == NULL) {
24072                 sv_catpv(msg, error_msg);
24073                 goto append_name_to_msg;
24074             }
24075
24076             lookup_loose = get_cv("_charnames::_loose_regcomp_lookup", 0);
24077             if (! lookup_loose) {
24078                 Perl_croak(aTHX_
24079                        "panic: Can't find '_charnames::_loose_regcomp_lookup");
24080             }
24081
24082             PUSHSTACKi(PERLSI_REGCOMP);
24083             ENTER ;
24084             SAVETMPS;
24085             save_re_context();
24086
24087             PUSHMARK(SP) ;
24088             XPUSHs(character_name);
24089             PUTBACK;
24090             call_sv(MUTABLE_SV(lookup_loose), G_SCALAR);
24091
24092             SPAGAIN ;
24093
24094             character = POPs;
24095             SvREFCNT_inc_simple_void_NN(character);
24096
24097             PUTBACK ;
24098             FREETMPS ;
24099             LEAVE ;
24100             POPSTACK;
24101
24102             if (! SvOK(character)) {
24103                 goto failed;
24104             }
24105
24106             cp = valid_utf8_to_uvchr((U8 *) SvPVX(character), &character_len);
24107             if (character_len == SvCUR(character)) {
24108                 prop_definition = add_cp_to_invlist(NULL, cp);
24109             }
24110             else {
24111                 AV * this_string;
24112
24113                 /* First of the remaining characters in the string. */
24114                 char * remaining = SvPVX(character) + character_len;
24115
24116                 if (strings == NULL) {
24117                     goto failed;    /* XXX Perhaps a specific msg instead, like
24118                                        'not available here' */
24119                 }
24120
24121                 if (*strings == NULL) {
24122                     *strings = newAV();
24123                 }
24124
24125                 this_string = newAV();
24126                 av_push(this_string, newSVuv(cp));
24127
24128                 do {
24129                     cp = valid_utf8_to_uvchr((U8 *) remaining, &character_len);
24130                     av_push(this_string, newSVuv(cp));
24131                     remaining += character_len;
24132                 } while (remaining < SvEND(character));
24133
24134                 av_push(*strings, (SV *) this_string);
24135             }
24136
24137             return prop_definition;
24138         }
24139
24140         /* Certain properties whose values are numeric need special handling.
24141          * They may optionally be prefixed by 'is'.  Ignore that prefix for the
24142          * purposes of checking if this is one of those properties */
24143         if (memBEGINPs(lookup_name, j, "is")) {
24144             lookup_offset = 2;
24145         }
24146
24147         /* Then check if it is one of these specially-handled properties.  The
24148          * possibilities are hard-coded because easier this way, and the list
24149          * is unlikely to change.
24150          *
24151          * All numeric value type properties are of this ilk, and are also
24152          * special in a different way later on.  So find those first.  There
24153          * are several numeric value type properties in the Unihan DB (which is
24154          * unlikely to be compiled with perl, but we handle it here in case it
24155          * does get compiled).  They all end with 'numeric'.  The interiors
24156          * aren't checked for the precise property.  This would stop working if
24157          * a cjk property were to be created that ended with 'numeric' and
24158          * wasn't a numeric type */
24159         is_nv_type = memEQs(lookup_name + lookup_offset,
24160                        j - 1 - lookup_offset, "numericvalue")
24161                   || memEQs(lookup_name + lookup_offset,
24162                       j - 1 - lookup_offset, "nv")
24163                   || (   memENDPs(lookup_name + lookup_offset,
24164                             j - 1 - lookup_offset, "numeric")
24165                       && (   memBEGINPs(lookup_name + lookup_offset,
24166                                       j - 1 - lookup_offset, "cjk")
24167                           || memBEGINPs(lookup_name + lookup_offset,
24168                                       j - 1 - lookup_offset, "k")));
24169         if (   is_nv_type
24170             || memEQs(lookup_name + lookup_offset,
24171                       j - 1 - lookup_offset, "canonicalcombiningclass")
24172             || memEQs(lookup_name + lookup_offset,
24173                       j - 1 - lookup_offset, "ccc")
24174             || memEQs(lookup_name + lookup_offset,
24175                       j - 1 - lookup_offset, "age")
24176             || memEQs(lookup_name + lookup_offset,
24177                       j - 1 - lookup_offset, "in")
24178             || memEQs(lookup_name + lookup_offset,
24179                       j - 1 - lookup_offset, "presentin"))
24180         {
24181             unsigned int k;
24182
24183             /* Since the stuff after the '=' is a number, we can't throw away
24184              * '-' willy-nilly, as those could be a minus sign.  Other stricter
24185              * rules also apply.  However, these properties all can have the
24186              * rhs not be a number, in which case they contain at least one
24187              * alphabetic.  In those cases, the stricter rules don't apply.
24188              * But the numeric type properties can have the alphas [Ee] to
24189              * signify an exponent, and it is still a number with stricter
24190              * rules.  So look for an alpha that signifies not-strict */
24191             stricter = Strict;
24192             for (k = i; k < name_len; k++) {
24193                 if (   isALPHA_A(name[k])
24194                     && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
24195                 {
24196                     stricter = Not_Strict;
24197                     break;
24198                 }
24199             }
24200         }
24201
24202         if (stricter) {
24203
24204             /* A number may have a leading '+' or '-'.  The latter is retained
24205              * */
24206             if (name[i] == '+') {
24207                 i++;
24208             }
24209             else if (name[i] == '-') {
24210                 lookup_name[j++] = '-';
24211                 i++;
24212             }
24213
24214             /* Skip leading zeros including single underscores separating the
24215              * zeros, or between the final leading zero and the first other
24216              * digit */
24217             for (; i < name_len - 1; i++) {
24218                 if (    name[i] != '0'
24219                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
24220                 {
24221                     break;
24222                 }
24223             }
24224         }
24225     }
24226     else {  /* No '=' */
24227
24228        /* Only a few properties without an '=' should be parsed with stricter
24229         * rules.  The list is unlikely to change. */
24230         if (   memBEGINPs(lookup_name, j, "perl")
24231             && memNEs(lookup_name + 4, j - 4, "space")
24232             && memNEs(lookup_name + 4, j - 4, "word"))
24233         {
24234             stricter = Strict;
24235
24236             /* We set the inputs back to 0 and the code below will reparse,
24237              * using strict */
24238             i = j = 0;
24239         }
24240     }
24241
24242     /* Here, we have either finished the property, or are positioned to parse
24243      * the remainder, and we know if stricter rules apply.  Finish out, if not
24244      * already done */
24245     for (; i < name_len; i++) {
24246         char cur = name[i];
24247
24248         /* In all instances, case differences are ignored, and we normalize to
24249          * lowercase */
24250         if (isUPPER_A(cur)) {
24251             lookup_name[j++] = toLOWER(cur);
24252             continue;
24253         }
24254
24255         /* An underscore is skipped, but not under strict rules unless it
24256          * separates two digits */
24257         if (cur == '_') {
24258             if (    stricter
24259                 && (     i == 0 || (int) i == equals_pos || i == name_len- 1
24260                     || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
24261             {
24262                 lookup_name[j++] = '_';
24263             }
24264             continue;
24265         }
24266
24267         /* Hyphens are skipped except under strict */
24268         if (cur == '-' && ! stricter) {
24269             continue;
24270         }
24271
24272         /* XXX Bug in documentation.  It says white space skipped adjacent to
24273          * non-word char.  Maybe we should, but shouldn't skip it next to a dot
24274          * in a number */
24275         if (isSPACE_A(cur) && ! stricter) {
24276             continue;
24277         }
24278
24279         lookup_name[j++] = cur;
24280
24281         /* Unless this is a non-trailing slash, we are done with it */
24282         if (i >= name_len - 1 || cur != '/') {
24283             continue;
24284         }
24285
24286         slash_pos = j;
24287
24288         /* A slash in the 'numeric value' property indicates that what follows
24289          * is a denominator.  It can have a leading '+' and '0's that should be
24290          * skipped.  But we have never allowed a negative denominator, so treat
24291          * a minus like every other character.  (No need to rule out a second
24292          * '/', as that won't match anything anyway */
24293         if (is_nv_type) {
24294             i++;
24295             if (i < name_len && name[i] == '+') {
24296                 i++;
24297             }
24298
24299             /* Skip leading zeros including underscores separating digits */
24300             for (; i < name_len - 1; i++) {
24301                 if (   name[i] != '0'
24302                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
24303                 {
24304                     break;
24305                 }
24306             }
24307
24308             /* Store the first real character in the denominator */
24309             if (i < name_len) {
24310                 lookup_name[j++] = name[i];
24311             }
24312         }
24313     }
24314
24315     /* Here are completely done parsing the input 'name', and 'lookup_name'
24316      * contains a copy, normalized.
24317      *
24318      * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
24319      * different from without the underscores.  */
24320     if (  (   UNLIKELY(memEQs(lookup_name, j, "l"))
24321            || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
24322         && UNLIKELY(name[name_len-1] == '_'))
24323     {
24324         lookup_name[j++] = '&';
24325     }
24326
24327     /* If the original input began with 'In' or 'Is', it could be a subroutine
24328      * call to a user-defined property instead of a Unicode property name. */
24329     if (    name_len - non_pkg_begin > 2
24330         &&  name[non_pkg_begin+0] == 'I'
24331         && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
24332     {
24333         /* Names that start with In have different characterstics than those
24334          * that start with Is */
24335         if (name[non_pkg_begin+1] == 's') {
24336             starts_with_Is = TRUE;
24337         }
24338     }
24339     else {
24340         could_be_user_defined = FALSE;
24341     }
24342
24343     if (could_be_user_defined) {
24344         CV* user_sub;
24345
24346         /* If the user defined property returns the empty string, it could
24347          * easily be because the pattern is being compiled before the data it
24348          * actually needs to compile is available.  This could be argued to be
24349          * a bug in the perl code, but this is a change of behavior for Perl,
24350          * so we handle it.  This means that intentionally returning nothing
24351          * will not be resolved until runtime */
24352         bool empty_return = FALSE;
24353
24354         /* Here, the name could be for a user defined property, which are
24355          * implemented as subs. */
24356         user_sub = get_cvn_flags(name, name_len, 0);
24357         if (! user_sub) {
24358
24359             /* Here, the property name could be a user-defined one, but there
24360              * is no subroutine to handle it (as of now).   Defer handling it
24361              * until runtime.  Otherwise, a block defined by Unicode in a later
24362              * release would get the synonym InFoo added for it, and existing
24363              * code that used that name would suddenly break if it referred to
24364              * the property before the sub was declared.  See [perl #134146] */
24365             if (deferrable) {
24366                 goto definition_deferred;
24367             }
24368
24369             /* Here, we are at runtime, and didn't find the user property.  It
24370              * could be an official property, but only if no package was
24371              * specified, or just the utf8:: package. */
24372             if (could_be_deferred_official) {
24373                 lookup_name += lun_non_pkg_begin;
24374                 j -= lun_non_pkg_begin;
24375             }
24376             else if (! stripped_utf8_pkg) {
24377                 goto unknown_user_defined;
24378             }
24379
24380             /* Drop down to look up in the official properties */
24381         }
24382         else {
24383             const char insecure[] = "Insecure user-defined property";
24384
24385             /* Here, there is a sub by the correct name.  Normally we call it
24386              * to get the property definition */
24387             dSP;
24388             SV * user_sub_sv = MUTABLE_SV(user_sub);
24389             SV * error;     /* Any error returned by calling 'user_sub' */
24390             SV * key;       /* The key into the hash of user defined sub names
24391                              */
24392             SV * placeholder;
24393             SV ** saved_user_prop_ptr;      /* Hash entry for this property */
24394
24395             /* How many times to retry when another thread is in the middle of
24396              * expanding the same definition we want */
24397             PERL_INT_FAST8_T retry_countdown = 10;
24398
24399             DECLARATION_FOR_GLOBAL_CONTEXT;
24400
24401             /* If we get here, we know this property is user-defined */
24402             *user_defined_ptr = TRUE;
24403
24404             /* We refuse to call a potentially tainted subroutine; returning an
24405              * error instead */
24406             if (TAINT_get) {
24407                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24408                 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
24409                 goto append_name_to_msg;
24410             }
24411
24412             /* In principal, we only call each subroutine property definition
24413              * once during the life of the program.  This guarantees that the
24414              * property definition never changes.  The results of the single
24415              * sub call are stored in a hash, which is used instead for future
24416              * references to this property.  The property definition is thus
24417              * immutable.  But, to allow the user to have a /i-dependent
24418              * definition, we call the sub once for non-/i, and once for /i,
24419              * should the need arise, passing the /i status as a parameter.
24420              *
24421              * We start by constructing the hash key name, consisting of the
24422              * fully qualified subroutine name, preceded by the /i status, so
24423              * that there is a key for /i and a different key for non-/i */
24424             key = newSVpvn(((to_fold) ? "1" : "0"), 1);
24425             fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
24426                                           non_pkg_begin != 0);
24427             sv_catsv(key, fq_name);
24428             sv_2mortal(key);
24429
24430             /* We only call the sub once throughout the life of the program
24431              * (with the /i, non-/i exception noted above).  That means the
24432              * hash must be global and accessible to all threads.  It is
24433              * created at program start-up, before any threads are created, so
24434              * is accessible to all children.  But this creates some
24435              * complications.
24436              *
24437              * 1) The keys can't be shared, or else problems arise; sharing is
24438              *    turned off at hash creation time
24439              * 2) All SVs in it are there for the remainder of the life of the
24440              *    program, and must be created in the same interpreter context
24441              *    as the hash, or else they will be freed from the wrong pool
24442              *    at global destruction time.  This is handled by switching to
24443              *    the hash's context to create each SV going into it, and then
24444              *    immediately switching back
24445              * 3) All accesses to the hash must be controlled by a mutex, to
24446              *    prevent two threads from getting an unstable state should
24447              *    they simultaneously be accessing it.  The code below is
24448              *    crafted so that the mutex is locked whenever there is an
24449              *    access and unlocked only when the next stable state is
24450              *    achieved.
24451              *
24452              * The hash stores either the definition of the property if it was
24453              * valid, or, if invalid, the error message that was raised.  We
24454              * use the type of SV to distinguish.
24455              *
24456              * There's also the need to guard against the definition expansion
24457              * from infinitely recursing.  This is handled by storing the aTHX
24458              * of the expanding thread during the expansion.  Again the SV type
24459              * is used to distinguish this from the other two cases.  If we
24460              * come to here and the hash entry for this property is our aTHX,
24461              * it means we have recursed, and the code assumes that we would
24462              * infinitely recurse, so instead stops and raises an error.
24463              * (Any recursion has always been treated as infinite recursion in
24464              * this feature.)
24465              *
24466              * If instead, the entry is for a different aTHX, it means that
24467              * that thread has gotten here first, and hasn't finished expanding
24468              * the definition yet.  We just have to wait until it is done.  We
24469              * sleep and retry a few times, returning an error if the other
24470              * thread doesn't complete. */
24471
24472           re_fetch:
24473             USER_PROP_MUTEX_LOCK;
24474
24475             /* If we have an entry for this key, the subroutine has already
24476              * been called once with this /i status. */
24477             saved_user_prop_ptr = hv_fetch(PL_user_def_props,
24478                                                    SvPVX(key), SvCUR(key), 0);
24479             if (saved_user_prop_ptr) {
24480
24481                 /* If the saved result is an inversion list, it is the valid
24482                  * definition of this property */
24483                 if (is_invlist(*saved_user_prop_ptr)) {
24484                     prop_definition = *saved_user_prop_ptr;
24485
24486                     /* The SV in the hash won't be removed until global
24487                      * destruction, so it is stable and we can unlock */
24488                     USER_PROP_MUTEX_UNLOCK;
24489
24490                     /* The caller shouldn't try to free this SV */
24491                     return prop_definition;
24492                 }
24493
24494                 /* Otherwise, if it is a string, it is the error message
24495                  * that was returned when we first tried to evaluate this
24496                  * property.  Fail, and append the message */
24497                 if (SvPOK(*saved_user_prop_ptr)) {
24498                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24499                     sv_catsv(msg, *saved_user_prop_ptr);
24500
24501                     /* The SV in the hash won't be removed until global
24502                      * destruction, so it is stable and we can unlock */
24503                     USER_PROP_MUTEX_UNLOCK;
24504
24505                     return NULL;
24506                 }
24507
24508                 assert(SvIOK(*saved_user_prop_ptr));
24509
24510                 /* Here, we have an unstable entry in the hash.  Either another
24511                  * thread is in the middle of expanding the property's
24512                  * definition, or we are ourselves recursing.  We use the aTHX
24513                  * in it to distinguish */
24514                 if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
24515
24516                     /* Here, it's another thread doing the expanding.  We've
24517                      * looked as much as we are going to at the contents of the
24518                      * hash entry.  It's safe to unlock. */
24519                     USER_PROP_MUTEX_UNLOCK;
24520
24521                     /* Retry a few times */
24522                     if (retry_countdown-- > 0) {
24523                         PerlProc_sleep(1);
24524                         goto re_fetch;
24525                     }
24526
24527                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24528                     sv_catpvs(msg, "Timeout waiting for another thread to "
24529                                    "define");
24530                     goto append_name_to_msg;
24531                 }
24532
24533                 /* Here, we are recursing; don't dig any deeper */
24534                 USER_PROP_MUTEX_UNLOCK;
24535
24536                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24537                 sv_catpvs(msg,
24538                           "Infinite recursion in user-defined property");
24539                 goto append_name_to_msg;
24540             }
24541
24542             /* Here, this thread has exclusive control, and there is no entry
24543              * for this property in the hash.  So we have the go ahead to
24544              * expand the definition ourselves. */
24545
24546             PUSHSTACKi(PERLSI_REGCOMP);
24547             ENTER;
24548
24549             /* Create a temporary placeholder in the hash to detect recursion
24550              * */
24551             SWITCH_TO_GLOBAL_CONTEXT;
24552             placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
24553             (void) hv_store_ent(PL_user_def_props, key, placeholder, 0);
24554             RESTORE_CONTEXT;
24555
24556             /* Now that we have a placeholder, we can let other threads
24557              * continue */
24558             USER_PROP_MUTEX_UNLOCK;
24559
24560             /* Make sure the placeholder always gets destroyed */
24561             SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key));
24562
24563             PUSHMARK(SP);
24564             SAVETMPS;
24565
24566             /* Call the user's function, with the /i status as a parameter.
24567              * Note that we have gone to a lot of trouble to keep this call
24568              * from being within the locked mutex region. */
24569             XPUSHs(boolSV(to_fold));
24570             PUTBACK;
24571
24572             /* The following block was taken from swash_init().  Presumably
24573              * they apply to here as well, though we no longer use a swash --
24574              * khw */
24575             SAVEHINTS();
24576             save_re_context();
24577             /* We might get here via a subroutine signature which uses a utf8
24578              * parameter name, at which point PL_subname will have been set
24579              * but not yet used. */
24580             save_item(PL_subname);
24581
24582             /* G_SCALAR guarantees a single return value */
24583             (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
24584
24585             SPAGAIN;
24586
24587             error = ERRSV;
24588             if (TAINT_get || SvTRUE(error)) {
24589                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24590                 if (SvTRUE(error)) {
24591                     sv_catpvs(msg, "Error \"");
24592                     sv_catsv(msg, error);
24593                     sv_catpvs(msg, "\"");
24594                 }
24595                 if (TAINT_get) {
24596                     if (SvTRUE(error)) sv_catpvs(msg, "; ");
24597                     sv_catpvn(msg, insecure, sizeof(insecure) - 1);
24598                 }
24599
24600                 if (name_len > 0) {
24601                     sv_catpvs(msg, " in expansion of ");
24602                     Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
24603                                                                   name_len,
24604                                                                   name));
24605                 }
24606
24607                 (void) POPs;
24608                 prop_definition = NULL;
24609             }
24610             else {
24611                 SV * contents = POPs;
24612
24613                 /* The contents is supposed to be the expansion of the property
24614                  * definition.  If the definition is deferrable, and we got an
24615                  * empty string back, set a flag to later defer it (after clean
24616                  * up below). */
24617                 if (      deferrable
24618                     && (! SvPOK(contents) || SvCUR(contents) == 0))
24619                 {
24620                         empty_return = TRUE;
24621                 }
24622                 else { /* Otherwise, call a function to check for valid syntax,
24623                           and handle it */
24624
24625                     prop_definition = handle_user_defined_property(
24626                                                     name, name_len,
24627                                                     is_utf8, to_fold, runtime,
24628                                                     deferrable,
24629                                                     contents, user_defined_ptr,
24630                                                     msg,
24631                                                     level);
24632                 }
24633             }
24634
24635             /* Here, we have the results of the expansion.  Delete the
24636              * placeholder, and if the definition is now known, replace it with
24637              * that definition.  We need exclusive access to the hash, and we
24638              * can't let anyone else in, between when we delete the placeholder
24639              * and add the permanent entry */
24640             USER_PROP_MUTEX_LOCK;
24641
24642             S_delete_recursion_entry(aTHX_ SvPVX(key));
24643
24644             if (    ! empty_return
24645                 && (! prop_definition || is_invlist(prop_definition)))
24646             {
24647                 /* If we got success we use the inversion list defining the
24648                  * property; otherwise use the error message */
24649                 SWITCH_TO_GLOBAL_CONTEXT;
24650                 (void) hv_store_ent(PL_user_def_props,
24651                                     key,
24652                                     ((prop_definition)
24653                                      ? newSVsv(prop_definition)
24654                                      : newSVsv(msg)),
24655                                     0);
24656                 RESTORE_CONTEXT;
24657             }
24658
24659             /* All done, and the hash now has a permanent entry for this
24660              * property.  Give up exclusive control */
24661             USER_PROP_MUTEX_UNLOCK;
24662
24663             FREETMPS;
24664             LEAVE;
24665             POPSTACK;
24666
24667             if (empty_return) {
24668                 goto definition_deferred;
24669             }
24670
24671             if (prop_definition) {
24672
24673                 /* If the definition is for something not known at this time,
24674                  * we toss it, and go return the main property name, as that's
24675                  * the one the user will be aware of */
24676                 if (! is_invlist(prop_definition)) {
24677                     SvREFCNT_dec_NN(prop_definition);
24678                     goto definition_deferred;
24679                 }
24680
24681                 sv_2mortal(prop_definition);
24682             }
24683
24684             /* And return */
24685             return prop_definition;
24686
24687         }   /* End of calling the subroutine for the user-defined property */
24688     }       /* End of it could be a user-defined property */
24689
24690     /* Here it wasn't a user-defined property that is known at this time.  See
24691      * if it is a Unicode property */
24692
24693     lookup_len = j;     /* This is a more mnemonic name than 'j' */
24694
24695     /* Get the index into our pointer table of the inversion list corresponding
24696      * to the property */
24697     table_index = do_uniprop_match(lookup_name, lookup_len);
24698
24699     /* If it didn't find the property ... */
24700     if (table_index == 0) {
24701
24702         /* Try again stripping off any initial 'Is'.  This is because we
24703          * promise that an initial Is is optional.  The same isn't true of
24704          * names that start with 'In'.  Those can match only blocks, and the
24705          * lookup table already has those accounted for. */
24706         if (starts_with_Is) {
24707             lookup_name += 2;
24708             lookup_len -= 2;
24709             equals_pos -= 2;
24710             slash_pos -= 2;
24711
24712             table_index = do_uniprop_match(lookup_name, lookup_len);
24713         }
24714
24715         if (table_index == 0) {
24716             char * canonical;
24717
24718             /* Here, we didn't find it.  If not a numeric type property, and
24719              * can't be a user-defined one, it isn't a legal property */
24720             if (! is_nv_type) {
24721                 if (! could_be_user_defined) {
24722                     goto failed;
24723                 }
24724
24725                 /* Here, the property name is legal as a user-defined one.   At
24726                  * compile time, it might just be that the subroutine for that
24727                  * property hasn't been encountered yet, but at runtime, it's
24728                  * an error to try to use an undefined one */
24729                 if (! deferrable) {
24730                     goto unknown_user_defined;;
24731                 }
24732
24733                 goto definition_deferred;
24734             } /* End of isn't a numeric type property */
24735
24736             /* The numeric type properties need more work to decide.  What we
24737              * do is make sure we have the number in canonical form and look
24738              * that up. */
24739
24740             if (slash_pos < 0) {    /* No slash */
24741
24742                 /* When it isn't a rational, take the input, convert it to a
24743                  * NV, then create a canonical string representation of that
24744                  * NV. */
24745
24746                 NV value;
24747                 SSize_t value_len = lookup_len - equals_pos;
24748
24749                 /* Get the value */
24750                 if (   value_len <= 0
24751                     || my_atof3(lookup_name + equals_pos, &value,
24752                                 value_len)
24753                           != lookup_name + lookup_len)
24754                 {
24755                     goto failed;
24756                 }
24757
24758                 /* If the value is an integer, the canonical value is integral
24759                  * */
24760                 if (Perl_ceil(value) == value) {
24761                     canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
24762                                             equals_pos, lookup_name, value);
24763                 }
24764                 else {  /* Otherwise, it is %e with a known precision */
24765                     char * exp_ptr;
24766
24767                     canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
24768                                                 equals_pos, lookup_name,
24769                                                 PL_E_FORMAT_PRECISION, value);
24770
24771                     /* The exponent generated is expecting two digits, whereas
24772                      * %e on some systems will generate three.  Remove leading
24773                      * zeros in excess of 2 from the exponent.  We start
24774                      * looking for them after the '=' */
24775                     exp_ptr = strchr(canonical + equals_pos, 'e');
24776                     if (exp_ptr) {
24777                         char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
24778                         SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
24779
24780                         assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
24781
24782                         if (excess_exponent_len > 0) {
24783                             SSize_t leading_zeros = strspn(cur_ptr, "0");
24784                             SSize_t excess_leading_zeros
24785                                     = MIN(leading_zeros, excess_exponent_len);
24786                             if (excess_leading_zeros > 0) {
24787                                 Move(cur_ptr + excess_leading_zeros,
24788                                      cur_ptr,
24789                                      strlen(cur_ptr) - excess_leading_zeros
24790                                        + 1,  /* Copy the NUL as well */
24791                                      char);
24792                             }
24793                         }
24794                     }
24795                 }
24796             }
24797             else {  /* Has a slash.  Create a rational in canonical form  */
24798                 UV numerator, denominator, gcd, trial;
24799                 const char * end_ptr;
24800                 const char * sign = "";
24801
24802                 /* We can't just find the numerator, denominator, and do the
24803                  * division, then use the method above, because that is
24804                  * inexact.  And the input could be a rational that is within
24805                  * epsilon (given our precision) of a valid rational, and would
24806                  * then incorrectly compare valid.
24807                  *
24808                  * We're only interested in the part after the '=' */
24809                 const char * this_lookup_name = lookup_name + equals_pos;
24810                 lookup_len -= equals_pos;
24811                 slash_pos -= equals_pos;
24812
24813                 /* Handle any leading minus */
24814                 if (this_lookup_name[0] == '-') {
24815                     sign = "-";
24816                     this_lookup_name++;
24817                     lookup_len--;
24818                     slash_pos--;
24819                 }
24820
24821                 /* Convert the numerator to numeric */
24822                 end_ptr = this_lookup_name + slash_pos;
24823                 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
24824                     goto failed;
24825                 }
24826
24827                 /* It better have included all characters before the slash */
24828                 if (*end_ptr != '/') {
24829                     goto failed;
24830                 }
24831
24832                 /* Set to look at just the denominator */
24833                 this_lookup_name += slash_pos;
24834                 lookup_len -= slash_pos;
24835                 end_ptr = this_lookup_name + lookup_len;
24836
24837                 /* Convert the denominator to numeric */
24838                 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
24839                     goto failed;
24840                 }
24841
24842                 /* It better be the rest of the characters, and don't divide by
24843                  * 0 */
24844                 if (   end_ptr != this_lookup_name + lookup_len
24845                     || denominator == 0)
24846                 {
24847                     goto failed;
24848                 }
24849
24850                 /* Get the greatest common denominator using
24851                    http://en.wikipedia.org/wiki/Euclidean_algorithm */
24852                 gcd = numerator;
24853                 trial = denominator;
24854                 while (trial != 0) {
24855                     UV temp = trial;
24856                     trial = gcd % trial;
24857                     gcd = temp;
24858                 }
24859
24860                 /* If already in lowest possible terms, we have already tried
24861                  * looking this up */
24862                 if (gcd == 1) {
24863                     goto failed;
24864                 }
24865
24866                 /* Reduce the rational, which should put it in canonical form
24867                  * */
24868                 numerator /= gcd;
24869                 denominator /= gcd;
24870
24871                 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
24872                         equals_pos, lookup_name, sign, numerator, denominator);
24873             }
24874
24875             /* Here, we have the number in canonical form.  Try that */
24876             table_index = do_uniprop_match(canonical, strlen(canonical));
24877             if (table_index == 0) {
24878                 goto failed;
24879             }
24880         }   /* End of still didn't find the property in our table */
24881     }       /* End of       didn't find the property in our table */
24882
24883     /* Here, we have a non-zero return, which is an index into a table of ptrs.
24884      * A negative return signifies that the real index is the absolute value,
24885      * but the result needs to be inverted */
24886     if (table_index < 0) {
24887         invert_return = TRUE;
24888         table_index = -table_index;
24889     }
24890
24891     /* Out-of band indices indicate a deprecated property.  The proper index is
24892      * modulo it with the table size.  And dividing by the table size yields
24893      * an offset into a table constructed by regen/mk_invlists.pl to contain
24894      * the corresponding warning message */
24895     if (table_index > MAX_UNI_KEYWORD_INDEX) {
24896         Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
24897         table_index %= MAX_UNI_KEYWORD_INDEX;
24898         Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
24899                 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
24900                 (int) name_len, name,
24901                 get_deprecated_property_msg(warning_offset));
24902     }
24903
24904     /* In a few properties, a different property is used under /i.  These are
24905      * unlikely to change, so are hard-coded here. */
24906     if (to_fold) {
24907         if (   table_index == UNI_XPOSIXUPPER
24908             || table_index == UNI_XPOSIXLOWER
24909             || table_index == UNI_TITLE)
24910         {
24911             table_index = UNI_CASED;
24912         }
24913         else if (   table_index == UNI_UPPERCASELETTER
24914                  || table_index == UNI_LOWERCASELETTER
24915 #  ifdef UNI_TITLECASELETTER   /* Missing from early Unicodes */
24916                  || table_index == UNI_TITLECASELETTER
24917 #  endif
24918         ) {
24919             table_index = UNI_CASEDLETTER;
24920         }
24921         else if (  table_index == UNI_POSIXUPPER
24922                 || table_index == UNI_POSIXLOWER)
24923         {
24924             table_index = UNI_POSIXALPHA;
24925         }
24926     }
24927
24928     /* Create and return the inversion list */
24929     prop_definition = get_prop_definition(table_index);
24930     sv_2mortal(prop_definition);
24931
24932     /* See if there is a private use override to add to this definition */
24933     {
24934         COPHH * hinthash = (IN_PERL_COMPILETIME)
24935                            ? CopHINTHASH_get(&PL_compiling)
24936                            : CopHINTHASH_get(PL_curcop);
24937         SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0);
24938
24939         if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) {
24940
24941             /* See if there is an element in the hints hash for this table */
24942             SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index);
24943             const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup));
24944
24945             if (pos) {
24946                 bool dummy;
24947                 SV * pu_definition;
24948                 SV * pu_invlist;
24949                 SV * expanded_prop_definition =
24950                             sv_2mortal(invlist_clone(prop_definition, NULL));
24951
24952                 /* If so, it's definition is the string from here to the next
24953                  * \a character.  And its format is the same as a user-defined
24954                  * property */
24955                 pos += SvCUR(pu_lookup);
24956                 pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos);
24957                 pu_invlist = handle_user_defined_property(lookup_name,
24958                                                           lookup_len,
24959                                                           0, /* Not UTF-8 */
24960                                                           0, /* Not folded */
24961                                                           runtime,
24962                                                           deferrable,
24963                                                           pu_definition,
24964                                                           &dummy,
24965                                                           msg,
24966                                                           level);
24967                 if (TAINT_get) {
24968                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24969                     sv_catpvs(msg, "Insecure private-use override");
24970                     goto append_name_to_msg;
24971                 }
24972
24973                 /* For now, as a safety measure, make sure that it doesn't
24974                  * override non-private use code points */
24975                 _invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist);
24976
24977                 /* Add it to the list to be returned */
24978                 _invlist_union(prop_definition, pu_invlist,
24979                                &expanded_prop_definition);
24980                 prop_definition = expanded_prop_definition;
24981                 Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental");
24982             }
24983         }
24984     }
24985
24986     if (invert_return) {
24987         _invlist_invert(prop_definition);
24988     }
24989     return prop_definition;
24990
24991   unknown_user_defined:
24992     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24993     sv_catpvs(msg, "Unknown user-defined property name");
24994     goto append_name_to_msg;
24995
24996   failed:
24997     if (non_pkg_begin != 0) {
24998         if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24999         sv_catpvs(msg, "Illegal user-defined property name");
25000     }
25001     else {
25002         if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
25003         sv_catpvs(msg, "Can't find Unicode property definition");
25004     }
25005     /* FALLTHROUGH */
25006
25007   append_name_to_msg:
25008     {
25009         const char * prefix = (runtime && level == 0) ?  " \\p{" : " \"";
25010         const char * suffix = (runtime && level == 0) ?  "}" : "\"";
25011
25012         sv_catpv(msg, prefix);
25013         Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
25014         sv_catpv(msg, suffix);
25015     }
25016
25017     return NULL;
25018
25019   definition_deferred:
25020
25021     {
25022         bool is_qualified = non_pkg_begin != 0;  /* If has "::" */
25023
25024         /* Here it could yet to be defined, so defer evaluation of this until
25025          * its needed at runtime.  We need the fully qualified property name to
25026          * avoid ambiguity */
25027         if (! fq_name) {
25028             fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
25029                                                                 is_qualified);
25030         }
25031
25032         /* If it didn't come with a package, or the package is utf8::, this
25033          * actually could be an official Unicode property whose inclusion we
25034          * are deferring until runtime to make sure that it isn't overridden by
25035          * a user-defined property of the same name (which we haven't
25036          * encountered yet).  Add a marker to indicate this possibility, for
25037          * use at such time when we first need the definition during pattern
25038          * matching execution */
25039         if (! is_qualified || memBEGINPs(name, non_pkg_begin, "utf8::")) {
25040             sv_catpvs(fq_name, DEFERRED_COULD_BE_OFFICIAL_MARKERs);
25041         }
25042
25043         /* We also need a trailing newline */
25044         sv_catpvs(fq_name, "\n");
25045
25046         *user_defined_ptr = TRUE;
25047         return fq_name;
25048     }
25049 }
25050
25051 STATIC bool
25052 S_handle_names_wildcard(pTHX_ const char * wname, /* wildcard name to match */
25053                               const STRLEN wname_len, /* Its length */
25054                               SV ** prop_definition,
25055                               AV ** strings)
25056 {
25057     /* Deal with Name property wildcard subpatterns; returns TRUE if there were
25058      * any matches, adding them to prop_definition */
25059
25060     dSP;
25061
25062     CV * get_names_info;        /* entry to charnames.pm to get info we need */
25063     SV * names_string;          /* Contains all character names, except algo */
25064     SV * algorithmic_names;     /* Contains info about algorithmically
25065                                    generated character names */
25066     REGEXP * subpattern_re;     /* The user's pattern to match with */
25067     struct regexp * prog;       /* The compiled pattern */
25068     char * all_names_start;     /* lib/unicore/Name.pl string of every
25069                                    (non-algorithmic) character name */
25070     char * cur_pos;             /* We match, effectively using /gc; this is
25071                                    where we are now */
25072     bool found_matches = FALSE; /* Did any name match so far? */
25073     SV * empty;                 /* For matching zero length names */
25074     SV * must_sv;               /* Contains the substring, if any, that must be
25075                                    in a name for the subpattern to match */
25076     const char * must;          /* The PV of 'must' */
25077     STRLEN must_len;            /* And its length */
25078     SV * syllable_name = NULL;  /* For Hangul syllables */
25079     const char hangul_prefix[] = "HANGUL SYLLABLE ";
25080     const STRLEN hangul_prefix_len = sizeof(hangul_prefix) - 1;
25081
25082     /* By inspection, there are a maximum of 7 bytes in the suffix of a hangul
25083      * syllable name, and these are immutable and guaranteed by the Unicode
25084      * standard to never be extended */
25085     const STRLEN syl_max_len = hangul_prefix_len + 7;
25086
25087     IV i;
25088
25089     PERL_ARGS_ASSERT_HANDLE_NAMES_WILDCARD;
25090
25091     /* Make sure _charnames is loaded.  (The parameters give context
25092      * for any errors generated */
25093     get_names_info = get_cv("_charnames::_get_names_info", 0);
25094     if (! get_names_info) {
25095         Perl_croak(aTHX_ "panic: Can't find '_charnames::_get_names_info");
25096     }
25097
25098     /* Get the charnames data */
25099     PUSHSTACKi(PERLSI_REGCOMP);
25100     ENTER ;
25101     SAVETMPS;
25102     save_re_context();
25103
25104     PUSHMARK(SP) ;
25105     PUTBACK;
25106
25107     /* Special _charnames entry point that returns the info this routine
25108      * requires */
25109     call_sv(MUTABLE_SV(get_names_info), G_ARRAY);
25110
25111     SPAGAIN ;
25112
25113     /* Data structure for names which end in their very own code points */
25114     algorithmic_names = POPs;
25115     SvREFCNT_inc_simple_void_NN(algorithmic_names);
25116
25117     /* The lib/unicore/Name.pl string */
25118     names_string = POPs;
25119     SvREFCNT_inc_simple_void_NN(names_string);
25120
25121     PUTBACK ;
25122     FREETMPS ;
25123     LEAVE ;
25124     POPSTACK;
25125
25126     if (   ! SvROK(names_string)
25127         || ! SvROK(algorithmic_names))
25128     {   /* Perhaps should panic instead XXX */
25129         SvREFCNT_dec(names_string);
25130         SvREFCNT_dec(algorithmic_names);
25131         return FALSE;
25132     }
25133
25134     names_string = sv_2mortal(SvRV(names_string));
25135     all_names_start = SvPVX(names_string);
25136     cur_pos = all_names_start;
25137
25138     algorithmic_names= sv_2mortal(SvRV(algorithmic_names));
25139
25140     /* Compile the subpattern consisting of the name being looked for */
25141     subpattern_re = compile_wildcard(wname, wname_len, FALSE /* /-i */ );
25142
25143     must_sv = re_intuit_string(subpattern_re);
25144     if (must_sv) {
25145         /* regexec.c can free the re_intuit_string() return. GH #17734 */
25146         must_sv = sv_2mortal(newSVsv(must_sv));
25147         must = SvPV(must_sv, must_len);
25148     }
25149     else {
25150         must = "";
25151         must_len = 0;
25152     }
25153
25154     /* (Note: 'must' could contain a NUL.  And yet we use strspn() below on it.
25155      * This works because the NUL causes the function to return early, thus
25156      * showing that there are characters in it other than the acceptable ones,
25157      * which is our desired result.) */
25158
25159     prog = ReANY(subpattern_re);
25160
25161     /* If only nothing is matched, skip to where empty names are looked for */
25162     if (prog->maxlen == 0) {
25163         goto check_empty;
25164     }
25165
25166     /* And match against the string of all names /gc.  Don't even try if it
25167      * must match a character not found in any name. */
25168     if (strspn(must, "\n -0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ()") == must_len)
25169     {
25170         while (execute_wildcard(subpattern_re,
25171                                 cur_pos,
25172                                 SvEND(names_string),
25173                                 all_names_start, 0,
25174                                 names_string,
25175                                 0))
25176         { /* Here, matched. */
25177
25178             /* Note the string entries look like
25179              *      00001\nSTART OF HEADING\n\n
25180              * so we could match anywhere in that string.  We have to rule out
25181              * matching a code point line */
25182             char * this_name_start = all_names_start
25183                                                 + RX_OFFS(subpattern_re)->start;
25184             char * this_name_end   = all_names_start
25185                                                 + RX_OFFS(subpattern_re)->end;
25186             char * cp_start;
25187             char * cp_end;
25188             UV cp = 0;      /* Silences some compilers */
25189             AV * this_string = NULL;
25190             bool is_multi = FALSE;
25191
25192             /* If matched nothing, advance to next possible match */
25193             if (this_name_start == this_name_end) {
25194                 cur_pos = (char *) memchr(this_name_end + 1, '\n',
25195                                           SvEND(names_string) - this_name_end);
25196                 if (cur_pos == NULL) {
25197                     break;
25198                 }
25199             }
25200             else {
25201                 /* Position the next match to start beyond the current returned
25202                  * entry */
25203                 cur_pos = (char *) memchr(this_name_end, '\n',
25204                                           SvEND(names_string) - this_name_end);
25205             }
25206
25207             /* Back up to the \n just before the beginning of the character. */
25208             cp_end = (char *) my_memrchr(all_names_start,
25209                                          '\n',
25210                                          this_name_start - all_names_start);
25211
25212             /* If we didn't find a \n, it means it matched somewhere in the
25213              * initial '00000' in the string, so isn't a real match */
25214             if (cp_end == NULL) {
25215                 continue;
25216             }
25217
25218             this_name_start = cp_end + 1;   /* The name starts just after */
25219             cp_end--;                       /* the \n, and the code point */
25220                                             /* ends just before it */
25221
25222             /* All code points are 5 digits long */
25223             cp_start = cp_end - 4;
25224
25225             /* This shouldn't happen, as we found a \n, and the first \n is
25226              * further along than what we subtracted */
25227             assert(cp_start >= all_names_start);
25228
25229             if (cp_start == all_names_start) {
25230                 *prop_definition = add_cp_to_invlist(*prop_definition, 0);
25231                 continue;
25232             }
25233
25234             /* If the character is a blank, we either have a named sequence, or
25235              * something is wrong */
25236             if (*(cp_start - 1) == ' ') {
25237                 cp_start = (char *) my_memrchr(all_names_start,
25238                                                '\n',
25239                                                cp_start - all_names_start);
25240                 cp_start++;
25241             }
25242
25243             assert(cp_start != NULL && cp_start >= all_names_start + 2);
25244
25245             /* Except for the first line in the string, the sequence before the
25246              * code point is \n\n.  If that isn't the case here, we didn't
25247              * match the name of a character.  (We could have matched a named
25248              * sequence, not currently handled */
25249             if (*(cp_start - 1) != '\n' || *(cp_start - 2) != '\n') {
25250                 continue;
25251             }
25252
25253             /* We matched!  Add this to the list */
25254             found_matches = TRUE;
25255
25256             /* Loop through all the code points in the sequence */
25257             while (cp_start < cp_end) {
25258
25259                 /* Calculate this code point from its 5 digits */
25260                 cp = (XDIGIT_VALUE(cp_start[0]) << 16)
25261                    + (XDIGIT_VALUE(cp_start[1]) << 12)
25262                    + (XDIGIT_VALUE(cp_start[2]) << 8)
25263                    + (XDIGIT_VALUE(cp_start[3]) << 4)
25264                    +  XDIGIT_VALUE(cp_start[4]);
25265
25266                 cp_start += 6;  /* Go past any blank */
25267
25268                 if (cp_start < cp_end || is_multi) {
25269                     if (this_string == NULL) {
25270                         this_string = newAV();
25271                     }
25272
25273                     is_multi = TRUE;
25274                     av_push(this_string, newSVuv(cp));
25275                 }
25276             }
25277
25278             if (is_multi) { /* Was more than one code point */
25279                 if (*strings == NULL) {
25280                     *strings = newAV();
25281                 }
25282
25283                 av_push(*strings, (SV *) this_string);
25284             }
25285             else {  /* Only a single code point */
25286                 *prop_definition = add_cp_to_invlist(*prop_definition, cp);
25287             }
25288         } /* End of loop through the non-algorithmic names string */
25289     }
25290
25291     /* There are also character names not in 'names_string'.  These are
25292      * algorithmically generatable.  Try this pattern on each possible one.
25293      * (khw originally planned to leave this out given the large number of
25294      * matches attempted; but the speed turned out to be quite acceptable
25295      *
25296      * There are plenty of opportunities to optimize to skip many of the tests.
25297      * beyond the rudimentary ones already here */
25298
25299     /* First see if the subpattern matches any of the algorithmic generatable
25300      * Hangul syllable names.
25301      *
25302      * We know none of these syllable names will match if the input pattern
25303      * requires more bytes than any syllable has, or if the input pattern only
25304      * matches an empty name, or if the pattern has something it must match and
25305      * one of the characters in that isn't in any Hangul syllable. */
25306     if (    prog->minlen <= (SSize_t) syl_max_len
25307         &&  prog->maxlen > 0
25308         && (strspn(must, "\n ABCDEGHIJKLMNOPRSTUWY") == must_len))
25309     {
25310         /* These constants, names, values, and algorithm are adapted from the
25311          * Unicode standard, version 5.1, section 3.12, and should never
25312          * change. */
25313         const char * JamoL[] = {
25314             "G", "GG", "N", "D", "DD", "R", "M", "B", "BB",
25315             "S", "SS", "", "J", "JJ", "C", "K", "T", "P", "H"
25316         };
25317         const int LCount = C_ARRAY_LENGTH(JamoL);
25318
25319         const char * JamoV[] = {
25320             "A", "AE", "YA", "YAE", "EO", "E", "YEO", "YE", "O", "WA",
25321             "WAE", "OE", "YO", "U", "WEO", "WE", "WI", "YU", "EU", "YI",
25322             "I"
25323         };
25324         const int VCount = C_ARRAY_LENGTH(JamoV);
25325
25326         const char * JamoT[] = {
25327             "", "G", "GG", "GS", "N", "NJ", "NH", "D", "L",
25328             "LG", "LM", "LB", "LS", "LT", "LP", "LH", "M", "B",
25329             "BS", "S", "SS", "NG", "J", "C", "K", "T", "P", "H"
25330         };
25331         const int TCount = C_ARRAY_LENGTH(JamoT);
25332
25333         int L, V, T;
25334
25335         /* This is the initial Hangul syllable code point; each time through the
25336          * inner loop, it maps to the next higher code point.  For more info,
25337          * see the Hangul syllable section of the Unicode standard. */
25338         int cp = 0xAC00;
25339
25340         syllable_name = sv_2mortal(newSV(syl_max_len));
25341         sv_setpvn(syllable_name, hangul_prefix, hangul_prefix_len);
25342
25343         for (L = 0; L < LCount; L++) {
25344             for (V = 0; V < VCount; V++) {
25345                 for (T = 0; T < TCount; T++) {
25346
25347                     /* Truncate back to the prefix, which is unvarying */
25348                     SvCUR_set(syllable_name, hangul_prefix_len);
25349
25350                     sv_catpv(syllable_name, JamoL[L]);
25351                     sv_catpv(syllable_name, JamoV[V]);
25352                     sv_catpv(syllable_name, JamoT[T]);
25353
25354                     if (execute_wildcard(subpattern_re,
25355                                 SvPVX(syllable_name),
25356                                 SvEND(syllable_name),
25357                                 SvPVX(syllable_name), 0,
25358                                 syllable_name,
25359                                 0))
25360                     {
25361                         *prop_definition = add_cp_to_invlist(*prop_definition,
25362                                                              cp);
25363                         found_matches = TRUE;
25364                     }
25365
25366                     cp++;
25367                 }
25368             }
25369         }
25370     }
25371
25372     /* The rest of the algorithmically generatable names are of the form
25373      * "PREFIX-code_point".  The prefixes and the code point limits of each
25374      * were returned to us in the array 'algorithmic_names' from data in
25375      * lib/unicore/Name.pm.  'code_point' in the name is expressed in hex. */
25376     for (i = 0; i <= av_top_index((AV *) algorithmic_names); i++) {
25377         IV j;
25378
25379         /* Each element of the array is a hash, giving the details for the
25380          * series of names it covers.  There is the base name of the characters
25381          * in the series, and the low and high code points in the series.  And,
25382          * for optimization purposes a string containing all the legal
25383          * characters that could possibly be in a name in this series. */
25384         HV * this_series = (HV *) SvRV(* av_fetch((AV *) algorithmic_names, i, 0));
25385         SV * prefix = * hv_fetchs(this_series, "name", 0);
25386         IV low = SvIV(* hv_fetchs(this_series, "low", 0));
25387         IV high = SvIV(* hv_fetchs(this_series, "high", 0));
25388         char * legal = SvPVX(* hv_fetchs(this_series, "legal", 0));
25389
25390         /* Pre-allocate an SV with enough space */
25391         SV * algo_name = sv_2mortal(Perl_newSVpvf(aTHX_ "%s-0000",
25392                                                         SvPVX(prefix)));
25393         if (high >= 0x10000) {
25394             sv_catpvs(algo_name, "0");
25395         }
25396
25397         /* This series can be skipped entirely if the pattern requires
25398          * something longer than any name in the series, or can only match an
25399          * empty name, or contains a character not found in any name in the
25400          * series */
25401         if (    prog->minlen <= (SSize_t) SvCUR(algo_name)
25402             &&  prog->maxlen > 0
25403             && (strspn(must, legal) == must_len))
25404         {
25405             for (j = low; j <= high; j++) { /* For each code point in the series */
25406
25407                 /* Get its name, and see if it matches the subpattern */
25408                 Perl_sv_setpvf(aTHX_ algo_name, "%s-%X", SvPVX(prefix),
25409                                      (unsigned) j);
25410
25411                 if (execute_wildcard(subpattern_re,
25412                                     SvPVX(algo_name),
25413                                     SvEND(algo_name),
25414                                     SvPVX(algo_name), 0,
25415                                     algo_name,
25416                                     0))
25417                 {
25418                     *prop_definition = add_cp_to_invlist(*prop_definition, j);
25419                     found_matches = TRUE;
25420                 }
25421             }
25422         }
25423     }
25424
25425   check_empty:
25426     /* Finally, see if the subpattern matches an empty string */
25427     empty = newSVpvs("");
25428     if (execute_wildcard(subpattern_re,
25429                          SvPVX(empty),
25430                          SvEND(empty),
25431                          SvPVX(empty), 0,
25432                          empty,
25433                          0))
25434     {
25435         /* Many code points have empty names.  Currently these are the \p{GC=C}
25436          * ones, minus CC and CF */
25437
25438         SV * empty_names_ref = get_prop_definition(UNI_C);
25439         SV * empty_names = invlist_clone(empty_names_ref, NULL);
25440
25441         SV * subtract = get_prop_definition(UNI_CC);
25442
25443         _invlist_subtract(empty_names, subtract, &empty_names);
25444         SvREFCNT_dec_NN(empty_names_ref);
25445         SvREFCNT_dec_NN(subtract);
25446
25447         subtract = get_prop_definition(UNI_CF);
25448         _invlist_subtract(empty_names, subtract, &empty_names);
25449         SvREFCNT_dec_NN(subtract);
25450
25451         _invlist_union(*prop_definition, empty_names, prop_definition);
25452         found_matches = TRUE;
25453         SvREFCNT_dec_NN(empty_names);
25454     }
25455     SvREFCNT_dec_NN(empty);
25456
25457 #if 0
25458     /* If we ever were to accept aliases for, say private use names, we would
25459      * need to do something fancier to find empty names.  The code below works
25460      * (at the time it was written), and is slower than the above */
25461     const char empties_pat[] = "^.";
25462     if (strNE(name, empties_pat)) {
25463         SV * empty = newSVpvs("");
25464         if (execute_wildcard(subpattern_re,
25465                     SvPVX(empty),
25466                     SvEND(empty),
25467                     SvPVX(empty), 0,
25468                     empty,
25469                     0))
25470         {
25471             SV * empties = NULL;
25472
25473             (void) handle_names_wildcard(empties_pat, strlen(empties_pat), &empties);
25474
25475             _invlist_union_complement_2nd(*prop_definition, empties, prop_definition);
25476             SvREFCNT_dec_NN(empties);
25477
25478             found_matches = TRUE;
25479         }
25480         SvREFCNT_dec_NN(empty);
25481     }
25482 #endif
25483
25484     SvREFCNT_dec_NN(subpattern_re);
25485     return found_matches;
25486 }
25487
25488 /*
25489  * ex: set ts=8 sts=4 sw=4 et:
25490  */