This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
POSIX.xs: Fix typo displayed when fcn doesn't exist
[perl5.git] / regcomp.c
1 /*    regcomp.c
2  */
3
4 /*
5  * 'A fair jaw-cracker dwarf-language must be.'            --Samwise Gamgee
6  *
7  *     [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
8  */
9
10 /* This file contains functions for compiling a regular expression.  See
11  * also regexec.c which funnily enough, contains functions for executing
12  * a regular expression.
13  *
14  * This file is also copied at build time to ext/re/re_comp.c, where
15  * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
16  * This causes the main functions to be compiled under new names and with
17  * debugging support added, which makes "use re 'debug'" work.
18  */
19
20 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
21  * confused with the original package (see point 3 below).  Thanks, Henry!
22  */
23
24 /* Additional note: this code is very heavily munged from Henry's version
25  * in places.  In some spots I've traded clarity for efficiency, so don't
26  * blame Henry for some of the lack of readability.
27  */
28
29 /* The names of the functions have been changed from regcomp and
30  * regexec to pregcomp and pregexec in order to avoid conflicts
31  * with the POSIX routines of the same names.
32 */
33
34 #ifdef PERL_EXT_RE_BUILD
35 #include "re_top.h"
36 #endif
37
38 /*
39  * pregcomp and pregexec -- regsub and regerror are not used in perl
40  *
41  *      Copyright (c) 1986 by University of Toronto.
42  *      Written by Henry Spencer.  Not derived from licensed software.
43  *
44  *      Permission is granted to anyone to use this software for any
45  *      purpose on any computer system, and to redistribute it freely,
46  *      subject to the following restrictions:
47  *
48  *      1. The author is not responsible for the consequences of use of
49  *              this software, no matter how awful, even if they arise
50  *              from defects in it.
51  *
52  *      2. The origin of this software must not be misrepresented, either
53  *              by explicit claim or by omission.
54  *
55  *      3. Altered versions must be plainly marked as such, and must not
56  *              be misrepresented as being the original software.
57  *
58  *
59  ****    Alterations to Henry's code are...
60  ****
61  ****    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
62  ****    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63  ****    by Larry Wall and others
64  ****
65  ****    You may distribute under the terms of either the GNU General Public
66  ****    License or the Artistic License, as specified in the README file.
67
68  *
69  * Beware that some of this code is subtly aware of the way operator
70  * precedence is structured in regular expressions.  Serious changes in
71  * regular-expression syntax might require a total rethink.
72  */
73 #include "EXTERN.h"
74 #define PERL_IN_REGCOMP_C
75 #include "perl.h"
76
77 #define REG_COMP_C
78 #ifdef PERL_IN_XSUB_RE
79 #  include "re_comp.h"
80 EXTERN_C const struct regexp_engine my_reg_engine;
81 #else
82 #  include "regcomp.h"
83 #endif
84
85 #include "dquote_inline.h"
86 #include "invlist_inline.h"
87 #include "unicode_constants.h"
88
89 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
90  _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
91 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
92  _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
93 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
94 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
95
96 #ifndef STATIC
97 #define STATIC  static
98 #endif
99
100 /* this is a chain of data about sub patterns we are processing that
101    need to be handled separately/specially in study_chunk. Its so
102    we can simulate recursion without losing state.  */
103 struct scan_frame;
104 typedef struct scan_frame {
105     regnode *last_regnode;      /* last node to process in this frame */
106     regnode *next_regnode;      /* next node to process when last is reached */
107     U32 prev_recursed_depth;
108     I32 stopparen;              /* what stopparen do we use */
109
110     struct scan_frame *this_prev_frame; /* this previous frame */
111     struct scan_frame *prev_frame;      /* previous frame */
112     struct scan_frame *next_frame;      /* next frame */
113 } scan_frame;
114
115 /* Certain characters are output as a sequence with the first being a
116  * backslash. */
117 #define isBACKSLASHED_PUNCT(c)  memCHRs("-[]\\^", c)
118
119
120 struct RExC_state_t {
121     U32         flags;                  /* RXf_* are we folding, multilining? */
122     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
123     char        *precomp;               /* uncompiled string. */
124     char        *precomp_end;           /* pointer to end of uncompiled string. */
125     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
126     regexp      *rx;                    /* perl core regexp structure */
127     regexp_internal     *rxi;           /* internal data for regexp object
128                                            pprivate field */
129     char        *start;                 /* Start of input for compile */
130     char        *end;                   /* End of input for compile */
131     char        *parse;                 /* Input-scan pointer. */
132     char        *copy_start;            /* start of copy of input within
133                                            constructed parse string */
134     char        *save_copy_start;       /* Provides one level of saving
135                                            and restoring 'copy_start' */
136     char        *copy_start_in_input;   /* Position in input string
137                                            corresponding to copy_start */
138     SSize_t     whilem_seen;            /* number of WHILEM in this expr */
139     regnode     *emit_start;            /* Start of emitted-code area */
140     regnode_offset emit;                /* Code-emit pointer */
141     I32         naughty;                /* How bad is this pattern? */
142     I32         sawback;                /* Did we see \1, ...? */
143     U32         seen;
144     SSize_t     size;                   /* Number of regnode equivalents in
145                                            pattern */
146
147     /* position beyond 'precomp' of the warning message furthest away from
148      * 'precomp'.  During the parse, no warnings are raised for any problems
149      * earlier in the parse than this position.  This works if warnings are
150      * raised the first time a given spot is parsed, and if only one
151      * independent warning is raised for any given spot */
152     Size_t      latest_warn_offset;
153
154     I32         npar;                   /* Capture buffer count so far in the
155                                            parse, (OPEN) plus one. ("par" 0 is
156                                            the whole pattern)*/
157     I32         total_par;              /* During initial parse, is either 0,
158                                            or -1; the latter indicating a
159                                            reparse is needed.  After that pass,
160                                            it is what 'npar' became after the
161                                            pass.  Hence, it being > 0 indicates
162                                            we are in a reparse situation */
163     I32         nestroot;               /* root parens we are in - used by
164                                            accept */
165     I32         seen_zerolen;
166     regnode_offset *open_parens;        /* offsets to open parens */
167     regnode_offset *close_parens;       /* offsets to close parens */
168     I32      parens_buf_size;           /* #slots malloced open/close_parens */
169     regnode     *end_op;                /* END node in program */
170     I32         utf8;           /* whether the pattern is utf8 or not */
171     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
172                                 /* XXX use this for future optimisation of case
173                                  * where pattern must be upgraded to utf8. */
174     I32         uni_semantics;  /* If a d charset modifier should use unicode
175                                    rules, even if the pattern is not in
176                                    utf8 */
177     HV          *paren_names;           /* Paren names */
178
179     regnode     **recurse;              /* Recurse regops */
180     I32         recurse_count;          /* Number of recurse regops we have generated */
181     U8          *study_chunk_recursed;  /* bitmap of which subs we have moved
182                                            through */
183     U32         study_chunk_recursed_bytes;  /* bytes in bitmap */
184     I32         in_lookbehind;
185     I32         in_lookahead;
186     I32         contains_locale;
187     I32         override_recoding;
188     I32         recode_x_to_native;
189     I32         in_multi_char_class;
190     struct reg_code_blocks *code_blocks;/* positions of literal (?{})
191                                             within pattern */
192     int         code_index;             /* next code_blocks[] slot */
193     SSize_t     maxlen;                        /* mininum possible number of chars in string to match */
194     scan_frame *frame_head;
195     scan_frame *frame_last;
196     U32         frame_count;
197     AV         *warn_text;
198     HV         *unlexed_names;
199 #ifdef ADD_TO_REGEXEC
200     char        *starttry;              /* -Dr: where regtry was called. */
201 #define RExC_starttry   (pRExC_state->starttry)
202 #endif
203     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
204 #ifdef DEBUGGING
205     const char  *lastparse;
206     I32         lastnum;
207     AV          *paren_name_list;       /* idx -> name */
208     U32         study_chunk_recursed_count;
209     SV          *mysv1;
210     SV          *mysv2;
211
212 #define RExC_lastparse  (pRExC_state->lastparse)
213 #define RExC_lastnum    (pRExC_state->lastnum)
214 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
215 #define RExC_study_chunk_recursed_count    (pRExC_state->study_chunk_recursed_count)
216 #define RExC_mysv       (pRExC_state->mysv1)
217 #define RExC_mysv1      (pRExC_state->mysv1)
218 #define RExC_mysv2      (pRExC_state->mysv2)
219
220 #endif
221     bool        seen_d_op;
222     bool        strict;
223     bool        study_started;
224     bool        in_script_run;
225     bool        use_BRANCHJ;
226 };
227
228 #define RExC_flags      (pRExC_state->flags)
229 #define RExC_pm_flags   (pRExC_state->pm_flags)
230 #define RExC_precomp    (pRExC_state->precomp)
231 #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input)
232 #define RExC_copy_start_in_constructed  (pRExC_state->copy_start)
233 #define RExC_save_copy_start_in_constructed  (pRExC_state->save_copy_start)
234 #define RExC_precomp_end (pRExC_state->precomp_end)
235 #define RExC_rx_sv      (pRExC_state->rx_sv)
236 #define RExC_rx         (pRExC_state->rx)
237 #define RExC_rxi        (pRExC_state->rxi)
238 #define RExC_start      (pRExC_state->start)
239 #define RExC_end        (pRExC_state->end)
240 #define RExC_parse      (pRExC_state->parse)
241 #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset )
242 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
243 #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs
244                                                    under /d from /u ? */
245
246 #ifdef RE_TRACK_PATTERN_OFFSETS
247 #  define RExC_offsets  (RExC_rxi->u.offsets) /* I am not like the
248                                                          others */
249 #endif
250 #define RExC_emit       (pRExC_state->emit)
251 #define RExC_emit_start (pRExC_state->emit_start)
252 #define RExC_sawback    (pRExC_state->sawback)
253 #define RExC_seen       (pRExC_state->seen)
254 #define RExC_size       (pRExC_state->size)
255 #define RExC_maxlen        (pRExC_state->maxlen)
256 #define RExC_npar       (pRExC_state->npar)
257 #define RExC_total_parens       (pRExC_state->total_par)
258 #define RExC_parens_buf_size    (pRExC_state->parens_buf_size)
259 #define RExC_nestroot   (pRExC_state->nestroot)
260 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
261 #define RExC_utf8       (pRExC_state->utf8)
262 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
263 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
264 #define RExC_open_parens        (pRExC_state->open_parens)
265 #define RExC_close_parens       (pRExC_state->close_parens)
266 #define RExC_end_op     (pRExC_state->end_op)
267 #define RExC_paren_names        (pRExC_state->paren_names)
268 #define RExC_recurse    (pRExC_state->recurse)
269 #define RExC_recurse_count      (pRExC_state->recurse_count)
270 #define RExC_study_chunk_recursed        (pRExC_state->study_chunk_recursed)
271 #define RExC_study_chunk_recursed_bytes  \
272                                    (pRExC_state->study_chunk_recursed_bytes)
273 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
274 #define RExC_in_lookahead       (pRExC_state->in_lookahead)
275 #define RExC_contains_locale    (pRExC_state->contains_locale)
276 #define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
277
278 #ifdef EBCDIC
279 #  define SET_recode_x_to_native(x)                                         \
280                     STMT_START { RExC_recode_x_to_native = (x); } STMT_END
281 #else
282 #  define SET_recode_x_to_native(x) NOOP
283 #endif
284
285 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
286 #define RExC_frame_head (pRExC_state->frame_head)
287 #define RExC_frame_last (pRExC_state->frame_last)
288 #define RExC_frame_count (pRExC_state->frame_count)
289 #define RExC_strict (pRExC_state->strict)
290 #define RExC_study_started      (pRExC_state->study_started)
291 #define RExC_warn_text (pRExC_state->warn_text)
292 #define RExC_in_script_run      (pRExC_state->in_script_run)
293 #define RExC_use_BRANCHJ        (pRExC_state->use_BRANCHJ)
294 #define RExC_unlexed_names (pRExC_state->unlexed_names)
295
296 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
297  * a flag to disable back-off on the fixed/floating substrings - if it's
298  * a high complexity pattern we assume the benefit of avoiding a full match
299  * is worth the cost of checking for the substrings even if they rarely help.
300  */
301 #define RExC_naughty    (pRExC_state->naughty)
302 #define TOO_NAUGHTY (10)
303 #define MARK_NAUGHTY(add) \
304     if (RExC_naughty < TOO_NAUGHTY) \
305         RExC_naughty += (add)
306 #define MARK_NAUGHTY_EXP(exp, add) \
307     if (RExC_naughty < TOO_NAUGHTY) \
308         RExC_naughty += RExC_naughty / (exp) + (add)
309
310 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
311 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
312         ((*s) == '{' && regcurly(s)))
313
314 /*
315  * Flags to be passed up and down.
316  */
317 #define WORST           0       /* Worst case. */
318 #define HASWIDTH        0x01    /* Known to not match null strings, could match
319                                    non-null ones. */
320
321 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
322  * character.  (There needs to be a case: in the switch statement in regexec.c
323  * for any node marked SIMPLE.)  Note that this is not the same thing as
324  * REGNODE_SIMPLE */
325 #define SIMPLE          0x02
326 #define SPSTART         0x04    /* Starts with * or + */
327 #define POSTPONED       0x08    /* (?1),(?&name), (??{...}) or similar */
328 #define TRYAGAIN        0x10    /* Weeded out a declaration. */
329 #define RESTART_PARSE   0x20    /* Need to redo the parse */
330 #define NEED_UTF8       0x40    /* In conjunction with RESTART_PARSE, need to
331                                    calcuate sizes as UTF-8 */
332
333 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
334
335 /* whether trie related optimizations are enabled */
336 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
337 #define TRIE_STUDY_OPT
338 #define FULL_TRIE_STUDY
339 #define TRIE_STCLASS
340 #endif
341
342
343
344 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
345 #define PBITVAL(paren) (1 << ((paren) & 7))
346 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
347 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
348 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
349
350 #define REQUIRE_UTF8(flagp) STMT_START {                                   \
351                                      if (!UTF) {                           \
352                                          *flagp = RESTART_PARSE|NEED_UTF8; \
353                                          return 0;                         \
354                                      }                                     \
355                              } STMT_END
356
357 /* Change from /d into /u rules, and restart the parse.  RExC_uni_semantics is
358  * a flag that indicates we need to override /d with /u as a result of
359  * something in the pattern.  It should only be used in regards to calling
360  * set_regex_charset() or get_regex_charset() */
361 #define REQUIRE_UNI_RULES(flagp, restart_retval)                            \
362     STMT_START {                                                            \
363             if (DEPENDS_SEMANTICS) {                                        \
364                 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);      \
365                 RExC_uni_semantics = 1;                                     \
366                 if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) {           \
367                     /* No need to restart the parse if we haven't seen      \
368                      * anything that differs between /u and /d, and no need \
369                      * to restart immediately if we're going to reparse     \
370                      * anyway to count parens */                            \
371                     *flagp |= RESTART_PARSE;                                \
372                     return restart_retval;                                  \
373                 }                                                           \
374             }                                                               \
375     } STMT_END
376
377 #define REQUIRE_BRANCHJ(flagp, restart_retval)                              \
378     STMT_START {                                                            \
379                 RExC_use_BRANCHJ = 1;                                       \
380                 *flagp |= RESTART_PARSE;                                    \
381                 return restart_retval;                                      \
382     } STMT_END
383
384 /* Until we have completed the parse, we leave RExC_total_parens at 0 or
385  * less.  After that, it must always be positive, because the whole re is
386  * considered to be surrounded by virtual parens.  Setting it to negative
387  * indicates there is some construct that needs to know the actual number of
388  * parens to be properly handled.  And that means an extra pass will be
389  * required after we've counted them all */
390 #define ALL_PARENS_COUNTED (RExC_total_parens > 0)
391 #define REQUIRE_PARENS_PASS                                                 \
392     STMT_START {  /* No-op if have completed a pass */                      \
393                     if (! ALL_PARENS_COUNTED) RExC_total_parens = -1;       \
394     } STMT_END
395 #define IN_PARENS_PASS (RExC_total_parens < 0)
396
397
398 /* This is used to return failure (zero) early from the calling function if
399  * various flags in 'flags' are set.  Two flags always cause a return:
400  * 'RESTART_PARSE' and 'NEED_UTF8'.   'extra' can be used to specify any
401  * additional flags that should cause a return; 0 if none.  If the return will
402  * be done, '*flagp' is first set to be all of the flags that caused the
403  * return. */
404 #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra)                  \
405     STMT_START {                                                            \
406             if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) {              \
407                 *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra));     \
408                 return 0;                                                   \
409             }                                                               \
410     } STMT_END
411
412 #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE))
413
414 #define RETURN_FAIL_ON_RESTART(flags,flagp)                                 \
415                         RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0)
416 #define RETURN_FAIL_ON_RESTART_FLAGP(flagp)                                 \
417                                     if (MUST_RESTART(*(flagp))) return 0
418
419 /* This converts the named class defined in regcomp.h to its equivalent class
420  * number defined in handy.h. */
421 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
422 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
423
424 #define _invlist_union_complement_2nd(a, b, output) \
425                         _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
426 #define _invlist_intersection_complement_2nd(a, b, output) \
427                  _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
428
429 /* We add a marker if we are deferring expansion of a property that is both
430  * 1) potentiallly user-defined; and
431  * 2) could also be an official Unicode property.
432  *
433  * Without this marker, any deferred expansion can only be for a user-defined
434  * one.  This marker shouldn't conflict with any that could be in a legal name,
435  * and is appended to its name to indicate this.  There is a string and
436  * character form */
437 #define DEFERRED_COULD_BE_OFFICIAL_MARKERs  "~"
438 #define DEFERRED_COULD_BE_OFFICIAL_MARKERc  '~'
439
440 /* About scan_data_t.
441
442   During optimisation we recurse through the regexp program performing
443   various inplace (keyhole style) optimisations. In addition study_chunk
444   and scan_commit populate this data structure with information about
445   what strings MUST appear in the pattern. We look for the longest
446   string that must appear at a fixed location, and we look for the
447   longest string that may appear at a floating location. So for instance
448   in the pattern:
449
450     /FOO[xX]A.*B[xX]BAR/
451
452   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
453   strings (because they follow a .* construct). study_chunk will identify
454   both FOO and BAR as being the longest fixed and floating strings respectively.
455
456   The strings can be composites, for instance
457
458      /(f)(o)(o)/
459
460   will result in a composite fixed substring 'foo'.
461
462   For each string some basic information is maintained:
463
464   - min_offset
465     This is the position the string must appear at, or not before.
466     It also implicitly (when combined with minlenp) tells us how many
467     characters must match before the string we are searching for.
468     Likewise when combined with minlenp and the length of the string it
469     tells us how many characters must appear after the string we have
470     found.
471
472   - max_offset
473     Only used for floating strings. This is the rightmost point that
474     the string can appear at. If set to SSize_t_MAX it indicates that the
475     string can occur infinitely far to the right.
476     For fixed strings, it is equal to min_offset.
477
478   - minlenp
479     A pointer to the minimum number of characters of the pattern that the
480     string was found inside. This is important as in the case of positive
481     lookahead or positive lookbehind we can have multiple patterns
482     involved. Consider
483
484     /(?=FOO).*F/
485
486     The minimum length of the pattern overall is 3, the minimum length
487     of the lookahead part is 3, but the minimum length of the part that
488     will actually match is 1. So 'FOO's minimum length is 3, but the
489     minimum length for the F is 1. This is important as the minimum length
490     is used to determine offsets in front of and behind the string being
491     looked for.  Since strings can be composites this is the length of the
492     pattern at the time it was committed with a scan_commit. Note that
493     the length is calculated by study_chunk, so that the minimum lengths
494     are not known until the full pattern has been compiled, thus the
495     pointer to the value.
496
497   - lookbehind
498
499     In the case of lookbehind the string being searched for can be
500     offset past the start point of the final matching string.
501     If this value was just blithely removed from the min_offset it would
502     invalidate some of the calculations for how many chars must match
503     before or after (as they are derived from min_offset and minlen and
504     the length of the string being searched for).
505     When the final pattern is compiled and the data is moved from the
506     scan_data_t structure into the regexp structure the information
507     about lookbehind is factored in, with the information that would
508     have been lost precalculated in the end_shift field for the
509     associated string.
510
511   The fields pos_min and pos_delta are used to store the minimum offset
512   and the delta to the maximum offset at the current point in the pattern.
513
514 */
515
516 struct scan_data_substrs {
517     SV      *str;       /* longest substring found in pattern */
518     SSize_t min_offset; /* earliest point in string it can appear */
519     SSize_t max_offset; /* latest point in string it can appear */
520     SSize_t *minlenp;   /* pointer to the minlen relevant to the string */
521     SSize_t lookbehind; /* is the pos of the string modified by LB */
522     I32 flags;          /* per substring SF_* and SCF_* flags */
523 };
524
525 typedef struct scan_data_t {
526     /*I32 len_min;      unused */
527     /*I32 len_delta;    unused */
528     SSize_t pos_min;
529     SSize_t pos_delta;
530     SV *last_found;
531     SSize_t last_end;       /* min value, <0 unless valid. */
532     SSize_t last_start_min;
533     SSize_t last_start_max;
534     U8      cur_is_floating; /* whether the last_* values should be set as
535                               * the next fixed (0) or floating (1)
536                               * substring */
537
538     /* [0] is longest fixed substring so far, [1] is longest float so far */
539     struct scan_data_substrs  substrs[2];
540
541     I32 flags;             /* common SF_* and SCF_* flags */
542     I32 whilem_c;
543     SSize_t *last_closep;
544     regnode_ssc *start_class;
545 } scan_data_t;
546
547 /*
548  * Forward declarations for pregcomp()'s friends.
549  */
550
551 static const scan_data_t zero_scan_data = {
552     0, 0, NULL, 0, 0, 0, 0,
553     {
554         { NULL, 0, 0, 0, 0, 0 },
555         { NULL, 0, 0, 0, 0, 0 },
556     },
557     0, 0, NULL, NULL
558 };
559
560 /* study flags */
561
562 #define SF_BEFORE_SEOL          0x0001
563 #define SF_BEFORE_MEOL          0x0002
564 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
565
566 #define SF_IS_INF               0x0040
567 #define SF_HAS_PAR              0x0080
568 #define SF_IN_PAR               0x0100
569 #define SF_HAS_EVAL             0x0200
570
571
572 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the
573  * longest substring in the pattern. When it is not set the optimiser keeps
574  * track of position, but does not keep track of the actual strings seen,
575  *
576  * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but
577  * /foo/i will not.
578  *
579  * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble"
580  * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be
581  * turned off because of the alternation (BRANCH). */
582 #define SCF_DO_SUBSTR           0x0400
583
584 #define SCF_DO_STCLASS_AND      0x0800
585 #define SCF_DO_STCLASS_OR       0x1000
586 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
587 #define SCF_WHILEM_VISITED_POS  0x2000
588
589 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
590 #define SCF_SEEN_ACCEPT         0x8000
591 #define SCF_TRIE_DOING_RESTUDY 0x10000
592 #define SCF_IN_DEFINE          0x20000
593
594
595
596
597 #define UTF cBOOL(RExC_utf8)
598
599 /* The enums for all these are ordered so things work out correctly */
600 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
601 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags)                    \
602                                                      == REGEX_DEPENDS_CHARSET)
603 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
604 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags)                \
605                                                      >= REGEX_UNICODE_CHARSET)
606 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags)                      \
607                                             == REGEX_ASCII_RESTRICTED_CHARSET)
608 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags)             \
609                                             >= REGEX_ASCII_RESTRICTED_CHARSET)
610 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags)                 \
611                                         == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
612
613 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
614
615 /* For programs that want to be strictly Unicode compatible by dying if any
616  * attempt is made to match a non-Unicode code point against a Unicode
617  * property.  */
618 #define ALWAYS_WARN_SUPER  ckDEAD(packWARN(WARN_NON_UNICODE))
619
620 #define OOB_NAMEDCLASS          -1
621
622 /* There is no code point that is out-of-bounds, so this is problematic.  But
623  * its only current use is to initialize a variable that is always set before
624  * looked at. */
625 #define OOB_UNICODE             0xDEADBEEF
626
627 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
628
629
630 /* length of regex to show in messages that don't mark a position within */
631 #define RegexLengthToShowInErrorMessages 127
632
633 /*
634  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
635  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
636  * op/pragma/warn/regcomp.
637  */
638 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
639 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
640
641 #define REPORT_LOCATION " in regex; marked by " MARKER1    \
642                         " in m/%" UTF8f MARKER2 "%" UTF8f "/"
643
644 /* The code in this file in places uses one level of recursion with parsing
645  * rebased to an alternate string constructed by us in memory.  This can take
646  * the form of something that is completely different from the input, or
647  * something that uses the input as part of the alternate.  In the first case,
648  * there should be no possibility of an error, as we are in complete control of
649  * the alternate string.  But in the second case we don't completely control
650  * the input portion, so there may be errors in that.  Here's an example:
651  *      /[abc\x{DF}def]/ui
652  * is handled specially because \x{df} folds to a sequence of more than one
653  * character: 'ss'.  What is done is to create and parse an alternate string,
654  * which looks like this:
655  *      /(?:\x{DF}|[abc\x{DF}def])/ui
656  * where it uses the input unchanged in the middle of something it constructs,
657  * which is a branch for the DF outside the character class, and clustering
658  * parens around the whole thing. (It knows enough to skip the DF inside the
659  * class while in this substitute parse.) 'abc' and 'def' may have errors that
660  * need to be reported.  The general situation looks like this:
661  *
662  *                                       |<------- identical ------>|
663  *              sI                       tI               xI       eI
664  * Input:       ---------------------------------------------------------------
665  * Constructed:         ---------------------------------------------------
666  *                      sC               tC               xC       eC     EC
667  *                                       |<------- identical ------>|
668  *
669  * sI..eI   is the portion of the input pattern we are concerned with here.
670  * sC..EC   is the constructed substitute parse string.
671  *  sC..tC  is constructed by us
672  *  tC..eC  is an exact duplicate of the portion of the input pattern tI..eI.
673  *          In the diagram, these are vertically aligned.
674  *  eC..EC  is also constructed by us.
675  * xC       is the position in the substitute parse string where we found a
676  *          problem.
677  * xI       is the position in the original pattern corresponding to xC.
678  *
679  * We want to display a message showing the real input string.  Thus we need to
680  * translate from xC to xI.  We know that xC >= tC, since the portion of the
681  * string sC..tC has been constructed by us, and so shouldn't have errors.  We
682  * get:
683  *      xI = tI + (xC - tC)
684  *
685  * When the substitute parse is constructed, the code needs to set:
686  *      RExC_start (sC)
687  *      RExC_end (eC)
688  *      RExC_copy_start_in_input  (tI)
689  *      RExC_copy_start_in_constructed (tC)
690  * and restore them when done.
691  *
692  * During normal processing of the input pattern, both
693  * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to
694  * sI, so that xC equals xI.
695  */
696
697 #define sI              RExC_precomp
698 #define eI              RExC_precomp_end
699 #define sC              RExC_start
700 #define eC              RExC_end
701 #define tI              RExC_copy_start_in_input
702 #define tC              RExC_copy_start_in_constructed
703 #define xI(xC)          (tI + (xC - tC))
704 #define xI_offset(xC)   (xI(xC) - sI)
705
706 #define REPORT_LOCATION_ARGS(xC)                                            \
707     UTF8fARG(UTF,                                                           \
708              (xI(xC) > eI) /* Don't run off end */                          \
709               ? eI - sI   /* Length before the <--HERE */                   \
710               : ((xI_offset(xC) >= 0)                                       \
711                  ? xI_offset(xC)                                            \
712                  : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %"    \
713                                     IVdf " trying to output message for "   \
714                                     " pattern %.*s",                        \
715                                     __FILE__, __LINE__, (IV) xI_offset(xC), \
716                                     ((int) (eC - sC)), sC), 0)),            \
717              sI),         /* The input pattern printed up to the <--HERE */ \
718     UTF8fARG(UTF,                                                           \
719              (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */    \
720              (xI(xC) > eI) ? eI : xI(xC))     /* pattern after <--HERE */
721
722 /* Used to point after bad bytes for an error message, but avoid skipping
723  * past a nul byte. */
724 #define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1)
725
726 /* Set up to clean up after our imminent demise */
727 #define PREPARE_TO_DIE                                                      \
728     STMT_START {                                                            \
729         if (RExC_rx_sv)                                                     \
730             SAVEFREESV(RExC_rx_sv);                                         \
731         if (RExC_open_parens)                                               \
732             SAVEFREEPV(RExC_open_parens);                                   \
733         if (RExC_close_parens)                                              \
734             SAVEFREEPV(RExC_close_parens);                                  \
735     } STMT_END
736
737 /*
738  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
739  * arg. Show regex, up to a maximum length. If it's too long, chop and add
740  * "...".
741  */
742 #define _FAIL(code) STMT_START {                                        \
743     const char *ellipses = "";                                          \
744     IV len = RExC_precomp_end - RExC_precomp;                           \
745                                                                         \
746     PREPARE_TO_DIE;                                                     \
747     if (len > RegexLengthToShowInErrorMessages) {                       \
748         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
749         len = RegexLengthToShowInErrorMessages - 10;                    \
750         ellipses = "...";                                               \
751     }                                                                   \
752     code;                                                               \
753 } STMT_END
754
755 #define FAIL(msg) _FAIL(                            \
756     Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/",         \
757             msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
758
759 #define FAIL2(msg,arg) _FAIL(                       \
760     Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/",       \
761             arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
762
763 #define FAIL3(msg,arg1,arg2) _FAIL(                         \
764     Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/",       \
765      arg1, arg2, UTF8fARG(UTF, len, RExC_precomp), ellipses))
766
767 /*
768  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
769  */
770 #define Simple_vFAIL(m) STMT_START {                                    \
771     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
772             m, REPORT_LOCATION_ARGS(RExC_parse));                       \
773 } STMT_END
774
775 /*
776  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
777  */
778 #define vFAIL(m) STMT_START {                           \
779     PREPARE_TO_DIE;                                     \
780     Simple_vFAIL(m);                                    \
781 } STMT_END
782
783 /*
784  * Like Simple_vFAIL(), but accepts two arguments.
785  */
786 #define Simple_vFAIL2(m,a1) STMT_START {                        \
787     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,              \
788                       REPORT_LOCATION_ARGS(RExC_parse));        \
789 } STMT_END
790
791 /*
792  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
793  */
794 #define vFAIL2(m,a1) STMT_START {                       \
795     PREPARE_TO_DIE;                                     \
796     Simple_vFAIL2(m, a1);                               \
797 } STMT_END
798
799
800 /*
801  * Like Simple_vFAIL(), but accepts three arguments.
802  */
803 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
804     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,          \
805             REPORT_LOCATION_ARGS(RExC_parse));                  \
806 } STMT_END
807
808 /*
809  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
810  */
811 #define vFAIL3(m,a1,a2) STMT_START {                    \
812     PREPARE_TO_DIE;                                     \
813     Simple_vFAIL3(m, a1, a2);                           \
814 } STMT_END
815
816 /*
817  * Like Simple_vFAIL(), but accepts four arguments.
818  */
819 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
820     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3,      \
821             REPORT_LOCATION_ARGS(RExC_parse));                  \
822 } STMT_END
823
824 #define vFAIL4(m,a1,a2,a3) STMT_START {                 \
825     PREPARE_TO_DIE;                                     \
826     Simple_vFAIL4(m, a1, a2, a3);                       \
827 } STMT_END
828
829 /* A specialized version of vFAIL2 that works with UTF8f */
830 #define vFAIL2utf8f(m, a1) STMT_START {             \
831     PREPARE_TO_DIE;                                 \
832     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,  \
833             REPORT_LOCATION_ARGS(RExC_parse));      \
834 } STMT_END
835
836 #define vFAIL3utf8f(m, a1, a2) STMT_START {             \
837     PREPARE_TO_DIE;                                     \
838     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,  \
839             REPORT_LOCATION_ARGS(RExC_parse));          \
840 } STMT_END
841
842 /* Setting this to NULL is a signal to not output warnings */
843 #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE                               \
844     STMT_START {                                                            \
845       RExC_save_copy_start_in_constructed  = RExC_copy_start_in_constructed;\
846       RExC_copy_start_in_constructed = NULL;                                \
847     } STMT_END
848 #define RESTORE_WARNINGS                                                    \
849     RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed
850
851 /* Since a warning can be generated multiple times as the input is reparsed, we
852  * output it the first time we come to that point in the parse, but suppress it
853  * otherwise.  'RExC_copy_start_in_constructed' being NULL is a flag to not
854  * generate any warnings */
855 #define TO_OUTPUT_WARNINGS(loc)                                         \
856   (   RExC_copy_start_in_constructed                                    \
857    && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset)
858
859 /* After we've emitted a warning, we save the position in the input so we don't
860  * output it again */
861 #define UPDATE_WARNINGS_LOC(loc)                                        \
862     STMT_START {                                                        \
863         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
864             RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc)))         \
865                                                        - RExC_precomp;  \
866         }                                                               \
867     } STMT_END
868
869 /* 'warns' is the output of the packWARNx macro used in 'code' */
870 #define _WARN_HELPER(loc, warns, code)                                  \
871     STMT_START {                                                        \
872         if (! RExC_copy_start_in_constructed) {                         \
873             Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none"  \
874                               " expected at '%s'",                      \
875                               __FILE__, __LINE__, loc);                 \
876         }                                                               \
877         if (TO_OUTPUT_WARNINGS(loc)) {                                  \
878             if (ckDEAD(warns))                                          \
879                 PREPARE_TO_DIE;                                         \
880             code;                                                       \
881             UPDATE_WARNINGS_LOC(loc);                                   \
882         }                                                               \
883     } STMT_END
884
885 /* m is not necessarily a "literal string", in this macro */
886 #define reg_warn_non_literal_string(loc, m)                             \
887     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
888                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
889                                        "%s" REPORT_LOCATION,            \
890                                   m, REPORT_LOCATION_ARGS(loc)))
891
892 #define ckWARNreg(loc,m)                                                \
893     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
894                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
895                                           m REPORT_LOCATION,            \
896                                           REPORT_LOCATION_ARGS(loc)))
897
898 #define vWARN(loc, m)                                                   \
899     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
900                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
901                                        m REPORT_LOCATION,               \
902                                        REPORT_LOCATION_ARGS(loc)))      \
903
904 #define vWARN_dep(loc, m)                                               \
905     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
906                       Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),      \
907                                        m REPORT_LOCATION,               \
908                                        REPORT_LOCATION_ARGS(loc)))
909
910 #define ckWARNdep(loc,m)                                                \
911     _WARN_HELPER(loc, packWARN(WARN_DEPRECATED),                        \
912                       Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \
913                                             m REPORT_LOCATION,          \
914                                             REPORT_LOCATION_ARGS(loc)))
915
916 #define ckWARNregdep(loc,m)                                                 \
917     _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP),              \
918                       Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED,     \
919                                                       WARN_REGEXP),         \
920                                              m REPORT_LOCATION,             \
921                                              REPORT_LOCATION_ARGS(loc)))
922
923 #define ckWARN2reg_d(loc,m, a1)                                             \
924     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
925                       Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP),         \
926                                             m REPORT_LOCATION,              \
927                                             a1, REPORT_LOCATION_ARGS(loc)))
928
929 #define ckWARN2reg(loc, m, a1)                                              \
930     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
931                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
932                                           m REPORT_LOCATION,                \
933                                           a1, REPORT_LOCATION_ARGS(loc)))
934
935 #define vWARN3(loc, m, a1, a2)                                              \
936     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
937                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),              \
938                                        m REPORT_LOCATION,                   \
939                                        a1, a2, REPORT_LOCATION_ARGS(loc)))
940
941 #define ckWARN3reg(loc, m, a1, a2)                                          \
942     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                                \
943                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),           \
944                                           m REPORT_LOCATION,                \
945                                           a1, a2,                           \
946                                           REPORT_LOCATION_ARGS(loc)))
947
948 #define vWARN4(loc, m, a1, a2, a3)                                      \
949     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
950                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
951                                        m REPORT_LOCATION,               \
952                                        a1, a2, a3,                      \
953                                        REPORT_LOCATION_ARGS(loc)))
954
955 #define ckWARN4reg(loc, m, a1, a2, a3)                                  \
956     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
957                       Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),       \
958                                           m REPORT_LOCATION,            \
959                                           a1, a2, a3,                   \
960                                           REPORT_LOCATION_ARGS(loc)))
961
962 #define vWARN5(loc, m, a1, a2, a3, a4)                                  \
963     _WARN_HELPER(loc, packWARN(WARN_REGEXP),                            \
964                       Perl_warner(aTHX_ packWARN(WARN_REGEXP),          \
965                                        m REPORT_LOCATION,               \
966                                        a1, a2, a3, a4,                  \
967                                        REPORT_LOCATION_ARGS(loc)))
968
969 #define ckWARNexperimental(loc, class, m)                               \
970     _WARN_HELPER(loc, packWARN(class),                                  \
971                       Perl_ck_warner_d(aTHX_ packWARN(class),           \
972                                             m REPORT_LOCATION,          \
973                                             REPORT_LOCATION_ARGS(loc)))
974
975 /* Convert between a pointer to a node and its offset from the beginning of the
976  * program */
977 #define REGNODE_p(offset)    (RExC_emit_start + (offset))
978 #define REGNODE_OFFSET(node) ((node) - RExC_emit_start)
979
980 /* Macros for recording node offsets.   20001227 mjd@plover.com
981  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
982  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
983  * Element 0 holds the number n.
984  * Position is 1 indexed.
985  */
986 #ifndef RE_TRACK_PATTERN_OFFSETS
987 #define Set_Node_Offset_To_R(offset,byte)
988 #define Set_Node_Offset(node,byte)
989 #define Set_Cur_Node_Offset
990 #define Set_Node_Length_To_R(node,len)
991 #define Set_Node_Length(node,len)
992 #define Set_Node_Cur_Length(node,start)
993 #define Node_Offset(n)
994 #define Node_Length(n)
995 #define Set_Node_Offset_Length(node,offset,len)
996 #define ProgLen(ri) ri->u.proglen
997 #define SetProgLen(ri,x) ri->u.proglen = x
998 #define Track_Code(code)
999 #else
1000 #define ProgLen(ri) ri->u.offsets[0]
1001 #define SetProgLen(ri,x) ri->u.offsets[0] = x
1002 #define Set_Node_Offset_To_R(offset,byte) STMT_START {                  \
1003         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
1004                     __LINE__, (int)(offset), (int)(byte)));             \
1005         if((offset) < 0) {                                              \
1006             Perl_croak(aTHX_ "value of node is %d in Offset macro",     \
1007                                          (int)(offset));                \
1008         } else {                                                        \
1009             RExC_offsets[2*(offset)-1] = (byte);                        \
1010         }                                                               \
1011 } STMT_END
1012
1013 #define Set_Node_Offset(node,byte)                                      \
1014     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start)
1015 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
1016
1017 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
1018         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
1019                 __LINE__, (int)(node), (int)(len)));                    \
1020         if((node) < 0) {                                                \
1021             Perl_croak(aTHX_ "value of node is %d in Length macro",     \
1022                                          (int)(node));                  \
1023         } else {                                                        \
1024             RExC_offsets[2*(node)] = (len);                             \
1025         }                                                               \
1026 } STMT_END
1027
1028 #define Set_Node_Length(node,len) \
1029     Set_Node_Length_To_R(REGNODE_OFFSET(node), len)
1030 #define Set_Node_Cur_Length(node, start)                \
1031     Set_Node_Length(node, RExC_parse - start)
1032
1033 /* Get offsets and lengths */
1034 #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1])
1035 #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))])
1036
1037 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
1038     Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset));       \
1039     Set_Node_Length_To_R(REGNODE_OFFSET(node), (len));  \
1040 } STMT_END
1041
1042 #define Track_Code(code) STMT_START { code } STMT_END
1043 #endif
1044
1045 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
1046 #define EXPERIMENTAL_INPLACESCAN
1047 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
1048
1049 #ifdef DEBUGGING
1050 int
1051 Perl_re_printf(pTHX_ const char *fmt, ...)
1052 {
1053     va_list ap;
1054     int result;
1055     PerlIO *f= Perl_debug_log;
1056     PERL_ARGS_ASSERT_RE_PRINTF;
1057     va_start(ap, fmt);
1058     result = PerlIO_vprintf(f, fmt, ap);
1059     va_end(ap);
1060     return result;
1061 }
1062
1063 int
1064 Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...)
1065 {
1066     va_list ap;
1067     int result;
1068     PerlIO *f= Perl_debug_log;
1069     PERL_ARGS_ASSERT_RE_INDENTF;
1070     va_start(ap, depth);
1071     PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, "");
1072     result = PerlIO_vprintf(f, fmt, ap);
1073     va_end(ap);
1074     return result;
1075 }
1076 #endif /* DEBUGGING */
1077
1078 #define DEBUG_RExC_seen()                                                   \
1079         DEBUG_OPTIMISE_MORE_r({                                             \
1080             Perl_re_printf( aTHX_ "RExC_seen: ");                           \
1081                                                                             \
1082             if (RExC_seen & REG_ZERO_LEN_SEEN)                              \
1083                 Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN ");                \
1084                                                                             \
1085             if (RExC_seen & REG_LOOKBEHIND_SEEN)                            \
1086                 Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN ");              \
1087                                                                             \
1088             if (RExC_seen & REG_GPOS_SEEN)                                  \
1089                 Perl_re_printf( aTHX_ "REG_GPOS_SEEN ");                    \
1090                                                                             \
1091             if (RExC_seen & REG_RECURSE_SEEN)                               \
1092                 Perl_re_printf( aTHX_ "REG_RECURSE_SEEN ");                 \
1093                                                                             \
1094             if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)                    \
1095                 Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN ");      \
1096                                                                             \
1097             if (RExC_seen & REG_VERBARG_SEEN)                               \
1098                 Perl_re_printf( aTHX_ "REG_VERBARG_SEEN ");                 \
1099                                                                             \
1100             if (RExC_seen & REG_CUTGROUP_SEEN)                              \
1101                 Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN ");                \
1102                                                                             \
1103             if (RExC_seen & REG_RUN_ON_COMMENT_SEEN)                        \
1104                 Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN ");          \
1105                                                                             \
1106             if (RExC_seen & REG_UNFOLDED_MULTI_SEEN)                        \
1107                 Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN ");          \
1108                                                                             \
1109             if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)                  \
1110                 Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN ");    \
1111                                                                             \
1112             Perl_re_printf( aTHX_ "\n");                                    \
1113         });
1114
1115 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
1116   if ((flags) & flag) Perl_re_printf( aTHX_  "%s ", #flag)
1117
1118
1119 #ifdef DEBUGGING
1120 static void
1121 S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str,
1122                                     const char *close_str)
1123 {
1124     if (!flags)
1125         return;
1126
1127     Perl_re_printf( aTHX_  "%s", open_str);
1128     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL);
1129     DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL);
1130     DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF);
1131     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR);
1132     DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR);
1133     DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL);
1134     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR);
1135     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND);
1136     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR);
1137     DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS);
1138     DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS);
1139     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY);
1140     DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT);
1141     DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY);
1142     DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE);
1143     Perl_re_printf( aTHX_  "%s", close_str);
1144 }
1145
1146
1147 static void
1148 S_debug_studydata(pTHX_ const char *where, scan_data_t *data,
1149                     U32 depth, int is_inf)
1150 {
1151     GET_RE_DEBUG_FLAGS_DECL;
1152
1153     DEBUG_OPTIMISE_MORE_r({
1154         if (!data)
1155             return;
1156         Perl_re_indentf(aTHX_  "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf,
1157             depth,
1158             where,
1159             (IV)data->pos_min,
1160             (IV)data->pos_delta,
1161             (UV)data->flags
1162         );
1163
1164         S_debug_show_study_flags(aTHX_ data->flags," [","]");
1165
1166         Perl_re_printf( aTHX_
1167             " Whilem_c: %" IVdf " Lcp: %" IVdf " %s",
1168             (IV)data->whilem_c,
1169             (IV)(data->last_closep ? *((data)->last_closep) : -1),
1170             is_inf ? "INF " : ""
1171         );
1172
1173         if (data->last_found) {
1174             int i;
1175             Perl_re_printf(aTHX_
1176                 "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf,
1177                     SvPVX_const(data->last_found),
1178                     (IV)data->last_end,
1179                     (IV)data->last_start_min,
1180                     (IV)data->last_start_max
1181             );
1182
1183             for (i = 0; i < 2; i++) {
1184                 Perl_re_printf(aTHX_
1185                     " %s%s: '%s' @ %" IVdf "/%" IVdf,
1186                     data->cur_is_floating == i ? "*" : "",
1187                     i ? "Float" : "Fixed",
1188                     SvPVX_const(data->substrs[i].str),
1189                     (IV)data->substrs[i].min_offset,
1190                     (IV)data->substrs[i].max_offset
1191                 );
1192                 S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]");
1193             }
1194         }
1195
1196         Perl_re_printf( aTHX_ "\n");
1197     });
1198 }
1199
1200
1201 static void
1202 S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state,
1203                 regnode *scan, U32 depth, U32 flags)
1204 {
1205     GET_RE_DEBUG_FLAGS_DECL;
1206
1207     DEBUG_OPTIMISE_r({
1208         regnode *Next;
1209
1210         if (!scan)
1211             return;
1212         Next = regnext(scan);
1213         regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
1214         Perl_re_indentf( aTHX_   "%s>%3d: %s (%d)",
1215             depth,
1216             str,
1217             REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),
1218             Next ? (REG_NODE_NUM(Next)) : 0 );
1219         S_debug_show_study_flags(aTHX_ flags," [ ","]");
1220         Perl_re_printf( aTHX_  "\n");
1221    });
1222 }
1223
1224
1225 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) \
1226                     S_debug_studydata(aTHX_ where, data, depth, is_inf)
1227
1228 #  define DEBUG_PEEP(str, scan, depth, flags)   \
1229                     S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags)
1230
1231 #else
1232 #  define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP
1233 #  define DEBUG_PEEP(str, scan, depth, flags)         NOOP
1234 #endif
1235
1236
1237 /* =========================================================
1238  * BEGIN edit_distance stuff.
1239  *
1240  * This calculates how many single character changes of any type are needed to
1241  * transform a string into another one.  It is taken from version 3.1 of
1242  *
1243  * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1244  */
1245
1246 /* Our unsorted dictionary linked list.   */
1247 /* Note we use UVs, not chars. */
1248
1249 struct dictionary{
1250   UV key;
1251   UV value;
1252   struct dictionary* next;
1253 };
1254 typedef struct dictionary item;
1255
1256
1257 PERL_STATIC_INLINE item*
1258 push(UV key, item* curr)
1259 {
1260     item* head;
1261     Newx(head, 1, item);
1262     head->key = key;
1263     head->value = 0;
1264     head->next = curr;
1265     return head;
1266 }
1267
1268
1269 PERL_STATIC_INLINE item*
1270 find(item* head, UV key)
1271 {
1272     item* iterator = head;
1273     while (iterator){
1274         if (iterator->key == key){
1275             return iterator;
1276         }
1277         iterator = iterator->next;
1278     }
1279
1280     return NULL;
1281 }
1282
1283 PERL_STATIC_INLINE item*
1284 uniquePush(item* head, UV key)
1285 {
1286     item* iterator = head;
1287
1288     while (iterator){
1289         if (iterator->key == key) {
1290             return head;
1291         }
1292         iterator = iterator->next;
1293     }
1294
1295     return push(key, head);
1296 }
1297
1298 PERL_STATIC_INLINE void
1299 dict_free(item* head)
1300 {
1301     item* iterator = head;
1302
1303     while (iterator) {
1304         item* temp = iterator;
1305         iterator = iterator->next;
1306         Safefree(temp);
1307     }
1308
1309     head = NULL;
1310 }
1311
1312 /* End of Dictionary Stuff */
1313
1314 /* All calculations/work are done here */
1315 STATIC int
1316 S_edit_distance(const UV* src,
1317                 const UV* tgt,
1318                 const STRLEN x,             /* length of src[] */
1319                 const STRLEN y,             /* length of tgt[] */
1320                 const SSize_t maxDistance
1321 )
1322 {
1323     item *head = NULL;
1324     UV swapCount, swapScore, targetCharCount, i, j;
1325     UV *scores;
1326     UV score_ceil = x + y;
1327
1328     PERL_ARGS_ASSERT_EDIT_DISTANCE;
1329
1330     /* intialize matrix start values */
1331     Newx(scores, ( (x + 2) * (y + 2)), UV);
1332     scores[0] = score_ceil;
1333     scores[1 * (y + 2) + 0] = score_ceil;
1334     scores[0 * (y + 2) + 1] = score_ceil;
1335     scores[1 * (y + 2) + 1] = 0;
1336     head = uniquePush(uniquePush(head, src[0]), tgt[0]);
1337
1338     /* work loops    */
1339     /* i = src index */
1340     /* j = tgt index */
1341     for (i=1;i<=x;i++) {
1342         if (i < x)
1343             head = uniquePush(head, src[i]);
1344         scores[(i+1) * (y + 2) + 1] = i;
1345         scores[(i+1) * (y + 2) + 0] = score_ceil;
1346         swapCount = 0;
1347
1348         for (j=1;j<=y;j++) {
1349             if (i == 1) {
1350                 if(j < y)
1351                 head = uniquePush(head, tgt[j]);
1352                 scores[1 * (y + 2) + (j + 1)] = j;
1353                 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1354             }
1355
1356             targetCharCount = find(head, tgt[j-1])->value;
1357             swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1358
1359             if (src[i-1] != tgt[j-1]){
1360                 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));
1361             }
1362             else {
1363                 swapCount = j;
1364                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1365             }
1366         }
1367
1368         find(head, src[i-1])->value = i;
1369     }
1370
1371     {
1372         IV score = scores[(x+1) * (y + 2) + (y + 1)];
1373         dict_free(head);
1374         Safefree(scores);
1375         return (maxDistance != 0 && maxDistance < score)?(-1):score;
1376     }
1377 }
1378
1379 /* END of edit_distance() stuff
1380  * ========================================================= */
1381
1382 /* is c a control character for which we have a mnemonic? */
1383 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1384
1385 STATIC const char *
1386 S_cntrl_to_mnemonic(const U8 c)
1387 {
1388     /* Returns the mnemonic string that represents character 'c', if one
1389      * exists; NULL otherwise.  The only ones that exist for the purposes of
1390      * this routine are a few control characters */
1391
1392     switch (c) {
1393         case '\a':       return "\\a";
1394         case '\b':       return "\\b";
1395         case ESC_NATIVE: return "\\e";
1396         case '\f':       return "\\f";
1397         case '\n':       return "\\n";
1398         case '\r':       return "\\r";
1399         case '\t':       return "\\t";
1400     }
1401
1402     return NULL;
1403 }
1404
1405 /* Mark that we cannot extend a found fixed substring at this point.
1406    Update the longest found anchored substring or the longest found
1407    floating substrings if needed. */
1408
1409 STATIC void
1410 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1411                     SSize_t *minlenp, int is_inf)
1412 {
1413     const STRLEN l = CHR_SVLEN(data->last_found);
1414     SV * const longest_sv = data->substrs[data->cur_is_floating].str;
1415     const STRLEN old_l = CHR_SVLEN(longest_sv);
1416     GET_RE_DEBUG_FLAGS_DECL;
1417
1418     PERL_ARGS_ASSERT_SCAN_COMMIT;
1419
1420     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1421         const U8 i = data->cur_is_floating;
1422         SvSetMagicSV(longest_sv, data->last_found);
1423         data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min;
1424
1425         if (!i) /* fixed */
1426             data->substrs[0].max_offset = data->substrs[0].min_offset;
1427         else { /* float */
1428             data->substrs[1].max_offset = (l
1429                           ? data->last_start_max
1430                           : (data->pos_delta > SSize_t_MAX - data->pos_min
1431                                          ? SSize_t_MAX
1432                                          : data->pos_min + data->pos_delta));
1433             if (is_inf
1434                  || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX)
1435                 data->substrs[1].max_offset = SSize_t_MAX;
1436         }
1437
1438         if (data->flags & SF_BEFORE_EOL)
1439             data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL);
1440         else
1441             data->substrs[i].flags &= ~SF_BEFORE_EOL;
1442         data->substrs[i].minlenp = minlenp;
1443         data->substrs[i].lookbehind = 0;
1444     }
1445
1446     SvCUR_set(data->last_found, 0);
1447     {
1448         SV * const sv = data->last_found;
1449         if (SvUTF8(sv) && SvMAGICAL(sv)) {
1450             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1451             if (mg)
1452                 mg->mg_len = 0;
1453         }
1454     }
1455     data->last_end = -1;
1456     data->flags &= ~SF_BEFORE_EOL;
1457     DEBUG_STUDYDATA("commit", data, 0, is_inf);
1458 }
1459
1460 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1461  * list that describes which code points it matches */
1462
1463 STATIC void
1464 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1465 {
1466     /* Set the SSC 'ssc' to match an empty string or any code point */
1467
1468     PERL_ARGS_ASSERT_SSC_ANYTHING;
1469
1470     assert(is_ANYOF_SYNTHETIC(ssc));
1471
1472     /* mortalize so won't leak */
1473     ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX));
1474     ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING;  /* Plus matches empty */
1475 }
1476
1477 STATIC int
1478 S_ssc_is_anything(const regnode_ssc *ssc)
1479 {
1480     /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1481      * point; FALSE otherwise.  Thus, this is used to see if using 'ssc' buys
1482      * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1483      * in any way, so there's no point in using it */
1484
1485     UV start, end;
1486     bool ret;
1487
1488     PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1489
1490     assert(is_ANYOF_SYNTHETIC(ssc));
1491
1492     if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1493         return FALSE;
1494     }
1495
1496     /* See if the list consists solely of the range 0 - Infinity */
1497     invlist_iterinit(ssc->invlist);
1498     ret = invlist_iternext(ssc->invlist, &start, &end)
1499           && start == 0
1500           && end == UV_MAX;
1501
1502     invlist_iterfinish(ssc->invlist);
1503
1504     if (ret) {
1505         return TRUE;
1506     }
1507
1508     /* If e.g., both \w and \W are set, matches everything */
1509     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1510         int i;
1511         for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1512             if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1513                 return TRUE;
1514             }
1515         }
1516     }
1517
1518     return FALSE;
1519 }
1520
1521 STATIC void
1522 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1523 {
1524     /* Initializes the SSC 'ssc'.  This includes setting it to match an empty
1525      * string, any code point, or any posix class under locale */
1526
1527     PERL_ARGS_ASSERT_SSC_INIT;
1528
1529     Zero(ssc, 1, regnode_ssc);
1530     set_ANYOF_SYNTHETIC(ssc);
1531     ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1532     ssc_anything(ssc);
1533
1534     /* If any portion of the regex is to operate under locale rules that aren't
1535      * fully known at compile time, initialization includes it.  The reason
1536      * this isn't done for all regexes is that the optimizer was written under
1537      * the assumption that locale was all-or-nothing.  Given the complexity and
1538      * lack of documentation in the optimizer, and that there are inadequate
1539      * test cases for locale, many parts of it may not work properly, it is
1540      * safest to avoid locale unless necessary. */
1541     if (RExC_contains_locale) {
1542         ANYOF_POSIXL_SETALL(ssc);
1543     }
1544     else {
1545         ANYOF_POSIXL_ZERO(ssc);
1546     }
1547 }
1548
1549 STATIC int
1550 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1551                         const regnode_ssc *ssc)
1552 {
1553     /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1554      * to the list of code points matched, and locale posix classes; hence does
1555      * not check its flags) */
1556
1557     UV start, end;
1558     bool ret;
1559
1560     PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1561
1562     assert(is_ANYOF_SYNTHETIC(ssc));
1563
1564     invlist_iterinit(ssc->invlist);
1565     ret = invlist_iternext(ssc->invlist, &start, &end)
1566           && start == 0
1567           && end == UV_MAX;
1568
1569     invlist_iterfinish(ssc->invlist);
1570
1571     if (! ret) {
1572         return FALSE;
1573     }
1574
1575     if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1576         return FALSE;
1577     }
1578
1579     return TRUE;
1580 }
1581
1582 #define INVLIST_INDEX 0
1583 #define ONLY_LOCALE_MATCHES_INDEX 1
1584 #define DEFERRED_USER_DEFINED_INDEX 2
1585
1586 STATIC SV*
1587 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1588                                const regnode_charclass* const node)
1589 {
1590     /* Returns a mortal inversion list defining which code points are matched
1591      * by 'node', which is of type ANYOF.  Handles complementing the result if
1592      * appropriate.  If some code points aren't knowable at this time, the
1593      * returned list must, and will, contain every code point that is a
1594      * possibility. */
1595
1596     dVAR;
1597     SV* invlist = NULL;
1598     SV* only_utf8_locale_invlist = NULL;
1599     unsigned int i;
1600     const U32 n = ARG(node);
1601     bool new_node_has_latin1 = FALSE;
1602     const U8 flags = (inRANGE(OP(node), ANYOFH, ANYOFRb))
1603                       ? 0
1604                       : ANYOF_FLAGS(node);
1605
1606     PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1607
1608     /* Look at the data structure created by S_set_ANYOF_arg() */
1609     if (n != ANYOF_ONLY_HAS_BITMAP) {
1610         SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1611         AV * const av = MUTABLE_AV(SvRV(rv));
1612         SV **const ary = AvARRAY(av);
1613         assert(RExC_rxi->data->what[n] == 's');
1614
1615         if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
1616
1617             /* Here there are things that won't be known until runtime -- we
1618              * have to assume it could be anything */
1619             invlist = sv_2mortal(_new_invlist(1));
1620             return _add_range_to_invlist(invlist, 0, UV_MAX);
1621         }
1622         else if (ary[INVLIST_INDEX]) {
1623
1624             /* Use the node's inversion list */
1625             invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL));
1626         }
1627
1628         /* Get the code points valid only under UTF-8 locales */
1629         if (   (flags & ANYOFL_FOLD)
1630             &&  av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX)
1631         {
1632             only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX];
1633         }
1634     }
1635
1636     if (! invlist) {
1637         invlist = sv_2mortal(_new_invlist(0));
1638     }
1639
1640     /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1641      * code points, and an inversion list for the others, but if there are code
1642      * points that should match only conditionally on the target string being
1643      * UTF-8, those are placed in the inversion list, and not the bitmap.
1644      * Since there are circumstances under which they could match, they are
1645      * included in the SSC.  But if the ANYOF node is to be inverted, we have
1646      * to exclude them here, so that when we invert below, the end result
1647      * actually does include them.  (Think about "\xe0" =~ /[^\xc0]/di;).  We
1648      * have to do this here before we add the unconditionally matched code
1649      * points */
1650     if (flags & ANYOF_INVERT) {
1651         _invlist_intersection_complement_2nd(invlist,
1652                                              PL_UpperLatin1,
1653                                              &invlist);
1654     }
1655
1656     /* Add in the points from the bit map */
1657     if (! inRANGE(OP(node), ANYOFH, ANYOFRb)) {
1658         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1659             if (ANYOF_BITMAP_TEST(node, i)) {
1660                 unsigned int start = i++;
1661
1662                 for (;    i < NUM_ANYOF_CODE_POINTS
1663                        && ANYOF_BITMAP_TEST(node, i); ++i)
1664                 {
1665                     /* empty */
1666                 }
1667                 invlist = _add_range_to_invlist(invlist, start, i-1);
1668                 new_node_has_latin1 = TRUE;
1669             }
1670         }
1671     }
1672
1673     /* If this can match all upper Latin1 code points, have to add them
1674      * as well.  But don't add them if inverting, as when that gets done below,
1675      * it would exclude all these characters, including the ones it shouldn't
1676      * that were added just above */
1677     if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD
1678         && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1679     {
1680         _invlist_union(invlist, PL_UpperLatin1, &invlist);
1681     }
1682
1683     /* Similarly for these */
1684     if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1685         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1686     }
1687
1688     if (flags & ANYOF_INVERT) {
1689         _invlist_invert(invlist);
1690     }
1691     else if (flags & ANYOFL_FOLD) {
1692         if (new_node_has_latin1) {
1693
1694             /* Under /li, any 0-255 could fold to any other 0-255, depending on
1695              * the locale.  We can skip this if there are no 0-255 at all. */
1696             _invlist_union(invlist, PL_Latin1, &invlist);
1697
1698             invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I);
1699             invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
1700         }
1701         else {
1702             if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) {
1703                 invlist = add_cp_to_invlist(invlist, 'I');
1704             }
1705             if (_invlist_contains_cp(invlist,
1706                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
1707             {
1708                 invlist = add_cp_to_invlist(invlist, 'i');
1709             }
1710         }
1711     }
1712
1713     /* Similarly add the UTF-8 locale possible matches.  These have to be
1714      * deferred until after the non-UTF-8 locale ones are taken care of just
1715      * above, or it leads to wrong results under ANYOF_INVERT */
1716     if (only_utf8_locale_invlist) {
1717         _invlist_union_maybe_complement_2nd(invlist,
1718                                             only_utf8_locale_invlist,
1719                                             flags & ANYOF_INVERT,
1720                                             &invlist);
1721     }
1722
1723     return invlist;
1724 }
1725
1726 /* These two functions currently do the exact same thing */
1727 #define ssc_init_zero           ssc_init
1728
1729 #define ssc_add_cp(ssc, cp)   ssc_add_range((ssc), (cp), (cp))
1730 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1731
1732 /* 'AND' a given class with another one.  Can create false positives.  'ssc'
1733  * should not be inverted.  'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1734  * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1735
1736 STATIC void
1737 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1738                 const regnode_charclass *and_with)
1739 {
1740     /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1741      * another SSC or a regular ANYOF class.  Can create false positives. */
1742
1743     SV* anded_cp_list;
1744     U8  and_with_flags = inRANGE(OP(and_with), ANYOFH, ANYOFRb)
1745                           ? 0
1746                           : ANYOF_FLAGS(and_with);
1747     U8  anded_flags;
1748
1749     PERL_ARGS_ASSERT_SSC_AND;
1750
1751     assert(is_ANYOF_SYNTHETIC(ssc));
1752
1753     /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1754      * the code point inversion list and just the relevant flags */
1755     if (is_ANYOF_SYNTHETIC(and_with)) {
1756         anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1757         anded_flags = and_with_flags;
1758
1759         /* XXX This is a kludge around what appears to be deficiencies in the
1760          * optimizer.  If we make S_ssc_anything() add in the WARN_SUPER flag,
1761          * there are paths through the optimizer where it doesn't get weeded
1762          * out when it should.  And if we don't make some extra provision for
1763          * it like the code just below, it doesn't get added when it should.
1764          * This solution is to add it only when AND'ing, which is here, and
1765          * only when what is being AND'ed is the pristine, original node
1766          * matching anything.  Thus it is like adding it to ssc_anything() but
1767          * only when the result is to be AND'ed.  Probably the same solution
1768          * could be adopted for the same problem we have with /l matching,
1769          * which is solved differently in S_ssc_init(), and that would lead to
1770          * fewer false positives than that solution has.  But if this solution
1771          * creates bugs, the consequences are only that a warning isn't raised
1772          * that should be; while the consequences for having /l bugs is
1773          * incorrect matches */
1774         if (ssc_is_anything((regnode_ssc *)and_with)) {
1775             anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1776         }
1777     }
1778     else {
1779         anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1780         if (OP(and_with) == ANYOFD) {
1781             anded_flags = and_with_flags & ANYOF_COMMON_FLAGS;
1782         }
1783         else {
1784             anded_flags = and_with_flags
1785             &( ANYOF_COMMON_FLAGS
1786               |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1787               |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1788             if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) {
1789                 anded_flags &=
1790                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1791             }
1792         }
1793     }
1794
1795     ANYOF_FLAGS(ssc) &= anded_flags;
1796
1797     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1798      * C2 is the list of code points in 'and-with'; P2, its posix classes.
1799      * 'and_with' may be inverted.  When not inverted, we have the situation of
1800      * computing:
1801      *  (C1 | P1) & (C2 | P2)
1802      *                     =  (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1803      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1804      *                    <=  ((C1 & C2) |       P2)) | ( P1       | (P1 & P2))
1805      *                    <=  ((C1 & C2) | P1 | P2)
1806      * Alternatively, the last few steps could be:
1807      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1808      *                    <=  ((C1 & C2) |  C1      ) | (      C2  | (P1 & P2))
1809      *                    <=  (C1 | C2 | (P1 & P2))
1810      * We favor the second approach if either P1 or P2 is non-empty.  This is
1811      * because these components are a barrier to doing optimizations, as what
1812      * they match cannot be known until the moment of matching as they are
1813      * dependent on the current locale, 'AND"ing them likely will reduce or
1814      * eliminate them.
1815      * But we can do better if we know that C1,P1 are in their initial state (a
1816      * frequent occurrence), each matching everything:
1817      *  (<everything>) & (C2 | P2) =  C2 | P2
1818      * Similarly, if C2,P2 are in their initial state (again a frequent
1819      * occurrence), the result is a no-op
1820      *  (C1 | P1) & (<everything>) =  C1 | P1
1821      *
1822      * Inverted, we have
1823      *  (C1 | P1) & ~(C2 | P2)  =  (C1 | P1) & (~C2 & ~P2)
1824      *                          =  (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1825      *                         <=  (C1 & ~C2) | (P1 & ~P2)
1826      * */
1827
1828     if ((and_with_flags & ANYOF_INVERT)
1829         && ! is_ANYOF_SYNTHETIC(and_with))
1830     {
1831         unsigned int i;
1832
1833         ssc_intersection(ssc,
1834                          anded_cp_list,
1835                          FALSE /* Has already been inverted */
1836                          );
1837
1838         /* If either P1 or P2 is empty, the intersection will be also; can skip
1839          * the loop */
1840         if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) {
1841             ANYOF_POSIXL_ZERO(ssc);
1842         }
1843         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1844
1845             /* Note that the Posix class component P from 'and_with' actually
1846              * looks like:
1847              *      P = Pa | Pb | ... | Pn
1848              * where each component is one posix class, such as in [\w\s].
1849              * Thus
1850              *      ~P = ~(Pa | Pb | ... | Pn)
1851              *         = ~Pa & ~Pb & ... & ~Pn
1852              *        <= ~Pa | ~Pb | ... | ~Pn
1853              * The last is something we can easily calculate, but unfortunately
1854              * is likely to have many false positives.  We could do better
1855              * in some (but certainly not all) instances if two classes in
1856              * P have known relationships.  For example
1857              *      :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1858              * So
1859              *      :lower: & :print: = :lower:
1860              * And similarly for classes that must be disjoint.  For example,
1861              * since \s and \w can have no elements in common based on rules in
1862              * the POSIX standard,
1863              *      \w & ^\S = nothing
1864              * Unfortunately, some vendor locales do not meet the Posix
1865              * standard, in particular almost everything by Microsoft.
1866              * The loop below just changes e.g., \w into \W and vice versa */
1867
1868             regnode_charclass_posixl temp;
1869             int add = 1;    /* To calculate the index of the complement */
1870
1871             Zero(&temp, 1, regnode_charclass_posixl);
1872             ANYOF_POSIXL_ZERO(&temp);
1873             for (i = 0; i < ANYOF_MAX; i++) {
1874                 assert(i % 2 != 0
1875                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1876                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1877
1878                 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1879                     ANYOF_POSIXL_SET(&temp, i + add);
1880                 }
1881                 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1882             }
1883             ANYOF_POSIXL_AND(&temp, ssc);
1884
1885         } /* else ssc already has no posixes */
1886     } /* else: Not inverted.  This routine is a no-op if 'and_with' is an SSC
1887          in its initial state */
1888     else if (! is_ANYOF_SYNTHETIC(and_with)
1889              || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1890     {
1891         /* But if 'ssc' is in its initial state, the result is just 'and_with';
1892          * copy it over 'ssc' */
1893         if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1894             if (is_ANYOF_SYNTHETIC(and_with)) {
1895                 StructCopy(and_with, ssc, regnode_ssc);
1896             }
1897             else {
1898                 ssc->invlist = anded_cp_list;
1899                 ANYOF_POSIXL_ZERO(ssc);
1900                 if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1901                     ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1902                 }
1903             }
1904         }
1905         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1906                  || (and_with_flags & ANYOF_MATCHES_POSIXL))
1907         {
1908             /* One or the other of P1, P2 is non-empty. */
1909             if (and_with_flags & ANYOF_MATCHES_POSIXL) {
1910                 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1911             }
1912             ssc_union(ssc, anded_cp_list, FALSE);
1913         }
1914         else { /* P1 = P2 = empty */
1915             ssc_intersection(ssc, anded_cp_list, FALSE);
1916         }
1917     }
1918 }
1919
1920 STATIC void
1921 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1922                const regnode_charclass *or_with)
1923 {
1924     /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1925      * another SSC or a regular ANYOF class.  Can create false positives if
1926      * 'or_with' is to be inverted. */
1927
1928     SV* ored_cp_list;
1929     U8 ored_flags;
1930     U8  or_with_flags = inRANGE(OP(or_with), ANYOFH, ANYOFRb)
1931                          ? 0
1932                          : ANYOF_FLAGS(or_with);
1933
1934     PERL_ARGS_ASSERT_SSC_OR;
1935
1936     assert(is_ANYOF_SYNTHETIC(ssc));
1937
1938     /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1939      * the code point inversion list and just the relevant flags */
1940     if (is_ANYOF_SYNTHETIC(or_with)) {
1941         ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1942         ored_flags = or_with_flags;
1943     }
1944     else {
1945         ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1946         ored_flags = or_with_flags & ANYOF_COMMON_FLAGS;
1947         if (OP(or_with) != ANYOFD) {
1948             ored_flags
1949             |= or_with_flags
1950              & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1951                 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1952             if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) {
1953                 ored_flags |=
1954                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1955             }
1956         }
1957     }
1958
1959     ANYOF_FLAGS(ssc) |= ored_flags;
1960
1961     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1962      * C2 is the list of code points in 'or-with'; P2, its posix classes.
1963      * 'or_with' may be inverted.  When not inverted, we have the simple
1964      * situation of computing:
1965      *  (C1 | P1) | (C2 | P2)  =  (C1 | C2) | (P1 | P2)
1966      * If P1|P2 yields a situation with both a class and its complement are
1967      * set, like having both \w and \W, this matches all code points, and we
1968      * can delete these from the P component of the ssc going forward.  XXX We
1969      * might be able to delete all the P components, but I (khw) am not certain
1970      * about this, and it is better to be safe.
1971      *
1972      * Inverted, we have
1973      *  (C1 | P1) | ~(C2 | P2)  =  (C1 | P1) | (~C2 & ~P2)
1974      *                         <=  (C1 | P1) | ~C2
1975      *                         <=  (C1 | ~C2) | P1
1976      * (which results in actually simpler code than the non-inverted case)
1977      * */
1978
1979     if ((or_with_flags & ANYOF_INVERT)
1980         && ! is_ANYOF_SYNTHETIC(or_with))
1981     {
1982         /* We ignore P2, leaving P1 going forward */
1983     }   /* else  Not inverted */
1984     else if (or_with_flags & ANYOF_MATCHES_POSIXL) {
1985         ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1986         if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1987             unsigned int i;
1988             for (i = 0; i < ANYOF_MAX; i += 2) {
1989                 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1990                 {
1991                     ssc_match_all_cp(ssc);
1992                     ANYOF_POSIXL_CLEAR(ssc, i);
1993                     ANYOF_POSIXL_CLEAR(ssc, i+1);
1994                 }
1995             }
1996         }
1997     }
1998
1999     ssc_union(ssc,
2000               ored_cp_list,
2001               FALSE /* Already has been inverted */
2002               );
2003 }
2004
2005 PERL_STATIC_INLINE void
2006 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
2007 {
2008     PERL_ARGS_ASSERT_SSC_UNION;
2009
2010     assert(is_ANYOF_SYNTHETIC(ssc));
2011
2012     _invlist_union_maybe_complement_2nd(ssc->invlist,
2013                                         invlist,
2014                                         invert2nd,
2015                                         &ssc->invlist);
2016 }
2017
2018 PERL_STATIC_INLINE void
2019 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
2020                          SV* const invlist,
2021                          const bool invert2nd)
2022 {
2023     PERL_ARGS_ASSERT_SSC_INTERSECTION;
2024
2025     assert(is_ANYOF_SYNTHETIC(ssc));
2026
2027     _invlist_intersection_maybe_complement_2nd(ssc->invlist,
2028                                                invlist,
2029                                                invert2nd,
2030                                                &ssc->invlist);
2031 }
2032
2033 PERL_STATIC_INLINE void
2034 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
2035 {
2036     PERL_ARGS_ASSERT_SSC_ADD_RANGE;
2037
2038     assert(is_ANYOF_SYNTHETIC(ssc));
2039
2040     ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
2041 }
2042
2043 PERL_STATIC_INLINE void
2044 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
2045 {
2046     /* AND just the single code point 'cp' into the SSC 'ssc' */
2047
2048     SV* cp_list = _new_invlist(2);
2049
2050     PERL_ARGS_ASSERT_SSC_CP_AND;
2051
2052     assert(is_ANYOF_SYNTHETIC(ssc));
2053
2054     cp_list = add_cp_to_invlist(cp_list, cp);
2055     ssc_intersection(ssc, cp_list,
2056                      FALSE /* Not inverted */
2057                      );
2058     SvREFCNT_dec_NN(cp_list);
2059 }
2060
2061 PERL_STATIC_INLINE void
2062 S_ssc_clear_locale(regnode_ssc *ssc)
2063 {
2064     /* Set the SSC 'ssc' to not match any locale things */
2065     PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
2066
2067     assert(is_ANYOF_SYNTHETIC(ssc));
2068
2069     ANYOF_POSIXL_ZERO(ssc);
2070     ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
2071 }
2072
2073 #define NON_OTHER_COUNT   NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
2074
2075 STATIC bool
2076 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
2077 {
2078     /* The synthetic start class is used to hopefully quickly winnow down
2079      * places where a pattern could start a match in the target string.  If it
2080      * doesn't really narrow things down that much, there isn't much point to
2081      * having the overhead of using it.  This function uses some very crude
2082      * heuristics to decide if to use the ssc or not.
2083      *
2084      * It returns TRUE if 'ssc' rules out more than half what it considers to
2085      * be the "likely" possible matches, but of course it doesn't know what the
2086      * actual things being matched are going to be; these are only guesses
2087      *
2088      * For /l matches, it assumes that the only likely matches are going to be
2089      *      in the 0-255 range, uniformly distributed, so half of that is 127
2090      * For /a and /d matches, it assumes that the likely matches will be just
2091      *      the ASCII range, so half of that is 63
2092      * For /u and there isn't anything matching above the Latin1 range, it
2093      *      assumes that that is the only range likely to be matched, and uses
2094      *      half that as the cut-off: 127.  If anything matches above Latin1,
2095      *      it assumes that all of Unicode could match (uniformly), except for
2096      *      non-Unicode code points and things in the General Category "Other"
2097      *      (unassigned, private use, surrogates, controls and formats).  This
2098      *      is a much large number. */
2099
2100     U32 count = 0;      /* Running total of number of code points matched by
2101                            'ssc' */
2102     UV start, end;      /* Start and end points of current range in inversion
2103                            XXX outdated.  UTF-8 locales are common, what about invert? list */
2104     const U32 max_code_points = (LOC)
2105                                 ?  256
2106                                 : ((  ! UNI_SEMANTICS
2107                                     ||  invlist_highest(ssc->invlist) < 256)
2108                                   ? 128
2109                                   : NON_OTHER_COUNT);
2110     const U32 max_match = max_code_points / 2;
2111
2112     PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
2113
2114     invlist_iterinit(ssc->invlist);
2115     while (invlist_iternext(ssc->invlist, &start, &end)) {
2116         if (start >= max_code_points) {
2117             break;
2118         }
2119         end = MIN(end, max_code_points - 1);
2120         count += end - start + 1;
2121         if (count >= max_match) {
2122             invlist_iterfinish(ssc->invlist);
2123             return FALSE;
2124         }
2125     }
2126
2127     return TRUE;
2128 }
2129
2130
2131 STATIC void
2132 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
2133 {
2134     /* The inversion list in the SSC is marked mortal; now we need a more
2135      * permanent copy, which is stored the same way that is done in a regular
2136      * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
2137      * map */
2138
2139     SV* invlist = invlist_clone(ssc->invlist, NULL);
2140
2141     PERL_ARGS_ASSERT_SSC_FINALIZE;
2142
2143     assert(is_ANYOF_SYNTHETIC(ssc));
2144
2145     /* The code in this file assumes that all but these flags aren't relevant
2146      * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
2147      * by the time we reach here */
2148     assert(! (ANYOF_FLAGS(ssc)
2149         & ~( ANYOF_COMMON_FLAGS
2150             |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
2151             |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
2152
2153     populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
2154
2155     set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL);
2156     SvREFCNT_dec(invlist);
2157
2158     /* Make sure is clone-safe */
2159     ssc->invlist = NULL;
2160
2161     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
2162         ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
2163         OP(ssc) = ANYOFPOSIXL;
2164     }
2165     else if (RExC_contains_locale) {
2166         OP(ssc) = ANYOFL;
2167     }
2168
2169     assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
2170 }
2171
2172 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
2173 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
2174 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
2175 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list         \
2176                                ? (TRIE_LIST_CUR( idx ) - 1)           \
2177                                : 0 )
2178
2179
2180 #ifdef DEBUGGING
2181 /*
2182    dump_trie(trie,widecharmap,revcharmap)
2183    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
2184    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
2185
2186    These routines dump out a trie in a somewhat readable format.
2187    The _interim_ variants are used for debugging the interim
2188    tables that are used to generate the final compressed
2189    representation which is what dump_trie expects.
2190
2191    Part of the reason for their existence is to provide a form
2192    of documentation as to how the different representations function.
2193
2194 */
2195
2196 /*
2197   Dumps the final compressed table form of the trie to Perl_debug_log.
2198   Used for debugging make_trie().
2199 */
2200
2201 STATIC void
2202 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
2203             AV *revcharmap, U32 depth)
2204 {
2205     U32 state;
2206     SV *sv=sv_newmortal();
2207     int colwidth= widecharmap ? 6 : 4;
2208     U16 word;
2209     GET_RE_DEBUG_FLAGS_DECL;
2210
2211     PERL_ARGS_ASSERT_DUMP_TRIE;
2212
2213     Perl_re_indentf( aTHX_  "Char : %-6s%-6s%-4s ",
2214         depth+1, "Match","Base","Ofs" );
2215
2216     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
2217         SV ** const tmp = av_fetch( revcharmap, state, 0);
2218         if ( tmp ) {
2219             Perl_re_printf( aTHX_  "%*s",
2220                 colwidth,
2221                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2222                             PL_colors[0], PL_colors[1],
2223                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2224                             PERL_PV_ESCAPE_FIRSTCHAR
2225                 )
2226             );
2227         }
2228     }
2229     Perl_re_printf( aTHX_  "\n");
2230     Perl_re_indentf( aTHX_ "State|-----------------------", depth+1);
2231
2232     for( state = 0 ; state < trie->uniquecharcount ; state++ )
2233         Perl_re_printf( aTHX_  "%.*s", colwidth, "--------");
2234     Perl_re_printf( aTHX_  "\n");
2235
2236     for( state = 1 ; state < trie->statecount ; state++ ) {
2237         const U32 base = trie->states[ state ].trans.base;
2238
2239         Perl_re_indentf( aTHX_  "#%4" UVXf "|", depth+1, (UV)state);
2240
2241         if ( trie->states[ state ].wordnum ) {
2242             Perl_re_printf( aTHX_  " W%4X", trie->states[ state ].wordnum );
2243         } else {
2244             Perl_re_printf( aTHX_  "%6s", "" );
2245         }
2246
2247         Perl_re_printf( aTHX_  " @%4" UVXf " ", (UV)base );
2248
2249         if ( base ) {
2250             U32 ofs = 0;
2251
2252             while( ( base + ofs  < trie->uniquecharcount ) ||
2253                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
2254                      && trie->trans[ base + ofs - trie->uniquecharcount ].check
2255                                                                     != state))
2256                     ofs++;
2257
2258             Perl_re_printf( aTHX_  "+%2" UVXf "[ ", (UV)ofs);
2259
2260             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2261                 if ( ( base + ofs >= trie->uniquecharcount )
2262                         && ( base + ofs - trie->uniquecharcount
2263                                                         < trie->lasttrans )
2264                         && trie->trans[ base + ofs
2265                                     - trie->uniquecharcount ].check == state )
2266                 {
2267                    Perl_re_printf( aTHX_  "%*" UVXf, colwidth,
2268                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next
2269                    );
2270                 } else {
2271                     Perl_re_printf( aTHX_  "%*s", colwidth,"   ." );
2272                 }
2273             }
2274
2275             Perl_re_printf( aTHX_  "]");
2276
2277         }
2278         Perl_re_printf( aTHX_  "\n" );
2279     }
2280     Perl_re_indentf( aTHX_  "word_info N:(prev,len)=",
2281                                 depth);
2282     for (word=1; word <= trie->wordcount; word++) {
2283         Perl_re_printf( aTHX_  " %d:(%d,%d)",
2284             (int)word, (int)(trie->wordinfo[word].prev),
2285             (int)(trie->wordinfo[word].len));
2286     }
2287     Perl_re_printf( aTHX_  "\n" );
2288 }
2289 /*
2290   Dumps a fully constructed but uncompressed trie in list form.
2291   List tries normally only are used for construction when the number of
2292   possible chars (trie->uniquecharcount) is very high.
2293   Used for debugging make_trie().
2294 */
2295 STATIC void
2296 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2297                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
2298                          U32 depth)
2299 {
2300     U32 state;
2301     SV *sv=sv_newmortal();
2302     int colwidth= widecharmap ? 6 : 4;
2303     GET_RE_DEBUG_FLAGS_DECL;
2304
2305     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2306
2307     /* print out the table precompression.  */
2308     Perl_re_indentf( aTHX_  "State :Word | Transition Data\n",
2309             depth+1 );
2310     Perl_re_indentf( aTHX_  "%s",
2311             depth+1, "------:-----+-----------------\n" );
2312
2313     for( state=1 ; state < next_alloc ; state ++ ) {
2314         U16 charid;
2315
2316         Perl_re_indentf( aTHX_  " %4" UVXf " :",
2317             depth+1, (UV)state  );
2318         if ( ! trie->states[ state ].wordnum ) {
2319             Perl_re_printf( aTHX_  "%5s| ","");
2320         } else {
2321             Perl_re_printf( aTHX_  "W%4x| ",
2322                 trie->states[ state ].wordnum
2323             );
2324         }
2325         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2326             SV ** const tmp = av_fetch( revcharmap,
2327                                         TRIE_LIST_ITEM(state, charid).forid, 0);
2328             if ( tmp ) {
2329                 Perl_re_printf( aTHX_  "%*s:%3X=%4" UVXf " | ",
2330                     colwidth,
2331                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2332                               colwidth,
2333                               PL_colors[0], PL_colors[1],
2334                               (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2335                               | PERL_PV_ESCAPE_FIRSTCHAR
2336                     ) ,
2337                     TRIE_LIST_ITEM(state, charid).forid,
2338                     (UV)TRIE_LIST_ITEM(state, charid).newstate
2339                 );
2340                 if (!(charid % 10))
2341                     Perl_re_printf( aTHX_  "\n%*s| ",
2342                         (int)((depth * 2) + 14), "");
2343             }
2344         }
2345         Perl_re_printf( aTHX_  "\n");
2346     }
2347 }
2348
2349 /*
2350   Dumps a fully constructed but uncompressed trie in table form.
2351   This is the normal DFA style state transition table, with a few
2352   twists to facilitate compression later.
2353   Used for debugging make_trie().
2354 */
2355 STATIC void
2356 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2357                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
2358                           U32 depth)
2359 {
2360     U32 state;
2361     U16 charid;
2362     SV *sv=sv_newmortal();
2363     int colwidth= widecharmap ? 6 : 4;
2364     GET_RE_DEBUG_FLAGS_DECL;
2365
2366     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2367
2368     /*
2369        print out the table precompression so that we can do a visual check
2370        that they are identical.
2371      */
2372
2373     Perl_re_indentf( aTHX_  "Char : ", depth+1 );
2374
2375     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2376         SV ** const tmp = av_fetch( revcharmap, charid, 0);
2377         if ( tmp ) {
2378             Perl_re_printf( aTHX_  "%*s",
2379                 colwidth,
2380                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2381                             PL_colors[0], PL_colors[1],
2382                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2383                             PERL_PV_ESCAPE_FIRSTCHAR
2384                 )
2385             );
2386         }
2387     }
2388
2389     Perl_re_printf( aTHX_ "\n");
2390     Perl_re_indentf( aTHX_  "State+-", depth+1 );
2391
2392     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2393         Perl_re_printf( aTHX_  "%.*s", colwidth,"--------");
2394     }
2395
2396     Perl_re_printf( aTHX_  "\n" );
2397
2398     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2399
2400         Perl_re_indentf( aTHX_  "%4" UVXf " : ",
2401             depth+1,
2402             (UV)TRIE_NODENUM( state ) );
2403
2404         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2405             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2406             if (v)
2407                 Perl_re_printf( aTHX_  "%*" UVXf, colwidth, v );
2408             else
2409                 Perl_re_printf( aTHX_  "%*s", colwidth, "." );
2410         }
2411         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2412             Perl_re_printf( aTHX_  " (%4" UVXf ")\n",
2413                                             (UV)trie->trans[ state ].check );
2414         } else {
2415             Perl_re_printf( aTHX_  " (%4" UVXf ") W%4X\n",
2416                                             (UV)trie->trans[ state ].check,
2417             trie->states[ TRIE_NODENUM( state ) ].wordnum );
2418         }
2419     }
2420 }
2421
2422 #endif
2423
2424
2425 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2426   startbranch: the first branch in the whole branch sequence
2427   first      : start branch of sequence of branch-exact nodes.
2428                May be the same as startbranch
2429   last       : Thing following the last branch.
2430                May be the same as tail.
2431   tail       : item following the branch sequence
2432   count      : words in the sequence
2433   flags      : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2434   depth      : indent depth
2435
2436 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2437
2438 A trie is an N'ary tree where the branches are determined by digital
2439 decomposition of the key. IE, at the root node you look up the 1st character and
2440 follow that branch repeat until you find the end of the branches. Nodes can be
2441 marked as "accepting" meaning they represent a complete word. Eg:
2442
2443   /he|she|his|hers/
2444
2445 would convert into the following structure. Numbers represent states, letters
2446 following numbers represent valid transitions on the letter from that state, if
2447 the number is in square brackets it represents an accepting state, otherwise it
2448 will be in parenthesis.
2449
2450       +-h->+-e->[3]-+-r->(8)-+-s->[9]
2451       |    |
2452       |   (2)
2453       |    |
2454      (1)   +-i->(6)-+-s->[7]
2455       |
2456       +-s->(3)-+-h->(4)-+-e->[5]
2457
2458       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2459
2460 This shows that when matching against the string 'hers' we will begin at state 1
2461 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2462 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2463 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2464 single traverse. We store a mapping from accepting to state to which word was
2465 matched, and then when we have multiple possibilities we try to complete the
2466 rest of the regex in the order in which they occurred in the alternation.
2467
2468 The only prior NFA like behaviour that would be changed by the TRIE support is
2469 the silent ignoring of duplicate alternations which are of the form:
2470
2471  / (DUPE|DUPE) X? (?{ ... }) Y /x
2472
2473 Thus EVAL blocks following a trie may be called a different number of times with
2474 and without the optimisation. With the optimisations dupes will be silently
2475 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2476 the following demonstrates:
2477
2478  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2479
2480 which prints out 'word' three times, but
2481
2482  'words'=~/(word|word|word)(?{ print $1 })S/
2483
2484 which doesnt print it out at all. This is due to other optimisations kicking in.
2485
2486 Example of what happens on a structural level:
2487
2488 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2489
2490    1: CURLYM[1] {1,32767}(18)
2491    5:   BRANCH(8)
2492    6:     EXACT <ac>(16)
2493    8:   BRANCH(11)
2494    9:     EXACT <ad>(16)
2495   11:   BRANCH(14)
2496   12:     EXACT <ab>(16)
2497   16:   SUCCEED(0)
2498   17:   NOTHING(18)
2499   18: END(0)
2500
2501 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2502 and should turn into:
2503
2504    1: CURLYM[1] {1,32767}(18)
2505    5:   TRIE(16)
2506         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2507           <ac>
2508           <ad>
2509           <ab>
2510   16:   SUCCEED(0)
2511   17:   NOTHING(18)
2512   18: END(0)
2513
2514 Cases where tail != last would be like /(?foo|bar)baz/:
2515
2516    1: BRANCH(4)
2517    2:   EXACT <foo>(8)
2518    4: BRANCH(7)
2519    5:   EXACT <bar>(8)
2520    7: TAIL(8)
2521    8: EXACT <baz>(10)
2522   10: END(0)
2523
2524 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2525 and would end up looking like:
2526
2527     1: TRIE(8)
2528       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2529         <foo>
2530         <bar>
2531    7: TAIL(8)
2532    8: EXACT <baz>(10)
2533   10: END(0)
2534
2535     d = uvchr_to_utf8_flags(d, uv, 0);
2536
2537 is the recommended Unicode-aware way of saying
2538
2539     *(d++) = uv;
2540 */
2541
2542 #define TRIE_STORE_REVCHAR(val)                                            \
2543     STMT_START {                                                           \
2544         if (UTF) {                                                         \
2545             SV *zlopp = newSV(UTF8_MAXBYTES);                              \
2546             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
2547             unsigned char *const kapow = uvchr_to_utf8(flrbbbbb, val);     \
2548             *kapow = '\0';                                                 \
2549             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
2550             SvPOK_on(zlopp);                                               \
2551             SvUTF8_on(zlopp);                                              \
2552             av_push(revcharmap, zlopp);                                    \
2553         } else {                                                           \
2554             char ooooff = (char)val;                                           \
2555             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
2556         }                                                                  \
2557         } STMT_END
2558
2559 /* This gets the next character from the input, folding it if not already
2560  * folded. */
2561 #define TRIE_READ_CHAR STMT_START {                                           \
2562     wordlen++;                                                                \
2563     if ( UTF ) {                                                              \
2564         /* if it is UTF then it is either already folded, or does not need    \
2565          * folding */                                                         \
2566         uvc = valid_utf8_to_uvchr( (const U8*) uc, &len);                     \
2567     }                                                                         \
2568     else if (folder == PL_fold_latin1) {                                      \
2569         /* This folder implies Unicode rules, which in the range expressible  \
2570          *  by not UTF is the lower case, with the two exceptions, one of     \
2571          *  which should have been taken care of before calling this */       \
2572         assert(*uc != LATIN_SMALL_LETTER_SHARP_S);                            \
2573         uvc = toLOWER_L1(*uc);                                                \
2574         if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU;         \
2575         len = 1;                                                              \
2576     } else {                                                                  \
2577         /* raw data, will be folded later if needed */                        \
2578         uvc = (U32)*uc;                                                       \
2579         len = 1;                                                              \
2580     }                                                                         \
2581 } STMT_END
2582
2583
2584
2585 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
2586     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
2587         U32 ging = TRIE_LIST_LEN( state ) * 2;                  \
2588         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2589         TRIE_LIST_LEN( state ) = ging;                          \
2590     }                                                           \
2591     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
2592     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
2593     TRIE_LIST_CUR( state )++;                                   \
2594 } STMT_END
2595
2596 #define TRIE_LIST_NEW(state) STMT_START {                       \
2597     Newx( trie->states[ state ].trans.list,                     \
2598         4, reg_trie_trans_le );                                 \
2599      TRIE_LIST_CUR( state ) = 1;                                \
2600      TRIE_LIST_LEN( state ) = 4;                                \
2601 } STMT_END
2602
2603 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
2604     U16 dupe= trie->states[ state ].wordnum;                    \
2605     regnode * const noper_next = regnext( noper );              \
2606                                                                 \
2607     DEBUG_r({                                                   \
2608         /* store the word for dumping */                        \
2609         SV* tmp;                                                \
2610         if (OP(noper) != NOTHING)                               \
2611             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
2612         else                                                    \
2613             tmp = newSVpvn_utf8( "", 0, UTF );                  \
2614         av_push( trie_words, tmp );                             \
2615     });                                                         \
2616                                                                 \
2617     curword++;                                                  \
2618     trie->wordinfo[curword].prev   = 0;                         \
2619     trie->wordinfo[curword].len    = wordlen;                   \
2620     trie->wordinfo[curword].accept = state;                     \
2621                                                                 \
2622     if ( noper_next < tail ) {                                  \
2623         if (!trie->jump)                                        \
2624             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2625                                                  sizeof(U16) ); \
2626         trie->jump[curword] = (U16)(noper_next - convert);      \
2627         if (!jumper)                                            \
2628             jumper = noper_next;                                \
2629         if (!nextbranch)                                        \
2630             nextbranch= regnext(cur);                           \
2631     }                                                           \
2632                                                                 \
2633     if ( dupe ) {                                               \
2634         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
2635         /* chain, so that when the bits of chain are later    */\
2636         /* linked together, the dups appear in the chain      */\
2637         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2638         trie->wordinfo[dupe].prev = curword;                    \
2639     } else {                                                    \
2640         /* we haven't inserted this word yet.                */ \
2641         trie->states[ state ].wordnum = curword;                \
2642     }                                                           \
2643 } STMT_END
2644
2645
2646 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
2647      ( ( base + charid >=  ucharcount                                   \
2648          && base + charid < ubound                                      \
2649          && state == trie->trans[ base - ucharcount + charid ].check    \
2650          && trie->trans[ base - ucharcount + charid ].next )            \
2651            ? trie->trans[ base - ucharcount + charid ].next             \
2652            : ( state==1 ? special : 0 )                                 \
2653       )
2654
2655 #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder)           \
2656 STMT_START {                                                \
2657     TRIE_BITMAP_SET(trie, uvc);                             \
2658     /* store the folded codepoint */                        \
2659     if ( folder )                                           \
2660         TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);           \
2661                                                             \
2662     if ( !UTF ) {                                           \
2663         /* store first byte of utf8 representation of */    \
2664         /* variant codepoints */                            \
2665         if (! UVCHR_IS_INVARIANT(uvc)) {                    \
2666             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));   \
2667         }                                                   \
2668     }                                                       \
2669 } STMT_END
2670 #define MADE_TRIE       1
2671 #define MADE_JUMP_TRIE  2
2672 #define MADE_EXACT_TRIE 4
2673
2674 STATIC I32
2675 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2676                   regnode *first, regnode *last, regnode *tail,
2677                   U32 word_count, U32 flags, U32 depth)
2678 {
2679     /* first pass, loop through and scan words */
2680     reg_trie_data *trie;
2681     HV *widecharmap = NULL;
2682     AV *revcharmap = newAV();
2683     regnode *cur;
2684     STRLEN len = 0;
2685     UV uvc = 0;
2686     U16 curword = 0;
2687     U32 next_alloc = 0;
2688     regnode *jumper = NULL;
2689     regnode *nextbranch = NULL;
2690     regnode *convert = NULL;
2691     U32 *prev_states; /* temp array mapping each state to previous one */
2692     /* we just use folder as a flag in utf8 */
2693     const U8 * folder = NULL;
2694
2695     /* in the below add_data call we are storing either 'tu' or 'tuaa'
2696      * which stands for one trie structure, one hash, optionally followed
2697      * by two arrays */
2698 #ifdef DEBUGGING
2699     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa"));
2700     AV *trie_words = NULL;
2701     /* along with revcharmap, this only used during construction but both are
2702      * useful during debugging so we store them in the struct when debugging.
2703      */
2704 #else
2705     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2706     STRLEN trie_charcount=0;
2707 #endif
2708     SV *re_trie_maxbuff;
2709     GET_RE_DEBUG_FLAGS_DECL;
2710
2711     PERL_ARGS_ASSERT_MAKE_TRIE;
2712 #ifndef DEBUGGING
2713     PERL_UNUSED_ARG(depth);
2714 #endif
2715
2716     switch (flags) {
2717         case EXACT: case EXACT_REQ8: case EXACTL: break;
2718         case EXACTFAA:
2719         case EXACTFUP:
2720         case EXACTFU:
2721         case EXACTFLU8: folder = PL_fold_latin1; break;
2722         case EXACTF:  folder = PL_fold; break;
2723         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2724     }
2725
2726     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2727     trie->refcount = 1;
2728     trie->startstate = 1;
2729     trie->wordcount = word_count;
2730     RExC_rxi->data->data[ data_slot ] = (void*)trie;
2731     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2732     if (flags == EXACT || flags == EXACT_REQ8 || flags == EXACTL)
2733         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2734     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2735                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
2736
2737     DEBUG_r({
2738         trie_words = newAV();
2739     });
2740
2741     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD);
2742     assert(re_trie_maxbuff);
2743     if (!SvIOK(re_trie_maxbuff)) {
2744         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2745     }
2746     DEBUG_TRIE_COMPILE_r({
2747         Perl_re_indentf( aTHX_
2748           "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2749           depth+1,
2750           REG_NODE_NUM(startbranch), REG_NODE_NUM(first),
2751           REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2752     });
2753
2754    /* Find the node we are going to overwrite */
2755     if ( first == startbranch && OP( last ) != BRANCH ) {
2756         /* whole branch chain */
2757         convert = first;
2758     } else {
2759         /* branch sub-chain */
2760         convert = NEXTOPER( first );
2761     }
2762
2763     /*  -- First loop and Setup --
2764
2765        We first traverse the branches and scan each word to determine if it
2766        contains widechars, and how many unique chars there are, this is
2767        important as we have to build a table with at least as many columns as we
2768        have unique chars.
2769
2770        We use an array of integers to represent the character codes 0..255
2771        (trie->charmap) and we use a an HV* to store Unicode characters. We use
2772        the native representation of the character value as the key and IV's for
2773        the coded index.
2774
2775        *TODO* If we keep track of how many times each character is used we can
2776        remap the columns so that the table compression later on is more
2777        efficient in terms of memory by ensuring the most common value is in the
2778        middle and the least common are on the outside.  IMO this would be better
2779        than a most to least common mapping as theres a decent chance the most
2780        common letter will share a node with the least common, meaning the node
2781        will not be compressible. With a middle is most common approach the worst
2782        case is when we have the least common nodes twice.
2783
2784      */
2785
2786     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2787         regnode *noper = NEXTOPER( cur );
2788         const U8 *uc;
2789         const U8 *e;
2790         int foldlen = 0;
2791         U32 wordlen      = 0;         /* required init */
2792         STRLEN minchars = 0;
2793         STRLEN maxchars = 0;
2794         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2795                                                bitmap?*/
2796
2797         if (OP(noper) == NOTHING) {
2798             /* skip past a NOTHING at the start of an alternation
2799              * eg, /(?:)a|(?:b)/ should be the same as /a|b/
2800              */
2801             regnode *noper_next= regnext(noper);
2802             if (noper_next < tail)
2803                 noper= noper_next;
2804         }
2805
2806         if (    noper < tail
2807             && (    OP(noper) == flags
2808                 || (flags == EXACT && OP(noper) == EXACT_REQ8)
2809                 || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
2810                                          || OP(noper) == EXACTFUP))))
2811         {
2812             uc= (U8*)STRING(noper);
2813             e= uc + STR_LEN(noper);
2814         } else {
2815             trie->minlen= 0;
2816             continue;
2817         }
2818
2819
2820         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2821             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2822                                           regardless of encoding */
2823             if (OP( noper ) == EXACTFUP) {
2824                 /* false positives are ok, so just set this */
2825                 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2826             }
2827         }
2828
2829         for ( ; uc < e ; uc += len ) {  /* Look at each char in the current
2830                                            branch */
2831             TRIE_CHARCOUNT(trie)++;
2832             TRIE_READ_CHAR;
2833
2834             /* TRIE_READ_CHAR returns the current character, or its fold if /i
2835              * is in effect.  Under /i, this character can match itself, or
2836              * anything that folds to it.  If not under /i, it can match just
2837              * itself.  Most folds are 1-1, for example k, K, and KELVIN SIGN
2838              * all fold to k, and all are single characters.   But some folds
2839              * expand to more than one character, so for example LATIN SMALL
2840              * LIGATURE FFI folds to the three character sequence 'ffi'.  If
2841              * the string beginning at 'uc' is 'ffi', it could be matched by
2842              * three characters, or just by the one ligature character. (It
2843              * could also be matched by two characters: LATIN SMALL LIGATURE FF
2844              * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2845              * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2846              * match.)  The trie needs to know the minimum and maximum number
2847              * of characters that could match so that it can use size alone to
2848              * quickly reject many match attempts.  The max is simple: it is
2849              * the number of folded characters in this branch (since a fold is
2850              * never shorter than what folds to it. */
2851
2852             maxchars++;
2853
2854             /* And the min is equal to the max if not under /i (indicated by
2855              * 'folder' being NULL), or there are no multi-character folds.  If
2856              * there is a multi-character fold, the min is incremented just
2857              * once, for the character that folds to the sequence.  Each
2858              * character in the sequence needs to be added to the list below of
2859              * characters in the trie, but we count only the first towards the
2860              * min number of characters needed.  This is done through the
2861              * variable 'foldlen', which is returned by the macros that look
2862              * for these sequences as the number of bytes the sequence
2863              * occupies.  Each time through the loop, we decrement 'foldlen' by
2864              * how many bytes the current char occupies.  Only when it reaches
2865              * 0 do we increment 'minchars' or look for another multi-character
2866              * sequence. */
2867             if (folder == NULL) {
2868                 minchars++;
2869             }
2870             else if (foldlen > 0) {
2871                 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2872             }
2873             else {
2874                 minchars++;
2875
2876                 /* See if *uc is the beginning of a multi-character fold.  If
2877                  * so, we decrement the length remaining to look at, to account
2878                  * for the current character this iteration.  (We can use 'uc'
2879                  * instead of the fold returned by TRIE_READ_CHAR because for
2880                  * non-UTF, the latin1_safe macro is smart enough to account
2881                  * for all the unfolded characters, and because for UTF, the
2882                  * string will already have been folded earlier in the
2883                  * compilation process */
2884                 if (UTF) {
2885                     if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2886                         foldlen -= UTF8SKIP(uc);
2887                     }
2888                 }
2889                 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2890                     foldlen--;
2891                 }
2892             }
2893
2894             /* The current character (and any potential folds) should be added
2895              * to the possible matching characters for this position in this
2896              * branch */
2897             if ( uvc < 256 ) {
2898                 if ( folder ) {
2899                     U8 folded= folder[ (U8) uvc ];
2900                     if ( !trie->charmap[ folded ] ) {
2901                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
2902                         TRIE_STORE_REVCHAR( folded );
2903                     }
2904                 }
2905                 if ( !trie->charmap[ uvc ] ) {
2906                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2907                     TRIE_STORE_REVCHAR( uvc );
2908                 }
2909                 if ( set_bit ) {
2910                     /* store the codepoint in the bitmap, and its folded
2911                      * equivalent. */
2912                     TRIE_BITMAP_SET_FOLDED(trie, uvc, folder);
2913                     set_bit = 0; /* We've done our bit :-) */
2914                 }
2915             } else {
2916
2917                 /* XXX We could come up with the list of code points that fold
2918                  * to this using PL_utf8_foldclosures, except not for
2919                  * multi-char folds, as there may be multiple combinations
2920                  * there that could work, which needs to wait until runtime to
2921                  * resolve (The comment about LIGATURE FFI above is such an
2922                  * example */
2923
2924                 SV** svpp;
2925                 if ( !widecharmap )
2926                     widecharmap = newHV();
2927
2928                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2929
2930                 if ( !svpp )
2931                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc );
2932
2933                 if ( !SvTRUE( *svpp ) ) {
2934                     sv_setiv( *svpp, ++trie->uniquecharcount );
2935                     TRIE_STORE_REVCHAR(uvc);
2936                 }
2937             }
2938         } /* end loop through characters in this branch of the trie */
2939
2940         /* We take the min and max for this branch and combine to find the min
2941          * and max for all branches processed so far */
2942         if( cur == first ) {
2943             trie->minlen = minchars;
2944             trie->maxlen = maxchars;
2945         } else if (minchars < trie->minlen) {
2946             trie->minlen = minchars;
2947         } else if (maxchars > trie->maxlen) {
2948             trie->maxlen = maxchars;
2949         }
2950     } /* end first pass */
2951     DEBUG_TRIE_COMPILE_r(
2952         Perl_re_indentf( aTHX_
2953                 "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2954                 depth+1,
2955                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2956                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2957                 (int)trie->minlen, (int)trie->maxlen )
2958     );
2959
2960     /*
2961         We now know what we are dealing with in terms of unique chars and
2962         string sizes so we can calculate how much memory a naive
2963         representation using a flat table  will take. If it's over a reasonable
2964         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2965         conservative but potentially much slower representation using an array
2966         of lists.
2967
2968         At the end we convert both representations into the same compressed
2969         form that will be used in regexec.c for matching with. The latter
2970         is a form that cannot be used to construct with but has memory
2971         properties similar to the list form and access properties similar
2972         to the table form making it both suitable for fast searches and
2973         small enough that its feasable to store for the duration of a program.
2974
2975         See the comment in the code where the compressed table is produced
2976         inplace from the flat tabe representation for an explanation of how
2977         the compression works.
2978
2979     */
2980
2981
2982     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2983     prev_states[1] = 0;
2984
2985     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2986                                                     > SvIV(re_trie_maxbuff) )
2987     {
2988         /*
2989             Second Pass -- Array Of Lists Representation
2990
2991             Each state will be represented by a list of charid:state records
2992             (reg_trie_trans_le) the first such element holds the CUR and LEN
2993             points of the allocated array. (See defines above).
2994
2995             We build the initial structure using the lists, and then convert
2996             it into the compressed table form which allows faster lookups
2997             (but cant be modified once converted).
2998         */
2999
3000         STRLEN transcount = 1;
3001
3002         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using list compiler\n",
3003             depth+1));
3004
3005         trie->states = (reg_trie_state *)
3006             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3007                                   sizeof(reg_trie_state) );
3008         TRIE_LIST_NEW(1);
3009         next_alloc = 2;
3010
3011         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3012
3013             regnode *noper   = NEXTOPER( cur );
3014             U32 state        = 1;         /* required init */
3015             U16 charid       = 0;         /* sanity init */
3016             U32 wordlen      = 0;         /* required init */
3017
3018             if (OP(noper) == NOTHING) {
3019                 regnode *noper_next= regnext(noper);
3020                 if (noper_next < tail)
3021                     noper= noper_next;
3022             }
3023
3024             if (    noper < tail
3025                 && (    OP(noper) == flags
3026                     || (flags == EXACT && OP(noper) == EXACT_REQ8)
3027                     || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
3028                                              || OP(noper) == EXACTFUP))))
3029             {
3030                 const U8 *uc= (U8*)STRING(noper);
3031                 const U8 *e= uc + STR_LEN(noper);
3032
3033                 for ( ; uc < e ; uc += len ) {
3034
3035                     TRIE_READ_CHAR;
3036
3037                     if ( uvc < 256 ) {
3038                         charid = trie->charmap[ uvc ];
3039                     } else {
3040                         SV** const svpp = hv_fetch( widecharmap,
3041                                                     (char*)&uvc,
3042                                                     sizeof( UV ),
3043                                                     0);
3044                         if ( !svpp ) {
3045                             charid = 0;
3046                         } else {
3047                             charid=(U16)SvIV( *svpp );
3048                         }
3049                     }
3050                     /* charid is now 0 if we dont know the char read, or
3051                      * nonzero if we do */
3052                     if ( charid ) {
3053
3054                         U16 check;
3055                         U32 newstate = 0;
3056
3057                         charid--;
3058                         if ( !trie->states[ state ].trans.list ) {
3059                             TRIE_LIST_NEW( state );
3060                         }
3061                         for ( check = 1;
3062                               check <= TRIE_LIST_USED( state );
3063                               check++ )
3064                         {
3065                             if ( TRIE_LIST_ITEM( state, check ).forid
3066                                                                     == charid )
3067                             {
3068                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
3069                                 break;
3070                             }
3071                         }
3072                         if ( ! newstate ) {
3073                             newstate = next_alloc++;
3074                             prev_states[newstate] = state;
3075                             TRIE_LIST_PUSH( state, charid, newstate );
3076                             transcount++;
3077                         }
3078                         state = newstate;
3079                     } else {
3080                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3081                     }
3082                 }
3083             }
3084             TRIE_HANDLE_WORD(state);
3085
3086         } /* end second pass */
3087
3088         /* next alloc is the NEXT state to be allocated */
3089         trie->statecount = next_alloc;
3090         trie->states = (reg_trie_state *)
3091             PerlMemShared_realloc( trie->states,
3092                                    next_alloc
3093                                    * sizeof(reg_trie_state) );
3094
3095         /* and now dump it out before we compress it */
3096         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
3097                                                          revcharmap, next_alloc,
3098                                                          depth+1)
3099         );
3100
3101         trie->trans = (reg_trie_trans *)
3102             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
3103         {
3104             U32 state;
3105             U32 tp = 0;
3106             U32 zp = 0;
3107
3108
3109             for( state=1 ; state < next_alloc ; state ++ ) {
3110                 U32 base=0;
3111
3112                 /*
3113                 DEBUG_TRIE_COMPILE_MORE_r(
3114                     Perl_re_printf( aTHX_  "tp: %d zp: %d ",tp,zp)
3115                 );
3116                 */
3117
3118                 if (trie->states[state].trans.list) {
3119                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
3120                     U16 maxid=minid;
3121                     U16 idx;
3122
3123                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3124                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
3125                         if ( forid < minid ) {
3126                             minid=forid;
3127                         } else if ( forid > maxid ) {
3128                             maxid=forid;
3129                         }
3130                     }
3131                     if ( transcount < tp + maxid - minid + 1) {
3132                         transcount *= 2;
3133                         trie->trans = (reg_trie_trans *)
3134                             PerlMemShared_realloc( trie->trans,
3135                                                      transcount
3136                                                      * sizeof(reg_trie_trans) );
3137                         Zero( trie->trans + (transcount / 2),
3138                               transcount / 2,
3139                               reg_trie_trans );
3140                     }
3141                     base = trie->uniquecharcount + tp - minid;
3142                     if ( maxid == minid ) {
3143                         U32 set = 0;
3144                         for ( ; zp < tp ; zp++ ) {
3145                             if ( ! trie->trans[ zp ].next ) {
3146                                 base = trie->uniquecharcount + zp - minid;
3147                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
3148                                                                    1).newstate;
3149                                 trie->trans[ zp ].check = state;
3150                                 set = 1;
3151                                 break;
3152                             }
3153                         }
3154                         if ( !set ) {
3155                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
3156                                                                    1).newstate;
3157                             trie->trans[ tp ].check = state;
3158                             tp++;
3159                             zp = tp;
3160                         }
3161                     } else {
3162                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
3163                             const U32 tid = base
3164                                            - trie->uniquecharcount
3165                                            + TRIE_LIST_ITEM( state, idx ).forid;
3166                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
3167                                                                 idx ).newstate;
3168                             trie->trans[ tid ].check = state;
3169                         }
3170                         tp += ( maxid - minid + 1 );
3171                     }
3172                     Safefree(trie->states[ state ].trans.list);
3173                 }
3174                 /*
3175                 DEBUG_TRIE_COMPILE_MORE_r(
3176                     Perl_re_printf( aTHX_  " base: %d\n",base);
3177                 );
3178                 */
3179                 trie->states[ state ].trans.base=base;
3180             }
3181             trie->lasttrans = tp + 1;
3182         }
3183     } else {
3184         /*
3185            Second Pass -- Flat Table Representation.
3186
3187            we dont use the 0 slot of either trans[] or states[] so we add 1 to
3188            each.  We know that we will need Charcount+1 trans at most to store
3189            the data (one row per char at worst case) So we preallocate both
3190            structures assuming worst case.
3191
3192            We then construct the trie using only the .next slots of the entry
3193            structs.
3194
3195            We use the .check field of the first entry of the node temporarily
3196            to make compression both faster and easier by keeping track of how
3197            many non zero fields are in the node.
3198
3199            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
3200            transition.
3201
3202            There are two terms at use here: state as a TRIE_NODEIDX() which is
3203            a number representing the first entry of the node, and state as a
3204            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
3205            and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
3206            if there are 2 entrys per node. eg:
3207
3208              A B       A B
3209           1. 2 4    1. 3 7
3210           2. 0 3    3. 0 5
3211           3. 0 0    5. 0 0
3212           4. 0 0    7. 0 0
3213
3214            The table is internally in the right hand, idx form. However as we
3215            also have to deal with the states array which is indexed by nodenum
3216            we have to use TRIE_NODENUM() to convert.
3217
3218         */
3219         DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_  "Compiling trie using table compiler\n",
3220             depth+1));
3221
3222         trie->trans = (reg_trie_trans *)
3223             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
3224                                   * trie->uniquecharcount + 1,
3225                                   sizeof(reg_trie_trans) );
3226         trie->states = (reg_trie_state *)
3227             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
3228                                   sizeof(reg_trie_state) );
3229         next_alloc = trie->uniquecharcount + 1;
3230
3231
3232         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
3233
3234             regnode *noper   = NEXTOPER( cur );
3235
3236             U32 state        = 1;         /* required init */
3237
3238             U16 charid       = 0;         /* sanity init */
3239             U32 accept_state = 0;         /* sanity init */
3240
3241             U32 wordlen      = 0;         /* required init */
3242
3243             if (OP(noper) == NOTHING) {
3244                 regnode *noper_next= regnext(noper);
3245                 if (noper_next < tail)
3246                     noper= noper_next;
3247             }
3248
3249             if (    noper < tail
3250                 && (    OP(noper) == flags
3251                     || (flags == EXACT && OP(noper) == EXACT_REQ8)
3252                     || (flags == EXACTFU && (   OP(noper) == EXACTFU_REQ8
3253                                              || OP(noper) == EXACTFUP))))
3254             {
3255                 const U8 *uc= (U8*)STRING(noper);
3256                 const U8 *e= uc + STR_LEN(noper);
3257
3258                 for ( ; uc < e ; uc += len ) {
3259
3260                     TRIE_READ_CHAR;
3261
3262                     if ( uvc < 256 ) {
3263                         charid = trie->charmap[ uvc ];
3264                     } else {
3265                         SV* const * const svpp = hv_fetch( widecharmap,
3266                                                            (char*)&uvc,
3267                                                            sizeof( UV ),
3268                                                            0);
3269                         charid = svpp ? (U16)SvIV(*svpp) : 0;
3270                     }
3271                     if ( charid ) {
3272                         charid--;
3273                         if ( !trie->trans[ state + charid ].next ) {
3274                             trie->trans[ state + charid ].next = next_alloc;
3275                             trie->trans[ state ].check++;
3276                             prev_states[TRIE_NODENUM(next_alloc)]
3277                                     = TRIE_NODENUM(state);
3278                             next_alloc += trie->uniquecharcount;
3279                         }
3280                         state = trie->trans[ state + charid ].next;
3281                     } else {
3282                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc );
3283                     }
3284                     /* charid is now 0 if we dont know the char read, or
3285                      * nonzero if we do */
3286                 }
3287             }
3288             accept_state = TRIE_NODENUM( state );
3289             TRIE_HANDLE_WORD(accept_state);
3290
3291         } /* end second pass */
3292
3293         /* and now dump it out before we compress it */
3294         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3295                                                           revcharmap,
3296                                                           next_alloc, depth+1));
3297
3298         {
3299         /*
3300            * Inplace compress the table.*
3301
3302            For sparse data sets the table constructed by the trie algorithm will
3303            be mostly 0/FAIL transitions or to put it another way mostly empty.
3304            (Note that leaf nodes will not contain any transitions.)
3305
3306            This algorithm compresses the tables by eliminating most such
3307            transitions, at the cost of a modest bit of extra work during lookup:
3308
3309            - Each states[] entry contains a .base field which indicates the
3310            index in the state[] array wheres its transition data is stored.
3311
3312            - If .base is 0 there are no valid transitions from that node.
3313
3314            - If .base is nonzero then charid is added to it to find an entry in
3315            the trans array.
3316
3317            -If trans[states[state].base+charid].check!=state then the
3318            transition is taken to be a 0/Fail transition. Thus if there are fail
3319            transitions at the front of the node then the .base offset will point
3320            somewhere inside the previous nodes data (or maybe even into a node
3321            even earlier), but the .check field determines if the transition is
3322            valid.
3323
3324            XXX - wrong maybe?
3325            The following process inplace converts the table to the compressed
3326            table: We first do not compress the root node 1,and mark all its
3327            .check pointers as 1 and set its .base pointer as 1 as well. This
3328            allows us to do a DFA construction from the compressed table later,
3329            and ensures that any .base pointers we calculate later are greater
3330            than 0.
3331
3332            - We set 'pos' to indicate the first entry of the second node.
3333
3334            - We then iterate over the columns of the node, finding the first and
3335            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3336            and set the .check pointers accordingly, and advance pos
3337            appropriately and repreat for the next node. Note that when we copy
3338            the next pointers we have to convert them from the original
3339            NODEIDX form to NODENUM form as the former is not valid post
3340            compression.
3341
3342            - If a node has no transitions used we mark its base as 0 and do not
3343            advance the pos pointer.
3344
3345            - If a node only has one transition we use a second pointer into the
3346            structure to fill in allocated fail transitions from other states.
3347            This pointer is independent of the main pointer and scans forward
3348            looking for null transitions that are allocated to a state. When it
3349            finds one it writes the single transition into the "hole".  If the
3350            pointer doesnt find one the single transition is appended as normal.
3351
3352            - Once compressed we can Renew/realloc the structures to release the
3353            excess space.
3354
3355            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3356            specifically Fig 3.47 and the associated pseudocode.
3357
3358            demq
3359         */
3360         const U32 laststate = TRIE_NODENUM( next_alloc );
3361         U32 state, charid;
3362         U32 pos = 0, zp=0;
3363         trie->statecount = laststate;
3364
3365         for ( state = 1 ; state < laststate ; state++ ) {
3366             U8 flag = 0;
3367             const U32 stateidx = TRIE_NODEIDX( state );
3368             const U32 o_used = trie->trans[ stateidx ].check;
3369             U32 used = trie->trans[ stateidx ].check;
3370             trie->trans[ stateidx ].check = 0;
3371
3372             for ( charid = 0;
3373                   used && charid < trie->uniquecharcount;
3374                   charid++ )
3375             {
3376                 if ( flag || trie->trans[ stateidx + charid ].next ) {
3377                     if ( trie->trans[ stateidx + charid ].next ) {
3378                         if (o_used == 1) {
3379                             for ( ; zp < pos ; zp++ ) {
3380                                 if ( ! trie->trans[ zp ].next ) {
3381                                     break;
3382                                 }
3383                             }
3384                             trie->states[ state ].trans.base
3385                                                     = zp
3386                                                       + trie->uniquecharcount
3387                                                       - charid ;
3388                             trie->trans[ zp ].next
3389                                 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3390                                                              + charid ].next );
3391                             trie->trans[ zp ].check = state;
3392                             if ( ++zp > pos ) pos = zp;
3393                             break;
3394                         }
3395                         used--;
3396                     }
3397                     if ( !flag ) {
3398                         flag = 1;
3399                         trie->states[ state ].trans.base
3400                                        = pos + trie->uniquecharcount - charid ;
3401                     }
3402                     trie->trans[ pos ].next
3403                         = SAFE_TRIE_NODENUM(
3404                                        trie->trans[ stateidx + charid ].next );
3405                     trie->trans[ pos ].check = state;
3406                     pos++;
3407                 }
3408             }
3409         }
3410         trie->lasttrans = pos + 1;
3411         trie->states = (reg_trie_state *)
3412             PerlMemShared_realloc( trie->states, laststate
3413                                    * sizeof(reg_trie_state) );
3414         DEBUG_TRIE_COMPILE_MORE_r(
3415             Perl_re_indentf( aTHX_  "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n",
3416                 depth+1,
3417                 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3418                        + 1 ),
3419                 (IV)next_alloc,
3420                 (IV)pos,
3421                 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3422             );
3423
3424         } /* end table compress */
3425     }
3426     DEBUG_TRIE_COMPILE_MORE_r(
3427             Perl_re_indentf( aTHX_  "Statecount:%" UVxf " Lasttrans:%" UVxf "\n",
3428                 depth+1,
3429                 (UV)trie->statecount,
3430                 (UV)trie->lasttrans)
3431     );
3432     /* resize the trans array to remove unused space */
3433     trie->trans = (reg_trie_trans *)
3434         PerlMemShared_realloc( trie->trans, trie->lasttrans
3435                                * sizeof(reg_trie_trans) );
3436
3437     {   /* Modify the program and insert the new TRIE node */
3438         U8 nodetype =(U8)(flags & 0xFF);
3439         char *str=NULL;
3440
3441 #ifdef DEBUGGING
3442         regnode *optimize = NULL;
3443 #ifdef RE_TRACK_PATTERN_OFFSETS
3444
3445         U32 mjd_offset = 0;
3446         U32 mjd_nodelen = 0;
3447 #endif /* RE_TRACK_PATTERN_OFFSETS */
3448 #endif /* DEBUGGING */
3449         /*
3450            This means we convert either the first branch or the first Exact,
3451            depending on whether the thing following (in 'last') is a branch
3452            or not and whther first is the startbranch (ie is it a sub part of
3453            the alternation or is it the whole thing.)
3454            Assuming its a sub part we convert the EXACT otherwise we convert
3455            the whole branch sequence, including the first.
3456          */
3457         /* Find the node we are going to overwrite */
3458         if ( first != startbranch || OP( last ) == BRANCH ) {
3459             /* branch sub-chain */
3460             NEXT_OFF( first ) = (U16)(last - first);
3461 #ifdef RE_TRACK_PATTERN_OFFSETS
3462             DEBUG_r({
3463                 mjd_offset= Node_Offset((convert));
3464                 mjd_nodelen= Node_Length((convert));
3465             });
3466 #endif
3467             /* whole branch chain */
3468         }
3469 #ifdef RE_TRACK_PATTERN_OFFSETS
3470         else {
3471             DEBUG_r({
3472                 const  regnode *nop = NEXTOPER( convert );
3473                 mjd_offset= Node_Offset((nop));
3474                 mjd_nodelen= Node_Length((nop));
3475             });
3476         }
3477         DEBUG_OPTIMISE_r(
3478             Perl_re_indentf( aTHX_  "MJD offset:%" UVuf " MJD length:%" UVuf "\n",
3479                 depth+1,
3480                 (UV)mjd_offset, (UV)mjd_nodelen)
3481         );
3482 #endif
3483         /* But first we check to see if there is a common prefix we can
3484            split out as an EXACT and put in front of the TRIE node.  */
3485         trie->startstate= 1;
3486         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
3487             /* we want to find the first state that has more than
3488              * one transition, if that state is not the first state
3489              * then we have a common prefix which we can remove.
3490              */
3491             U32 state;
3492             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3493                 U32 ofs = 0;
3494                 I32 first_ofs = -1; /* keeps track of the ofs of the first
3495                                        transition, -1 means none */
3496                 U32 count = 0;
3497                 const U32 base = trie->states[ state ].trans.base;
3498
3499                 /* does this state terminate an alternation? */
3500                 if ( trie->states[state].wordnum )
3501                         count = 1;
3502
3503                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3504                     if ( ( base + ofs >= trie->uniquecharcount ) &&
3505                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3506                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3507                     {
3508                         if ( ++count > 1 ) {
3509                             /* we have more than one transition */
3510                             SV **tmp;
3511                             U8 *ch;
3512                             /* if this is the first state there is no common prefix
3513                              * to extract, so we can exit */
3514                             if ( state == 1 ) break;
3515                             tmp = av_fetch( revcharmap, ofs, 0);
3516                             ch = (U8*)SvPV_nolen_const( *tmp );
3517
3518                             /* if we are on count 2 then we need to initialize the
3519                              * bitmap, and store the previous char if there was one
3520                              * in it*/
3521                             if ( count == 2 ) {
3522                                 /* clear the bitmap */
3523                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3524                                 DEBUG_OPTIMISE_r(
3525                                     Perl_re_indentf( aTHX_  "New Start State=%" UVuf " Class: [",
3526                                         depth+1,
3527                                         (UV)state));
3528                                 if (first_ofs >= 0) {
3529                                     SV ** const tmp = av_fetch( revcharmap, first_ofs, 0);
3530                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3531
3532                                     TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3533                                     DEBUG_OPTIMISE_r(
3534                                         Perl_re_printf( aTHX_  "%s", (char*)ch)
3535                                     );
3536                                 }
3537                             }
3538                             /* store the current firstchar in the bitmap */
3539                             TRIE_BITMAP_SET_FOLDED(trie,*ch, folder);
3540                             DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch));
3541                         }
3542                         first_ofs = ofs;
3543                     }
3544                 }
3545                 if ( count == 1 ) {
3546                     /* This state has only one transition, its transition is part
3547                      * of a common prefix - we need to concatenate the char it
3548                      * represents to what we have so far. */
3549                     SV **tmp = av_fetch( revcharmap, first_ofs, 0);
3550                     STRLEN len;
3551                     char *ch = SvPV( *tmp, len );
3552                     DEBUG_OPTIMISE_r({
3553                         SV *sv=sv_newmortal();
3554                         Perl_re_indentf( aTHX_  "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n",
3555                             depth+1,
3556                             (UV)state, (UV)first_ofs,
3557                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3558                                 PL_colors[0], PL_colors[1],
3559                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3560                                 PERL_PV_ESCAPE_FIRSTCHAR
3561                             )
3562                         );
3563                     });
3564                     if ( state==1 ) {
3565                         OP( convert ) = nodetype;
3566                         str=STRING(convert);
3567                         setSTR_LEN(convert, 0);
3568                     }
3569                     setSTR_LEN(convert, STR_LEN(convert) + len);
3570                     while (len--)
3571                         *str++ = *ch++;
3572                 } else {
3573 #ifdef DEBUGGING
3574                     if (state>1)
3575                         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n"));
3576 #endif
3577                     break;
3578                 }
3579             }
3580             trie->prefixlen = (state-1);
3581             if (str) {
3582                 regnode *n = convert+NODE_SZ_STR(convert);
3583                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3584                 trie->startstate = state;
3585                 trie->minlen -= (state - 1);
3586                 trie->maxlen -= (state - 1);
3587 #ifdef DEBUGGING
3588                /* At least the UNICOS C compiler choked on this
3589                 * being argument to DEBUG_r(), so let's just have
3590                 * it right here. */
3591                if (
3592 #ifdef PERL_EXT_RE_BUILD
3593                    1
3594 #else
3595                    DEBUG_r_TEST
3596 #endif
3597                    ) {
3598                    regnode *fix = convert;
3599                    U32 word = trie->wordcount;
3600 #ifdef RE_TRACK_PATTERN_OFFSETS
3601                    mjd_nodelen++;
3602 #endif
3603                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3604                    while( ++fix < n ) {
3605                        Set_Node_Offset_Length(fix, 0, 0);
3606                    }
3607                    while (word--) {
3608                        SV ** const tmp = av_fetch( trie_words, word, 0 );
3609                        if (tmp) {
3610                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
3611                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3612                            else
3613                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3614                        }
3615                    }
3616                }
3617 #endif
3618                 if (trie->maxlen) {
3619                     convert = n;
3620                 } else {
3621                     NEXT_OFF(convert) = (U16)(tail - convert);
3622                     DEBUG_r(optimize= n);
3623                 }
3624             }
3625         }
3626         if (!jumper)
3627             jumper = last;
3628         if ( trie->maxlen ) {
3629             NEXT_OFF( convert ) = (U16)(tail - convert);
3630             ARG_SET( convert, data_slot );
3631             /* Store the offset to the first unabsorbed branch in
3632                jump[0], which is otherwise unused by the jump logic.
3633                We use this when dumping a trie and during optimisation. */
3634             if (trie->jump)
3635                 trie->jump[0] = (U16)(nextbranch - convert);
3636
3637             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3638              *   and there is a bitmap
3639              *   and the first "jump target" node we found leaves enough room
3640              * then convert the TRIE node into a TRIEC node, with the bitmap
3641              * embedded inline in the opcode - this is hypothetically faster.
3642              */
3643             if ( !trie->states[trie->startstate].wordnum
3644                  && trie->bitmap
3645                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3646             {
3647                 OP( convert ) = TRIEC;
3648                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3649                 PerlMemShared_free(trie->bitmap);
3650                 trie->bitmap= NULL;
3651             } else
3652                 OP( convert ) = TRIE;
3653
3654             /* store the type in the flags */
3655             convert->flags = nodetype;
3656             DEBUG_r({
3657             optimize = convert
3658                       + NODE_STEP_REGNODE
3659                       + regarglen[ OP( convert ) ];
3660             });
3661             /* XXX We really should free up the resource in trie now,
3662                    as we won't use them - (which resources?) dmq */
3663         }
3664         /* needed for dumping*/
3665         DEBUG_r(if (optimize) {
3666             regnode *opt = convert;
3667
3668             while ( ++opt < optimize) {
3669                 Set_Node_Offset_Length(opt, 0, 0);
3670             }
3671             /*
3672                 Try to clean up some of the debris left after the
3673                 optimisation.
3674              */
3675             while( optimize < jumper ) {
3676                 Track_Code( mjd_nodelen += Node_Length((optimize)); );
3677                 OP( optimize ) = OPTIMIZED;
3678                 Set_Node_Offset_Length(optimize, 0, 0);
3679                 optimize++;
3680             }
3681             Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen);
3682         });
3683     } /* end node insert */
3684
3685     /*  Finish populating the prev field of the wordinfo array.  Walk back
3686      *  from each accept state until we find another accept state, and if
3687      *  so, point the first word's .prev field at the second word. If the
3688      *  second already has a .prev field set, stop now. This will be the
3689      *  case either if we've already processed that word's accept state,
3690      *  or that state had multiple words, and the overspill words were
3691      *  already linked up earlier.
3692      */
3693     {
3694         U16 word;
3695         U32 state;
3696         U16 prev;
3697
3698         for (word=1; word <= trie->wordcount; word++) {
3699             prev = 0;
3700             if (trie->wordinfo[word].prev)
3701                 continue;
3702             state = trie->wordinfo[word].accept;
3703             while (state) {
3704                 state = prev_states[state];
3705                 if (!state)
3706                     break;
3707                 prev = trie->states[state].wordnum;
3708                 if (prev)
3709                     break;
3710             }
3711             trie->wordinfo[word].prev = prev;
3712         }
3713         Safefree(prev_states);
3714     }
3715
3716
3717     /* and now dump out the compressed format */
3718     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3719
3720     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3721 #ifdef DEBUGGING
3722     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3723     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3724 #else
3725     SvREFCNT_dec_NN(revcharmap);
3726 #endif
3727     return trie->jump
3728            ? MADE_JUMP_TRIE
3729            : trie->startstate>1
3730              ? MADE_EXACT_TRIE
3731              : MADE_TRIE;
3732 }
3733
3734 STATIC regnode *
3735 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3736 {
3737 /* The Trie is constructed and compressed now so we can build a fail array if
3738  * it's needed
3739
3740    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3741    3.32 in the
3742    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3743    Ullman 1985/88
3744    ISBN 0-201-10088-6
3745
3746    We find the fail state for each state in the trie, this state is the longest
3747    proper suffix of the current state's 'word' that is also a proper prefix of
3748    another word in our trie. State 1 represents the word '' and is thus the
3749    default fail state. This allows the DFA not to have to restart after its
3750    tried and failed a word at a given point, it simply continues as though it
3751    had been matching the other word in the first place.
3752    Consider
3753       'abcdgu'=~/abcdefg|cdgu/
3754    When we get to 'd' we are still matching the first word, we would encounter
3755    'g' which would fail, which would bring us to the state representing 'd' in
3756    the second word where we would try 'g' and succeed, proceeding to match
3757    'cdgu'.
3758  */
3759  /* add a fail transition */
3760     const U32 trie_offset = ARG(source);
3761     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3762     U32 *q;
3763     const U32 ucharcount = trie->uniquecharcount;
3764     const U32 numstates = trie->statecount;
3765     const U32 ubound = trie->lasttrans + ucharcount;
3766     U32 q_read = 0;
3767     U32 q_write = 0;
3768     U32 charid;
3769     U32 base = trie->states[ 1 ].trans.base;
3770     U32 *fail;
3771     reg_ac_data *aho;
3772     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3773     regnode *stclass;
3774     GET_RE_DEBUG_FLAGS_DECL;
3775
3776     PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3777     PERL_UNUSED_CONTEXT;
3778 #ifndef DEBUGGING
3779     PERL_UNUSED_ARG(depth);
3780 #endif
3781
3782     if ( OP(source) == TRIE ) {
3783         struct regnode_1 *op = (struct regnode_1 *)
3784             PerlMemShared_calloc(1, sizeof(struct regnode_1));
3785         StructCopy(source, op, struct regnode_1);
3786         stclass = (regnode *)op;
3787     } else {
3788         struct regnode_charclass *op = (struct regnode_charclass *)
3789             PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3790         StructCopy(source, op, struct regnode_charclass);
3791         stclass = (regnode *)op;
3792     }
3793     OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3794
3795     ARG_SET( stclass, data_slot );
3796     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3797     RExC_rxi->data->data[ data_slot ] = (void*)aho;
3798     aho->trie=trie_offset;
3799     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3800     Copy( trie->states, aho->states, numstates, reg_trie_state );
3801     Newx( q, numstates, U32);
3802     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3803     aho->refcount = 1;
3804     fail = aho->fail;
3805     /* initialize fail[0..1] to be 1 so that we always have
3806        a valid final fail state */
3807     fail[ 0 ] = fail[ 1 ] = 1;
3808
3809     for ( charid = 0; charid < ucharcount ; charid++ ) {
3810         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3811         if ( newstate ) {
3812             q[ q_write ] = newstate;
3813             /* set to point at the root */
3814             fail[ q[ q_write++ ] ]=1;
3815         }
3816     }
3817     while ( q_read < q_write) {
3818         const U32 cur = q[ q_read++ % numstates ];
3819         base = trie->states[ cur ].trans.base;
3820
3821         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3822             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3823             if (ch_state) {
3824                 U32 fail_state = cur;
3825                 U32 fail_base;
3826                 do {
3827                     fail_state = fail[ fail_state ];
3828                     fail_base = aho->states[ fail_state ].trans.base;
3829                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3830
3831                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3832                 fail[ ch_state ] = fail_state;
3833                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3834                 {
3835                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
3836                 }
3837                 q[ q_write++ % numstates] = ch_state;
3838             }
3839         }
3840     }
3841     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3842        when we fail in state 1, this allows us to use the
3843        charclass scan to find a valid start char. This is based on the principle
3844        that theres a good chance the string being searched contains lots of stuff
3845        that cant be a start char.
3846      */
3847     fail[ 0 ] = fail[ 1 ] = 0;
3848     DEBUG_TRIE_COMPILE_r({
3849         Perl_re_indentf( aTHX_  "Stclass Failtable (%" UVuf " states): 0",
3850                       depth, (UV)numstates
3851         );
3852         for( q_read=1; q_read<numstates; q_read++ ) {
3853             Perl_re_printf( aTHX_  ", %" UVuf, (UV)fail[q_read]);
3854         }
3855         Perl_re_printf( aTHX_  "\n");
3856     });
3857     Safefree(q);
3858     /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3859     return stclass;
3860 }
3861
3862
3863 /* The below joins as many adjacent EXACTish nodes as possible into a single
3864  * one.  The regop may be changed if the node(s) contain certain sequences that
3865  * require special handling.  The joining is only done if:
3866  * 1) there is room in the current conglomerated node to entirely contain the
3867  *    next one.
3868  * 2) they are compatible node types
3869  *
3870  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3871  * these get optimized out
3872  *
3873  * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3874  * as possible, even if that means splitting an existing node so that its first
3875  * part is moved to the preceeding node.  This would maximise the efficiency of
3876  * memEQ during matching.
3877  *
3878  * If a node is to match under /i (folded), the number of characters it matches
3879  * can be different than its character length if it contains a multi-character
3880  * fold.  *min_subtract is set to the total delta number of characters of the
3881  * input nodes.
3882  *
3883  * And *unfolded_multi_char is set to indicate whether or not the node contains
3884  * an unfolded multi-char fold.  This happens when it won't be known until
3885  * runtime whether the fold is valid or not; namely
3886  *  1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the
3887  *      target string being matched against turns out to be UTF-8 is that fold
3888  *      valid; or
3889  *  2) for EXACTFL nodes whose folding rules depend on the locale in force at
3890  *      runtime.
3891  * (Multi-char folds whose components are all above the Latin1 range are not
3892  * run-time locale dependent, and have already been folded by the time this
3893  * function is called.)
3894  *
3895  * This is as good a place as any to discuss the design of handling these
3896  * multi-character fold sequences.  It's been wrong in Perl for a very long
3897  * time.  There are three code points in Unicode whose multi-character folds
3898  * were long ago discovered to mess things up.  The previous designs for
3899  * dealing with these involved assigning a special node for them.  This
3900  * approach doesn't always work, as evidenced by this example:
3901  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
3902  * Both sides fold to "sss", but if the pattern is parsed to create a node that
3903  * would match just the \xDF, it won't be able to handle the case where a
3904  * successful match would have to cross the node's boundary.  The new approach
3905  * that hopefully generally solves the problem generates an EXACTFUP node
3906  * that is "sss" in this case.
3907  *
3908  * It turns out that there are problems with all multi-character folds, and not
3909  * just these three.  Now the code is general, for all such cases.  The
3910  * approach taken is:
3911  * 1)   This routine examines each EXACTFish node that could contain multi-
3912  *      character folded sequences.  Since a single character can fold into
3913  *      such a sequence, the minimum match length for this node is less than
3914  *      the number of characters in the node.  This routine returns in
3915  *      *min_subtract how many characters to subtract from the the actual
3916  *      length of the string to get a real minimum match length; it is 0 if
3917  *      there are no multi-char foldeds.  This delta is used by the caller to
3918  *      adjust the min length of the match, and the delta between min and max,
3919  *      so that the optimizer doesn't reject these possibilities based on size
3920  *      constraints.
3921  *
3922  * 2)   For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF)
3923  *      under /u, we fold it to 'ss' in regatom(), and in this routine, after
3924  *      joining, we scan for occurrences of the sequence 'ss' in non-UTF-8
3925  *      EXACTFU nodes.  The node type of such nodes is then changed to
3926  *      EXACTFUP, indicating it is problematic, and needs careful handling.
3927  *      (The procedures in step 1) above are sufficient to handle this case in
3928  *      UTF-8 encoded nodes.)  The reason this is problematic is that this is
3929  *      the only case where there is a possible fold length change in non-UTF-8
3930  *      patterns.  By reserving a special node type for problematic cases, the
3931  *      far more common regular EXACTFU nodes can be processed faster.
3932  *      regexec.c takes advantage of this.
3933  *
3934  *      EXACTFUP has been created as a grab-bag for (hopefully uncommon)
3935  *      problematic cases.   These all only occur when the pattern is not
3936  *      UTF-8.  In addition to the 'ss' sequence where there is a possible fold
3937  *      length change, it handles the situation where the string cannot be
3938  *      entirely folded.  The strings in an EXACTFish node are folded as much
3939  *      as possible during compilation in regcomp.c.  This saves effort in
3940  *      regex matching.  By using an EXACTFUP node when it is not possible to
3941  *      fully fold at compile time, regexec.c can know that everything in an
3942  *      EXACTFU node is folded, so folding can be skipped at runtime.  The only
3943  *      case where folding in EXACTFU nodes can't be done at compile time is
3944  *      the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8.  This
3945  *      is because its fold requires UTF-8 to represent.  Thus EXACTFUP nodes
3946  *      handle two very different cases.  Alternatively, there could have been
3947  *      a node type where there are length changes, one for unfolded, and one
3948  *      for both.  If yet another special case needed to be created, the number
3949  *      of required node types would have to go to 7.  khw figures that even
3950  *      though there are plenty of node types to spare, that the maintenance
3951  *      cost wasn't worth the small speedup of doing it that way, especially
3952  *      since he thinks the MICRO SIGN is rarely encountered in practice.
3953  *
3954  *      There are other cases where folding isn't done at compile time, but
3955  *      none of them are under /u, and hence not for EXACTFU nodes.  The folds
3956  *      in EXACTFL nodes aren't known until runtime, and vary as the locale
3957  *      changes.  Some folds in EXACTF depend on if the runtime target string
3958  *      is UTF-8 or not.  (regatom() will create an EXACTFU node even under /di
3959  *      when no fold in it depends on the UTF-8ness of the target string.)
3960  *
3961  * 3)   A problem remains for unfolded multi-char folds. (These occur when the
3962  *      validity of the fold won't be known until runtime, and so must remain
3963  *      unfolded for now.  This happens for the sharp s in EXACTF and EXACTFAA
3964  *      nodes when the pattern isn't in UTF-8.  (Note, BTW, that there cannot
3965  *      be an EXACTF node with a UTF-8 pattern.)  They also occur for various
3966  *      folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3967  *      The reason this is a problem is that the optimizer part of regexec.c
3968  *      (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3969  *      that a character in the pattern corresponds to at most a single
3970  *      character in the target string.  (And I do mean character, and not byte
3971  *      here, unlike other parts of the documentation that have never been
3972  *      updated to account for multibyte Unicode.)  Sharp s in EXACTF and
3973  *      EXACTFL nodes can match the two character string 'ss'; in EXACTFAA
3974  *      nodes it can match "\x{17F}\x{17F}".  These, along with other ones in
3975  *      EXACTFL nodes, violate the assumption, and they are the only instances
3976  *      where it is violated.  I'm reluctant to try to change the assumption,
3977  *      as the code involved is impenetrable to me (khw), so instead the code
3978  *      here punts.  This routine examines EXACTFL nodes, and (when the pattern
3979  *      isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a
3980  *      boolean indicating whether or not the node contains such a fold.  When
3981  *      it is true, the caller sets a flag that later causes the optimizer in
3982  *      this file to not set values for the floating and fixed string lengths,
3983  *      and thus avoids the optimizer code in regexec.c that makes the invalid
3984  *      assumption.  Thus, there is no optimization based on string lengths for
3985  *      EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3986  *      EXACTF and EXACTFAA nodes that contain the sharp s.  (The reason the
3987  *      assumption is wrong only in these cases is that all other non-UTF-8
3988  *      folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3989  *      their expanded versions.  (Again, we can't prefold sharp s to 'ss' in
3990  *      EXACTF nodes because we don't know at compile time if it actually
3991  *      matches 'ss' or not.  For EXACTF nodes it will match iff the target
3992  *      string is in UTF-8.  This is in contrast to EXACTFU nodes, where it
3993  *      always matches; and EXACTFAA where it never does.  In an EXACTFAA node
3994  *      in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3995  *      problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3996  *      string would require the pattern to be forced into UTF-8, the overhead
3997  *      of which we want to avoid.  Similarly the unfolded multi-char folds in
3998  *      EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3999  *      locale.)
4000  *
4001  *      Similarly, the code that generates tries doesn't currently handle
4002  *      not-already-folded multi-char folds, and it looks like a pain to change
4003  *      that.  Therefore, trie generation of EXACTFAA nodes with the sharp s
4004  *      doesn't work.  Instead, such an EXACTFAA is turned into a new regnode,
4005  *      EXACTFAA_NO_TRIE, which the trie code knows not to handle.  Most people
4006  *      using /iaa matching will be doing so almost entirely with ASCII
4007  *      strings, so this should rarely be encountered in practice */
4008
4009 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags)    \
4010     if (PL_regkind[OP(scan)] == EXACT && OP(scan) != LEXACT         \
4011                                       && OP(scan) != LEXACT_REQ8)  \
4012         join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1)
4013
4014 STATIC U32
4015 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
4016                    UV *min_subtract, bool *unfolded_multi_char,
4017                    U32 flags, regnode *val, U32 depth)
4018 {
4019     /* Merge several consecutive EXACTish nodes into one. */
4020
4021     regnode *n = regnext(scan);
4022     U32 stringok = 1;
4023     regnode *next = scan + NODE_SZ_STR(scan);
4024     U32 merged = 0;
4025     U32 stopnow = 0;
4026 #ifdef DEBUGGING
4027     regnode *stop = scan;
4028     GET_RE_DEBUG_FLAGS_DECL;
4029 #else
4030     PERL_UNUSED_ARG(depth);
4031 #endif
4032
4033     PERL_ARGS_ASSERT_JOIN_EXACT;
4034 #ifndef EXPERIMENTAL_INPLACESCAN
4035     PERL_UNUSED_ARG(flags);
4036     PERL_UNUSED_ARG(val);
4037 #endif
4038     DEBUG_PEEP("join", scan, depth, 0);
4039
4040     assert(PL_regkind[OP(scan)] == EXACT);
4041
4042     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
4043      * EXACT ones that are mergeable to the current one. */
4044     while (    n
4045            && (    PL_regkind[OP(n)] == NOTHING
4046                || (stringok && PL_regkind[OP(n)] == EXACT))
4047            && NEXT_OFF(n)
4048            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
4049     {
4050
4051         if (OP(n) == TAIL || n > next)
4052             stringok = 0;
4053         if (PL_regkind[OP(n)] == NOTHING) {
4054             DEBUG_PEEP("skip:", n, depth, 0);
4055             NEXT_OFF(scan) += NEXT_OFF(n);
4056             next = n + NODE_STEP_REGNODE;
4057 #ifdef DEBUGGING
4058             if (stringok)
4059                 stop = n;
4060 #endif
4061             n = regnext(n);
4062         }
4063         else if (stringok) {
4064             const unsigned int oldl = STR_LEN(scan);
4065             regnode * const nnext = regnext(n);
4066
4067             /* XXX I (khw) kind of doubt that this works on platforms (should
4068              * Perl ever run on one) where U8_MAX is above 255 because of lots
4069              * of other assumptions */
4070             /* Don't join if the sum can't fit into a single node */
4071             if (oldl + STR_LEN(n) > U8_MAX)
4072                 break;
4073
4074             /* Joining something that requires UTF-8 with something that
4075              * doesn't, means the result requires UTF-8. */
4076             if (OP(scan) == EXACT && (OP(n) == EXACT_REQ8)) {
4077                 OP(scan) = EXACT_REQ8;
4078             }
4079             else if (OP(scan) == EXACT_REQ8 && (OP(n) == EXACT)) {
4080                 ;   /* join is compatible, no need to change OP */
4081             }
4082             else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_REQ8)) {
4083                 OP(scan) = EXACTFU_REQ8;
4084             }
4085             else if ((OP(scan) == EXACTFU_REQ8) && (OP(n) == EXACTFU)) {
4086                 ;   /* join is compatible, no need to change OP */
4087             }
4088             else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) {
4089                 ;   /* join is compatible, no need to change OP */
4090             }
4091             else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) {
4092
4093                  /* Under /di, temporary EXACTFU_S_EDGE nodes are generated,
4094                   * which can join with EXACTFU ones.  We check for this case
4095                   * here.  These need to be resolved to either EXACTFU or
4096                   * EXACTF at joining time.  They have nothing in them that
4097                   * would forbid them from being the more desirable EXACTFU
4098                   * nodes except that they begin and/or end with a single [Ss].
4099                   * The reason this is problematic is because they could be
4100                   * joined in this loop with an adjacent node that ends and/or
4101                   * begins with [Ss] which would then form the sequence 'ss',
4102                   * which matches differently under /di than /ui, in which case
4103                   * EXACTFU can't be used.  If the 'ss' sequence doesn't get
4104                   * formed, the nodes get absorbed into any adjacent EXACTFU
4105                   * node.  And if the only adjacent node is EXACTF, they get
4106                   * absorbed into that, under the theory that a longer node is
4107                   * better than two shorter ones, even if one is EXACTFU.  Note
4108                   * that EXACTFU_REQ8 is generated only for UTF-8 patterns,
4109                   * and the EXACTFU_S_EDGE ones only for non-UTF-8.  */
4110
4111                 if (STRING(n)[STR_LEN(n)-1] == 's') {
4112
4113                     /* Here the joined node would end with 's'.  If the node
4114                      * following the combination is an EXACTF one, it's better to
4115                      * join this trailing edge 's' node with that one, leaving the
4116                      * current one in 'scan' be the more desirable EXACTFU */
4117                     if (OP(nnext) == EXACTF) {
4118                         break;
4119                     }
4120
4121                     OP(scan) = EXACTFU_S_EDGE;
4122
4123                 }   /* Otherwise, the beginning 's' of the 2nd node just
4124                        becomes an interior 's' in 'scan' */
4125             }
4126             else if (OP(scan) == EXACTF && OP(n) == EXACTF) {
4127                 ;   /* join is compatible, no need to change OP */
4128             }
4129             else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) {
4130
4131                 /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE
4132                  * nodes.  But the latter nodes can be also joined with EXACTFU
4133                  * ones, and that is a better outcome, so if the node following
4134                  * 'n' is EXACTFU, quit now so that those two can be joined
4135                  * later */
4136                 if (OP(nnext) == EXACTFU) {
4137                     break;
4138                 }
4139
4140                 /* The join is compatible, and the combined node will be
4141                  * EXACTF.  (These don't care if they begin or end with 's' */
4142             }
4143             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) {
4144                 if (   STRING(scan)[STR_LEN(scan)-1] == 's'
4145                     && STRING(n)[0] == 's')
4146                 {
4147                     /* When combined, we have the sequence 'ss', which means we
4148                      * have to remain /di */
4149                     OP(scan) = EXACTF;
4150                 }
4151             }
4152             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) {
4153                 if (STRING(n)[0] == 's') {
4154                     ;   /* Here the join is compatible and the combined node
4155                            starts with 's', no need to change OP */
4156                 }
4157                 else {  /* Now the trailing 's' is in the interior */
4158                     OP(scan) = EXACTFU;
4159                 }
4160             }
4161             else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) {
4162
4163                 /* The join is compatible, and the combined node will be
4164                  * EXACTF.  (These don't care if they begin or end with 's' */
4165                 OP(scan) = EXACTF;
4166             }
4167             else if (OP(scan) != OP(n)) {
4168
4169                 /* The only other compatible joinings are the same node type */
4170                 break;
4171             }
4172
4173             DEBUG_PEEP("merg", n, depth, 0);
4174             merged++;
4175
4176             NEXT_OFF(scan) += NEXT_OFF(n);
4177             setSTR_LEN(scan, STR_LEN(scan) + STR_LEN(n));
4178             next = n + NODE_SZ_STR(n);
4179             /* Now we can overwrite *n : */
4180             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
4181 #ifdef DEBUGGING
4182             stop = next - 1;
4183 #endif
4184             n = nnext;
4185             if (stopnow) break;
4186         }
4187
4188 #ifdef EXPERIMENTAL_INPLACESCAN
4189         if (flags && !NEXT_OFF(n)) {
4190             DEBUG_PEEP("atch", val, depth, 0);
4191             if (reg_off_by_arg[OP(n)]) {
4192                 ARG_SET(n, val - n);
4193             }
4194             else {
4195                 NEXT_OFF(n) = val - n;
4196             }
4197             stopnow = 1;
4198         }
4199 #endif
4200     }
4201
4202     /* This temporary node can now be turned into EXACTFU, and must, as
4203      * regexec.c doesn't handle it */
4204     if (OP(scan) == EXACTFU_S_EDGE) {
4205         OP(scan) = EXACTFU;
4206     }
4207
4208     *min_subtract = 0;
4209     *unfolded_multi_char = FALSE;
4210
4211     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
4212      * can now analyze for sequences of problematic code points.  (Prior to
4213      * this final joining, sequences could have been split over boundaries, and
4214      * hence missed).  The sequences only happen in folding, hence for any
4215      * non-EXACT EXACTish node */
4216     if (OP(scan) != EXACT && OP(scan) != EXACT_REQ8 && OP(scan) != EXACTL) {
4217         U8* s0 = (U8*) STRING(scan);
4218         U8* s = s0;
4219         U8* s_end = s0 + STR_LEN(scan);
4220
4221         int total_count_delta = 0;  /* Total delta number of characters that
4222                                        multi-char folds expand to */
4223
4224         /* One pass is made over the node's string looking for all the
4225          * possibilities.  To avoid some tests in the loop, there are two main
4226          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
4227          * non-UTF-8 */
4228         if (UTF) {
4229             U8* folded = NULL;
4230
4231             if (OP(scan) == EXACTFL) {
4232                 U8 *d;
4233
4234                 /* An EXACTFL node would already have been changed to another
4235                  * node type unless there is at least one character in it that
4236                  * is problematic; likely a character whose fold definition
4237                  * won't be known until runtime, and so has yet to be folded.
4238                  * For all but the UTF-8 locale, folds are 1-1 in length, but
4239                  * to handle the UTF-8 case, we need to create a temporary
4240                  * folded copy using UTF-8 locale rules in order to analyze it.
4241                  * This is because our macros that look to see if a sequence is
4242                  * a multi-char fold assume everything is folded (otherwise the
4243                  * tests in those macros would be too complicated and slow).
4244                  * Note that here, the non-problematic folds will have already
4245                  * been done, so we can just copy such characters.  We actually
4246                  * don't completely fold the EXACTFL string.  We skip the
4247                  * unfolded multi-char folds, as that would just create work
4248                  * below to figure out the size they already are */
4249
4250                 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
4251                 d = folded;
4252                 while (s < s_end) {
4253                     STRLEN s_len = UTF8SKIP(s);
4254                     if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
4255                         Copy(s, d, s_len, U8);
4256                         d += s_len;
4257                     }
4258                     else if (is_FOLDS_TO_MULTI_utf8(s)) {
4259                         *unfolded_multi_char = TRUE;
4260                         Copy(s, d, s_len, U8);
4261                         d += s_len;
4262                     }
4263                     else if (isASCII(*s)) {
4264                         *(d++) = toFOLD(*s);
4265                     }
4266                     else {
4267                         STRLEN len;
4268                         _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL);
4269                         d += len;
4270                     }
4271                     s += s_len;
4272                 }
4273
4274                 /* Point the remainder of the routine to look at our temporary
4275                  * folded copy */
4276                 s = folded;
4277                 s_end = d;
4278             } /* End of creating folded copy of EXACTFL string */
4279
4280             /* Examine the string for a multi-character fold sequence.  UTF-8
4281              * patterns have all characters pre-folded by the time this code is
4282              * executed */
4283             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
4284                                      length sequence we are looking for is 2 */
4285             {
4286                 int count = 0;  /* How many characters in a multi-char fold */
4287                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
4288                 if (! len) {    /* Not a multi-char fold: get next char */
4289                     s += UTF8SKIP(s);
4290                     continue;
4291                 }
4292
4293                 { /* Here is a generic multi-char fold. */
4294                     U8* multi_end  = s + len;
4295
4296                     /* Count how many characters are in it.  In the case of
4297                      * /aa, no folds which contain ASCII code points are
4298                      * allowed, so check for those, and skip if found. */
4299                     if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) {
4300                         count = utf8_length(s, multi_end);
4301                         s = multi_end;
4302                     }
4303                     else {
4304                         while (s < multi_end) {
4305                             if (isASCII(*s)) {
4306                                 s++;
4307                                 goto next_iteration;
4308                             }
4309                             else {
4310                                 s += UTF8SKIP(s);
4311                             }
4312                             count++;
4313                         }
4314                     }
4315                 }
4316
4317                 /* The delta is how long the sequence is minus 1 (1 is how long
4318                  * the character that folds to the sequence is) */
4319                 total_count_delta += count - 1;
4320               next_iteration: ;
4321             }
4322
4323             /* We created a temporary folded copy of the string in EXACTFL
4324              * nodes.  Therefore we need to be sure it doesn't go below zero,
4325              * as the real string could be shorter */
4326             if (OP(scan) == EXACTFL) {
4327                 int total_chars = utf8_length((U8*) STRING(scan),
4328                                            (U8*) STRING(scan) + STR_LEN(scan));
4329                 if (total_count_delta > total_chars) {
4330                     total_count_delta = total_chars;
4331                 }
4332             }
4333
4334             *min_subtract += total_count_delta;
4335             Safefree(folded);
4336         }
4337         else if (OP(scan) == EXACTFAA) {
4338
4339             /* Non-UTF-8 pattern, EXACTFAA node.  There can't be a multi-char
4340              * fold to the ASCII range (and there are no existing ones in the
4341              * upper latin1 range).  But, as outlined in the comments preceding
4342              * this function, we need to flag any occurrences of the sharp s.
4343              * This character forbids trie formation (because of added
4344              * complexity) */
4345 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
4346    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
4347                                       || UNICODE_DOT_DOT_VERSION > 0)
4348             while (s < s_end) {
4349                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
4350                     OP(scan) = EXACTFAA_NO_TRIE;
4351                     *unfolded_multi_char = TRUE;
4352                     break;
4353                 }
4354                 s++;
4355             }
4356         }
4357         else {
4358
4359             /* Non-UTF-8 pattern, not EXACTFAA node.  Look for the multi-char
4360              * folds that are all Latin1.  As explained in the comments
4361              * preceding this function, we look also for the sharp s in EXACTF
4362              * and EXACTFL nodes; it can be in the final position.  Otherwise
4363              * we can stop looking 1 byte earlier because have to find at least
4364              * two characters for a multi-fold */
4365             const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
4366                               ? s_end
4367                               : s_end -1;
4368
4369             while (s < upper) {
4370                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
4371                 if (! len) {    /* Not a multi-char fold. */
4372                     if (*s == LATIN_SMALL_LETTER_SHARP_S
4373                         && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
4374                     {
4375                         *unfolded_multi_char = TRUE;
4376                     }
4377                     s++;
4378                     continue;
4379                 }
4380
4381                 if (len == 2
4382                     && isALPHA_FOLD_EQ(*s, 's')
4383                     && isALPHA_FOLD_EQ(*(s+1), 's'))
4384                 {
4385
4386                     /* EXACTF nodes need to know that the minimum length
4387                      * changed so that a sharp s in the string can match this
4388                      * ss in the pattern, but they remain EXACTF nodes, as they
4389                      * won't match this unless the target string is is UTF-8,
4390                      * which we don't know until runtime.  EXACTFL nodes can't
4391                      * transform into EXACTFU nodes */
4392                     if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
4393                         OP(scan) = EXACTFUP;
4394                     }
4395                 }
4396
4397                 *min_subtract += len - 1;
4398                 s += len;
4399             }
4400 #endif
4401         }
4402
4403         if (     STR_LEN(scan) == 1
4404             &&   isALPHA_A(* STRING(scan))
4405             &&  (         OP(scan) == EXACTFAA
4406                  || (     OP(scan) == EXACTFU
4407                      && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(scan)))))
4408         {
4409             U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */
4410
4411             /* Replace a length 1 ASCII fold pair node with an ANYOFM node,
4412              * with the mask set to the complement of the bit that differs
4413              * between upper and lower case, and the lowest code point of the
4414              * pair (which the '&' forces) */
4415             OP(scan) = ANYOFM;
4416             ARG_SET(scan, *STRING(scan) & mask);
4417             FLAGS(scan) = mask;
4418         }
4419     }
4420
4421 #ifdef DEBUGGING
4422     /* Allow dumping but overwriting the collection of skipped
4423      * ops and/or strings with fake optimized ops */
4424     n = scan + NODE_SZ_STR(scan);
4425     while (n <= stop) {
4426         OP(n) = OPTIMIZED;
4427         FLAGS(n) = 0;
4428         NEXT_OFF(n) = 0;
4429         n++;
4430     }
4431 #endif
4432     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);});
4433     return stopnow;
4434 }
4435
4436 /* REx optimizer.  Converts nodes into quicker variants "in place".
4437    Finds fixed substrings.  */
4438
4439 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4440    to the position after last scanned or to NULL. */
4441
4442 #define INIT_AND_WITHP \
4443     assert(!and_withp); \
4444     Newx(and_withp, 1, regnode_ssc); \
4445     SAVEFREEPV(and_withp)
4446
4447
4448 static void
4449 S_unwind_scan_frames(pTHX_ const void *p)
4450 {
4451     scan_frame *f= (scan_frame *)p;
4452     do {
4453         scan_frame *n= f->next_frame;
4454         Safefree(f);
4455         f= n;
4456     } while (f);
4457 }
4458
4459 /* the return from this sub is the minimum length that could possibly match */
4460 STATIC SSize_t
4461 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4462                         SSize_t *minlenp, SSize_t *deltap,
4463                         regnode *last,
4464                         scan_data_t *data,
4465                         I32 stopparen,
4466                         U32 recursed_depth,
4467                         regnode_ssc *and_withp,
4468                         U32 flags, U32 depth)
4469                         /* scanp: Start here (read-write). */
4470                         /* deltap: Write maxlen-minlen here. */
4471                         /* last: Stop before this one. */
4472                         /* data: string data about the pattern */
4473                         /* stopparen: treat close N as END */
4474                         /* recursed: which subroutines have we recursed into */
4475                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4476 {
4477     dVAR;
4478     /* There must be at least this number of characters to match */
4479     SSize_t min = 0;
4480     I32 pars = 0, code;
4481     regnode *scan = *scanp, *next;
4482     SSize_t delta = 0;
4483     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4484     int is_inf_internal = 0;            /* The studied chunk is infinite */
4485     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4486     scan_data_t data_fake;
4487     SV *re_trie_maxbuff = NULL;
4488     regnode *first_non_open = scan;
4489     SSize_t stopmin = SSize_t_MAX;
4490     scan_frame *frame = NULL;
4491     GET_RE_DEBUG_FLAGS_DECL;
4492
4493     PERL_ARGS_ASSERT_STUDY_CHUNK;
4494     RExC_study_started= 1;
4495
4496     Zero(&data_fake, 1, scan_data_t);
4497
4498     if ( depth == 0 ) {
4499         while (first_non_open && OP(first_non_open) == OPEN)
4500             first_non_open=regnext(first_non_open);
4501     }
4502
4503
4504   fake_study_recurse:
4505     DEBUG_r(
4506         RExC_study_chunk_recursed_count++;
4507     );
4508     DEBUG_OPTIMISE_MORE_r(
4509     {
4510         Perl_re_indentf( aTHX_  "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4511             depth, (long)stopparen,
4512             (unsigned long)RExC_study_chunk_recursed_count,
4513             (unsigned long)depth, (unsigned long)recursed_depth,
4514             scan,
4515             last);
4516         if (recursed_depth) {
4517             U32 i;
4518             U32 j;
4519             for ( j = 0 ; j < recursed_depth ; j++ ) {
4520                 for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) {
4521                     if (
4522                         PAREN_TEST(RExC_study_chunk_recursed +
4523                                    ( j * RExC_study_chunk_recursed_bytes), i )
4524                         && (
4525                             !j ||
4526                             !PAREN_TEST(RExC_study_chunk_recursed +
4527                                    (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
4528                         )
4529                     ) {
4530                         Perl_re_printf( aTHX_ " %d",(int)i);
4531                         break;
4532                     }
4533                 }
4534                 if ( j + 1 < recursed_depth ) {
4535                     Perl_re_printf( aTHX_  ",");
4536                 }
4537             }
4538         }
4539         Perl_re_printf( aTHX_ "\n");
4540     }
4541     );
4542     while ( scan && OP(scan) != END && scan < last ){
4543         UV min_subtract = 0;    /* How mmany chars to subtract from the minimum
4544                                    node length to get a real minimum (because
4545                                    the folded version may be shorter) */
4546         bool unfolded_multi_char = FALSE;
4547         /* Peephole optimizer: */
4548         DEBUG_STUDYDATA("Peep", data, depth, is_inf);
4549         DEBUG_PEEP("Peep", scan, depth, flags);
4550
4551
4552         /* The reason we do this here is that we need to deal with things like
4553          * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT
4554          * parsing code, as each (?:..) is handled by a different invocation of
4555          * reg() -- Yves
4556          */
4557         JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
4558
4559         /* Follow the next-chain of the current node and optimize
4560            away all the NOTHINGs from it.  */
4561         if (OP(scan) != CURLYX) {
4562             const int max = (reg_off_by_arg[OP(scan)]
4563                             ? I32_MAX
4564                               /* I32 may be smaller than U16 on CRAYs! */
4565                             : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4566             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4567             int noff;
4568             regnode *n = scan;
4569
4570             /* Skip NOTHING and LONGJMP. */
4571             while (   (n = regnext(n))
4572                    && (   (PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4573                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4574                    && off + noff < max)
4575                 off += noff;
4576             if (reg_off_by_arg[OP(scan)])
4577                 ARG(scan) = off;
4578             else
4579                 NEXT_OFF(scan) = off;
4580         }
4581
4582         /* The principal pseudo-switch.  Cannot be a switch, since we look into
4583          * several different things.  */
4584         if ( OP(scan) == DEFINEP ) {
4585             SSize_t minlen = 0;
4586             SSize_t deltanext = 0;
4587             SSize_t fake_last_close = 0;
4588             I32 f = SCF_IN_DEFINE;
4589
4590             StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4591             scan = regnext(scan);
4592             assert( OP(scan) == IFTHEN );
4593             DEBUG_PEEP("expect IFTHEN", scan, depth, flags);
4594
4595             data_fake.last_closep= &fake_last_close;
4596             minlen = *minlenp;
4597             next = regnext(scan);
4598             scan = NEXTOPER(NEXTOPER(scan));
4599             DEBUG_PEEP("scan", scan, depth, flags);
4600             DEBUG_PEEP("next", next, depth, flags);
4601
4602             /* we suppose the run is continuous, last=next...
4603              * NOTE we dont use the return here! */
4604             /* DEFINEP study_chunk() recursion */
4605             (void)study_chunk(pRExC_state, &scan, &minlen,
4606                               &deltanext, next, &data_fake, stopparen,
4607                               recursed_depth, NULL, f, depth+1);
4608
4609             scan = next;
4610         } else
4611         if (
4612             OP(scan) == BRANCH  ||
4613             OP(scan) == BRANCHJ ||
4614             OP(scan) == IFTHEN
4615         ) {
4616             next = regnext(scan);
4617             code = OP(scan);
4618
4619             /* The op(next)==code check below is to see if we
4620              * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4621              * IFTHEN is special as it might not appear in pairs.
4622              * Not sure whether BRANCH-BRANCHJ is possible, regardless
4623              * we dont handle it cleanly. */
4624             if (OP(next) == code || code == IFTHEN) {
4625                 /* NOTE - There is similar code to this block below for
4626                  * handling TRIE nodes on a re-study.  If you change stuff here
4627                  * check there too. */
4628                 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
4629                 regnode_ssc accum;
4630                 regnode * const startbranch=scan;
4631
4632                 if (flags & SCF_DO_SUBSTR) {
4633                     /* Cannot merge strings after this. */
4634                     scan_commit(pRExC_state, data, minlenp, is_inf);
4635                 }
4636
4637                 if (flags & SCF_DO_STCLASS)
4638                     ssc_init_zero(pRExC_state, &accum);
4639
4640                 while (OP(scan) == code) {
4641                     SSize_t deltanext, minnext, fake;
4642                     I32 f = 0;
4643                     regnode_ssc this_class;
4644
4645                     DEBUG_PEEP("Branch", scan, depth, flags);
4646
4647                     num++;
4648                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4649                     if (data) {
4650                         data_fake.whilem_c = data->whilem_c;
4651                         data_fake.last_closep = data->last_closep;
4652                     }
4653                     else
4654                         data_fake.last_closep = &fake;
4655
4656                     data_fake.pos_delta = delta;
4657                     next = regnext(scan);
4658
4659                     scan = NEXTOPER(scan); /* everything */
4660                     if (code != BRANCH)    /* everything but BRANCH */
4661                         scan = NEXTOPER(scan);
4662
4663                     if (flags & SCF_DO_STCLASS) {
4664                         ssc_init(pRExC_state, &this_class);
4665                         data_fake.start_class = &this_class;
4666                         f = SCF_DO_STCLASS_AND;
4667                     }
4668                     if (flags & SCF_WHILEM_VISITED_POS)
4669                         f |= SCF_WHILEM_VISITED_POS;
4670
4671                     /* we suppose the run is continuous, last=next...*/
4672                     /* recurse study_chunk() for each BRANCH in an alternation */
4673                     minnext = study_chunk(pRExC_state, &scan, minlenp,
4674                                       &deltanext, next, &data_fake, stopparen,
4675                                       recursed_depth, NULL, f, depth+1);
4676
4677                     if (min1 > minnext)
4678                         min1 = minnext;
4679                     if (deltanext == SSize_t_MAX) {
4680                         is_inf = is_inf_internal = 1;
4681                         max1 = SSize_t_MAX;
4682                     } else if (max1 < minnext + deltanext)
4683                         max1 = minnext + deltanext;
4684                     scan = next;
4685                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4686                         pars++;
4687                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4688                         if ( stopmin > minnext)
4689                             stopmin = min + min1;
4690                         flags &= ~SCF_DO_SUBSTR;
4691                         if (data)
4692                             data->flags |= SCF_SEEN_ACCEPT;
4693                     }
4694                     if (data) {
4695                         if (data_fake.flags & SF_HAS_EVAL)
4696                             data->flags |= SF_HAS_EVAL;
4697                         data->whilem_c = data_fake.whilem_c;
4698                     }
4699                     if (flags & SCF_DO_STCLASS)
4700                         ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4701                 }
4702                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4703                     min1 = 0;
4704                 if (flags & SCF_DO_SUBSTR) {
4705                     data->pos_min += min1;
4706                     if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
4707                         data->pos_delta = SSize_t_MAX;
4708                     else
4709                         data->pos_delta += max1 - min1;
4710                     if (max1 != min1 || is_inf)
4711                         data->cur_is_floating = 1;
4712                 }
4713                 min += min1;
4714                 if (delta == SSize_t_MAX
4715                  || SSize_t_MAX - delta - (max1 - min1) < 0)
4716                     delta = SSize_t_MAX;
4717                 else
4718                     delta += max1 - min1;
4719                 if (flags & SCF_DO_STCLASS_OR) {
4720                     ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4721                     if (min1) {
4722                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4723                         flags &= ~SCF_DO_STCLASS;
4724                     }
4725                 }
4726                 else if (flags & SCF_DO_STCLASS_AND) {
4727                     if (min1) {
4728                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4729                         flags &= ~SCF_DO_STCLASS;
4730                     }
4731                     else {
4732                         /* Switch to OR mode: cache the old value of
4733                          * data->start_class */
4734                         INIT_AND_WITHP;
4735                         StructCopy(data->start_class, and_withp, regnode_ssc);
4736                         flags &= ~SCF_DO_STCLASS_AND;
4737                         StructCopy(&accum, data->start_class, regnode_ssc);
4738                         flags |= SCF_DO_STCLASS_OR;
4739                     }
4740                 }
4741
4742                 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4743                         OP( startbranch ) == BRANCH )
4744                 {
4745                 /* demq.
4746
4747                    Assuming this was/is a branch we are dealing with: 'scan'
4748                    now points at the item that follows the branch sequence,
4749                    whatever it is. We now start at the beginning of the
4750                    sequence and look for subsequences of
4751
4752                    BRANCH->EXACT=>x1
4753                    BRANCH->EXACT=>x2
4754                    tail
4755
4756                    which would be constructed from a pattern like
4757                    /A|LIST|OF|WORDS/
4758
4759                    If we can find such a subsequence we need to turn the first
4760                    element into a trie and then add the subsequent branch exact
4761                    strings to the trie.
4762
4763                    We have two cases
4764
4765                      1. patterns where the whole set of branches can be
4766                         converted.
4767
4768                      2. patterns where only a subset can be converted.
4769
4770                    In case 1 we can replace the whole set with a single regop
4771                    for the trie. In case 2 we need to keep the start and end
4772                    branches so
4773
4774                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4775                      becomes BRANCH TRIE; BRANCH X;
4776
4777                   There is an additional case, that being where there is a
4778                   common prefix, which gets split out into an EXACT like node
4779                   preceding the TRIE node.
4780
4781                   If x(1..n)==tail then we can do a simple trie, if not we make
4782                   a "jump" trie, such that when we match the appropriate word
4783                   we "jump" to the appropriate tail node. Essentially we turn
4784                   a nested if into a case structure of sorts.
4785
4786                 */
4787
4788                     int made=0;
4789                     if (!re_trie_maxbuff) {
4790                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4791                         if (!SvIOK(re_trie_maxbuff))
4792                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4793                     }
4794                     if ( SvIV(re_trie_maxbuff)>=0  ) {
4795                         regnode *cur;
4796                         regnode *first = (regnode *)NULL;
4797                         regnode *prev = (regnode *)NULL;
4798                         regnode *tail = scan;
4799                         U8 trietype = 0;
4800                         U32 count=0;
4801
4802                         /* var tail is used because there may be a TAIL
4803                            regop in the way. Ie, the exacts will point to the
4804                            thing following the TAIL, but the last branch will
4805                            point at the TAIL. So we advance tail. If we
4806                            have nested (?:) we may have to move through several
4807                            tails.
4808                          */
4809
4810                         while ( OP( tail ) == TAIL ) {
4811                             /* this is the TAIL generated by (?:) */
4812                             tail = regnext( tail );
4813                         }
4814
4815
4816                         DEBUG_TRIE_COMPILE_r({
4817                             regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4818                             Perl_re_indentf( aTHX_  "%s %" UVuf ":%s\n",
4819                               depth+1,
4820                               "Looking for TRIE'able sequences. Tail node is ",
4821                               (UV) REGNODE_OFFSET(tail),
4822                               SvPV_nolen_const( RExC_mysv )
4823                             );
4824                         });
4825
4826                         /*
4827
4828                             Step through the branches
4829                                 cur represents each branch,
4830                                 noper is the first thing to be matched as part
4831                                       of that branch
4832                                 noper_next is the regnext() of that node.
4833
4834                             We normally handle a case like this
4835                             /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4836                             support building with NOJUMPTRIE, which restricts
4837                             the trie logic to structures like /FOO|BAR/.
4838
4839                             If noper is a trieable nodetype then the branch is
4840                             a possible optimization target. If we are building
4841                             under NOJUMPTRIE then we require that noper_next is
4842                             the same as scan (our current position in the regex
4843                             program).
4844
4845                             Once we have two or more consecutive such branches
4846                             we can create a trie of the EXACT's contents and
4847                             stitch it in place into the program.
4848
4849                             If the sequence represents all of the branches in
4850                             the alternation we replace the entire thing with a
4851                             single TRIE node.
4852
4853                             Otherwise when it is a subsequence we need to
4854                             stitch it in place and replace only the relevant
4855                             branches. This means the first branch has to remain
4856                             as it is used by the alternation logic, and its
4857                             next pointer, and needs to be repointed at the item
4858                             on the branch chain following the last branch we
4859                             have optimized away.
4860
4861                             This could be either a BRANCH, in which case the
4862                             subsequence is internal, or it could be the item
4863                             following the branch sequence in which case the
4864                             subsequence is at the end (which does not
4865                             necessarily mean the first node is the start of the
4866                             alternation).
4867
4868                             TRIE_TYPE(X) is a define which maps the optype to a
4869                             trietype.
4870
4871                                 optype          |  trietype
4872                                 ----------------+-----------
4873                                 NOTHING         | NOTHING
4874                                 EXACT           | EXACT
4875                                 EXACT_REQ8     | EXACT
4876                                 EXACTFU         | EXACTFU
4877                                 EXACTFU_REQ8   | EXACTFU
4878                                 EXACTFUP        | EXACTFU
4879                                 EXACTFAA        | EXACTFAA
4880                                 EXACTL          | EXACTL
4881                                 EXACTFLU8       | EXACTFLU8
4882
4883
4884                         */
4885 #define TRIE_TYPE(X) ( ( NOTHING == (X) )                                   \
4886                        ? NOTHING                                            \
4887                        : ( EXACT == (X) || EXACT_REQ8 == (X) )             \
4888                          ? EXACT                                            \
4889                          : (     EXACTFU == (X)                             \
4890                               || EXACTFU_REQ8 == (X)                       \
4891                               || EXACTFUP == (X) )                          \
4892                            ? EXACTFU                                        \
4893                            : ( EXACTFAA == (X) )                            \
4894                              ? EXACTFAA                                     \
4895                              : ( EXACTL == (X) )                            \
4896                                ? EXACTL                                     \
4897                                : ( EXACTFLU8 == (X) )                       \
4898                                  ? EXACTFLU8                                \
4899                                  : 0 )
4900
4901                         /* dont use tail as the end marker for this traverse */
4902                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4903                             regnode * const noper = NEXTOPER( cur );
4904                             U8 noper_type = OP( noper );
4905                             U8 noper_trietype = TRIE_TYPE( noper_type );
4906 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4907                             regnode * const noper_next = regnext( noper );
4908                             U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4909                             U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0;
4910 #endif
4911
4912                             DEBUG_TRIE_COMPILE_r({
4913                                 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4914                                 Perl_re_indentf( aTHX_  "- %d:%s (%d)",
4915                                    depth+1,
4916                                    REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4917
4918                                 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4919                                 Perl_re_printf( aTHX_  " -> %d:%s",
4920                                     REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv));
4921
4922                                 if ( noper_next ) {
4923                                   regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4924                                   Perl_re_printf( aTHX_ "\t=> %d:%s\t",
4925                                     REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv));
4926                                 }
4927                                 Perl_re_printf( aTHX_  "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n",
4928                                    REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
4929                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4930                                 );
4931                             });
4932
4933                             /* Is noper a trieable nodetype that can be merged
4934                              * with the current trie (if there is one)? */
4935                             if ( noper_trietype
4936                                   &&
4937                                   (
4938                                         ( noper_trietype == NOTHING )
4939                                         || ( trietype == NOTHING )
4940                                         || ( trietype == noper_trietype )
4941                                   )
4942 #ifdef NOJUMPTRIE
4943                                   && noper_next >= tail
4944 #endif
4945                                   && count < U16_MAX)
4946                             {
4947                                 /* Handle mergable triable node Either we are
4948                                  * the first node in a new trieable sequence,
4949                                  * in which case we do some bookkeeping,
4950                                  * otherwise we update the end pointer. */
4951                                 if ( !first ) {
4952                                     first = cur;
4953                                     if ( noper_trietype == NOTHING ) {
4954 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4955                                         regnode * const noper_next = regnext( noper );
4956                                         U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0;
4957                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4958 #endif
4959
4960                                         if ( noper_next_trietype ) {
4961                                             trietype = noper_next_trietype;
4962                                         } else if (noper_next_type)  {
4963                                             /* a NOTHING regop is 1 regop wide.
4964                                              * We need at least two for a trie
4965                                              * so we can't merge this in */
4966                                             first = NULL;
4967                                         }
4968                                     } else {
4969                                         trietype = noper_trietype;
4970                                     }
4971                                 } else {
4972                                     if ( trietype == NOTHING )
4973                                         trietype = noper_trietype;
4974                                     prev = cur;
4975                                 }
4976                                 if (first)
4977                                     count++;
4978                             } /* end handle mergable triable node */
4979                             else {
4980                                 /* handle unmergable node -
4981                                  * noper may either be a triable node which can
4982                                  * not be tried together with the current trie,
4983                                  * or a non triable node */
4984                                 if ( prev ) {
4985                                     /* If last is set and trietype is not
4986                                      * NOTHING then we have found at least two
4987                                      * triable branch sequences in a row of a
4988                                      * similar trietype so we can turn them
4989                                      * into a trie. If/when we allow NOTHING to
4990                                      * start a trie sequence this condition
4991                                      * will be required, and it isn't expensive
4992                                      * so we leave it in for now. */
4993                                     if ( trietype && trietype != NOTHING )
4994                                         make_trie( pRExC_state,
4995                                                 startbranch, first, cur, tail,
4996                                                 count, trietype, depth+1 );
4997                                     prev = NULL; /* note: we clear/update
4998                                                     first, trietype etc below,
4999                                                     so we dont do it here */
5000                                 }
5001                                 if ( noper_trietype
5002 #ifdef NOJUMPTRIE
5003                                      && noper_next >= tail
5004 #endif
5005                                 ){
5006                                     /* noper is triable, so we can start a new
5007                                      * trie sequence */
5008                                     count = 1;
5009                                     first = cur;
5010                                     trietype = noper_trietype;
5011                                 } else if (first) {
5012                                     /* if we already saw a first but the
5013                                      * current node is not triable then we have
5014                                      * to reset the first information. */
5015                                     count = 0;
5016                                     first = NULL;
5017                                     trietype = 0;
5018                                 }
5019                             } /* end handle unmergable node */
5020                         } /* loop over branches */
5021                         DEBUG_TRIE_COMPILE_r({
5022                             regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5023                             Perl_re_indentf( aTHX_  "- %s (%d) <SCAN FINISHED> ",
5024                               depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5025                             Perl_re_printf( aTHX_  "(First==%d, Last==%d, Cur==%d, tt==%s)\n",
5026                                REG_NODE_NUM(first), REG_NODE_NUM(prev), REG_NODE_NUM(cur),
5027                                PL_reg_name[trietype]
5028                             );
5029
5030                         });
5031                         if ( prev && trietype ) {
5032                             if ( trietype != NOTHING ) {
5033                                 /* the last branch of the sequence was part of
5034                                  * a trie, so we have to construct it here
5035                                  * outside of the loop */
5036                                 made= make_trie( pRExC_state, startbranch,
5037                                                  first, scan, tail, count,
5038                                                  trietype, depth+1 );
5039 #ifdef TRIE_STUDY_OPT
5040                                 if ( ((made == MADE_EXACT_TRIE &&
5041                                      startbranch == first)
5042                                      || ( first_non_open == first )) &&
5043                                      depth==0 ) {
5044                                     flags |= SCF_TRIE_RESTUDY;
5045                                     if ( startbranch == first
5046                                          && scan >= tail )
5047                                     {
5048                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
5049                                     }
5050                                 }
5051 #endif
5052                             } else {
5053                                 /* at this point we know whatever we have is a
5054                                  * NOTHING sequence/branch AND if 'startbranch'
5055                                  * is 'first' then we can turn the whole thing
5056                                  * into a NOTHING
5057                                  */
5058                                 if ( startbranch == first ) {
5059                                     regnode *opt;
5060                                     /* the entire thing is a NOTHING sequence,
5061                                      * something like this: (?:|) So we can
5062                                      * turn it into a plain NOTHING op. */
5063                                     DEBUG_TRIE_COMPILE_r({
5064                                         regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
5065                                         Perl_re_indentf( aTHX_  "- %s (%d) <NOTHING BRANCH SEQUENCE>\n",
5066                                           depth+1,
5067                                           SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur));
5068
5069                                     });
5070                                     OP(startbranch)= NOTHING;
5071                                     NEXT_OFF(startbranch)= tail - startbranch;
5072                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
5073                                         OP(opt)= OPTIMIZED;
5074                                 }
5075                             }
5076                         } /* end if ( prev) */
5077                     } /* TRIE_MAXBUF is non zero */
5078                 } /* do trie */
5079
5080             }
5081             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
5082                 scan = NEXTOPER(NEXTOPER(scan));
5083             } else                      /* single branch is optimized. */
5084                 scan = NEXTOPER(scan);
5085             continue;
5086         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) {
5087             I32 paren = 0;
5088             regnode *start = NULL;
5089             regnode *end = NULL;
5090             U32 my_recursed_depth= recursed_depth;
5091
5092             if (OP(scan) != SUSPEND) { /* GOSUB */
5093                 /* Do setup, note this code has side effects beyond
5094                  * the rest of this block. Specifically setting
5095                  * RExC_recurse[] must happen at least once during
5096                  * study_chunk(). */
5097                 paren = ARG(scan);
5098                 RExC_recurse[ARG2L(scan)] = scan;
5099                 start = REGNODE_p(RExC_open_parens[paren]);
5100                 end   = REGNODE_p(RExC_close_parens[paren]);
5101
5102                 /* NOTE we MUST always execute the above code, even
5103                  * if we do nothing with a GOSUB */
5104                 if (
5105                     ( flags & SCF_IN_DEFINE )
5106                     ||
5107                     (
5108                         (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
5109                         &&
5110                         ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
5111                     )
5112                 ) {
5113                     /* no need to do anything here if we are in a define. */
5114                     /* or we are after some kind of infinite construct
5115                      * so we can skip recursing into this item.
5116                      * Since it is infinite we will not change the maxlen
5117                      * or delta, and if we miss something that might raise
5118                      * the minlen it will merely pessimise a little.
5119                      *
5120                      * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
5121                      * might result in a minlen of 1 and not of 4,
5122                      * but this doesn't make us mismatch, just try a bit
5123                      * harder than we should.
5124                      * */
5125                     scan= regnext(scan);
5126                     continue;
5127                 }
5128
5129                 if (
5130                     !recursed_depth
5131                     ||
5132                     !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
5133                 ) {
5134                     /* it is quite possible that there are more efficient ways
5135                      * to do this. We maintain a bitmap per level of recursion
5136                      * of which patterns we have entered so we can detect if a
5137                      * pattern creates a possible infinite loop. When we
5138                      * recurse down a level we copy the previous levels bitmap
5139                      * down. When we are at recursion level 0 we zero the top
5140                      * level bitmap. It would be nice to implement a different
5141                      * more efficient way of doing this. In particular the top
5142                      * level bitmap may be unnecessary.
5143                      */
5144                     if (!recursed_depth) {
5145                         Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
5146                     } else {
5147                         Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
5148                              RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
5149                              RExC_study_chunk_recursed_bytes, U8);
5150                     }
5151                     /* we havent recursed into this paren yet, so recurse into it */
5152                     DEBUG_STUDYDATA("gosub-set", data, depth, is_inf);
5153                     PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
5154                     my_recursed_depth= recursed_depth + 1;
5155                 } else {
5156                     DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf);
5157                     /* some form of infinite recursion, assume infinite length
5158                      * */
5159                     if (flags & SCF_DO_SUBSTR) {
5160                         scan_commit(pRExC_state, data, minlenp, is_inf);
5161                         data->cur_is_floating = 1;
5162                     }
5163                     is_inf = is_inf_internal = 1;
5164                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5165                         ssc_anything(data->start_class);
5166                     flags &= ~SCF_DO_STCLASS;
5167
5168                     start= NULL; /* reset start so we dont recurse later on. */
5169                 }
5170             } else {
5171                 paren = stopparen;
5172                 start = scan + 2;
5173                 end = regnext(scan);
5174             }
5175             if (start) {
5176                 scan_frame *newframe;
5177                 assert(end);
5178                 if (!RExC_frame_last) {
5179                     Newxz(newframe, 1, scan_frame);
5180                     SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
5181                     RExC_frame_head= newframe;
5182                     RExC_frame_count++;
5183                 } else if (!RExC_frame_last->next_frame) {
5184                     Newxz(newframe, 1, scan_frame);
5185                     RExC_frame_last->next_frame= newframe;
5186                     newframe->prev_frame= RExC_frame_last;
5187                     RExC_frame_count++;
5188                 } else {
5189                     newframe= RExC_frame_last->next_frame;
5190                 }
5191                 RExC_frame_last= newframe;
5192
5193                 newframe->next_regnode = regnext(scan);
5194                 newframe->last_regnode = last;
5195                 newframe->stopparen = stopparen;
5196                 newframe->prev_recursed_depth = recursed_depth;
5197                 newframe->this_prev_frame= frame;
5198
5199                 DEBUG_STUDYDATA("frame-new", data, depth, is_inf);
5200                 DEBUG_PEEP("fnew", scan, depth, flags);
5201
5202                 frame = newframe;
5203                 scan =  start;
5204                 stopparen = paren;
5205                 last = end;
5206                 depth = depth + 1;
5207                 recursed_depth= my_recursed_depth;
5208
5209                 continue;
5210             }
5211         }
5212         else if (   OP(scan) == EXACT
5213                  || OP(scan) == LEXACT
5214                  || OP(scan) == EXACT_REQ8
5215                  || OP(scan) == LEXACT_REQ8
5216                  || OP(scan) == EXACTL)
5217         {
5218             SSize_t l = STR_LEN(scan);
5219             UV uc;
5220             assert(l);
5221             if (UTF) {
5222                 const U8 * const s = (U8*)STRING(scan);
5223                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
5224                 l = utf8_length(s, s + l);
5225             } else {
5226                 uc = *((U8*)STRING(scan));
5227             }
5228             min += l;
5229             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
5230                 /* The code below prefers earlier match for fixed
5231                    offset, later match for variable offset.  */
5232                 if (data->last_end == -1) { /* Update the start info. */
5233                     data->last_start_min = data->pos_min;
5234                     data->last_start_max = is_inf
5235                         ? SSize_t_MAX : data->pos_min + data->pos_delta;
5236                 }
5237                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
5238                 if (UTF)
5239                     SvUTF8_on(data->last_found);
5240                 {
5241                     SV * const sv = data->last_found;
5242                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5243                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5244                     if (mg && mg->mg_len >= 0)
5245                         mg->mg_len += utf8_length((U8*)STRING(scan),
5246                                               (U8*)STRING(scan)+STR_LEN(scan));
5247                 }
5248                 data->last_end = data->pos_min + l;
5249                 data->pos_min += l; /* As in the first entry. */
5250                 data->flags &= ~SF_BEFORE_EOL;
5251             }
5252
5253             /* ANDing the code point leaves at most it, and not in locale, and
5254              * can't match null string */
5255             if (flags & SCF_DO_STCLASS_AND) {
5256                 ssc_cp_and(data->start_class, uc);
5257                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5258                 ssc_clear_locale(data->start_class);
5259             }
5260             else if (flags & SCF_DO_STCLASS_OR) {
5261                 ssc_add_cp(data->start_class, uc);
5262                 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5263
5264                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5265                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5266             }
5267             flags &= ~SCF_DO_STCLASS;
5268         }
5269         else if (PL_regkind[OP(scan)] == EXACT) {
5270             /* But OP != EXACT!, so is EXACTFish */
5271             SSize_t l = STR_LEN(scan);
5272             const U8 * s = (U8*)STRING(scan);
5273
5274             /* Search for fixed substrings supports EXACT only. */
5275             if (flags & SCF_DO_SUBSTR) {
5276                 assert(data);
5277                 scan_commit(pRExC_state, data, minlenp, is_inf);
5278             }
5279             if (UTF) {
5280                 l = utf8_length(s, s + l);
5281             }
5282             if (unfolded_multi_char) {
5283                 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
5284             }
5285             min += l - min_subtract;
5286             assert (min >= 0);
5287             delta += min_subtract;
5288             if (flags & SCF_DO_SUBSTR) {
5289                 data->pos_min += l - min_subtract;
5290                 if (data->pos_min < 0) {
5291                     data->pos_min = 0;
5292                 }
5293                 data->pos_delta += min_subtract;
5294                 if (min_subtract) {
5295                     data->cur_is_floating = 1; /* float */
5296                 }
5297             }
5298
5299             if (flags & SCF_DO_STCLASS) {
5300                 SV* EXACTF_invlist = make_exactf_invlist(pRExC_state, scan);
5301
5302                 assert(EXACTF_invlist);
5303                 if (flags & SCF_DO_STCLASS_AND) {
5304                     if (OP(scan) != EXACTFL)
5305                         ssc_clear_locale(data->start_class);
5306                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5307                     ANYOF_POSIXL_ZERO(data->start_class);
5308                     ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
5309                 }
5310                 else {  /* SCF_DO_STCLASS_OR */
5311                     ssc_union(data->start_class, EXACTF_invlist, FALSE);
5312                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5313
5314                     /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5315                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5316                 }
5317                 flags &= ~SCF_DO_STCLASS;
5318                 SvREFCNT_dec(EXACTF_invlist);
5319             }
5320         }
5321         else if (REGNODE_VARIES(OP(scan))) {
5322             SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
5323             I32 fl = 0, f = flags;
5324             regnode * const oscan = scan;
5325             regnode_ssc this_class;
5326             regnode_ssc *oclass = NULL;
5327             I32 next_is_eval = 0;
5328
5329             switch (PL_regkind[OP(scan)]) {
5330             case WHILEM:                /* End of (?:...)* . */
5331                 scan = NEXTOPER(scan);
5332                 goto finish;
5333             case PLUS:
5334                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
5335                     next = NEXTOPER(scan);
5336                     if (   OP(next) == EXACT
5337                         || OP(next) == LEXACT
5338                         || OP(next) == EXACT_REQ8
5339                         || OP(next) == LEXACT_REQ8
5340                         || OP(next) == EXACTL
5341                         || (flags & SCF_DO_STCLASS))
5342                     {
5343                         mincount = 1;
5344                         maxcount = REG_INFTY;
5345                         next = regnext(scan);
5346                         scan = NEXTOPER(scan);
5347                         goto do_curly;
5348                     }
5349                 }
5350                 if (flags & SCF_DO_SUBSTR)
5351                     data->pos_min++;
5352                 min++;
5353                 /* FALLTHROUGH */
5354             case STAR:
5355                 next = NEXTOPER(scan);
5356
5357                 /* This temporary node can now be turned into EXACTFU, and
5358                  * must, as regexec.c doesn't handle it */
5359                 if (OP(next) == EXACTFU_S_EDGE) {
5360                     OP(next) = EXACTFU;
5361                 }
5362
5363                 if (     STR_LEN(next) == 1
5364                     &&   isALPHA_A(* STRING(next))
5365                     && (         OP(next) == EXACTFAA
5366                         || (     OP(next) == EXACTFU
5367                             && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next)))))
5368                 {
5369                     /* These differ in just one bit */
5370                     U8 mask = ~ ('A' ^ 'a');
5371
5372                     assert(isALPHA_A(* STRING(next)));
5373
5374                     /* Then replace it by an ANYOFM node, with
5375                     * the mask set to the complement of the
5376                     * bit that differs between upper and lower
5377                     * case, and the lowest code point of the
5378                     * pair (which the '&' forces) */
5379                     OP(next) = ANYOFM;
5380                     ARG_SET(next, *STRING(next) & mask);
5381                     FLAGS(next) = mask;
5382                 }
5383
5384                 if (flags & SCF_DO_STCLASS) {
5385                     mincount = 0;
5386                     maxcount = REG_INFTY;
5387                     next = regnext(scan);
5388                     scan = NEXTOPER(scan);
5389                     goto do_curly;
5390                 }
5391                 if (flags & SCF_DO_SUBSTR) {
5392                     scan_commit(pRExC_state, data, minlenp, is_inf);
5393                     /* Cannot extend fixed substrings */
5394                     data->cur_is_floating = 1; /* float */
5395                 }
5396                 is_inf = is_inf_internal = 1;
5397                 scan = regnext(scan);
5398                 goto optimize_curly_tail;
5399             case CURLY:
5400                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
5401                     && (scan->flags == stopparen))
5402                 {
5403                     mincount = 1;
5404                     maxcount = 1;
5405                 } else {
5406                     mincount = ARG1(scan);
5407                     maxcount = ARG2(scan);
5408                 }
5409                 next = regnext(scan);
5410                 if (OP(scan) == CURLYX) {
5411                     I32 lp = (data ? *(data->last_closep) : 0);
5412                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
5413                 }
5414                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
5415                 next_is_eval = (OP(scan) == EVAL);
5416               do_curly:
5417                 if (flags & SCF_DO_SUBSTR) {
5418                     if (mincount == 0)
5419                         scan_commit(pRExC_state, data, minlenp, is_inf);
5420                     /* Cannot extend fixed substrings */
5421                     pos_before = data->pos_min;
5422                 }
5423                 if (data) {
5424                     fl = data->flags;
5425                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
5426                     if (is_inf)
5427                         data->flags |= SF_IS_INF;
5428                 }
5429                 if (flags & SCF_DO_STCLASS) {
5430                     ssc_init(pRExC_state, &this_class);
5431                     oclass = data->start_class;
5432                     data->start_class = &this_class;
5433                     f |= SCF_DO_STCLASS_AND;
5434                     f &= ~SCF_DO_STCLASS_OR;
5435                 }
5436                 /* Exclude from super-linear cache processing any {n,m}
5437                    regops for which the combination of input pos and regex
5438                    pos is not enough information to determine if a match
5439                    will be possible.
5440
5441                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
5442                    regex pos at the \s*, the prospects for a match depend not
5443                    only on the input position but also on how many (bar\s*)
5444                    repeats into the {4,8} we are. */
5445                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
5446                     f &= ~SCF_WHILEM_VISITED_POS;
5447
5448                 /* This will finish on WHILEM, setting scan, or on NULL: */
5449                 /* recurse study_chunk() on loop bodies */
5450                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
5451                                   last, data, stopparen, recursed_depth, NULL,
5452                                   (mincount == 0
5453                                    ? (f & ~SCF_DO_SUBSTR)
5454                                    : f)
5455                                   ,depth+1);
5456
5457                 if (flags & SCF_DO_STCLASS)
5458                     data->start_class = oclass;
5459                 if (mincount == 0 || minnext == 0) {
5460                     if (flags & SCF_DO_STCLASS_OR) {
5461                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5462                     }
5463                     else if (flags & SCF_DO_STCLASS_AND) {
5464                         /* Switch to OR mode: cache the old value of
5465                          * data->start_class */
5466                         INIT_AND_WITHP;
5467                         StructCopy(data->start_class, and_withp, regnode_ssc);
5468                         flags &= ~SCF_DO_STCLASS_AND;
5469                         StructCopy(&this_class, data->start_class, regnode_ssc);
5470                         flags |= SCF_DO_STCLASS_OR;
5471                         ANYOF_FLAGS(data->start_class)
5472                                                 |= SSC_MATCHES_EMPTY_STRING;
5473                     }
5474                 } else {                /* Non-zero len */
5475                     if (flags & SCF_DO_STCLASS_OR) {
5476                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5477                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5478                     }
5479                     else if (flags & SCF_DO_STCLASS_AND)
5480                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5481                     flags &= ~SCF_DO_STCLASS;
5482                 }
5483                 if (!scan)              /* It was not CURLYX, but CURLY. */
5484                     scan = next;
5485                 if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR)
5486                     /* ? quantifier ok, except for (?{ ... }) */
5487                     && (next_is_eval || !(mincount == 0 && maxcount == 1))
5488                     && (minnext == 0) && (deltanext == 0)
5489                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5490                     && maxcount <= REG_INFTY/3) /* Complement check for big
5491                                                    count */
5492                 {
5493                     _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP),
5494                         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5495                             "Quantifier unexpected on zero-length expression "
5496                             "in regex m/%" UTF8f "/",
5497                              UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5498                                   RExC_precomp)));
5499                 }
5500
5501                 min += minnext * mincount;
5502                 is_inf_internal |= deltanext == SSize_t_MAX
5503                          || (maxcount == REG_INFTY && minnext + deltanext > 0);
5504                 is_inf |= is_inf_internal;
5505                 if (is_inf) {
5506                     delta = SSize_t_MAX;
5507                 } else {
5508                     delta += (minnext + deltanext) * maxcount
5509                              - minnext * mincount;
5510                 }
5511                 /* Try powerful optimization CURLYX => CURLYN. */
5512                 if (  OP(oscan) == CURLYX && data
5513                       && data->flags & SF_IN_PAR
5514                       && !(data->flags & SF_HAS_EVAL)
5515                       && !deltanext && minnext == 1 ) {
5516                     /* Try to optimize to CURLYN.  */
5517                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5518                     regnode * const nxt1 = nxt;
5519 #ifdef DEBUGGING
5520                     regnode *nxt2;
5521 #endif
5522
5523                     /* Skip open. */
5524                     nxt = regnext(nxt);
5525                     if (!REGNODE_SIMPLE(OP(nxt))
5526                         && !(PL_regkind[OP(nxt)] == EXACT
5527                              && STR_LEN(nxt) == 1))
5528                         goto nogo;
5529 #ifdef DEBUGGING
5530                     nxt2 = nxt;
5531 #endif
5532                     nxt = regnext(nxt);
5533                     if (OP(nxt) != CLOSE)
5534                         goto nogo;
5535                     if (RExC_open_parens) {
5536
5537                         /*open->CURLYM*/
5538                         RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5539
5540                         /*close->while*/
5541                         RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2;
5542                     }
5543                     /* Now we know that nxt2 is the only contents: */
5544                     oscan->flags = (U8)ARG(nxt);
5545                     OP(oscan) = CURLYN;
5546                     OP(nxt1) = NOTHING; /* was OPEN. */
5547
5548 #ifdef DEBUGGING
5549                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5550                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5551                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5552                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
5553                     OP(nxt + 1) = OPTIMIZED; /* was count. */
5554                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5555 #endif
5556                 }
5557               nogo:
5558
5559                 /* Try optimization CURLYX => CURLYM. */
5560                 if (  OP(oscan) == CURLYX && data
5561                       && !(data->flags & SF_HAS_PAR)
5562                       && !(data->flags & SF_HAS_EVAL)
5563                       && !deltanext     /* atom is fixed width */
5564                       && minnext != 0   /* CURLYM can't handle zero width */
5565
5566                          /* Nor characters whose fold at run-time may be
5567                           * multi-character */
5568                       && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5569                 ) {
5570                     /* XXXX How to optimize if data == 0? */
5571                     /* Optimize to a simpler form.  */
5572                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5573                     regnode *nxt2;
5574
5575                     OP(oscan) = CURLYM;
5576                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5577                             && (OP(nxt2) != WHILEM))
5578                         nxt = nxt2;
5579                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
5580                     /* Need to optimize away parenths. */
5581                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5582                         /* Set the parenth number.  */
5583                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5584
5585                         oscan->flags = (U8)ARG(nxt);
5586                         if (RExC_open_parens) {
5587                              /*open->CURLYM*/
5588                             RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan);
5589
5590                             /*close->NOTHING*/
5591                             RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2)
5592                                                          + 1;
5593                         }
5594                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
5595                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
5596
5597 #ifdef DEBUGGING
5598                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5599                         OP(nxt + 1) = OPTIMIZED; /* was count. */
5600                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5601                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5602 #endif
5603 #if 0
5604                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
5605                             regnode *nnxt = regnext(nxt1);
5606                             if (nnxt == nxt) {
5607                                 if (reg_off_by_arg[OP(nxt1)])
5608                                     ARG_SET(nxt1, nxt2 - nxt1);
5609                                 else if (nxt2 - nxt1 < U16_MAX)
5610                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
5611                                 else
5612                                     OP(nxt) = NOTHING;  /* Cannot beautify */
5613                             }
5614                             nxt1 = nnxt;
5615                         }
5616 #endif
5617                         /* Optimize again: */
5618                         /* recurse study_chunk() on optimised CURLYX => CURLYM */
5619                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5620                                     NULL, stopparen, recursed_depth, NULL, 0,
5621                                     depth+1);
5622                     }
5623                     else
5624                         oscan->flags = 0;
5625                 }
5626                 else if ((OP(oscan) == CURLYX)
5627                          && (flags & SCF_WHILEM_VISITED_POS)
5628                          /* See the comment on a similar expression above.
5629                             However, this time it's not a subexpression
5630                             we care about, but the expression itself. */
5631                          && (maxcount == REG_INFTY)
5632                          && data) {
5633                     /* This stays as CURLYX, we can put the count/of pair. */
5634                     /* Find WHILEM (as in regexec.c) */
5635                     regnode *nxt = oscan + NEXT_OFF(oscan);
5636
5637                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5638                         nxt += ARG(nxt);
5639                     nxt = PREVOPER(nxt);
5640                     if (nxt->flags & 0xf) {
5641                         /* we've already set whilem count on this node */
5642                     } else if (++data->whilem_c < 16) {
5643                         assert(data->whilem_c <= RExC_whilem_seen);
5644                         nxt->flags = (U8)(data->whilem_c
5645                             | (RExC_whilem_seen << 4)); /* On WHILEM */
5646                     }
5647                 }
5648                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5649                     pars++;
5650                 if (flags & SCF_DO_SUBSTR) {
5651                     SV *last_str = NULL;
5652                     STRLEN last_chrs = 0;
5653                     int counted = mincount != 0;
5654
5655                     if (data->last_end > 0 && mincount != 0) { /* Ends with a
5656                                                                   string. */
5657                         SSize_t b = pos_before >= data->last_start_min
5658                             ? pos_before : data->last_start_min;
5659                         STRLEN l;
5660                         const char * const s = SvPV_const(data->last_found, l);
5661                         SSize_t old = b - data->last_start_min;
5662                         assert(old >= 0);
5663
5664                         if (UTF)
5665                             old = utf8_hop_forward((U8*)s, old,
5666                                                (U8 *) SvEND(data->last_found))
5667                                 - (U8*)s;
5668                         l -= old;
5669                         /* Get the added string: */
5670                         last_str = newSVpvn_utf8(s  + old, l, UTF);
5671                         last_chrs = UTF ? utf8_length((U8*)(s + old),
5672                                             (U8*)(s + old + l)) : l;
5673                         if (deltanext == 0 && pos_before == b) {
5674                             /* What was added is a constant string */
5675                             if (mincount > 1) {
5676
5677                                 SvGROW(last_str, (mincount * l) + 1);
5678                                 repeatcpy(SvPVX(last_str) + l,
5679                                           SvPVX_const(last_str), l,
5680                                           mincount - 1);
5681                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5682                                 /* Add additional parts. */
5683                                 SvCUR_set(data->last_found,
5684                                           SvCUR(data->last_found) - l);
5685                                 sv_catsv(data->last_found, last_str);
5686                                 {
5687                                     SV * sv = data->last_found;
5688                                     MAGIC *mg =
5689                                         SvUTF8(sv) && SvMAGICAL(sv) ?
5690                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5691                                     if (mg && mg->mg_len >= 0)
5692                                         mg->mg_len += last_chrs * (mincount-1);
5693                                 }
5694                                 last_chrs *= mincount;
5695                                 data->last_end += l * (mincount - 1);
5696                             }
5697                         } else {
5698                             /* start offset must point into the last copy */
5699                             data->last_start_min += minnext * (mincount - 1);
5700                             data->last_start_max =
5701                               is_inf
5702                                ? SSize_t_MAX
5703                                : data->last_start_max +
5704                                  (maxcount - 1) * (minnext + data->pos_delta);
5705                         }
5706                     }
5707                     /* It is counted once already... */
5708                     data->pos_min += minnext * (mincount - counted);
5709 #if 0
5710 Perl_re_printf( aTHX_  "counted=%" UVuf " deltanext=%" UVuf
5711                               " SSize_t_MAX=%" UVuf " minnext=%" UVuf
5712                               " maxcount=%" UVuf " mincount=%" UVuf "\n",
5713     (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
5714     (UV)mincount);
5715 if (deltanext != SSize_t_MAX)
5716 Perl_re_printf( aTHX_  "LHS=%" UVuf " RHS=%" UVuf "\n",
5717     (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5718           - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
5719 #endif
5720                     if (deltanext == SSize_t_MAX
5721                         || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
5722                         data->pos_delta = SSize_t_MAX;
5723                     else
5724                         data->pos_delta += - counted * deltanext +
5725                         (minnext + deltanext) * maxcount - minnext * mincount;
5726                     if (mincount != maxcount) {
5727                          /* Cannot extend fixed substrings found inside
5728                             the group.  */
5729                         scan_commit(pRExC_state, data, minlenp, is_inf);
5730                         if (mincount && last_str) {
5731                             SV * const sv = data->last_found;
5732                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5733                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5734
5735                             if (mg)
5736                                 mg->mg_len = -1;
5737                             sv_setsv(sv, last_str);
5738                             data->last_end = data->pos_min;
5739                             data->last_start_min = data->pos_min - last_chrs;
5740                             data->last_start_max = is_inf
5741                                 ? SSize_t_MAX
5742                                 : data->pos_min + data->pos_delta - last_chrs;
5743                         }
5744                         data->cur_is_floating = 1; /* float */
5745                     }
5746                     SvREFCNT_dec(last_str);
5747                 }
5748                 if (data && (fl & SF_HAS_EVAL))
5749                     data->flags |= SF_HAS_EVAL;
5750               optimize_curly_tail:
5751                 if (OP(oscan) != CURLYX) {
5752                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5753                            && NEXT_OFF(next))
5754                         NEXT_OFF(oscan) += NEXT_OFF(next);
5755                 }
5756                 continue;
5757
5758             default:
5759 #ifdef DEBUGGING
5760                 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5761                                                                     OP(scan));
5762 #endif
5763             case REF:
5764             case CLUMP:
5765                 if (flags & SCF_DO_SUBSTR) {
5766                     /* Cannot expect anything... */
5767                     scan_commit(pRExC_state, data, minlenp, is_inf);
5768                     data->cur_is_floating = 1; /* float */
5769                 }
5770                 is_inf = is_inf_internal = 1;
5771                 if (flags & SCF_DO_STCLASS_OR) {
5772                     if (OP(scan) == CLUMP) {
5773                         /* Actually is any start char, but very few code points
5774                          * aren't start characters */
5775                         ssc_match_all_cp(data->start_class);
5776                     }
5777                     else {
5778                         ssc_anything(data->start_class);
5779                     }
5780                 }
5781                 flags &= ~SCF_DO_STCLASS;
5782                 break;
5783             }
5784         }
5785         else if (OP(scan) == LNBREAK) {
5786             if (flags & SCF_DO_STCLASS) {
5787                 if (flags & SCF_DO_STCLASS_AND) {
5788                     ssc_intersection(data->start_class,
5789                                     PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5790                     ssc_clear_locale(data->start_class);
5791                     ANYOF_FLAGS(data->start_class)
5792                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5793                 }
5794                 else if (flags & SCF_DO_STCLASS_OR) {
5795                     ssc_union(data->start_class,
5796                               PL_XPosix_ptrs[_CC_VERTSPACE],
5797                               FALSE);
5798                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5799
5800                     /* See commit msg for
5801                      * 749e076fceedeb708a624933726e7989f2302f6a */
5802                     ANYOF_FLAGS(data->start_class)
5803                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5804                 }
5805                 flags &= ~SCF_DO_STCLASS;
5806             }
5807             min++;
5808             if (delta != SSize_t_MAX)
5809                 delta++;    /* Because of the 2 char string cr-lf */
5810             if (flags & SCF_DO_SUBSTR) {
5811                 /* Cannot expect anything... */
5812                 scan_commit(pRExC_state, data, minlenp, is_inf);
5813                 data->pos_min += 1;
5814                 if (data->pos_delta != SSize_t_MAX) {
5815                     data->pos_delta += 1;
5816                 }
5817                 data->cur_is_floating = 1; /* float */
5818             }
5819         }
5820         else if (REGNODE_SIMPLE(OP(scan))) {
5821
5822             if (flags & SCF_DO_SUBSTR) {
5823                 scan_commit(pRExC_state, data, minlenp, is_inf);
5824                 data->pos_min++;
5825             }
5826             min++;
5827             if (flags & SCF_DO_STCLASS) {
5828                 bool invert = 0;
5829                 SV* my_invlist = NULL;
5830                 U8 namedclass;
5831
5832                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5833                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5834
5835                 /* Some of the logic below assumes that switching
5836                    locale on will only add false positives. */
5837                 switch (OP(scan)) {
5838
5839                 default:
5840 #ifdef DEBUGGING
5841                    Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5842                                                                      OP(scan));
5843 #endif
5844                 case SANY:
5845                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5846                         ssc_match_all_cp(data->start_class);
5847                     break;
5848
5849                 case REG_ANY:
5850                     {
5851                         SV* REG_ANY_invlist = _new_invlist(2);
5852                         REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5853                                                             '\n');
5854                         if (flags & SCF_DO_STCLASS_OR) {
5855                             ssc_union(data->start_class,
5856                                       REG_ANY_invlist,
5857                                       TRUE /* TRUE => invert, hence all but \n
5858                                             */
5859                                       );
5860                         }
5861                         else if (flags & SCF_DO_STCLASS_AND) {
5862                             ssc_intersection(data->start_class,
5863                                              REG_ANY_invlist,
5864                                              TRUE  /* TRUE => invert */
5865                                              );
5866                             ssc_clear_locale(data->start_class);
5867                         }
5868                         SvREFCNT_dec_NN(REG_ANY_invlist);
5869                     }
5870                     break;
5871
5872                 case ANYOFD:
5873                 case ANYOFL:
5874                 case ANYOFPOSIXL:
5875                 case ANYOFH:
5876                 case ANYOFHb:
5877                 case ANYOFHr:
5878                 case ANYOFHs:
5879                 case ANYOF:
5880                     if (flags & SCF_DO_STCLASS_AND)
5881                         ssc_and(pRExC_state, data->start_class,
5882                                 (regnode_charclass *) scan);
5883                     else
5884                         ssc_or(pRExC_state, data->start_class,
5885                                                           (regnode_charclass *) scan);
5886                     break;
5887
5888                 case NANYOFM:
5889                 case ANYOFM:
5890                   {
5891                     SV* cp_list = get_ANYOFM_contents(scan);
5892
5893                     if (flags & SCF_DO_STCLASS_OR) {
5894                         ssc_union(data->start_class, cp_list, invert);
5895                     }
5896                     else if (flags & SCF_DO_STCLASS_AND) {
5897                         ssc_intersection(data->start_class, cp_list, invert);
5898                     }
5899
5900                     SvREFCNT_dec_NN(cp_list);
5901                     break;
5902                   }
5903
5904                 case ANYOFR:
5905                 case ANYOFRb:
5906                   {
5907                     SV* cp_list = NULL;
5908
5909                     cp_list = _add_range_to_invlist(cp_list,
5910                                         ANYOFRbase(scan),
5911                                         ANYOFRbase(scan) + ANYOFRdelta(scan));
5912
5913                     if (flags & SCF_DO_STCLASS_OR) {
5914                         ssc_union(data->start_class, cp_list, invert);
5915                     }
5916                     else if (flags & SCF_DO_STCLASS_AND) {
5917                         ssc_intersection(data->start_class, cp_list, invert);
5918                     }
5919
5920                     SvREFCNT_dec_NN(cp_list);
5921                     break;
5922                   }
5923
5924                 case NPOSIXL:
5925                     invert = 1;
5926                     /* FALLTHROUGH */
5927
5928                 case POSIXL:
5929                     namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5930                     if (flags & SCF_DO_STCLASS_AND) {
5931                         bool was_there = cBOOL(
5932                                           ANYOF_POSIXL_TEST(data->start_class,
5933                                                                  namedclass));
5934                         ANYOF_POSIXL_ZERO(data->start_class);
5935                         if (was_there) {    /* Do an AND */
5936                             ANYOF_POSIXL_SET(data->start_class, namedclass);
5937                         }
5938                         /* No individual code points can now match */
5939                         data->start_class->invlist
5940                                                 = sv_2mortal(_new_invlist(0));
5941                     }
5942                     else {
5943                         int complement = namedclass + ((invert) ? -1 : 1);
5944
5945                         assert(flags & SCF_DO_STCLASS_OR);
5946
5947                         /* If the complement of this class was already there,
5948                          * the result is that they match all code points,
5949                          * (\d + \D == everything).  Remove the classes from
5950                          * future consideration.  Locale is not relevant in
5951                          * this case */
5952                         if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5953                             ssc_match_all_cp(data->start_class);
5954                             ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5955                             ANYOF_POSIXL_CLEAR(data->start_class, complement);
5956                         }
5957                         else {  /* The usual case; just add this class to the
5958                                    existing set */
5959                             ANYOF_POSIXL_SET(data->start_class, namedclass);
5960                         }
5961                     }
5962                     break;
5963
5964                 case NPOSIXA:   /* For these, we always know the exact set of
5965                                    what's matched */
5966                     invert = 1;
5967                     /* FALLTHROUGH */
5968                 case POSIXA:
5969                     my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL);
5970                     goto join_posix_and_ascii;
5971
5972                 case NPOSIXD:
5973                 case NPOSIXU:
5974                     invert = 1;
5975                     /* FALLTHROUGH */
5976                 case POSIXD:
5977                 case POSIXU:
5978                     my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL);
5979
5980                     /* NPOSIXD matches all upper Latin1 code points unless the
5981                      * target string being matched is UTF-8, which is
5982                      * unknowable until match time.  Since we are going to
5983                      * invert, we want to get rid of all of them so that the
5984                      * inversion will match all */
5985                     if (OP(scan) == NPOSIXD) {
5986                         _invlist_subtract(my_invlist, PL_UpperLatin1,
5987                                           &my_invlist);
5988                     }
5989
5990                   join_posix_and_ascii:
5991
5992                     if (flags & SCF_DO_STCLASS_AND) {
5993                         ssc_intersection(data->start_class, my_invlist, invert);
5994                         ssc_clear_locale(data->start_class);
5995                     }
5996                     else {
5997                         assert(flags & SCF_DO_STCLASS_OR);
5998                         ssc_union(data->start_class, my_invlist, invert);
5999                     }
6000                     SvREFCNT_dec(my_invlist);
6001                 }
6002                 if (flags & SCF_DO_STCLASS_OR)
6003                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6004                 flags &= ~SCF_DO_STCLASS;
6005             }
6006         }
6007         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
6008             data->flags |= (OP(scan) == MEOL
6009                             ? SF_BEFORE_MEOL
6010                             : SF_BEFORE_SEOL);
6011             scan_commit(pRExC_state, data, minlenp, is_inf);
6012
6013         }
6014         else if (  PL_regkind[OP(scan)] == BRANCHJ
6015                  /* Lookbehind, or need to calculate parens/evals/stclass: */
6016                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
6017                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
6018         {
6019             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6020                 || OP(scan) == UNLESSM )
6021             {
6022                 /* Negative Lookahead/lookbehind
6023                    In this case we can't do fixed string optimisation.
6024                 */
6025
6026                 SSize_t deltanext, minnext, fake = 0;
6027                 regnode *nscan;
6028                 regnode_ssc intrnl;
6029                 int f = 0;
6030
6031                 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6032                 if (data) {
6033                     data_fake.whilem_c = data->whilem_c;
6034                     data_fake.last_closep = data->last_closep;
6035                 }
6036                 else
6037                     data_fake.last_closep = &fake;
6038                 data_fake.pos_delta = delta;
6039                 if ( flags & SCF_DO_STCLASS && !scan->flags
6040                      && OP(scan) == IFMATCH ) { /* Lookahead */
6041                     ssc_init(pRExC_state, &intrnl);
6042                     data_fake.start_class = &intrnl;
6043                     f |= SCF_DO_STCLASS_AND;
6044                 }
6045                 if (flags & SCF_WHILEM_VISITED_POS)
6046                     f |= SCF_WHILEM_VISITED_POS;
6047                 next = regnext(scan);
6048                 nscan = NEXTOPER(NEXTOPER(scan));
6049
6050                 /* recurse study_chunk() for lookahead body */
6051                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
6052                                       last, &data_fake, stopparen,
6053                                       recursed_depth, NULL, f, depth+1);
6054                 if (scan->flags) {
6055                     if (   deltanext < 0
6056                         || deltanext > (I32) U8_MAX
6057                         || minnext > (I32)U8_MAX
6058                         || minnext + deltanext > (I32)U8_MAX)
6059                     {
6060                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
6061                               (UV)U8_MAX);
6062                     }
6063
6064                     /* The 'next_off' field has been repurposed to count the
6065                      * additional starting positions to try beyond the initial
6066                      * one.  (This leaves it at 0 for non-variable length
6067                      * matches to avoid breakage for those not using this
6068                      * extension) */
6069                     if (deltanext) {
6070                         scan->next_off = deltanext;
6071                         ckWARNexperimental(RExC_parse,
6072                             WARN_EXPERIMENTAL__VLB,
6073                             "Variable length lookbehind is experimental");
6074                     }
6075                     scan->flags = (U8)minnext + deltanext;
6076                 }
6077                 if (data) {
6078                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6079                         pars++;
6080                     if (data_fake.flags & SF_HAS_EVAL)
6081                         data->flags |= SF_HAS_EVAL;
6082                     data->whilem_c = data_fake.whilem_c;
6083                 }
6084                 if (f & SCF_DO_STCLASS_AND) {
6085                     if (flags & SCF_DO_STCLASS_OR) {
6086                         /* OR before, AND after: ideally we would recurse with
6087                          * data_fake to get the AND applied by study of the
6088                          * remainder of the pattern, and then derecurse;
6089                          * *** HACK *** for now just treat as "no information".
6090                          * See [perl #56690].
6091                          */
6092                         ssc_init(pRExC_state, data->start_class);
6093                     }  else {
6094                         /* AND before and after: combine and continue.  These
6095                          * assertions are zero-length, so can match an EMPTY
6096                          * string */
6097                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6098                         ANYOF_FLAGS(data->start_class)
6099                                                    |= SSC_MATCHES_EMPTY_STRING;
6100                     }
6101                 }
6102             }
6103 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
6104             else {
6105                 /* Positive Lookahead/lookbehind
6106                    In this case we can do fixed string optimisation,
6107                    but we must be careful about it. Note in the case of
6108                    lookbehind the positions will be offset by the minimum
6109                    length of the pattern, something we won't know about
6110                    until after the recurse.
6111                 */
6112                 SSize_t deltanext, fake = 0;
6113                 regnode *nscan;
6114                 regnode_ssc intrnl;
6115                 int f = 0;
6116                 /* We use SAVEFREEPV so that when the full compile
6117                     is finished perl will clean up the allocated
6118                     minlens when it's all done. This way we don't
6119                     have to worry about freeing them when we know
6120                     they wont be used, which would be a pain.
6121                  */
6122                 SSize_t *minnextp;
6123                 Newx( minnextp, 1, SSize_t );
6124                 SAVEFREEPV(minnextp);
6125
6126                 if (data) {
6127                     StructCopy(data, &data_fake, scan_data_t);
6128                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
6129                         f |= SCF_DO_SUBSTR;
6130                         if (scan->flags)
6131                             scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
6132                         data_fake.last_found=newSVsv(data->last_found);
6133                     }
6134                 }
6135                 else
6136                     data_fake.last_closep = &fake;
6137                 data_fake.flags = 0;
6138                 data_fake.substrs[0].flags = 0;
6139                 data_fake.substrs[1].flags = 0;
6140                 data_fake.pos_delta = delta;
6141                 if (is_inf)
6142                     data_fake.flags |= SF_IS_INF;
6143                 if ( flags & SCF_DO_STCLASS && !scan->flags
6144                      && OP(scan) == IFMATCH ) { /* Lookahead */
6145                     ssc_init(pRExC_state, &intrnl);
6146                     data_fake.start_class = &intrnl;
6147                     f |= SCF_DO_STCLASS_AND;
6148                 }
6149                 if (flags & SCF_WHILEM_VISITED_POS)
6150                     f |= SCF_WHILEM_VISITED_POS;
6151                 next = regnext(scan);
6152                 nscan = NEXTOPER(NEXTOPER(scan));
6153
6154                 /* positive lookahead study_chunk() recursion */
6155                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
6156                                         &deltanext, last, &data_fake,
6157                                         stopparen, recursed_depth, NULL,
6158                                         f, depth+1);
6159                 if (scan->flags) {
6160                     assert(0);  /* This code has never been tested since this
6161                                    is normally not compiled */
6162                     if (   deltanext < 0
6163                         || deltanext > (I32) U8_MAX
6164                         || *minnextp > (I32)U8_MAX
6165                         || *minnextp + deltanext > (I32)U8_MAX)
6166                     {
6167                         FAIL2("Lookbehind longer than %" UVuf " not implemented",
6168                               (UV)U8_MAX);
6169                     }
6170
6171                     if (deltanext) {
6172                         scan->next_off = deltanext;
6173                     }
6174                     scan->flags = (U8)*minnextp + deltanext;
6175                 }
6176
6177                 *minnextp += min;
6178
6179                 if (f & SCF_DO_STCLASS_AND) {
6180                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
6181                     ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
6182                 }
6183                 if (data) {
6184                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6185                         pars++;
6186                     if (data_fake.flags & SF_HAS_EVAL)
6187                         data->flags |= SF_HAS_EVAL;
6188                     data->whilem_c = data_fake.whilem_c;
6189                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
6190                         int i;
6191                         if (RExC_rx->minlen<*minnextp)
6192                             RExC_rx->minlen=*minnextp;
6193                         scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
6194                         SvREFCNT_dec_NN(data_fake.last_found);
6195
6196                         for (i = 0; i < 2; i++) {
6197                             if (data_fake.substrs[i].minlenp != minlenp) {
6198                                 data->substrs[i].min_offset =
6199                                             data_fake.substrs[i].min_offset;
6200                                 data->substrs[i].max_offset =
6201                                             data_fake.substrs[i].max_offset;
6202                                 data->substrs[i].minlenp =
6203                                             data_fake.substrs[i].minlenp;
6204                                 data->substrs[i].lookbehind += scan->flags;
6205                             }
6206                         }
6207                     }
6208                 }
6209             }
6210 #endif
6211         }
6212         else if (OP(scan) == OPEN) {
6213             if (stopparen != (I32)ARG(scan))
6214                 pars++;
6215         }
6216         else if (OP(scan) == CLOSE) {
6217             if (stopparen == (I32)ARG(scan)) {
6218                 break;
6219             }
6220             if ((I32)ARG(scan) == is_par) {
6221                 next = regnext(scan);
6222
6223                 if ( next && (OP(next) != WHILEM) && next < last)
6224                     is_par = 0;         /* Disable optimization */
6225             }
6226             if (data)
6227                 *(data->last_closep) = ARG(scan);
6228         }
6229         else if (OP(scan) == EVAL) {
6230                 if (data)
6231                     data->flags |= SF_HAS_EVAL;
6232         }
6233         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
6234             if (flags & SCF_DO_SUBSTR) {
6235                 scan_commit(pRExC_state, data, minlenp, is_inf);
6236                 flags &= ~SCF_DO_SUBSTR;
6237             }
6238             if (data && OP(scan)==ACCEPT) {
6239                 data->flags |= SCF_SEEN_ACCEPT;
6240                 if (stopmin > min)
6241                     stopmin = min;
6242             }
6243         }
6244         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
6245         {
6246                 if (flags & SCF_DO_SUBSTR) {
6247                     scan_commit(pRExC_state, data, minlenp, is_inf);
6248                     data->cur_is_floating = 1; /* float */
6249                 }
6250                 is_inf = is_inf_internal = 1;
6251                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
6252                     ssc_anything(data->start_class);
6253                 flags &= ~SCF_DO_STCLASS;
6254         }
6255         else if (OP(scan) == GPOS) {
6256             if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
6257                 !(delta || is_inf || (data && data->pos_delta)))
6258             {
6259                 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
6260                     RExC_rx->intflags |= PREGf_ANCH_GPOS;
6261                 if (RExC_rx->gofs < (STRLEN)min)
6262                     RExC_rx->gofs = min;
6263             } else {
6264                 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
6265                 RExC_rx->gofs = 0;
6266             }
6267         }
6268 #ifdef TRIE_STUDY_OPT
6269 #ifdef FULL_TRIE_STUDY
6270         else if (PL_regkind[OP(scan)] == TRIE) {
6271             /* NOTE - There is similar code to this block above for handling
6272                BRANCH nodes on the initial study.  If you change stuff here
6273                check there too. */
6274             regnode *trie_node= scan;
6275             regnode *tail= regnext(scan);
6276             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6277             SSize_t max1 = 0, min1 = SSize_t_MAX;
6278             regnode_ssc accum;
6279
6280             if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
6281                 /* Cannot merge strings after this. */
6282                 scan_commit(pRExC_state, data, minlenp, is_inf);
6283             }
6284             if (flags & SCF_DO_STCLASS)
6285                 ssc_init_zero(pRExC_state, &accum);
6286
6287             if (!trie->jump) {
6288                 min1= trie->minlen;
6289                 max1= trie->maxlen;
6290             } else {
6291                 const regnode *nextbranch= NULL;
6292                 U32 word;
6293
6294                 for ( word=1 ; word <= trie->wordcount ; word++)
6295                 {
6296                     SSize_t deltanext=0, minnext=0, f = 0, fake;
6297                     regnode_ssc this_class;
6298
6299                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
6300                     if (data) {
6301                         data_fake.whilem_c = data->whilem_c;
6302                         data_fake.last_closep = data->last_closep;
6303                     }
6304                     else
6305                         data_fake.last_closep = &fake;
6306                     data_fake.pos_delta = delta;
6307                     if (flags & SCF_DO_STCLASS) {
6308                         ssc_init(pRExC_state, &this_class);
6309                         data_fake.start_class = &this_class;
6310                         f = SCF_DO_STCLASS_AND;
6311                     }
6312                     if (flags & SCF_WHILEM_VISITED_POS)
6313                         f |= SCF_WHILEM_VISITED_POS;
6314
6315                     if (trie->jump[word]) {
6316                         if (!nextbranch)
6317                             nextbranch = trie_node + trie->jump[0];
6318                         scan= trie_node + trie->jump[word];
6319                         /* We go from the jump point to the branch that follows
6320                            it. Note this means we need the vestigal unused
6321                            branches even though they arent otherwise used. */
6322                         /* optimise study_chunk() for TRIE */
6323                         minnext = study_chunk(pRExC_state, &scan, minlenp,
6324                             &deltanext, (regnode *)nextbranch, &data_fake,
6325                             stopparen, recursed_depth, NULL, f, depth+1);
6326                     }
6327                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
6328                         nextbranch= regnext((regnode*)nextbranch);
6329
6330                     if (min1 > (SSize_t)(minnext + trie->minlen))
6331                         min1 = minnext + trie->minlen;
6332                     if (deltanext == SSize_t_MAX) {
6333                         is_inf = is_inf_internal = 1;
6334                         max1 = SSize_t_MAX;
6335                     } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
6336                         max1 = minnext + deltanext + trie->maxlen;
6337
6338                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
6339                         pars++;
6340                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
6341                         if ( stopmin > min + min1)
6342                             stopmin = min + min1;
6343                         flags &= ~SCF_DO_SUBSTR;
6344                         if (data)
6345                             data->flags |= SCF_SEEN_ACCEPT;
6346                     }
6347                     if (data) {
6348                         if (data_fake.flags & SF_HAS_EVAL)
6349                             data->flags |= SF_HAS_EVAL;
6350                         data->whilem_c = data_fake.whilem_c;
6351                     }
6352                     if (flags & SCF_DO_STCLASS)
6353                         ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
6354                 }
6355             }
6356             if (flags & SCF_DO_SUBSTR) {
6357                 data->pos_min += min1;
6358                 data->pos_delta += max1 - min1;
6359                 if (max1 != min1 || is_inf)
6360                     data->cur_is_floating = 1; /* float */
6361             }
6362             min += min1;
6363             if (delta != SSize_t_MAX) {
6364                 if (SSize_t_MAX - (max1 - min1) >= delta)
6365                     delta += max1 - min1;
6366                 else
6367                     delta = SSize_t_MAX;
6368             }
6369             if (flags & SCF_DO_STCLASS_OR) {
6370                 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6371                 if (min1) {
6372                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6373                     flags &= ~SCF_DO_STCLASS;
6374                 }
6375             }
6376             else if (flags & SCF_DO_STCLASS_AND) {
6377                 if (min1) {
6378                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
6379                     flags &= ~SCF_DO_STCLASS;
6380                 }
6381                 else {
6382                     /* Switch to OR mode: cache the old value of
6383                      * data->start_class */
6384                     INIT_AND_WITHP;
6385                     StructCopy(data->start_class, and_withp, regnode_ssc);
6386                     flags &= ~SCF_DO_STCLASS_AND;
6387                     StructCopy(&accum, data->start_class, regnode_ssc);
6388                     flags |= SCF_DO_STCLASS_OR;
6389                 }
6390             }
6391             scan= tail;
6392             continue;
6393         }
6394 #else
6395         else if (PL_regkind[OP(scan)] == TRIE) {
6396             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
6397             U8*bang=NULL;
6398
6399             min += trie->minlen;
6400             delta += (trie->maxlen - trie->minlen);
6401             flags &= ~SCF_DO_STCLASS; /* xxx */
6402             if (flags & SCF_DO_SUBSTR) {
6403                 /* Cannot expect anything... */
6404                 scan_commit(pRExC_state, data, minlenp, is_inf);
6405                 data->pos_min += trie->minlen;
6406                 data->pos_delta += (trie->maxlen - trie->minlen);
6407                 if (trie->maxlen != trie->minlen)
6408                     data->cur_is_floating = 1; /* float */
6409             }
6410             if (trie->jump) /* no more substrings -- for now /grr*/
6411                flags &= ~SCF_DO_SUBSTR;
6412         }
6413 #endif /* old or new */
6414 #endif /* TRIE_STUDY_OPT */
6415
6416         /* Else: zero-length, ignore. */
6417         scan = regnext(scan);
6418     }
6419
6420   finish:
6421     if (frame) {
6422         /* we need to unwind recursion. */
6423         depth = depth - 1;
6424
6425         DEBUG_STUDYDATA("frame-end", data, depth, is_inf);
6426         DEBUG_PEEP("fend", scan, depth, flags);
6427
6428         /* restore previous context */
6429         last = frame->last_regnode;
6430         scan = frame->next_regnode;
6431         stopparen = frame->stopparen;
6432         recursed_depth = frame->prev_recursed_depth;
6433
6434         RExC_frame_last = frame->prev_frame;
6435         frame = frame->this_prev_frame;
6436         goto fake_study_recurse;
6437     }
6438
6439     assert(!frame);
6440     DEBUG_STUDYDATA("pre-fin", data, depth, is_inf);
6441
6442     *scanp = scan;
6443     *deltap = is_inf_internal ? SSize_t_MAX : delta;
6444
6445     if (flags & SCF_DO_SUBSTR && is_inf)
6446         data->pos_delta = SSize_t_MAX - data->pos_min;
6447     if (is_par > (I32)U8_MAX)
6448         is_par = 0;
6449     if (is_par && pars==1 && data) {
6450         data->flags |= SF_IN_PAR;
6451         data->flags &= ~SF_HAS_PAR;
6452     }
6453     else if (pars && data) {
6454         data->flags |= SF_HAS_PAR;
6455         data->flags &= ~SF_IN_PAR;
6456     }
6457     if (flags & SCF_DO_STCLASS_OR)
6458         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
6459     if (flags & SCF_TRIE_RESTUDY)
6460         data->flags |=  SCF_TRIE_RESTUDY;
6461
6462     DEBUG_STUDYDATA("post-fin", data, depth, is_inf);
6463
6464     {
6465         SSize_t final_minlen= min < stopmin ? min : stopmin;
6466
6467         if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
6468             if (final_minlen > SSize_t_MAX - delta)
6469                 RExC_maxlen = SSize_t_MAX;
6470             else if (RExC_maxlen < final_minlen + delta)
6471                 RExC_maxlen = final_minlen + delta;
6472         }
6473         return final_minlen;
6474     }
6475     NOT_REACHED; /* NOTREACHED */
6476 }
6477
6478 STATIC U32
6479 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
6480 {
6481     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
6482
6483     PERL_ARGS_ASSERT_ADD_DATA;
6484
6485     Renewc(RExC_rxi->data,
6486            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
6487            char, struct reg_data);
6488     if(count)
6489         Renew(RExC_rxi->data->what, count + n, U8);
6490     else
6491         Newx(RExC_rxi->data->what, n, U8);
6492     RExC_rxi->data->count = count + n;
6493     Copy(s, RExC_rxi->data->what + count, n, U8);
6494     return count;
6495 }
6496
6497 /*XXX: todo make this not included in a non debugging perl, but appears to be
6498  * used anyway there, in 'use re' */
6499 #ifndef PERL_IN_XSUB_RE
6500 void
6501 Perl_reginitcolors(pTHX)
6502 {
6503     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
6504     if (s) {
6505         char *t = savepv(s);
6506         int i = 0;
6507         PL_colors[0] = t;
6508         while (++i < 6) {
6509             t = strchr(t, '\t');
6510             if (t) {
6511                 *t = '\0';
6512                 PL_colors[i] = ++t;
6513             }
6514             else
6515                 PL_colors[i] = t = (char *)"";
6516         }
6517     } else {
6518         int i = 0;
6519         while (i < 6)
6520             PL_colors[i++] = (char *)"";
6521     }
6522     PL_colorset = 1;
6523 }
6524 #endif
6525
6526
6527 #ifdef TRIE_STUDY_OPT
6528 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething)            \
6529     STMT_START {                                            \
6530         if (                                                \
6531               (data.flags & SCF_TRIE_RESTUDY)               \
6532               && ! restudied++                              \
6533         ) {                                                 \
6534             dOsomething;                                    \
6535             goto reStudy;                                   \
6536         }                                                   \
6537     } STMT_END
6538 #else
6539 #define CHECK_RESTUDY_GOTO_butfirst
6540 #endif
6541
6542 /*
6543  * pregcomp - compile a regular expression into internal code
6544  *
6545  * Decides which engine's compiler to call based on the hint currently in
6546  * scope
6547  */
6548
6549 #ifndef PERL_IN_XSUB_RE
6550
6551 /* return the currently in-scope regex engine (or the default if none)  */
6552
6553 regexp_engine const *
6554 Perl_current_re_engine(pTHX)
6555 {
6556     if (IN_PERL_COMPILETIME) {
6557         HV * const table = GvHV(PL_hintgv);
6558         SV **ptr;
6559
6560         if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6561             return &PL_core_reg_engine;
6562         ptr = hv_fetchs(table, "regcomp", FALSE);
6563         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6564             return &PL_core_reg_engine;
6565         return INT2PTR(regexp_engine*, SvIV(*ptr));
6566     }
6567     else {
6568         SV *ptr;
6569         if (!PL_curcop->cop_hints_hash)
6570             return &PL_core_reg_engine;
6571         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6572         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6573             return &PL_core_reg_engine;
6574         return INT2PTR(regexp_engine*, SvIV(ptr));
6575     }
6576 }
6577
6578
6579 REGEXP *
6580 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6581 {
6582     regexp_engine const *eng = current_re_engine();
6583     GET_RE_DEBUG_FLAGS_DECL;
6584
6585     PERL_ARGS_ASSERT_PREGCOMP;
6586
6587     /* Dispatch a request to compile a regexp to correct regexp engine. */
6588     DEBUG_COMPILE_r({
6589         Perl_re_printf( aTHX_  "Using engine %" UVxf "\n",
6590                         PTR2UV(eng));
6591     });
6592     return CALLREGCOMP_ENG(eng, pattern, flags);
6593 }
6594 #endif
6595
6596 /* public(ish) entry point for the perl core's own regex compiling code.
6597  * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6598  * pattern rather than a list of OPs, and uses the internal engine rather
6599  * than the current one */
6600
6601 REGEXP *
6602 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6603 {
6604     SV *pat = pattern; /* defeat constness! */
6605     PERL_ARGS_ASSERT_RE_COMPILE;
6606     return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6607 #ifdef PERL_IN_XSUB_RE
6608                                 &my_reg_engine,
6609 #else
6610                                 &PL_core_reg_engine,
6611 #endif
6612                                 NULL, NULL, rx_flags, 0);
6613 }
6614
6615
6616 static void
6617 S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs)
6618 {
6619     int n;
6620
6621     if (--cbs->refcnt > 0)
6622         return;
6623     for (n = 0; n < cbs->count; n++) {
6624         REGEXP *rx = cbs->cb[n].src_regex;
6625         if (rx) {
6626             cbs->cb[n].src_regex = NULL;
6627             SvREFCNT_dec_NN(rx);
6628         }
6629     }
6630     Safefree(cbs->cb);
6631     Safefree(cbs);
6632 }
6633
6634
6635 static struct reg_code_blocks *
6636 S_alloc_code_blocks(pTHX_  int ncode)
6637 {
6638      struct reg_code_blocks *cbs;
6639     Newx(cbs, 1, struct reg_code_blocks);
6640     cbs->count = ncode;
6641     cbs->refcnt = 1;
6642     SAVEDESTRUCTOR_X(S_free_codeblocks, cbs);
6643     if (ncode)
6644         Newx(cbs->cb, ncode, struct reg_code_block);
6645     else
6646         cbs->cb = NULL;
6647     return cbs;
6648 }
6649
6650
6651 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6652  * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6653  * point to the realloced string and length.
6654  *
6655  * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6656  * stuff added */
6657
6658 static void
6659 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6660                     char **pat_p, STRLEN *plen_p, int num_code_blocks)
6661 {
6662     U8 *const src = (U8*)*pat_p;
6663     U8 *dst, *d;
6664     int n=0;
6665     STRLEN s = 0;
6666     bool do_end = 0;
6667     GET_RE_DEBUG_FLAGS_DECL;
6668
6669     DEBUG_PARSE_r(Perl_re_printf( aTHX_
6670         "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6671
6672     /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */
6673     Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8);
6674     d = dst;
6675
6676     while (s < *plen_p) {
6677         append_utf8_from_native_byte(src[s], &d);
6678
6679         if (n < num_code_blocks) {
6680             assert(pRExC_state->code_blocks);
6681             if (!do_end && pRExC_state->code_blocks->cb[n].start == s) {
6682                 pRExC_state->code_blocks->cb[n].start = d - dst - 1;
6683                 assert(*(d - 1) == '(');
6684                 do_end = 1;
6685             }
6686             else if (do_end && pRExC_state->code_blocks->cb[n].end == s) {
6687                 pRExC_state->code_blocks->cb[n].end = d - dst - 1;
6688                 assert(*(d - 1) == ')');
6689                 do_end = 0;
6690                 n++;
6691             }
6692         }
6693         s++;
6694     }
6695     *d = '\0';
6696     *plen_p = d - dst;
6697     *pat_p = (char*) dst;
6698     SAVEFREEPV(*pat_p);
6699     RExC_orig_utf8 = RExC_utf8 = 1;
6700 }
6701
6702
6703
6704 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6705  * while recording any code block indices, and handling overloading,
6706  * nested qr// objects etc.  If pat is null, it will allocate a new
6707  * string, or just return the first arg, if there's only one.
6708  *
6709  * Returns the malloced/updated pat.
6710  * patternp and pat_count is the array of SVs to be concatted;
6711  * oplist is the optional list of ops that generated the SVs;
6712  * recompile_p is a pointer to a boolean that will be set if
6713  *   the regex will need to be recompiled.
6714  * delim, if non-null is an SV that will be inserted between each element
6715  */
6716
6717 static SV*
6718 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6719                 SV *pat, SV ** const patternp, int pat_count,
6720                 OP *oplist, bool *recompile_p, SV *delim)
6721 {
6722     SV **svp;
6723     int n = 0;
6724     bool use_delim = FALSE;
6725     bool alloced = FALSE;
6726
6727     /* if we know we have at least two args, create an empty string,
6728      * then concatenate args to that. For no args, return an empty string */
6729     if (!pat && pat_count != 1) {
6730         pat = newSVpvs("");
6731         SAVEFREESV(pat);
6732         alloced = TRUE;
6733     }
6734
6735     for (svp = patternp; svp < patternp + pat_count; svp++) {
6736         SV *sv;
6737         SV *rx  = NULL;
6738         STRLEN orig_patlen = 0;
6739         bool code = 0;
6740         SV *msv = use_delim ? delim : *svp;
6741         if (!msv) msv = &PL_sv_undef;
6742
6743         /* if we've got a delimiter, we go round the loop twice for each
6744          * svp slot (except the last), using the delimiter the second
6745          * time round */
6746         if (use_delim) {
6747             svp--;
6748             use_delim = FALSE;
6749         }
6750         else if (delim)
6751             use_delim = TRUE;
6752
6753         if (SvTYPE(msv) == SVt_PVAV) {
6754             /* we've encountered an interpolated array within
6755              * the pattern, e.g. /...@a..../. Expand the list of elements,
6756              * then recursively append elements.
6757              * The code in this block is based on S_pushav() */
6758
6759             AV *const av = (AV*)msv;
6760             const SSize_t maxarg = AvFILL(av) + 1;
6761             SV **array;
6762
6763             if (oplist) {
6764                 assert(oplist->op_type == OP_PADAV
6765                     || oplist->op_type == OP_RV2AV);
6766                 oplist = OpSIBLING(oplist);
6767             }
6768
6769             if (SvRMAGICAL(av)) {
6770                 SSize_t i;
6771
6772                 Newx(array, maxarg, SV*);
6773                 SAVEFREEPV(array);
6774                 for (i=0; i < maxarg; i++) {
6775                     SV ** const svp = av_fetch(av, i, FALSE);
6776                     array[i] = svp ? *svp : &PL_sv_undef;
6777                 }
6778             }
6779             else
6780                 array = AvARRAY(av);
6781
6782             pat = S_concat_pat(aTHX_ pRExC_state, pat,
6783                                 array, maxarg, NULL, recompile_p,
6784                                 /* $" */
6785                                 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6786
6787             continue;
6788         }
6789
6790
6791         /* we make the assumption here that each op in the list of
6792          * op_siblings maps to one SV pushed onto the stack,
6793          * except for code blocks, with have both an OP_NULL and
6794          * and OP_CONST.
6795          * This allows us to match up the list of SVs against the
6796          * list of OPs to find the next code block.
6797          *
6798          * Note that       PUSHMARK PADSV PADSV ..
6799          * is optimised to
6800          *                 PADRANGE PADSV  PADSV  ..
6801          * so the alignment still works. */
6802
6803         if (oplist) {
6804             if (oplist->op_type == OP_NULL
6805                 && (oplist->op_flags & OPf_SPECIAL))
6806             {
6807                 assert(n < pRExC_state->code_blocks->count);
6808                 pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0;
6809                 pRExC_state->code_blocks->cb[n].block = oplist;
6810                 pRExC_state->code_blocks->cb[n].src_regex = NULL;
6811                 n++;
6812                 code = 1;
6813                 oplist = OpSIBLING(oplist); /* skip CONST */
6814                 assert(oplist);
6815             }
6816             oplist = OpSIBLING(oplist);;
6817         }
6818
6819         /* apply magic and QR overloading to arg */
6820
6821         SvGETMAGIC(msv);
6822         if (SvROK(msv) && SvAMAGIC(msv)) {
6823             SV *sv = AMG_CALLunary(msv, regexp_amg);
6824             if (sv) {
6825                 if (SvROK(sv))
6826                     sv = SvRV(sv);
6827                 if (SvTYPE(sv) != SVt_REGEXP)
6828                     Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6829                 msv = sv;
6830             }
6831         }
6832
6833         /* try concatenation overload ... */
6834         if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6835                 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6836         {
6837             sv_setsv(pat, sv);
6838             /* overloading involved: all bets are off over literal
6839              * code. Pretend we haven't seen it */
6840             if (n)
6841                 pRExC_state->code_blocks->count -= n;
6842             n = 0;
6843         }
6844         else  {
6845             /* ... or failing that, try "" overload */
6846             while (SvAMAGIC(msv)
6847                     && (sv = AMG_CALLunary(msv, string_amg))
6848                     && sv != msv
6849                     &&  !(   SvROK(msv)
6850                           && SvROK(sv)
6851                           && SvRV(msv) == SvRV(sv))
6852             ) {
6853                 msv = sv;
6854                 SvGETMAGIC(msv);
6855             }
6856             if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6857                 msv = SvRV(msv);
6858
6859             if (pat) {
6860                 /* this is a partially unrolled
6861                  *     sv_catsv_nomg(pat, msv);
6862                  * that allows us to adjust code block indices if
6863                  * needed */
6864                 STRLEN dlen;
6865                 char *dst = SvPV_force_nomg(pat, dlen);
6866                 orig_patlen = dlen;
6867                 if (SvUTF8(msv) && !SvUTF8(pat)) {
6868                     S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6869                     sv_setpvn(pat, dst, dlen);
6870                     SvUTF8_on(pat);
6871                 }
6872                 sv_catsv_nomg(pat, msv);
6873                 rx = msv;
6874             }
6875             else {
6876                 /* We have only one SV to process, but we need to verify
6877                  * it is properly null terminated or we will fail asserts
6878                  * later. In theory we probably shouldn't get such SV's,
6879                  * but if we do we should handle it gracefully. */
6880                 if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) {
6881                     /* not a string, or a string with a trailing null */
6882                     pat = msv;
6883                 } else {
6884                     /* a string with no trailing null, we need to copy it
6885                      * so it has a trailing null */
6886                     pat = sv_2mortal(newSVsv(msv));
6887                 }
6888             }
6889
6890             if (code)
6891                 pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1;
6892         }
6893
6894         /* extract any code blocks within any embedded qr//'s */
6895         if (rx && SvTYPE(rx) == SVt_REGEXP
6896             && RX_ENGINE((REGEXP*)rx)->op_comp)
6897         {
6898
6899             RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6900             if (ri->code_blocks && ri->code_blocks->count) {
6901                 int i;
6902                 /* the presence of an embedded qr// with code means
6903                  * we should always recompile: the text of the
6904                  * qr// may not have changed, but it may be a
6905                  * different closure than last time */
6906                 *recompile_p = 1;
6907                 if (pRExC_state->code_blocks) {
6908                     int new_count = pRExC_state->code_blocks->count
6909                             + ri->code_blocks->count;
6910                     Renew(pRExC_state->code_blocks->cb,
6911                             new_count, struct reg_code_block);
6912                     pRExC_state->code_blocks->count = new_count;
6913                 }
6914                 else
6915                     pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_
6916                                                     ri->code_blocks->count);
6917
6918                 for (i=0; i < ri->code_blocks->count; i++) {
6919                     struct reg_code_block *src, *dst;
6920                     STRLEN offset =  orig_patlen
6921                         + ReANY((REGEXP *)rx)->pre_prefix;
6922                     assert(n < pRExC_state->code_blocks->count);
6923                     src = &ri->code_blocks->cb[i];
6924                     dst = &pRExC_state->code_blocks->cb[n];
6925                     dst->start      = src->start + offset;
6926                     dst->end        = src->end   + offset;
6927                     dst->block      = src->block;
6928                     dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
6929                                             src->src_regex
6930                                                 ? src->src_regex
6931                                                 : (REGEXP*)rx);
6932                     n++;
6933                 }
6934             }
6935         }
6936     }
6937     /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6938     if (alloced)
6939         SvSETMAGIC(pat);
6940
6941     return pat;
6942 }
6943
6944
6945
6946 /* see if there are any run-time code blocks in the pattern.
6947  * False positives are allowed */
6948
6949 static bool
6950 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6951                     char *pat, STRLEN plen)
6952 {
6953     int n = 0;
6954     STRLEN s;
6955
6956     PERL_UNUSED_CONTEXT;
6957
6958     for (s = 0; s < plen; s++) {
6959         if (   pRExC_state->code_blocks
6960             && n < pRExC_state->code_blocks->count
6961             && s == pRExC_state->code_blocks->cb[n].start)
6962         {
6963             s = pRExC_state->code_blocks->cb[n].end;
6964             n++;
6965             continue;
6966         }
6967         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
6968          * positives here */
6969         if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
6970             (pat[s+2] == '{'
6971                 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
6972         )
6973             return 1;
6974     }
6975     return 0;
6976 }
6977
6978 /* Handle run-time code blocks. We will already have compiled any direct
6979  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
6980  * copy of it, but with any literal code blocks blanked out and
6981  * appropriate chars escaped; then feed it into
6982  *
6983  *    eval "qr'modified_pattern'"
6984  *
6985  * For example,
6986  *
6987  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
6988  *
6989  * becomes
6990  *
6991  *    qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
6992  *
6993  * After eval_sv()-ing that, grab any new code blocks from the returned qr
6994  * and merge them with any code blocks of the original regexp.
6995  *
6996  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
6997  * instead, just save the qr and return FALSE; this tells our caller that
6998  * the original pattern needs upgrading to utf8.
6999  */
7000
7001 static bool
7002 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
7003     char *pat, STRLEN plen)
7004 {
7005     SV *qr;
7006
7007     GET_RE_DEBUG_FLAGS_DECL;
7008
7009     if (pRExC_state->runtime_code_qr) {
7010         /* this is the second time we've been called; this should
7011          * only happen if the main pattern got upgraded to utf8
7012          * during compilation; re-use the qr we compiled first time
7013          * round (which should be utf8 too)
7014          */
7015         qr = pRExC_state->runtime_code_qr;
7016         pRExC_state->runtime_code_qr = NULL;
7017         assert(RExC_utf8 && SvUTF8(qr));
7018     }
7019     else {
7020         int n = 0;
7021         STRLEN s;
7022         char *p, *newpat;
7023         int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */
7024         SV *sv, *qr_ref;
7025         dSP;
7026
7027         /* determine how many extra chars we need for ' and \ escaping */
7028         for (s = 0; s < plen; s++) {
7029             if (pat[s] == '\'' || pat[s] == '\\')
7030                 newlen++;
7031         }
7032
7033         Newx(newpat, newlen, char);
7034         p = newpat;
7035         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
7036
7037         for (s = 0; s < plen; s++) {
7038             if (   pRExC_state->code_blocks
7039                 && n < pRExC_state->code_blocks->count
7040                 && s == pRExC_state->code_blocks->cb[n].start)
7041             {
7042                 /* blank out literal code block so that they aren't
7043                  * recompiled: eg change from/to:
7044                  *     /(?{xyz})/
7045                  *     /(?=====)/
7046                  * and
7047                  *     /(??{xyz})/
7048                  *     /(?======)/
7049                  * and
7050                  *     /(?(?{xyz}))/
7051                  *     /(?(?=====))/
7052                 */
7053                 assert(pat[s]   == '(');
7054                 assert(pat[s+1] == '?');
7055                 *p++ = '(';
7056                 *p++ = '?';
7057                 s += 2;
7058                 while (s < pRExC_state->code_blocks->cb[n].end) {
7059                     *p++ = '=';
7060                     s++;
7061                 }
7062                 *p++ = ')';
7063                 n++;
7064                 continue;
7065             }
7066             if (pat[s] == '\'' || pat[s] == '\\')
7067                 *p++ = '\\';
7068             *p++ = pat[s];
7069         }
7070         *p++ = '\'';
7071         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) {
7072             *p++ = 'x';
7073             if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) {
7074                 *p++ = 'x';
7075             }
7076         }
7077         *p++ = '\0';
7078         DEBUG_COMPILE_r({
7079             Perl_re_printf( aTHX_
7080                 "%sre-parsing pattern for runtime code:%s %s\n",
7081                 PL_colors[4], PL_colors[5], newpat);
7082         });
7083
7084         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
7085         Safefree(newpat);
7086
7087         ENTER;
7088         SAVETMPS;
7089         save_re_context();
7090         PUSHSTACKi(PERLSI_REQUIRE);
7091         /* G_RE_REPARSING causes the toker to collapse \\ into \ when
7092          * parsing qr''; normally only q'' does this. It also alters
7093          * hints handling */
7094         eval_sv(sv, G_SCALAR|G_RE_REPARSING);
7095         SvREFCNT_dec_NN(sv);
7096         SPAGAIN;
7097         qr_ref = POPs;
7098         PUTBACK;
7099         {
7100             SV * const errsv = ERRSV;
7101             if (SvTRUE_NN(errsv))
7102                 /* use croak_sv ? */
7103                 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
7104         }
7105         assert(SvROK(qr_ref));
7106         qr = SvRV(qr_ref);
7107         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
7108         /* the leaving below frees the tmp qr_ref.
7109          * Give qr a life of its own */
7110         SvREFCNT_inc(qr);
7111         POPSTACK;
7112         FREETMPS;
7113         LEAVE;
7114
7115     }
7116
7117     if (!RExC_utf8 && SvUTF8(qr)) {
7118         /* first time through; the pattern got upgraded; save the
7119          * qr for the next time through */
7120         assert(!pRExC_state->runtime_code_qr);
7121         pRExC_state->runtime_code_qr = qr;
7122         return 0;
7123     }
7124
7125
7126     /* extract any code blocks within the returned qr//  */
7127
7128
7129     /* merge the main (r1) and run-time (r2) code blocks into one */
7130     {
7131         RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
7132         struct reg_code_block *new_block, *dst;
7133         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
7134         int i1 = 0, i2 = 0;
7135         int r1c, r2c;
7136
7137         if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */
7138         {
7139             SvREFCNT_dec_NN(qr);
7140             return 1;
7141         }
7142
7143         if (!r1->code_blocks)
7144             r1->code_blocks = S_alloc_code_blocks(aTHX_ 0);
7145
7146         r1c = r1->code_blocks->count;
7147         r2c = r2->code_blocks->count;
7148
7149         Newx(new_block, r1c + r2c, struct reg_code_block);
7150
7151         dst = new_block;
7152
7153         while (i1 < r1c || i2 < r2c) {
7154             struct reg_code_block *src;
7155             bool is_qr = 0;
7156
7157             if (i1 == r1c) {
7158                 src = &r2->code_blocks->cb[i2++];
7159                 is_qr = 1;
7160             }
7161             else if (i2 == r2c)
7162                 src = &r1->code_blocks->cb[i1++];
7163             else if (  r1->code_blocks->cb[i1].start
7164                      < r2->code_blocks->cb[i2].start)
7165             {
7166                 src = &r1->code_blocks->cb[i1++];
7167                 assert(src->end < r2->code_blocks->cb[i2].start);
7168             }
7169             else {
7170                 assert(  r1->code_blocks->cb[i1].start
7171                        > r2->code_blocks->cb[i2].start);
7172                 src = &r2->code_blocks->cb[i2++];
7173                 is_qr = 1;
7174                 assert(src->end < r1->code_blocks->cb[i1].start);
7175             }
7176
7177             assert(pat[src->start] == '(');
7178             assert(pat[src->end]   == ')');
7179             dst->start      = src->start;
7180             dst->end        = src->end;
7181             dst->block      = src->block;
7182             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
7183                                     : src->src_regex;
7184             dst++;
7185         }
7186         r1->code_blocks->count += r2c;
7187         Safefree(r1->code_blocks->cb);
7188         r1->code_blocks->cb = new_block;
7189     }
7190
7191     SvREFCNT_dec_NN(qr);
7192     return 1;
7193 }
7194
7195
7196 STATIC bool
7197 S_setup_longest(pTHX_ RExC_state_t *pRExC_state,
7198                       struct reg_substr_datum  *rsd,
7199                       struct scan_data_substrs *sub,
7200                       STRLEN longest_length)
7201 {
7202     /* This is the common code for setting up the floating and fixed length
7203      * string data extracted from Perl_re_op_compile() below.  Returns a boolean
7204      * as to whether succeeded or not */
7205
7206     I32 t;
7207     SSize_t ml;
7208     bool eol  = cBOOL(sub->flags & SF_BEFORE_EOL);
7209     bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL);
7210
7211     if (! (longest_length
7212            || (eol /* Can't have SEOL and MULTI */
7213                && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
7214           )
7215             /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
7216         || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
7217     {
7218         return FALSE;
7219     }
7220
7221     /* copy the information about the longest from the reg_scan_data
7222         over to the program. */
7223     if (SvUTF8(sub->str)) {
7224         rsd->substr      = NULL;
7225         rsd->utf8_substr = sub->str;
7226     } else {
7227         rsd->substr      = sub->str;
7228         rsd->utf8_substr = NULL;
7229     }
7230     /* end_shift is how many chars that must be matched that
7231         follow this item. We calculate it ahead of time as once the
7232         lookbehind offset is added in we lose the ability to correctly
7233         calculate it.*/
7234     ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length;
7235     rsd->end_shift = ml - sub->min_offset
7236         - longest_length
7237             /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL
7238              * intead? - DAPM
7239             + (SvTAIL(sub->str) != 0)
7240             */
7241         + sub->lookbehind;
7242
7243     t = (eol/* Can't have SEOL and MULTI */
7244          && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
7245     fbm_compile(sub->str, t ? FBMcf_TAIL : 0);
7246
7247     return TRUE;
7248 }
7249
7250 STATIC void
7251 S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx)
7252 {
7253     /* Calculates and sets in the compiled pattern 'Rx' the string to compile,
7254      * properly wrapped with the right modifiers */
7255
7256     bool has_p     = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7257     bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags)
7258                                                 != REGEX_DEPENDS_CHARSET);
7259
7260     /* The caret is output if there are any defaults: if not all the STD
7261         * flags are set, or if no character set specifier is needed */
7262     bool has_default =
7263                 (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7264                 || ! has_charset);
7265     bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7266                                                 == REG_RUN_ON_COMMENT_SEEN);
7267     U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD)
7268                         >> RXf_PMf_STD_PMMOD_SHIFT);
7269     const char *fptr = STD_PAT_MODS;        /*"msixxn"*/
7270     char *p;
7271     STRLEN pat_len = RExC_precomp_end - RExC_precomp;
7272
7273     /* We output all the necessary flags; we never output a minus, as all
7274         * those are defaults, so are
7275         * covered by the caret */
7276     const STRLEN wraplen = pat_len + has_p + has_runon
7277         + has_default       /* If needs a caret */
7278         + PL_bitcount[reganch] /* 1 char for each set standard flag */
7279
7280             /* If needs a character set specifier */
7281         + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7282         + (sizeof("(?:)") - 1);
7283
7284     PERL_ARGS_ASSERT_SET_REGEX_PV;
7285
7286     /* make sure PL_bitcount bounds not exceeded */
7287     assert(sizeof(STD_PAT_MODS) <= 8);
7288
7289     p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */
7290     SvPOK_on(Rx);
7291     if (RExC_utf8)
7292         SvFLAGS(Rx) |= SVf_UTF8;
7293     *p++='('; *p++='?';
7294
7295     /* If a default, cover it using the caret */
7296     if (has_default) {
7297         *p++= DEFAULT_PAT_MOD;
7298     }
7299     if (has_charset) {
7300         STRLEN len;
7301         const char* name;
7302
7303         name = get_regex_charset_name(RExC_rx->extflags, &len);
7304         if (strEQ(name, DEPENDS_PAT_MODS)) {  /* /d under UTF-8 => /u */
7305             assert(RExC_utf8);
7306             name = UNICODE_PAT_MODS;
7307             len = sizeof(UNICODE_PAT_MODS) - 1;
7308         }
7309         Copy(name, p, len, char);
7310         p += len;
7311     }
7312     if (has_p)
7313         *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7314     {
7315         char ch;
7316         while((ch = *fptr++)) {
7317             if(reganch & 1)
7318                 *p++ = ch;
7319             reganch >>= 1;
7320         }
7321     }
7322
7323     *p++ = ':';
7324     Copy(RExC_precomp, p, pat_len, char);
7325     assert ((RX_WRAPPED(Rx) - p) < 16);
7326     RExC_rx->pre_prefix = p - RX_WRAPPED(Rx);
7327     p += pat_len;
7328
7329     /* Adding a trailing \n causes this to compile properly:
7330             my $R = qr / A B C # D E/x; /($R)/
7331         Otherwise the parens are considered part of the comment */
7332     if (has_runon)
7333         *p++ = '\n';
7334     *p++ = ')';
7335     *p = 0;
7336     SvCUR_set(Rx, p - RX_WRAPPED(Rx));
7337 }
7338
7339 /*
7340  * Perl_re_op_compile - the perl internal RE engine's function to compile a
7341  * regular expression into internal code.
7342  * The pattern may be passed either as:
7343  *    a list of SVs (patternp plus pat_count)
7344  *    a list of OPs (expr)
7345  * If both are passed, the SV list is used, but the OP list indicates
7346  * which SVs are actually pre-compiled code blocks
7347  *
7348  * The SVs in the list have magic and qr overloading applied to them (and
7349  * the list may be modified in-place with replacement SVs in the latter
7350  * case).
7351  *
7352  * If the pattern hasn't changed from old_re, then old_re will be
7353  * returned.
7354  *
7355  * eng is the current engine. If that engine has an op_comp method, then
7356  * handle directly (i.e. we assume that op_comp was us); otherwise, just
7357  * do the initial concatenation of arguments and pass on to the external
7358  * engine.
7359  *
7360  * If is_bare_re is not null, set it to a boolean indicating whether the
7361  * arg list reduced (after overloading) to a single bare regex which has
7362  * been returned (i.e. /$qr/).
7363  *
7364  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
7365  *
7366  * pm_flags contains the PMf_* flags, typically based on those from the
7367  * pm_flags field of the related PMOP. Currently we're only interested in
7368  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
7369  *
7370  * For many years this code had an initial sizing pass that calculated
7371  * (sometimes incorrectly, leading to security holes) the size needed for the
7372  * compiled pattern.  That was changed by commit
7373  * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a
7374  * node at a time, as parsing goes along.  Patches welcome to fix any obsolete
7375  * references to this sizing pass.
7376  *
7377  * Now, an initial crude guess as to the size needed is made, based on the
7378  * length of the pattern.  Patches welcome to improve that guess.  That amount
7379  * of space is malloc'd and then immediately freed, and then clawed back node
7380  * by node.  This design is to minimze, to the extent possible, memory churn
7381  * when doing the the reallocs.
7382  *
7383  * A separate parentheses counting pass may be needed in some cases.
7384  * (Previously the sizing pass did this.)  Patches welcome to reduce the number
7385  * of these cases.
7386  *
7387  * The existence of a sizing pass necessitated design decisions that are no
7388  * longer needed.  There are potential areas of simplification.
7389  *
7390  * Beware that the optimization-preparation code in here knows about some
7391  * of the structure of the compiled regexp.  [I'll say.]
7392  */
7393
7394 REGEXP *
7395 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
7396                     OP *expr, const regexp_engine* eng, REGEXP *old_re,
7397                      bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags)
7398 {
7399     dVAR;
7400     REGEXP *Rx;         /* Capital 'R' means points to a REGEXP */
7401     STRLEN plen;
7402     char *exp;
7403     regnode *scan;
7404     I32 flags;
7405     SSize_t minlen = 0;
7406     U32 rx_flags;
7407     SV *pat;
7408     SV** new_patternp = patternp;
7409
7410     /* these are all flags - maybe they should be turned
7411      * into a single int with different bit masks */
7412     I32 sawlookahead = 0;
7413     I32 sawplus = 0;
7414     I32 sawopen = 0;
7415     I32 sawminmod = 0;
7416
7417     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
7418     bool recompile = 0;
7419     bool runtime_code = 0;
7420     scan_data_t data;
7421     RExC_state_t RExC_state;
7422     RExC_state_t * const pRExC_state = &RExC_state;
7423 #ifdef TRIE_STUDY_OPT
7424     int restudied = 0;
7425     RExC_state_t copyRExC_state;
7426 #endif
7427     GET_RE_DEBUG_FLAGS_DECL;
7428
7429     PERL_ARGS_ASSERT_RE_OP_COMPILE;
7430
7431     DEBUG_r(if (!PL_colorset) reginitcolors());
7432
7433
7434     pRExC_state->warn_text = NULL;
7435     pRExC_state->unlexed_names = NULL;
7436     pRExC_state->code_blocks = NULL;
7437
7438     if (is_bare_re)
7439         *is_bare_re = FALSE;
7440
7441     if (expr && (expr->op_type == OP_LIST ||
7442                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
7443         /* allocate code_blocks if needed */
7444         OP *o;
7445         int ncode = 0;
7446
7447         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
7448             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
7449                 ncode++; /* count of DO blocks */
7450
7451         if (ncode)
7452             pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode);
7453     }
7454
7455     if (!pat_count) {
7456         /* compile-time pattern with just OP_CONSTs and DO blocks */
7457
7458         int n;
7459         OP *o;
7460
7461         /* find how many CONSTs there are */
7462         assert(expr);
7463         n = 0;
7464         if (expr->op_type == OP_CONST)
7465             n = 1;
7466         else
7467             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7468                 if (o->op_type == OP_CONST)
7469                     n++;
7470             }
7471
7472         /* fake up an SV array */
7473
7474         assert(!new_patternp);
7475         Newx(new_patternp, n, SV*);
7476         SAVEFREEPV(new_patternp);
7477         pat_count = n;
7478
7479         n = 0;
7480         if (expr->op_type == OP_CONST)
7481             new_patternp[n] = cSVOPx_sv(expr);
7482         else
7483             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
7484                 if (o->op_type == OP_CONST)
7485                     new_patternp[n++] = cSVOPo_sv;
7486             }
7487
7488     }
7489
7490     DEBUG_PARSE_r(Perl_re_printf( aTHX_
7491         "Assembling pattern from %d elements%s\n", pat_count,
7492             orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7493
7494     /* set expr to the first arg op */
7495
7496     if (pRExC_state->code_blocks && pRExC_state->code_blocks->count
7497          && expr->op_type != OP_CONST)
7498     {
7499             expr = cLISTOPx(expr)->op_first;
7500             assert(   expr->op_type == OP_PUSHMARK
7501                    || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
7502                    || expr->op_type == OP_PADRANGE);
7503             expr = OpSIBLING(expr);
7504     }
7505
7506     pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
7507                         expr, &recompile, NULL);
7508
7509     /* handle bare (possibly after overloading) regex: foo =~ $re */
7510     {
7511         SV *re = pat;
7512         if (SvROK(re))
7513             re = SvRV(re);
7514         if (SvTYPE(re) == SVt_REGEXP) {
7515             if (is_bare_re)
7516                 *is_bare_re = TRUE;
7517             SvREFCNT_inc(re);
7518             DEBUG_PARSE_r(Perl_re_printf( aTHX_
7519                 "Precompiled pattern%s\n",
7520                     orig_rx_flags & RXf_SPLIT ? " for split" : ""));
7521
7522             return (REGEXP*)re;
7523         }
7524     }
7525
7526     exp = SvPV_nomg(pat, plen);
7527
7528     if (!eng->op_comp) {
7529         if ((SvUTF8(pat) && IN_BYTES)
7530                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
7531         {
7532             /* make a temporary copy; either to convert to bytes,
7533              * or to avoid repeating get-magic / overloaded stringify */
7534             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
7535                                         (IN_BYTES ? 0 : SvUTF8(pat)));
7536         }
7537         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
7538     }
7539
7540     /* ignore the utf8ness if the pattern is 0 length */
7541     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
7542     RExC_uni_semantics = 0;
7543     RExC_contains_locale = 0;
7544     RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
7545     RExC_in_script_run = 0;
7546     RExC_study_started = 0;
7547     pRExC_state->runtime_code_qr = NULL;
7548     RExC_frame_head= NULL;
7549     RExC_frame_last= NULL;
7550     RExC_frame_count= 0;
7551     RExC_latest_warn_offset = 0;
7552     RExC_use_BRANCHJ = 0;
7553     RExC_total_parens = 0;
7554     RExC_open_parens = NULL;
7555     RExC_close_parens = NULL;
7556     RExC_paren_names = NULL;
7557     RExC_size = 0;
7558     RExC_seen_d_op = FALSE;
7559 #ifdef DEBUGGING
7560     RExC_paren_name_list = NULL;
7561 #endif
7562
7563     DEBUG_r({
7564         RExC_mysv1= sv_newmortal();
7565         RExC_mysv2= sv_newmortal();
7566     });
7567
7568     DEBUG_COMPILE_r({
7569             SV *dsv= sv_newmortal();
7570             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7571             Perl_re_printf( aTHX_  "%sCompiling REx%s %s\n",
7572                           PL_colors[4], PL_colors[5], s);
7573         });
7574
7575     /* we jump here if we have to recompile, e.g., from upgrading the pattern
7576      * to utf8 */
7577
7578     if ((pm_flags & PMf_USE_RE_EVAL)
7579                 /* this second condition covers the non-regex literal case,
7580                  * i.e.  $foo =~ '(?{})'. */
7581                 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
7582     )
7583         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
7584
7585   redo_parse:
7586     /* return old regex if pattern hasn't changed */
7587     /* XXX: note in the below we have to check the flags as well as the
7588      * pattern.
7589      *
7590      * Things get a touch tricky as we have to compare the utf8 flag
7591      * independently from the compile flags.  */
7592
7593     if (   old_re
7594         && !recompile
7595         && !!RX_UTF8(old_re) == !!RExC_utf8
7596         && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
7597         && RX_PRECOMP(old_re)
7598         && RX_PRELEN(old_re) == plen
7599         && memEQ(RX_PRECOMP(old_re), exp, plen)
7600         && !runtime_code /* with runtime code, always recompile */ )
7601     {
7602         DEBUG_COMPILE_r({
7603             SV *dsv= sv_newmortal();
7604             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len);
7605             Perl_re_printf( aTHX_  "%sSkipping recompilation of unchanged REx%s %s\n",
7606                           PL_colors[4], PL_colors[5], s);
7607         });
7608         return old_re;
7609     }
7610
7611     /* Allocate the pattern's SV */
7612     RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP);
7613     RExC_rx = ReANY(Rx);
7614     if ( RExC_rx == NULL )
7615         FAIL("Regexp out of space");
7616
7617     rx_flags = orig_rx_flags;
7618
7619     if (   (UTF || RExC_uni_semantics)
7620         && initial_charset == REGEX_DEPENDS_CHARSET)
7621     {
7622
7623         /* Set to use unicode semantics if the pattern is in utf8 and has the
7624          * 'depends' charset specified, as it means unicode when utf8  */
7625         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7626         RExC_uni_semantics = 1;
7627     }
7628
7629     RExC_pm_flags = pm_flags;
7630
7631     if (runtime_code) {
7632         assert(TAINTING_get || !TAINT_get);
7633         if (TAINT_get)
7634             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
7635
7636         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
7637             /* whoops, we have a non-utf8 pattern, whilst run-time code
7638              * got compiled as utf8. Try again with a utf8 pattern */
7639             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7640                 pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7641             goto redo_parse;
7642         }
7643     }
7644     assert(!pRExC_state->runtime_code_qr);
7645
7646     RExC_sawback = 0;
7647
7648     RExC_seen = 0;
7649     RExC_maxlen = 0;
7650     RExC_in_lookbehind = 0;
7651     RExC_in_lookahead = 0;
7652     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
7653     RExC_recode_x_to_native = 0;
7654     RExC_in_multi_char_class = 0;
7655
7656     RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp;
7657     RExC_precomp_end = RExC_end = exp + plen;
7658     RExC_nestroot = 0;
7659     RExC_whilem_seen = 0;
7660     RExC_end_op = NULL;
7661     RExC_recurse = NULL;
7662     RExC_study_chunk_recursed = NULL;
7663     RExC_study_chunk_recursed_bytes= 0;
7664     RExC_recurse_count = 0;
7665     pRExC_state->code_index = 0;
7666
7667     /* Initialize the string in the compiled pattern.  This is so that there is
7668      * something to output if necessary */
7669     set_regex_pv(pRExC_state, Rx);
7670
7671     DEBUG_PARSE_r({
7672         Perl_re_printf( aTHX_
7673             "Starting parse and generation\n");
7674         RExC_lastnum=0;
7675         RExC_lastparse=NULL;
7676     });
7677
7678     /* Allocate space and zero-initialize. Note, the two step process
7679        of zeroing when in debug mode, thus anything assigned has to
7680        happen after that */
7681     if (!  RExC_size) {
7682
7683         /* On the first pass of the parse, we guess how big this will be.  Then
7684          * we grow in one operation to that amount and then give it back.  As
7685          * we go along, we re-allocate what we need.
7686          *
7687          * XXX Currently the guess is essentially that the pattern will be an
7688          * EXACT node with one byte input, one byte output.  This is crude, and
7689          * better heuristics are welcome.
7690          *
7691          * On any subsequent passes, we guess what we actually computed in the
7692          * latest earlier pass.  Such a pass probably didn't complete so is
7693          * missing stuff.  We could improve those guesses by knowing where the
7694          * parse stopped, and use the length so far plus apply the above
7695          * assumption to what's left. */
7696         RExC_size = STR_SZ(RExC_end - RExC_start);
7697     }
7698
7699     Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal);
7700     if ( RExC_rxi == NULL )
7701         FAIL("Regexp out of space");
7702
7703     Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char);
7704     RXi_SET( RExC_rx, RExC_rxi );
7705
7706     /* We start from 0 (over from 0 in the case this is a reparse.  The first
7707      * node parsed will give back any excess memory we have allocated so far).
7708      * */
7709     RExC_size = 0;
7710
7711     /* non-zero initialization begins here */
7712     RExC_rx->engine= eng;
7713     RExC_rx->extflags = rx_flags;
7714     RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7715
7716     if (pm_flags & PMf_IS_QR) {
7717         RExC_rxi->code_blocks = pRExC_state->code_blocks;
7718         if (RExC_rxi->code_blocks) {
7719             RExC_rxi->code_blocks->refcnt++;
7720         }
7721     }
7722
7723     RExC_rx->intflags = 0;
7724
7725     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
7726     RExC_parse = exp;
7727
7728     /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
7729      * code makes sure the final byte is an uncounted NUL.  But should this
7730      * ever not be the case, lots of things could read beyond the end of the
7731      * buffer: loops like
7732      *      while(isFOO(*RExC_parse)) RExC_parse++;
7733      *      strchr(RExC_parse, "foo");
7734      * etc.  So it is worth noting. */
7735     assert(*RExC_end == '\0');
7736
7737     RExC_naughty = 0;
7738     RExC_npar = 1;
7739     RExC_parens_buf_size = 0;
7740     RExC_emit_start = RExC_rxi->program;
7741     pRExC_state->code_index = 0;
7742
7743     *((char*) RExC_emit_start) = (char) REG_MAGIC;
7744     RExC_emit = 1;
7745
7746     /* Do the parse */
7747     if (reg(pRExC_state, 0, &flags, 1)) {
7748
7749         /* Success!, But we may need to redo the parse knowing how many parens
7750          * there actually are */
7751         if (IN_PARENS_PASS) {
7752             flags |= RESTART_PARSE;
7753         }
7754
7755         /* We have that number in RExC_npar */
7756         RExC_total_parens = RExC_npar;
7757     }
7758     else if (! MUST_RESTART(flags)) {
7759         ReREFCNT_dec(Rx);
7760         Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags);
7761     }
7762
7763     /* Here, we either have success, or we have to redo the parse for some reason */
7764     if (MUST_RESTART(flags)) {
7765
7766         /* It's possible to write a regexp in ascii that represents Unicode
7767         codepoints outside of the byte range, such as via \x{100}. If we
7768         detect such a sequence we have to convert the entire pattern to utf8
7769         and then recompile, as our sizing calculation will have been based
7770         on 1 byte == 1 character, but we will need to use utf8 to encode
7771         at least some part of the pattern, and therefore must convert the whole
7772         thing.
7773         -- dmq */
7774         if (flags & NEED_UTF8) {
7775
7776             /* We have stored the offset of the final warning output so far.
7777              * That must be adjusted.  Any variant characters between the start
7778              * of the pattern and this warning count for 2 bytes in the final,
7779              * so just add them again */
7780             if (UNLIKELY(RExC_latest_warn_offset > 0)) {
7781                 RExC_latest_warn_offset +=
7782                             variant_under_utf8_count((U8 *) exp, (U8 *) exp
7783                                                 + RExC_latest_warn_offset);
7784             }
7785             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
7786             pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0);
7787             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n"));
7788         }
7789         else {
7790             DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n"));
7791         }
7792
7793         if (ALL_PARENS_COUNTED) {
7794             /* Make enough room for all the known parens, and zero it */
7795             Renew(RExC_open_parens, RExC_total_parens, regnode_offset);
7796             Zero(RExC_open_parens, RExC_total_parens, regnode_offset);
7797             RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
7798
7799             Renew(RExC_close_parens, RExC_total_parens, regnode_offset);
7800             Zero(RExC_close_parens, RExC_total_parens, regnode_offset);
7801         }
7802         else { /* Parse did not complete.  Reinitialize the parentheses
7803                   structures */
7804             RExC_total_parens = 0;
7805             if (RExC_open_parens) {
7806                 Safefree(RExC_open_parens);
7807                 RExC_open_parens = NULL;
7808             }
7809             if (RExC_close_parens) {
7810                 Safefree(RExC_close_parens);
7811                 RExC_close_parens = NULL;
7812             }
7813         }
7814
7815         /* Clean up what we did in this parse */
7816         SvREFCNT_dec_NN(RExC_rx_sv);
7817
7818         goto redo_parse;
7819     }
7820
7821     /* Here, we have successfully parsed and generated the pattern's program
7822      * for the regex engine.  We are ready to finish things up and look for
7823      * optimizations. */
7824
7825     /* Update the string to compile, with correct modifiers, etc */
7826     set_regex_pv(pRExC_state, Rx);
7827
7828     RExC_rx->nparens = RExC_total_parens - 1;
7829
7830     /* Uses the upper 4 bits of the FLAGS field, so keep within that size */
7831     if (RExC_whilem_seen > 15)
7832         RExC_whilem_seen = 15;
7833
7834     DEBUG_PARSE_r({
7835         Perl_re_printf( aTHX_
7836             "Required size %" IVdf " nodes\n", (IV)RExC_size);
7837         RExC_lastnum=0;
7838         RExC_lastparse=NULL;
7839     });
7840
7841 #ifdef RE_TRACK_PATTERN_OFFSETS
7842     DEBUG_OFFSETS_r(Perl_re_printf( aTHX_
7843                           "%s %" UVuf " bytes for offset annotations.\n",
7844                           RExC_offsets ? "Got" : "Couldn't get",
7845                           (UV)((RExC_offsets[0] * 2 + 1))));
7846     DEBUG_OFFSETS_r(if (RExC_offsets) {
7847         const STRLEN len = RExC_offsets[0];
7848         STRLEN i;
7849         GET_RE_DEBUG_FLAGS_DECL;
7850         Perl_re_printf( aTHX_
7851                       "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]);
7852         for (i = 1; i <= len; i++) {
7853             if (RExC_offsets[i*2-1] || RExC_offsets[i*2])
7854                 Perl_re_printf( aTHX_  "%" UVuf ":%" UVuf "[%" UVuf "] ",
7855                 (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]);
7856         }
7857         Perl_re_printf( aTHX_  "\n");
7858     });
7859
7860 #else
7861     SetProgLen(RExC_rxi,RExC_size);
7862 #endif
7863
7864     DEBUG_DUMP_PRE_OPTIMIZE_r({
7865         SV * const sv = sv_newmortal();
7866         RXi_GET_DECL(RExC_rx, ri);
7867         DEBUG_RExC_seen();
7868         Perl_re_printf( aTHX_ "Program before optimization:\n");
7869
7870         (void)dumpuntil(RExC_rx, ri->program, ri->program + 1, NULL, NULL,
7871                         sv, 0, 0);
7872     });
7873
7874     DEBUG_OPTIMISE_r(
7875         Perl_re_printf( aTHX_  "Starting post parse optimization\n");
7876     );
7877
7878     /* XXXX To minimize changes to RE engine we always allocate
7879        3-units-long substrs field. */
7880     Newx(RExC_rx->substrs, 1, struct reg_substr_data);
7881     if (RExC_recurse_count) {
7882         Newx(RExC_recurse, RExC_recurse_count, regnode *);
7883         SAVEFREEPV(RExC_recurse);
7884     }
7885
7886     if (RExC_seen & REG_RECURSE_SEEN) {
7887         /* Note, RExC_total_parens is 1 + the number of parens in a pattern.
7888          * So its 1 if there are no parens. */
7889         RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) +
7890                                          ((RExC_total_parens & 0x07) != 0);
7891         Newx(RExC_study_chunk_recursed,
7892              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7893         SAVEFREEPV(RExC_study_chunk_recursed);
7894     }
7895
7896   reStudy:
7897     RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7898     DEBUG_r(
7899         RExC_study_chunk_recursed_count= 0;
7900     );
7901     Zero(RExC_rx->substrs, 1, struct reg_substr_data);
7902     if (RExC_study_chunk_recursed) {
7903         Zero(RExC_study_chunk_recursed,
7904              RExC_study_chunk_recursed_bytes * RExC_total_parens, U8);
7905     }
7906
7907
7908 #ifdef TRIE_STUDY_OPT
7909     if (!restudied) {
7910         StructCopy(&zero_scan_data, &data, scan_data_t);
7911         copyRExC_state = RExC_state;
7912     } else {
7913         U32 seen=RExC_seen;
7914         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n"));
7915
7916         RExC_state = copyRExC_state;
7917         if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7918             RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7919         else
7920             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7921         StructCopy(&zero_scan_data, &data, scan_data_t);
7922     }
7923 #else
7924     StructCopy(&zero_scan_data, &data, scan_data_t);
7925 #endif
7926
7927     /* Dig out information for optimizations. */
7928     RExC_rx->extflags = RExC_flags; /* was pm_op */
7929     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7930
7931     if (UTF)
7932         SvUTF8_on(Rx);  /* Unicode in it? */
7933     RExC_rxi->regstclass = NULL;
7934     if (RExC_naughty >= TOO_NAUGHTY)    /* Probably an expensive pattern. */
7935         RExC_rx->intflags |= PREGf_NAUGHTY;
7936     scan = RExC_rxi->program + 1;               /* First BRANCH. */
7937
7938     /* testing for BRANCH here tells us whether there is "must appear"
7939        data in the pattern. If there is then we can use it for optimisations */
7940     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /*  Only one top-level choice.
7941                                                   */
7942         SSize_t fake;
7943         STRLEN longest_length[2];
7944         regnode_ssc ch_class; /* pointed to by data */
7945         int stclass_flag;
7946         SSize_t last_close = 0; /* pointed to by data */
7947         regnode *first= scan;
7948         regnode *first_next= regnext(first);
7949         int i;
7950
7951         /*
7952          * Skip introductions and multiplicators >= 1
7953          * so that we can extract the 'meat' of the pattern that must
7954          * match in the large if() sequence following.
7955          * NOTE that EXACT is NOT covered here, as it is normally
7956          * picked up by the optimiser separately.
7957          *
7958          * This is unfortunate as the optimiser isnt handling lookahead
7959          * properly currently.
7960          *
7961          */
7962         while ((OP(first) == OPEN && (sawopen = 1)) ||
7963                /* An OR of *one* alternative - should not happen now. */
7964             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
7965             /* for now we can't handle lookbehind IFMATCH*/
7966             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
7967             (OP(first) == PLUS) ||
7968             (OP(first) == MINMOD) ||
7969                /* An {n,m} with n>0 */
7970             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
7971             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
7972         {
7973                 /*
7974                  * the only op that could be a regnode is PLUS, all the rest
7975                  * will be regnode_1 or regnode_2.
7976                  *
7977                  * (yves doesn't think this is true)
7978                  */
7979                 if (OP(first) == PLUS)
7980                     sawplus = 1;
7981                 else {
7982                     if (OP(first) == MINMOD)
7983                         sawminmod = 1;
7984                     first += regarglen[OP(first)];
7985                 }
7986                 first = NEXTOPER(first);
7987                 first_next= regnext(first);
7988         }
7989
7990         /* Starting-point info. */
7991       again:
7992         DEBUG_PEEP("first:", first, 0, 0);
7993         /* Ignore EXACT as we deal with it later. */
7994         if (PL_regkind[OP(first)] == EXACT) {
7995             if (   OP(first) == EXACT
7996                 || OP(first) == LEXACT
7997                 || OP(first) == EXACT_REQ8
7998                 || OP(first) == LEXACT_REQ8
7999                 || OP(first) == EXACTL)
8000             {
8001                 NOOP;   /* Empty, get anchored substr later. */
8002             }
8003             else
8004                 RExC_rxi->regstclass = first;
8005         }
8006 #ifdef TRIE_STCLASS
8007         else if (PL_regkind[OP(first)] == TRIE &&
8008                 ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0)
8009         {
8010             /* this can happen only on restudy */
8011             RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
8012         }
8013 #endif
8014         else if (REGNODE_SIMPLE(OP(first)))
8015             RExC_rxi->regstclass = first;
8016         else if (PL_regkind[OP(first)] == BOUND ||
8017                  PL_regkind[OP(first)] == NBOUND)
8018             RExC_rxi->regstclass = first;
8019         else if (PL_regkind[OP(first)] == BOL) {
8020             RExC_rx->intflags |= (OP(first) == MBOL
8021                            ? PREGf_ANCH_MBOL
8022                            : PREGf_ANCH_SBOL);
8023             first = NEXTOPER(first);
8024             goto again;
8025         }
8026         else if (OP(first) == GPOS) {
8027             RExC_rx->intflags |= PREGf_ANCH_GPOS;
8028             first = NEXTOPER(first);
8029             goto again;
8030         }
8031         else if ((!sawopen || !RExC_sawback) &&
8032             !sawlookahead &&
8033             (OP(first) == STAR &&
8034             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
8035             !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks)
8036         {
8037             /* turn .* into ^.* with an implied $*=1 */
8038             const int type =
8039                 (OP(NEXTOPER(first)) == REG_ANY)
8040                     ? PREGf_ANCH_MBOL
8041                     : PREGf_ANCH_SBOL;
8042             RExC_rx->intflags |= (type | PREGf_IMPLICIT);
8043             first = NEXTOPER(first);
8044             goto again;
8045         }
8046         if (sawplus && !sawminmod && !sawlookahead
8047             && (!sawopen || !RExC_sawback)
8048             && !pRExC_state->code_blocks) /* May examine pos and $& */
8049             /* x+ must match at the 1st pos of run of x's */
8050             RExC_rx->intflags |= PREGf_SKIP;
8051
8052         /* Scan is after the zeroth branch, first is atomic matcher. */
8053 #ifdef TRIE_STUDY_OPT
8054         DEBUG_PARSE_r(
8055             if (!restudied)
8056                 Perl_re_printf( aTHX_  "first at %" IVdf "\n",
8057                               (IV)(first - scan + 1))
8058         );
8059 #else
8060         DEBUG_PARSE_r(
8061             Perl_re_printf( aTHX_  "first at %" IVdf "\n",
8062                 (IV)(first - scan + 1))
8063         );
8064 #endif
8065
8066
8067         /*
8068         * If there's something expensive in the r.e., find the
8069         * longest literal string that must appear and make it the
8070         * regmust.  Resolve ties in favor of later strings, since
8071         * the regstart check works with the beginning of the r.e.
8072         * and avoiding duplication strengthens checking.  Not a
8073         * strong reason, but sufficient in the absence of others.
8074         * [Now we resolve ties in favor of the earlier string if
8075         * it happens that c_offset_min has been invalidated, since the
8076         * earlier string may buy us something the later one won't.]
8077         */
8078
8079         data.substrs[0].str = newSVpvs("");
8080         data.substrs[1].str = newSVpvs("");
8081         data.last_found = newSVpvs("");
8082         data.cur_is_floating = 0; /* initially any found substring is fixed */
8083         ENTER_with_name("study_chunk");
8084         SAVEFREESV(data.substrs[0].str);
8085         SAVEFREESV(data.substrs[1].str);
8086         SAVEFREESV(data.last_found);
8087         first = scan;
8088         if (!RExC_rxi->regstclass) {
8089             ssc_init(pRExC_state, &ch_class);
8090             data.start_class = &ch_class;
8091             stclass_flag = SCF_DO_STCLASS_AND;
8092         } else                          /* XXXX Check for BOUND? */
8093             stclass_flag = 0;
8094         data.last_closep = &last_close;
8095
8096         DEBUG_RExC_seen();
8097         /*
8098          * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/
8099          * (NO top level branches)
8100          */
8101         minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
8102                              scan + RExC_size, /* Up to end */
8103             &data, -1, 0, NULL,
8104             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
8105                           | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
8106             0);
8107
8108
8109         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
8110
8111
8112         if ( RExC_total_parens == 1 && !data.cur_is_floating
8113              && data.last_start_min == 0 && data.last_end > 0
8114              && !RExC_seen_zerolen
8115              && !(RExC_seen & REG_VERBARG_SEEN)
8116              && !(RExC_seen & REG_GPOS_SEEN)
8117         ){
8118             RExC_rx->extflags |= RXf_CHECK_ALL;
8119         }
8120         scan_commit(pRExC_state, &data,&minlen, 0);
8121
8122
8123         /* XXX this is done in reverse order because that's the way the
8124          * code was before it was parameterised. Don't know whether it
8125          * actually needs doing in reverse order. DAPM */
8126         for (i = 1; i >= 0; i--) {
8127             longest_length[i] = CHR_SVLEN(data.substrs[i].str);
8128
8129             if (   !(   i
8130                      && SvCUR(data.substrs[0].str)  /* ok to leave SvCUR */
8131                      &&    data.substrs[0].min_offset
8132                         == data.substrs[1].min_offset
8133                      &&    SvCUR(data.substrs[0].str)
8134                         == SvCUR(data.substrs[1].str)
8135                     )
8136                 && S_setup_longest (aTHX_ pRExC_state,
8137                                         &(RExC_rx->substrs->data[i]),
8138                                         &(data.substrs[i]),
8139                                         longest_length[i]))
8140             {
8141                 RExC_rx->substrs->data[i].min_offset =
8142                         data.substrs[i].min_offset - data.substrs[i].lookbehind;
8143
8144                 RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset;
8145                 /* Don't offset infinity */
8146                 if (data.substrs[i].max_offset < SSize_t_MAX)
8147                     RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind;
8148                 SvREFCNT_inc_simple_void_NN(data.substrs[i].str);
8149             }
8150             else {
8151                 RExC_rx->substrs->data[i].substr      = NULL;
8152                 RExC_rx->substrs->data[i].utf8_substr = NULL;
8153                 longest_length[i] = 0;
8154             }
8155         }
8156
8157         LEAVE_with_name("study_chunk");
8158
8159         if (RExC_rxi->regstclass
8160             && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY))
8161             RExC_rxi->regstclass = NULL;
8162
8163         if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr)
8164               || RExC_rx->substrs->data[0].min_offset)
8165             && stclass_flag
8166             && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8167             && is_ssc_worth_it(pRExC_state, data.start_class))
8168         {
8169             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8170
8171             ssc_finalize(pRExC_state, data.start_class);
8172
8173             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8174             StructCopy(data.start_class,
8175                        (regnode_ssc*)RExC_rxi->data->data[n],
8176                        regnode_ssc);
8177             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8178             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
8179             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
8180                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8181                       Perl_re_printf( aTHX_
8182                                     "synthetic stclass \"%s\".\n",
8183                                     SvPVX_const(sv));});
8184             data.start_class = NULL;
8185         }
8186
8187         /* A temporary algorithm prefers floated substr to fixed one of
8188          * same length to dig more info. */
8189         i = (longest_length[0] <= longest_length[1]);
8190         RExC_rx->substrs->check_ix = i;
8191         RExC_rx->check_end_shift  = RExC_rx->substrs->data[i].end_shift;
8192         RExC_rx->check_substr     = RExC_rx->substrs->data[i].substr;
8193         RExC_rx->check_utf8       = RExC_rx->substrs->data[i].utf8_substr;
8194         RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset;
8195         RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset;
8196         if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS)))
8197             RExC_rx->intflags |= PREGf_NOSCAN;
8198
8199         if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) {
8200             RExC_rx->extflags |= RXf_USE_INTUIT;
8201             if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8))
8202                 RExC_rx->extflags |= RXf_INTUIT_TAIL;
8203         }
8204
8205         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
8206         if ( (STRLEN)minlen < longest_length[1] )
8207             minlen= longest_length[1];
8208         if ( (STRLEN)minlen < longest_length[0] )
8209             minlen= longest_length[0];
8210         */
8211     }
8212     else {
8213         /* Several toplevels. Best we can is to set minlen. */
8214         SSize_t fake;
8215         regnode_ssc ch_class;
8216         SSize_t last_close = 0;
8217
8218         DEBUG_PARSE_r(Perl_re_printf( aTHX_  "\nMulti Top Level\n"));
8219
8220         scan = RExC_rxi->program + 1;
8221         ssc_init(pRExC_state, &ch_class);
8222         data.start_class = &ch_class;
8223         data.last_closep = &last_close;
8224
8225         DEBUG_RExC_seen();
8226         /*
8227          * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../
8228          * (patterns WITH top level branches)
8229          */
8230         minlen = study_chunk(pRExC_state,
8231             &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
8232             SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
8233                                                       ? SCF_TRIE_DOING_RESTUDY
8234                                                       : 0),
8235             0);
8236
8237         CHECK_RESTUDY_GOTO_butfirst(NOOP);
8238
8239         RExC_rx->check_substr = NULL;
8240         RExC_rx->check_utf8 = NULL;
8241         RExC_rx->substrs->data[0].substr      = NULL;
8242         RExC_rx->substrs->data[0].utf8_substr = NULL;
8243         RExC_rx->substrs->data[1].substr      = NULL;
8244         RExC_rx->substrs->data[1].utf8_substr = NULL;
8245
8246         if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
8247             && is_ssc_worth_it(pRExC_state, data.start_class))
8248         {
8249             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
8250
8251             ssc_finalize(pRExC_state, data.start_class);
8252
8253             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
8254             StructCopy(data.start_class,
8255                        (regnode_ssc*)RExC_rxi->data->data[n],
8256                        regnode_ssc);
8257             RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n];
8258             RExC_rx->intflags &= ~PREGf_SKIP;   /* Used in find_byclass(). */
8259             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
8260                       regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state);
8261                       Perl_re_printf( aTHX_
8262                                     "synthetic stclass \"%s\".\n",
8263                                     SvPVX_const(sv));});
8264             data.start_class = NULL;
8265         }
8266     }
8267
8268     if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
8269         RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
8270         RExC_rx->maxlen = REG_INFTY;
8271     }
8272     else {
8273         RExC_rx->maxlen = RExC_maxlen;
8274     }
8275
8276     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
8277        the "real" pattern. */
8278     DEBUG_OPTIMISE_r({
8279         Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n",
8280                       (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen);
8281     });
8282     RExC_rx->minlenret = minlen;
8283     if (RExC_rx->minlen < minlen)
8284         RExC_rx->minlen = minlen;
8285
8286     if (RExC_seen & REG_RECURSE_SEEN ) {
8287         RExC_rx->intflags |= PREGf_RECURSE_SEEN;
8288         Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *);
8289     }
8290     if (RExC_seen & REG_GPOS_SEEN)
8291         RExC_rx->intflags |= PREGf_GPOS_SEEN;
8292     if (RExC_seen & REG_LOOKBEHIND_SEEN)
8293         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
8294                                                 lookbehind */
8295     if (pRExC_state->code_blocks)
8296         RExC_rx->extflags |= RXf_EVAL_SEEN;
8297     if (RExC_seen & REG_VERBARG_SEEN)
8298     {
8299         RExC_rx->intflags |= PREGf_VERBARG_SEEN;
8300         RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
8301     }
8302     if (RExC_seen & REG_CUTGROUP_SEEN)
8303         RExC_rx->intflags |= PREGf_CUTGROUP_SEEN;
8304     if (pm_flags & PMf_USE_RE_EVAL)
8305         RExC_rx->intflags |= PREGf_USE_RE_EVAL;
8306     if (RExC_paren_names)
8307         RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
8308     else
8309         RXp_PAREN_NAMES(RExC_rx) = NULL;
8310
8311     /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
8312      * so it can be used in pp.c */
8313     if (RExC_rx->intflags & PREGf_ANCH)
8314         RExC_rx->extflags |= RXf_IS_ANCHORED;
8315
8316
8317     {
8318         /* this is used to identify "special" patterns that might result
8319          * in Perl NOT calling the regex engine and instead doing the match "itself",
8320          * particularly special cases in split//. By having the regex compiler
8321          * do this pattern matching at a regop level (instead of by inspecting the pattern)
8322          * we avoid weird issues with equivalent patterns resulting in different behavior,
8323          * AND we allow non Perl engines to get the same optimizations by the setting the
8324          * flags appropriately - Yves */
8325         regnode *first = RExC_rxi->program + 1;
8326         U8 fop = OP(first);
8327         regnode *next = regnext(first);
8328         U8 nop = OP(next);
8329
8330         if (PL_regkind[fop] == NOTHING && nop == END)
8331             RExC_rx->extflags |= RXf_NULL;
8332         else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
8333             /* when fop is SBOL first->flags will be true only when it was
8334              * produced by parsing /\A/, and not when parsing /^/. This is
8335              * very important for the split code as there we want to
8336              * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
8337              * See rt #122761 for more details. -- Yves */
8338             RExC_rx->extflags |= RXf_START_ONLY;
8339         else if (fop == PLUS
8340                  && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
8341                  && nop == END)
8342             RExC_rx->extflags |= RXf_WHITE;
8343         else if ( RExC_rx->extflags & RXf_SPLIT
8344                   && (   fop == EXACT || fop == LEXACT
8345                       || fop == EXACT_REQ8 || fop == LEXACT_REQ8
8346                       || fop == EXACTL)
8347                   && STR_LEN(first) == 1
8348                   && *(STRING(first)) == ' '
8349                   && nop == END )
8350             RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
8351
8352     }
8353
8354     if (RExC_contains_locale) {
8355         RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED;
8356     }
8357
8358 #ifdef DEBUGGING
8359     if (RExC_paren_names) {
8360         RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
8361         RExC_rxi->data->data[RExC_rxi->name_list_idx]
8362                                    = (void*)SvREFCNT_inc(RExC_paren_name_list);
8363     } else
8364 #endif
8365     RExC_rxi->name_list_idx = 0;
8366
8367     while ( RExC_recurse_count > 0 ) {
8368         const regnode *scan = RExC_recurse[ --RExC_recurse_count ];
8369         /*
8370          * This data structure is set up in study_chunk() and is used
8371          * to calculate the distance between a GOSUB regopcode and
8372          * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's)
8373          * it refers to.
8374          *
8375          * If for some reason someone writes code that optimises
8376          * away a GOSUB opcode then the assert should be changed to
8377          * an if(scan) to guard the ARG2L_SET() - Yves
8378          *
8379          */
8380         assert(scan && OP(scan) == GOSUB);
8381         ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan));
8382     }
8383
8384     Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair);
8385     /* assume we don't need to swap parens around before we match */
8386     DEBUG_TEST_r({
8387         Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n",
8388             (unsigned long)RExC_study_chunk_recursed_count);
8389     });
8390     DEBUG_DUMP_r({
8391         DEBUG_RExC_seen();
8392         Perl_re_printf( aTHX_ "Final program:\n");
8393         regdump(RExC_rx);
8394     });
8395
8396     if (RExC_open_parens) {
8397         Safefree(RExC_open_parens);
8398         RExC_open_parens = NULL;
8399     }
8400     if (RExC_close_parens) {
8401         Safefree(RExC_close_parens);
8402         RExC_close_parens = NULL;
8403     }
8404
8405 #ifdef USE_ITHREADS
8406     /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
8407      * by setting the regexp SV to readonly-only instead. If the
8408      * pattern's been recompiled, the USEDness should remain. */
8409     if (old_re && SvREADONLY(old_re))
8410         SvREADONLY_on(Rx);
8411 #endif
8412     return Rx;
8413 }
8414
8415
8416 SV*
8417 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
8418                     const U32 flags)
8419 {
8420     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
8421
8422     PERL_UNUSED_ARG(value);
8423
8424     if (flags & RXapif_FETCH) {
8425         return reg_named_buff_fetch(rx, key, flags);
8426     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
8427         Perl_croak_no_modify();
8428         return NULL;
8429     } else if (flags & RXapif_EXISTS) {
8430         return reg_named_buff_exists(rx, key, flags)
8431             ? &PL_sv_yes
8432             : &PL_sv_no;
8433     } else if (flags & RXapif_REGNAMES) {
8434         return reg_named_buff_all(rx, flags);
8435     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
8436         return reg_named_buff_scalar(rx, flags);
8437     } else {
8438         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
8439         return NULL;
8440     }
8441 }
8442
8443 SV*
8444 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
8445                          const U32 flags)
8446 {
8447     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
8448     PERL_UNUSED_ARG(lastkey);
8449
8450     if (flags & RXapif_FIRSTKEY)
8451         return reg_named_buff_firstkey(rx, flags);
8452     else if (flags & RXapif_NEXTKEY)
8453         return reg_named_buff_nextkey(rx, flags);
8454     else {
8455         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
8456                                             (int)flags);
8457         return NULL;
8458     }
8459 }
8460
8461 SV*
8462 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
8463                           const U32 flags)
8464 {
8465     SV *ret;
8466     struct regexp *const rx = ReANY(r);
8467
8468     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
8469
8470     if (rx && RXp_PAREN_NAMES(rx)) {
8471         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
8472         if (he_str) {
8473             IV i;
8474             SV* sv_dat=HeVAL(he_str);
8475             I32 *nums=(I32*)SvPVX(sv_dat);
8476             AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL;
8477             for ( i=0; i<SvIVX(sv_dat); i++ ) {
8478                 if ((I32)(rx->nparens) >= nums[i]
8479                     && rx->offs[nums[i]].start != -1
8480                     && rx->offs[nums[i]].end != -1)
8481                 {
8482                     ret = newSVpvs("");
8483                     CALLREG_NUMBUF_FETCH(r, nums[i], ret);
8484                     if (!retarray)
8485                         return ret;
8486                 } else {
8487                     if (retarray)
8488                         ret = newSVsv(&PL_sv_undef);
8489                 }
8490                 if (retarray)
8491                     av_push(retarray, ret);
8492             }
8493             if (retarray)
8494                 return newRV_noinc(MUTABLE_SV(retarray));
8495         }
8496     }
8497     return NULL;
8498 }
8499
8500 bool
8501 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
8502                            const U32 flags)
8503 {
8504     struct regexp *const rx = ReANY(r);
8505
8506     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
8507
8508     if (rx && RXp_PAREN_NAMES(rx)) {
8509         if (flags & RXapif_ALL) {
8510             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
8511         } else {
8512             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
8513             if (sv) {
8514                 SvREFCNT_dec_NN(sv);
8515                 return TRUE;
8516             } else {
8517                 return FALSE;
8518             }
8519         }
8520     } else {
8521         return FALSE;
8522     }
8523 }
8524
8525 SV*
8526 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
8527 {
8528     struct regexp *const rx = ReANY(r);
8529
8530     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
8531
8532     if ( rx && RXp_PAREN_NAMES(rx) ) {
8533         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
8534
8535         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
8536     } else {
8537         return FALSE;
8538     }
8539 }
8540
8541 SV*
8542 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
8543 {
8544     struct regexp *const rx = ReANY(r);
8545     GET_RE_DEBUG_FLAGS_DECL;
8546
8547     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
8548
8549     if (rx && RXp_PAREN_NAMES(rx)) {
8550         HV *hv = RXp_PAREN_NAMES(rx);
8551         HE *temphe;
8552         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8553             IV i;
8554             IV parno = 0;
8555             SV* sv_dat = HeVAL(temphe);
8556             I32 *nums = (I32*)SvPVX(sv_dat);
8557             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8558                 if ((I32)(rx->lastparen) >= nums[i] &&
8559                     rx->offs[nums[i]].start != -1 &&
8560                     rx->offs[nums[i]].end != -1)
8561                 {
8562                     parno = nums[i];
8563                     break;
8564                 }
8565             }
8566             if (parno || flags & RXapif_ALL) {
8567                 return newSVhek(HeKEY_hek(temphe));
8568             }
8569         }
8570     }
8571     return NULL;
8572 }
8573
8574 SV*
8575 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
8576 {
8577     SV *ret;
8578     AV *av;
8579     SSize_t length;
8580     struct regexp *const rx = ReANY(r);
8581
8582     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
8583
8584     if (rx && RXp_PAREN_NAMES(rx)) {
8585         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
8586             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
8587         } else if (flags & RXapif_ONE) {
8588             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
8589             av = MUTABLE_AV(SvRV(ret));
8590             length = av_tindex(av);
8591             SvREFCNT_dec_NN(ret);
8592             return newSViv(length + 1);
8593         } else {
8594             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
8595                                                 (int)flags);
8596             return NULL;
8597         }
8598     }
8599     return &PL_sv_undef;
8600 }
8601
8602 SV*
8603 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
8604 {
8605     struct regexp *const rx = ReANY(r);
8606     AV *av = newAV();
8607
8608     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
8609
8610     if (rx && RXp_PAREN_NAMES(rx)) {
8611         HV *hv= RXp_PAREN_NAMES(rx);
8612         HE *temphe;
8613         (void)hv_iterinit(hv);
8614         while ( (temphe = hv_iternext_flags(hv, 0)) ) {
8615             IV i;
8616             IV parno = 0;
8617             SV* sv_dat = HeVAL(temphe);
8618             I32 *nums = (I32*)SvPVX(sv_dat);
8619             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
8620                 if ((I32)(rx->lastparen) >= nums[i] &&
8621                     rx->offs[nums[i]].start != -1 &&
8622                     rx->offs[nums[i]].end != -1)
8623                 {
8624                     parno = nums[i];
8625                     break;
8626                 }
8627             }
8628             if (parno || flags & RXapif_ALL) {
8629                 av_push(av, newSVhek(HeKEY_hek(temphe)));
8630             }
8631         }
8632     }
8633
8634     return newRV_noinc(MUTABLE_SV(av));
8635 }
8636
8637 void
8638 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
8639                              SV * const sv)
8640 {
8641     struct regexp *const rx = ReANY(r);
8642     char *s = NULL;
8643     SSize_t i = 0;
8644     SSize_t s1, t1;
8645     I32 n = paren;
8646
8647     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
8648
8649     if (      n == RX_BUFF_IDX_CARET_PREMATCH
8650            || n == RX_BUFF_IDX_CARET_FULLMATCH
8651            || n == RX_BUFF_IDX_CARET_POSTMATCH
8652        )
8653     {
8654         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8655         if (!keepcopy) {
8656             /* on something like
8657              *    $r = qr/.../;
8658              *    /$qr/p;
8659              * the KEEPCOPY is set on the PMOP rather than the regex */
8660             if (PL_curpm && r == PM_GETRE(PL_curpm))
8661                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8662         }
8663         if (!keepcopy)
8664             goto ret_undef;
8665     }
8666
8667     if (!rx->subbeg)
8668         goto ret_undef;
8669
8670     if (n == RX_BUFF_IDX_CARET_FULLMATCH)
8671         /* no need to distinguish between them any more */
8672         n = RX_BUFF_IDX_FULLMATCH;
8673
8674     if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
8675         && rx->offs[0].start != -1)
8676     {
8677         /* $`, ${^PREMATCH} */
8678         i = rx->offs[0].start;
8679         s = rx->subbeg;
8680     }
8681     else
8682     if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
8683         && rx->offs[0].end != -1)
8684     {
8685         /* $', ${^POSTMATCH} */
8686         s = rx->subbeg - rx->suboffset + rx->offs[0].end;
8687         i = rx->sublen + rx->suboffset - rx->offs[0].end;
8688     }
8689     else
8690     if (inRANGE(n, 0, (I32)rx->nparens) &&
8691         (s1 = rx->offs[n].start) != -1  &&
8692         (t1 = rx->offs[n].end) != -1)
8693     {
8694         /* $&, ${^MATCH},  $1 ... */
8695         i = t1 - s1;
8696         s = rx->subbeg + s1 - rx->suboffset;
8697     } else {
8698         goto ret_undef;
8699     }
8700
8701     assert(s >= rx->subbeg);
8702     assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8703     if (i >= 0) {
8704 #ifdef NO_TAINT_SUPPORT
8705         sv_setpvn(sv, s, i);
8706 #else
8707         const int oldtainted = TAINT_get;
8708         TAINT_NOT;
8709         sv_setpvn(sv, s, i);
8710         TAINT_set(oldtainted);
8711 #endif
8712         if (RXp_MATCH_UTF8(rx))
8713             SvUTF8_on(sv);
8714         else
8715             SvUTF8_off(sv);
8716         if (TAINTING_get) {
8717             if (RXp_MATCH_TAINTED(rx)) {
8718                 if (SvTYPE(sv) >= SVt_PVMG) {
8719                     MAGIC* const mg = SvMAGIC(sv);
8720                     MAGIC* mgt;
8721                     TAINT;
8722                     SvMAGIC_set(sv, mg->mg_moremagic);
8723                     SvTAINT(sv);
8724                     if ((mgt = SvMAGIC(sv))) {
8725                         mg->mg_moremagic = mgt;
8726                         SvMAGIC_set(sv, mg);
8727                     }
8728                 } else {
8729                     TAINT;
8730                     SvTAINT(sv);
8731                 }
8732             } else
8733                 SvTAINTED_off(sv);
8734         }
8735     } else {
8736       ret_undef:
8737         sv_set_undef(sv);
8738         return;
8739     }
8740 }
8741
8742 void
8743 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8744                                                          SV const * const value)
8745 {
8746     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8747
8748     PERL_UNUSED_ARG(rx);
8749     PERL_UNUSED_ARG(paren);
8750     PERL_UNUSED_ARG(value);
8751
8752     if (!PL_localizing)
8753         Perl_croak_no_modify();
8754 }
8755
8756 I32
8757 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8758                               const I32 paren)
8759 {
8760     struct regexp *const rx = ReANY(r);
8761     I32 i;
8762     I32 s1, t1;
8763
8764     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8765
8766     if (   paren == RX_BUFF_IDX_CARET_PREMATCH
8767         || paren == RX_BUFF_IDX_CARET_FULLMATCH
8768         || paren == RX_BUFF_IDX_CARET_POSTMATCH
8769     )
8770     {
8771         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8772         if (!keepcopy) {
8773             /* on something like
8774              *    $r = qr/.../;
8775              *    /$qr/p;
8776              * the KEEPCOPY is set on the PMOP rather than the regex */
8777             if (PL_curpm && r == PM_GETRE(PL_curpm))
8778                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8779         }
8780         if (!keepcopy)
8781             goto warn_undef;
8782     }
8783
8784     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8785     switch (paren) {
8786       case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8787       case RX_BUFF_IDX_PREMATCH:       /* $` */
8788         if (rx->offs[0].start != -1) {
8789                         i = rx->offs[0].start;
8790                         if (i > 0) {
8791                                 s1 = 0;
8792                                 t1 = i;
8793                                 goto getlen;
8794                         }
8795             }
8796         return 0;
8797
8798       case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8799       case RX_BUFF_IDX_POSTMATCH:       /* $' */
8800             if (rx->offs[0].end != -1) {
8801                         i = rx->sublen - rx->offs[0].end;
8802                         if (i > 0) {
8803                                 s1 = rx->offs[0].end;
8804                                 t1 = rx->sublen;
8805                                 goto getlen;
8806                         }
8807             }
8808         return 0;
8809
8810       default: /* $& / ${^MATCH}, $1, $2, ... */
8811             if (paren <= (I32)rx->nparens &&
8812             (s1 = rx->offs[paren].start) != -1 &&
8813             (t1 = rx->offs[paren].end) != -1)
8814             {
8815             i = t1 - s1;
8816             goto getlen;
8817         } else {
8818           warn_undef:
8819             if (ckWARN(WARN_UNINITIALIZED))
8820                 report_uninit((const SV *)sv);
8821             return 0;
8822         }
8823     }
8824   getlen:
8825     if (i > 0 && RXp_MATCH_UTF8(rx)) {
8826         const char * const s = rx->subbeg - rx->suboffset + s1;
8827         const U8 *ep;
8828         STRLEN el;
8829
8830         i = t1 - s1;
8831         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8832                         i = el;
8833     }
8834     return i;
8835 }
8836
8837 SV*
8838 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8839 {
8840     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8841         PERL_UNUSED_ARG(rx);
8842         if (0)
8843             return NULL;
8844         else
8845             return newSVpvs("Regexp");
8846 }
8847
8848 /* Scans the name of a named buffer from the pattern.
8849  * If flags is REG_RSN_RETURN_NULL returns null.
8850  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8851  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8852  * to the parsed name as looked up in the RExC_paren_names hash.
8853  * If there is an error throws a vFAIL().. type exception.
8854  */
8855
8856 #define REG_RSN_RETURN_NULL    0
8857 #define REG_RSN_RETURN_NAME    1
8858 #define REG_RSN_RETURN_DATA    2
8859
8860 STATIC SV*
8861 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8862 {
8863     char *name_start = RExC_parse;
8864     SV* sv_name;
8865
8866     PERL_ARGS_ASSERT_REG_SCAN_NAME;
8867
8868     assert (RExC_parse <= RExC_end);
8869     if (RExC_parse == RExC_end) NOOP;
8870     else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) {
8871          /* Note that the code here assumes well-formed UTF-8.  Skip IDFIRST by
8872           * using do...while */
8873         if (UTF)
8874             do {
8875                 RExC_parse += UTF8SKIP(RExC_parse);
8876             } while (   RExC_parse < RExC_end
8877                      && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end));
8878         else
8879             do {
8880                 RExC_parse++;
8881             } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse));
8882     } else {
8883         RExC_parse++; /* so the <- from the vFAIL is after the offending
8884                          character */
8885         vFAIL("Group name must start with a non-digit word character");
8886     }
8887     sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8888                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8889     if ( flags == REG_RSN_RETURN_NAME)
8890         return sv_name;
8891     else if (flags==REG_RSN_RETURN_DATA) {
8892         HE *he_str = NULL;
8893         SV *sv_dat = NULL;
8894         if ( ! sv_name )      /* should not happen*/
8895             Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8896         if (RExC_paren_names)
8897             he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8898         if ( he_str )
8899             sv_dat = HeVAL(he_str);
8900         if ( ! sv_dat ) {   /* Didn't find group */
8901
8902             /* It might be a forward reference; we can't fail until we
8903                 * know, by completing the parse to get all the groups, and
8904                 * then reparsing */
8905             if (ALL_PARENS_COUNTED)  {
8906                 vFAIL("Reference to nonexistent named group");
8907             }
8908             else {
8909                 REQUIRE_PARENS_PASS;
8910             }
8911         }
8912         return sv_dat;
8913     }
8914
8915     Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8916                      (unsigned long) flags);
8917 }
8918
8919 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
8920     if (RExC_lastparse!=RExC_parse) {                           \
8921         Perl_re_printf( aTHX_  "%s",                            \
8922             Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse,        \
8923                 RExC_end - RExC_parse, 16,                      \
8924                 "", "",                                         \
8925                 PERL_PV_ESCAPE_UNI_DETECT |                     \
8926                 PERL_PV_PRETTY_ELLIPSES   |                     \
8927                 PERL_PV_PRETTY_LTGT       |                     \
8928                 PERL_PV_ESCAPE_RE         |                     \
8929                 PERL_PV_PRETTY_EXACTSIZE                        \
8930             )                                                   \
8931         );                                                      \
8932     } else                                                      \
8933         Perl_re_printf( aTHX_ "%16s","");                       \
8934                                                                 \
8935     if (RExC_lastnum!=RExC_emit)                                \
8936        Perl_re_printf( aTHX_ "|%4d", RExC_emit);                \
8937     else                                                        \
8938        Perl_re_printf( aTHX_ "|%4s","");                        \
8939     Perl_re_printf( aTHX_ "|%*s%-4s",                           \
8940         (int)((depth*2)), "",                                   \
8941         (funcname)                                              \
8942     );                                                          \
8943     RExC_lastnum=RExC_emit;                                     \
8944     RExC_lastparse=RExC_parse;                                  \
8945 })
8946
8947
8948
8949 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
8950     DEBUG_PARSE_MSG((funcname));                            \
8951     Perl_re_printf( aTHX_ "%4s","\n");                                  \
8952 })
8953 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({\
8954     DEBUG_PARSE_MSG((funcname));                            \
8955     Perl_re_printf( aTHX_ fmt "\n",args);                               \
8956 })
8957
8958 /* This section of code defines the inversion list object and its methods.  The
8959  * interfaces are highly subject to change, so as much as possible is static to
8960  * this file.  An inversion list is here implemented as a malloc'd C UV array
8961  * as an SVt_INVLIST scalar.
8962  *
8963  * An inversion list for Unicode is an array of code points, sorted by ordinal
8964  * number.  Each element gives the code point that begins a range that extends
8965  * up-to but not including the code point given by the next element.  The final
8966  * element gives the first code point of a range that extends to the platform's
8967  * infinity.  The even-numbered elements (invlist[0], invlist[2], invlist[4],
8968  * ...) give ranges whose code points are all in the inversion list.  We say
8969  * that those ranges are in the set.  The odd-numbered elements give ranges
8970  * whose code points are not in the inversion list, and hence not in the set.
8971  * Thus, element [0] is the first code point in the list.  Element [1]
8972  * is the first code point beyond that not in the list; and element [2] is the
8973  * first code point beyond that that is in the list.  In other words, the first
8974  * range is invlist[0]..(invlist[1]-1), and all code points in that range are
8975  * in the inversion list.  The second range is invlist[1]..(invlist[2]-1), and
8976  * all code points in that range are not in the inversion list.  The third
8977  * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion
8978  * list, and so forth.  Thus every element whose index is divisible by two
8979  * gives the beginning of a range that is in the list, and every element whose
8980  * index is not divisible by two gives the beginning of a range not in the
8981  * list.  If the final element's index is divisible by two, the inversion list
8982  * extends to the platform's infinity; otherwise the highest code point in the
8983  * inversion list is the contents of that element minus 1.
8984  *
8985  * A range that contains just a single code point N will look like
8986  *  invlist[i]   == N
8987  *  invlist[i+1] == N+1
8988  *
8989  * If N is UV_MAX (the highest representable code point on the machine), N+1 is
8990  * impossible to represent, so element [i+1] is omitted.  The single element
8991  * inversion list
8992  *  invlist[0] == UV_MAX
8993  * contains just UV_MAX, but is interpreted as matching to infinity.
8994  *
8995  * Taking the complement (inverting) an inversion list is quite simple, if the
8996  * first element is 0, remove it; otherwise add a 0 element at the beginning.
8997  * This implementation reserves an element at the beginning of each inversion
8998  * list to always contain 0; there is an additional flag in the header which
8999  * indicates if the list begins at the 0, or is offset to begin at the next
9000  * element.  This means that the inversion list can be inverted without any
9001  * copying; just flip the flag.
9002  *
9003  * More about inversion lists can be found in "Unicode Demystified"
9004  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
9005  *
9006  * The inversion list data structure is currently implemented as an SV pointing
9007  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
9008  * array of UV whose memory management is automatically handled by the existing
9009  * facilities for SV's.
9010  *
9011  * Some of the methods should always be private to the implementation, and some
9012  * should eventually be made public */
9013
9014 /* The header definitions are in F<invlist_inline.h> */
9015
9016 #ifndef PERL_IN_XSUB_RE
9017
9018 PERL_STATIC_INLINE UV*
9019 S__invlist_array_init(SV* const invlist, const bool will_have_0)
9020 {
9021     /* Returns a pointer to the first element in the inversion list's array.
9022      * This is called upon initialization of an inversion list.  Where the
9023      * array begins depends on whether the list has the code point U+0000 in it
9024      * or not.  The other parameter tells it whether the code that follows this
9025      * call is about to put a 0 in the inversion list or not.  The first
9026      * element is either the element reserved for 0, if TRUE, or the element
9027      * after it, if FALSE */
9028
9029     bool* offset = get_invlist_offset_addr(invlist);
9030     UV* zero_addr = (UV *) SvPVX(invlist);
9031
9032     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
9033
9034     /* Must be empty */
9035     assert(! _invlist_len(invlist));
9036
9037     *zero_addr = 0;
9038
9039     /* 1^1 = 0; 1^0 = 1 */
9040     *offset = 1 ^ will_have_0;
9041     return zero_addr + *offset;
9042 }
9043
9044 STATIC void
9045 S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src)
9046 {
9047     /* Replaces the inversion list in 'dest' with the one from 'src'.  It
9048      * steals the list from 'src', so 'src' is made to have a NULL list.  This
9049      * is similar to what SvSetMagicSV() would do, if it were implemented on
9050      * inversion lists, though this routine avoids a copy */
9051
9052     const UV src_len          = _invlist_len(src);
9053     const bool src_offset     = *get_invlist_offset_addr(src);
9054     const STRLEN src_byte_len = SvLEN(src);
9055     char * array              = SvPVX(src);
9056
9057     const int oldtainted = TAINT_get;
9058
9059     PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC;
9060
9061     assert(is_invlist(src));
9062     assert(is_invlist(dest));
9063     assert(! invlist_is_iterating(src));
9064     assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src));
9065
9066     /* Make sure it ends in the right place with a NUL, as our inversion list
9067      * manipulations aren't careful to keep this true, but sv_usepvn_flags()
9068      * asserts it */
9069     array[src_byte_len - 1] = '\0';
9070
9071     TAINT_NOT;      /* Otherwise it breaks */
9072     sv_usepvn_flags(dest,
9073                     (char *) array,
9074                     src_byte_len - 1,
9075
9076                     /* This flag is documented to cause a copy to be avoided */
9077                     SV_HAS_TRAILING_NUL);
9078     TAINT_set(oldtainted);
9079     SvPV_set(src, 0);
9080     SvLEN_set(src, 0);
9081     SvCUR_set(src, 0);
9082
9083     /* Finish up copying over the other fields in an inversion list */
9084     *get_invlist_offset_addr(dest) = src_offset;
9085     invlist_set_len(dest, src_len, src_offset);
9086     *get_invlist_previous_index_addr(dest) = 0;
9087     invlist_iterfinish(dest);
9088 }
9089
9090 PERL_STATIC_INLINE IV*
9091 S_get_invlist_previous_index_addr(SV* invlist)
9092 {
9093     /* Return the address of the IV that is reserved to hold the cached index
9094      * */
9095     PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
9096
9097     assert(is_invlist(invlist));
9098
9099     return &(((XINVLIST*) SvANY(invlist))->prev_index);
9100 }
9101
9102 PERL_STATIC_INLINE IV
9103 S_invlist_previous_index(SV* const invlist)
9104 {
9105     /* Returns cached index of previous search */
9106
9107     PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
9108
9109     return *get_invlist_previous_index_addr(invlist);
9110 }
9111
9112 PERL_STATIC_INLINE void
9113 S_invlist_set_previous_index(SV* const invlist, const IV index)
9114 {
9115     /* Caches <index> for later retrieval */
9116
9117     PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
9118
9119     assert(index == 0 || index < (int) _invlist_len(invlist));
9120
9121     *get_invlist_previous_index_addr(invlist) = index;
9122 }
9123
9124 PERL_STATIC_INLINE void
9125 S_invlist_trim(SV* invlist)
9126 {
9127     /* Free the not currently-being-used space in an inversion list */
9128
9129     /* But don't free up the space needed for the 0 UV that is always at the
9130      * beginning of the list, nor the trailing NUL */
9131     const UV min_size = TO_INTERNAL_SIZE(1) + 1;
9132
9133     PERL_ARGS_ASSERT_INVLIST_TRIM;
9134
9135     assert(is_invlist(invlist));
9136
9137     SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1));
9138 }
9139
9140 PERL_STATIC_INLINE void
9141 S_invlist_clear(pTHX_ SV* invlist)    /* Empty the inversion list */
9142 {
9143     PERL_ARGS_ASSERT_INVLIST_CLEAR;
9144
9145     assert(is_invlist(invlist));
9146
9147     invlist_set_len(invlist, 0, 0);
9148     invlist_trim(invlist);
9149 }
9150
9151 #endif /* ifndef PERL_IN_XSUB_RE */
9152
9153 PERL_STATIC_INLINE bool
9154 S_invlist_is_iterating(SV* const invlist)
9155 {
9156     PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
9157
9158     return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
9159 }
9160
9161 #ifndef PERL_IN_XSUB_RE
9162
9163 PERL_STATIC_INLINE UV
9164 S_invlist_max(SV* const invlist)
9165 {
9166     /* Returns the maximum number of elements storable in the inversion list's
9167      * array, without having to realloc() */
9168
9169     PERL_ARGS_ASSERT_INVLIST_MAX;
9170
9171     assert(is_invlist(invlist));
9172
9173     /* Assumes worst case, in which the 0 element is not counted in the
9174      * inversion list, so subtracts 1 for that */
9175     return SvLEN(invlist) == 0  /* This happens under _new_invlist_C_array */
9176            ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
9177            : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
9178 }
9179
9180 STATIC void
9181 S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size)
9182 {
9183     PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS;
9184
9185     /* First 1 is in case the zero element isn't in the list; second 1 is for
9186      * trailing NUL */
9187     SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1);
9188     invlist_set_len(invlist, 0, 0);
9189
9190     /* Force iterinit() to be used to get iteration to work */
9191     invlist_iterfinish(invlist);
9192
9193     *get_invlist_previous_index_addr(invlist) = 0;
9194     SvPOK_on(invlist);  /* This allows B to extract the PV */
9195 }
9196
9197 SV*
9198 Perl__new_invlist(pTHX_ IV initial_size)
9199 {
9200
9201     /* Return a pointer to a newly constructed inversion list, with enough
9202      * space to store 'initial_size' elements.  If that number is negative, a
9203      * system default is used instead */
9204
9205     SV* new_list;
9206
9207     if (initial_size < 0) {
9208         initial_size = 10;
9209     }
9210
9211     new_list = newSV_type(SVt_INVLIST);
9212     initialize_invlist_guts(new_list, initial_size);
9213
9214     return new_list;
9215 }
9216
9217 SV*
9218 Perl__new_invlist_C_array(pTHX_ const UV* const list)
9219 {
9220     /* Return a pointer to a newly constructed inversion list, initialized to
9221      * point to <list>, which has to be in the exact correct inversion list
9222      * form, including internal fields.  Thus this is a dangerous routine that
9223      * should not be used in the wrong hands.  The passed in 'list' contains
9224      * several header fields at the beginning that are not part of the
9225      * inversion list body proper */
9226
9227     const STRLEN length = (STRLEN) list[0];
9228     const UV version_id =          list[1];
9229     const bool offset   =    cBOOL(list[2]);
9230 #define HEADER_LENGTH 3
9231     /* If any of the above changes in any way, you must change HEADER_LENGTH
9232      * (if appropriate) and regenerate INVLIST_VERSION_ID by running
9233      *      perl -E 'say int(rand 2**31-1)'
9234      */
9235 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
9236                                         data structure type, so that one being
9237                                         passed in can be validated to be an
9238                                         inversion list of the correct vintage.
9239                                        */
9240
9241     SV* invlist = newSV_type(SVt_INVLIST);
9242
9243     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
9244
9245     if (version_id != INVLIST_VERSION_ID) {
9246         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
9247     }
9248
9249     /* The generated array passed in includes header elements that aren't part
9250      * of the list proper, so start it just after them */
9251     SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
9252
9253     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
9254                                shouldn't touch it */
9255
9256     *(get_invlist_offset_addr(invlist)) = offset;
9257
9258     /* The 'length' passed to us is the physical number of elements in the
9259      * inversion list.  But if there is an offset the logical number is one
9260      * less than that */
9261     invlist_set_len(invlist, length  - offset, offset);
9262
9263     invlist_set_previous_index(invlist, 0);
9264
9265     /* Initialize the iteration pointer. */
9266     invlist_iterfinish(invlist);
9267
9268     SvREADONLY_on(invlist);
9269     SvPOK_on(invlist);
9270
9271     return invlist;
9272 }
9273
9274 STATIC void
9275 S__append_range_to_invlist(pTHX_ SV* const invlist,
9276                                  const UV start, const UV end)
9277 {
9278    /* Subject to change or removal.  Append the range from 'start' to 'end' at
9279     * the end of the inversion list.  The range must be above any existing
9280     * ones. */
9281
9282     UV* array;
9283     UV max = invlist_max(invlist);
9284     UV len = _invlist_len(invlist);
9285     bool offset;
9286
9287     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
9288
9289     if (len == 0) { /* Empty lists must be initialized */
9290         offset = start != 0;
9291         array = _invlist_array_init(invlist, ! offset);
9292     }
9293     else {
9294         /* Here, the existing list is non-empty. The current max entry in the
9295          * list is generally the first value not in the set, except when the
9296          * set extends to the end of permissible values, in which case it is
9297          * the first entry in that final set, and so this call is an attempt to
9298          * append out-of-order */
9299
9300         UV final_element = len - 1;
9301         array = invlist_array(invlist);
9302         if (   array[final_element] > start
9303             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
9304         {
9305             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",
9306                      array[final_element], start,
9307                      ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
9308         }
9309
9310         /* Here, it is a legal append.  If the new range begins 1 above the end
9311          * of the range below it, it is extending the range below it, so the
9312          * new first value not in the set is one greater than the newly
9313          * extended range.  */
9314         offset = *get_invlist_offset_addr(invlist);
9315         if (array[final_element] == start) {
9316             if (end != UV_MAX) {
9317                 array[final_element] = end + 1;
9318             }
9319             else {
9320                 /* But if the end is the maximum representable on the machine,
9321                  * assume that infinity was actually what was meant.  Just let
9322                  * the range that this would extend to have no end */
9323                 invlist_set_len(invlist, len - 1, offset);
9324             }
9325             return;
9326         }
9327     }
9328
9329     /* Here the new range doesn't extend any existing set.  Add it */
9330
9331     len += 2;   /* Includes an element each for the start and end of range */
9332
9333     /* If wll overflow the existing space, extend, which may cause the array to
9334      * be moved */
9335     if (max < len) {
9336         invlist_extend(invlist, len);
9337
9338         /* Have to set len here to avoid assert failure in invlist_array() */
9339         invlist_set_len(invlist, len, offset);
9340
9341         array = invlist_array(invlist);
9342     }
9343     else {
9344         invlist_set_len(invlist, len, offset);
9345     }
9346
9347     /* The next item on the list starts the range, the one after that is
9348      * one past the new range.  */
9349     array[len - 2] = start;
9350     if (end != UV_MAX) {
9351         array[len - 1] = end + 1;
9352     }
9353     else {
9354         /* But if the end is the maximum representable on the machine, just let
9355          * the range have no end */
9356         invlist_set_len(invlist, len - 1, offset);
9357     }
9358 }
9359
9360 SSize_t
9361 Perl__invlist_search(SV* const invlist, const UV cp)
9362 {
9363     /* Searches the inversion list for the entry that contains the input code
9364      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
9365      * return value is the index into the list's array of the range that
9366      * contains <cp>, that is, 'i' such that
9367      *  array[i] <= cp < array[i+1]
9368      */
9369
9370     IV low = 0;
9371     IV mid;
9372     IV high = _invlist_len(invlist);
9373     const IV highest_element = high - 1;
9374     const UV* array;
9375
9376     PERL_ARGS_ASSERT__INVLIST_SEARCH;
9377
9378     /* If list is empty, return failure. */
9379     if (high == 0) {
9380         return -1;
9381     }
9382
9383     /* (We can't get the array unless we know the list is non-empty) */
9384     array = invlist_array(invlist);
9385
9386     mid = invlist_previous_index(invlist);
9387     assert(mid >=0);
9388     if (mid > highest_element) {
9389         mid = highest_element;
9390     }
9391
9392     /* <mid> contains the cache of the result of the previous call to this
9393      * function (0 the first time).  See if this call is for the same result,
9394      * or if it is for mid-1.  This is under the theory that calls to this
9395      * function will often be for related code points that are near each other.
9396      * And benchmarks show that caching gives better results.  We also test
9397      * here if the code point is within the bounds of the list.  These tests
9398      * replace others that would have had to be made anyway to make sure that
9399      * the array bounds were not exceeded, and these give us extra information
9400      * at the same time */
9401     if (cp >= array[mid]) {
9402         if (cp >= array[highest_element]) {
9403             return highest_element;
9404         }
9405
9406         /* Here, array[mid] <= cp < array[highest_element].  This means that
9407          * the final element is not the answer, so can exclude it; it also
9408          * means that <mid> is not the final element, so can refer to 'mid + 1'
9409          * safely */
9410         if (cp < array[mid + 1]) {
9411             return mid;
9412         }
9413         high--;
9414         low = mid + 1;
9415     }
9416     else { /* cp < aray[mid] */
9417         if (cp < array[0]) { /* Fail if outside the array */
9418             return -1;
9419         }
9420         high = mid;
9421         if (cp >= array[mid - 1]) {
9422             goto found_entry;
9423         }
9424     }
9425
9426     /* Binary search.  What we are looking for is <i> such that
9427      *  array[i] <= cp < array[i+1]
9428      * The loop below converges on the i+1.  Note that there may not be an
9429      * (i+1)th element in the array, and things work nonetheless */
9430     while (low < high) {
9431         mid = (low + high) / 2;
9432         assert(mid <= highest_element);
9433         if (array[mid] <= cp) { /* cp >= array[mid] */
9434             low = mid + 1;
9435
9436             /* We could do this extra test to exit the loop early.
9437             if (cp < array[low]) {
9438                 return mid;
9439             }
9440             */
9441         }
9442         else { /* cp < array[mid] */
9443             high = mid;
9444         }
9445     }
9446
9447   found_entry:
9448     high--;
9449     invlist_set_previous_index(invlist, high);
9450     return high;
9451 }
9452
9453 void
9454 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9455                                          const bool complement_b, SV** output)
9456 {
9457     /* Take the union of two inversion lists and point '*output' to it.  On
9458      * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9459      * even 'a' or 'b').  If to an inversion list, the contents of the original
9460      * list will be replaced by the union.  The first list, 'a', may be
9461      * NULL, in which case a copy of the second list is placed in '*output'.
9462      * If 'complement_b' is TRUE, the union is taken of the complement
9463      * (inversion) of 'b' instead of b itself.
9464      *
9465      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9466      * Richard Gillam, published by Addison-Wesley, and explained at some
9467      * length there.  The preface says to incorporate its examples into your
9468      * code at your own risk.
9469      *
9470      * The algorithm is like a merge sort. */
9471
9472     const UV* array_a;    /* a's array */
9473     const UV* array_b;
9474     UV len_a;       /* length of a's array */
9475     UV len_b;
9476
9477     SV* u;                      /* the resulting union */
9478     UV* array_u;
9479     UV len_u = 0;
9480
9481     UV i_a = 0;             /* current index into a's array */
9482     UV i_b = 0;
9483     UV i_u = 0;
9484
9485     /* running count, as explained in the algorithm source book; items are
9486      * stopped accumulating and are output when the count changes to/from 0.
9487      * The count is incremented when we start a range that's in an input's set,
9488      * and decremented when we start a range that's not in a set.  So this
9489      * variable can be 0, 1, or 2.  When it is 0 neither input is in their set,
9490      * and hence nothing goes into the union; 1, just one of the inputs is in
9491      * its set (and its current range gets added to the union); and 2 when both
9492      * inputs are in their sets.  */
9493     UV count = 0;
9494
9495     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
9496     assert(a != b);
9497     assert(*output == NULL || is_invlist(*output));
9498
9499     len_b = _invlist_len(b);
9500     if (len_b == 0) {
9501
9502         /* Here, 'b' is empty, hence it's complement is all possible code
9503          * points.  So if the union includes the complement of 'b', it includes
9504          * everything, and we need not even look at 'a'.  It's easiest to
9505          * create a new inversion list that matches everything.  */
9506         if (complement_b) {
9507             SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX);
9508
9509             if (*output == NULL) { /* If the output didn't exist, just point it
9510                                       at the new list */
9511                 *output = everything;
9512             }
9513             else { /* Otherwise, replace its contents with the new list */
9514                 invlist_replace_list_destroys_src(*output, everything);
9515                 SvREFCNT_dec_NN(everything);
9516             }
9517
9518             return;
9519         }
9520
9521         /* Here, we don't want the complement of 'b', and since 'b' is empty,
9522          * the union will come entirely from 'a'.  If 'a' is NULL or empty, the
9523          * output will be empty */
9524
9525         if (a == NULL || _invlist_len(a) == 0) {
9526             if (*output == NULL) {
9527                 *output = _new_invlist(0);
9528             }
9529             else {
9530                 invlist_clear(*output);
9531             }
9532             return;
9533         }
9534
9535         /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the
9536          * union.  We can just return a copy of 'a' if '*output' doesn't point
9537          * to an existing list */
9538         if (*output == NULL) {
9539             *output = invlist_clone(a, NULL);
9540             return;
9541         }
9542
9543         /* If the output is to overwrite 'a', we have a no-op, as it's
9544          * already in 'a' */
9545         if (*output == a) {
9546             return;
9547         }
9548
9549         /* Here, '*output' is to be overwritten by 'a' */
9550         u = invlist_clone(a, NULL);
9551         invlist_replace_list_destroys_src(*output, u);
9552         SvREFCNT_dec_NN(u);
9553
9554         return;
9555     }
9556
9557     /* Here 'b' is not empty.  See about 'a' */
9558
9559     if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
9560
9561         /* Here, 'a' is empty (and b is not).  That means the union will come
9562          * entirely from 'b'.  If '*output' is NULL, we can directly return a
9563          * clone of 'b'.  Otherwise, we replace the contents of '*output' with
9564          * the clone */
9565
9566         SV ** dest = (*output == NULL) ? output : &u;
9567         *dest = invlist_clone(b, NULL);
9568         if (complement_b) {
9569             _invlist_invert(*dest);
9570         }
9571
9572         if (dest == &u) {
9573             invlist_replace_list_destroys_src(*output, u);
9574             SvREFCNT_dec_NN(u);
9575         }
9576
9577         return;
9578     }
9579
9580     /* Here both lists exist and are non-empty */
9581     array_a = invlist_array(a);
9582     array_b = invlist_array(b);
9583
9584     /* If are to take the union of 'a' with the complement of b, set it
9585      * up so are looking at b's complement. */
9586     if (complement_b) {
9587
9588         /* To complement, we invert: if the first element is 0, remove it.  To
9589          * do this, we just pretend the array starts one later */
9590         if (array_b[0] == 0) {
9591             array_b++;
9592             len_b--;
9593         }
9594         else {
9595
9596             /* But if the first element is not zero, we pretend the list starts
9597              * at the 0 that is always stored immediately before the array. */
9598             array_b--;
9599             len_b++;
9600         }
9601     }
9602
9603     /* Size the union for the worst case: that the sets are completely
9604      * disjoint */
9605     u = _new_invlist(len_a + len_b);
9606
9607     /* Will contain U+0000 if either component does */
9608     array_u = _invlist_array_init(u, (    len_a > 0 && array_a[0] == 0)
9609                                       || (len_b > 0 && array_b[0] == 0));
9610
9611     /* Go through each input list item by item, stopping when have exhausted
9612      * one of them */
9613     while (i_a < len_a && i_b < len_b) {
9614         UV cp;      /* The element to potentially add to the union's array */
9615         bool cp_in_set;   /* is it in the the input list's set or not */
9616
9617         /* We need to take one or the other of the two inputs for the union.
9618          * Since we are merging two sorted lists, we take the smaller of the
9619          * next items.  In case of a tie, we take first the one that is in its
9620          * set.  If we first took the one not in its set, it would decrement
9621          * the count, possibly to 0 which would cause it to be output as ending
9622          * the range, and the next time through we would take the same number,
9623          * and output it again as beginning the next range.  By doing it the
9624          * opposite way, there is no possibility that the count will be
9625          * momentarily decremented to 0, and thus the two adjoining ranges will
9626          * be seamlessly merged.  (In a tie and both are in the set or both not
9627          * in the set, it doesn't matter which we take first.) */
9628         if (       array_a[i_a] < array_b[i_b]
9629             || (   array_a[i_a] == array_b[i_b]
9630                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9631         {
9632             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9633             cp = array_a[i_a++];
9634         }
9635         else {
9636             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9637             cp = array_b[i_b++];
9638         }
9639
9640         /* Here, have chosen which of the two inputs to look at.  Only output
9641          * if the running count changes to/from 0, which marks the
9642          * beginning/end of a range that's in the set */
9643         if (cp_in_set) {
9644             if (count == 0) {
9645                 array_u[i_u++] = cp;
9646             }
9647             count++;
9648         }
9649         else {
9650             count--;
9651             if (count == 0) {
9652                 array_u[i_u++] = cp;
9653             }
9654         }
9655     }
9656
9657
9658     /* The loop above increments the index into exactly one of the input lists
9659      * each iteration, and ends when either index gets to its list end.  That
9660      * means the other index is lower than its end, and so something is
9661      * remaining in that one.  We decrement 'count', as explained below, if
9662      * that list is in its set.  (i_a and i_b each currently index the element
9663      * beyond the one we care about.) */
9664     if (   (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9665         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9666     {
9667         count--;
9668     }
9669
9670     /* Above we decremented 'count' if the list that had unexamined elements in
9671      * it was in its set.  This has made it so that 'count' being non-zero
9672      * means there isn't anything left to output; and 'count' equal to 0 means
9673      * that what is left to output is precisely that which is left in the
9674      * non-exhausted input list.
9675      *
9676      * To see why, note first that the exhausted input obviously has nothing
9677      * left to add to the union.  If it was in its set at its end, that means
9678      * the set extends from here to the platform's infinity, and hence so does
9679      * the union and the non-exhausted set is irrelevant.  The exhausted set
9680      * also contributed 1 to 'count'.  If 'count' was 2, it got decremented to
9681      * 1, but if it was 1, the non-exhausted set wasn't in its set, and so
9682      * 'count' remains at 1.  This is consistent with the decremented 'count'
9683      * != 0 meaning there's nothing left to add to the union.
9684      *
9685      * But if the exhausted input wasn't in its set, it contributed 0 to
9686      * 'count', and the rest of the union will be whatever the other input is.
9687      * If 'count' was 0, neither list was in its set, and 'count' remains 0;
9688      * otherwise it gets decremented to 0.  This is consistent with 'count'
9689      * == 0 meaning the remainder of the union is whatever is left in the
9690      * non-exhausted list. */
9691     if (count != 0) {
9692         len_u = i_u;
9693     }
9694     else {
9695         IV copy_count = len_a - i_a;
9696         if (copy_count > 0) {   /* The non-exhausted input is 'a' */
9697             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9698         }
9699         else { /* The non-exhausted input is b */
9700             copy_count = len_b - i_b;
9701             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9702         }
9703         len_u = i_u + copy_count;
9704     }
9705
9706     /* Set the result to the final length, which can change the pointer to
9707      * array_u, so re-find it.  (Note that it is unlikely that this will
9708      * change, as we are shrinking the space, not enlarging it) */
9709     if (len_u != _invlist_len(u)) {
9710         invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9711         invlist_trim(u);
9712         array_u = invlist_array(u);
9713     }
9714
9715     if (*output == NULL) {  /* Simply return the new inversion list */
9716         *output = u;
9717     }
9718     else {
9719         /* Otherwise, overwrite the inversion list that was in '*output'.  We
9720          * could instead free '*output', and then set it to 'u', but experience
9721          * has shown [perl #127392] that if the input is a mortal, we can get a
9722          * huge build-up of these during regex compilation before they get
9723          * freed. */
9724         invlist_replace_list_destroys_src(*output, u);
9725         SvREFCNT_dec_NN(u);
9726     }
9727
9728     return;
9729 }
9730
9731 void
9732 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9733                                                const bool complement_b, SV** i)
9734 {
9735     /* Take the intersection of two inversion lists and point '*i' to it.  On
9736      * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly
9737      * even 'a' or 'b').  If to an inversion list, the contents of the original
9738      * list will be replaced by the intersection.  The first list, 'a', may be
9739      * NULL, in which case '*i' will be an empty list.  If 'complement_b' is
9740      * TRUE, the result will be the intersection of 'a' and the complement (or
9741      * inversion) of 'b' instead of 'b' directly.
9742      *
9743      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9744      * Richard Gillam, published by Addison-Wesley, and explained at some
9745      * length there.  The preface says to incorporate its examples into your
9746      * code at your own risk.  In fact, it had bugs
9747      *
9748      * The algorithm is like a merge sort, and is essentially the same as the
9749      * union above
9750      */
9751
9752     const UV* array_a;          /* a's array */
9753     const UV* array_b;
9754     UV len_a;   /* length of a's array */
9755     UV len_b;
9756
9757     SV* r;                   /* the resulting intersection */
9758     UV* array_r;
9759     UV len_r = 0;
9760
9761     UV i_a = 0;             /* current index into a's array */
9762     UV i_b = 0;
9763     UV i_r = 0;
9764
9765     /* running count of how many of the two inputs are postitioned at ranges
9766      * that are in their sets.  As explained in the algorithm source book,
9767      * items are stopped accumulating and are output when the count changes
9768      * to/from 2.  The count is incremented when we start a range that's in an
9769      * input's set, and decremented when we start a range that's not in a set.
9770      * Only when it is 2 are we in the intersection. */
9771     UV count = 0;
9772
9773     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9774     assert(a != b);
9775     assert(*i == NULL || is_invlist(*i));
9776
9777     /* Special case if either one is empty */
9778     len_a = (a == NULL) ? 0 : _invlist_len(a);
9779     if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9780         if (len_a != 0 && complement_b) {
9781
9782             /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b'
9783              * must be empty.  Here, also we are using 'b's complement, which
9784              * hence must be every possible code point.  Thus the intersection
9785              * is simply 'a'. */
9786
9787             if (*i == a) {  /* No-op */
9788                 return;
9789             }
9790
9791             if (*i == NULL) {
9792                 *i = invlist_clone(a, NULL);
9793                 return;
9794             }
9795
9796             r = invlist_clone(a, NULL);
9797             invlist_replace_list_destroys_src(*i, r);
9798             SvREFCNT_dec_NN(r);
9799             return;
9800         }
9801
9802         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
9803          * intersection must be empty */
9804         if (*i == NULL) {
9805             *i = _new_invlist(0);
9806             return;
9807         }
9808
9809         invlist_clear(*i);
9810         return;
9811     }
9812
9813     /* Here both lists exist and are non-empty */
9814     array_a = invlist_array(a);
9815     array_b = invlist_array(b);
9816
9817     /* If are to take the intersection of 'a' with the complement of b, set it
9818      * up so are looking at b's complement. */
9819     if (complement_b) {
9820
9821         /* To complement, we invert: if the first element is 0, remove it.  To
9822          * do this, we just pretend the array starts one later */
9823         if (array_b[0] == 0) {
9824             array_b++;
9825             len_b--;
9826         }
9827         else {
9828
9829             /* But if the first element is not zero, we pretend the list starts
9830              * at the 0 that is always stored immediately before the array. */
9831             array_b--;
9832             len_b++;
9833         }
9834     }
9835
9836     /* Size the intersection for the worst case: that the intersection ends up
9837      * fragmenting everything to be completely disjoint */
9838     r= _new_invlist(len_a + len_b);
9839
9840     /* Will contain U+0000 iff both components do */
9841     array_r = _invlist_array_init(r,    len_a > 0 && array_a[0] == 0
9842                                      && len_b > 0 && array_b[0] == 0);
9843
9844     /* Go through each list item by item, stopping when have exhausted one of
9845      * them */
9846     while (i_a < len_a && i_b < len_b) {
9847         UV cp;      /* The element to potentially add to the intersection's
9848                        array */
9849         bool cp_in_set; /* Is it in the input list's set or not */
9850
9851         /* We need to take one or the other of the two inputs for the
9852          * intersection.  Since we are merging two sorted lists, we take the
9853          * smaller of the next items.  In case of a tie, we take first the one
9854          * that is not in its set (a difference from the union algorithm).  If
9855          * we first took the one in its set, it would increment the count,
9856          * possibly to 2 which would cause it to be output as starting a range
9857          * in the intersection, and the next time through we would take that
9858          * same number, and output it again as ending the set.  By doing the
9859          * opposite of this, there is no possibility that the count will be
9860          * momentarily incremented to 2.  (In a tie and both are in the set or
9861          * both not in the set, it doesn't matter which we take first.) */
9862         if (       array_a[i_a] < array_b[i_b]
9863             || (   array_a[i_a] == array_b[i_b]
9864                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9865         {
9866             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9867             cp = array_a[i_a++];
9868         }
9869         else {
9870             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9871             cp= array_b[i_b++];
9872         }
9873
9874         /* Here, have chosen which of the two inputs to look at.  Only output
9875          * if the running count changes to/from 2, which marks the
9876          * beginning/end of a range that's in the intersection */
9877         if (cp_in_set) {
9878             count++;
9879             if (count == 2) {
9880                 array_r[i_r++] = cp;
9881             }
9882         }
9883         else {
9884             if (count == 2) {
9885                 array_r[i_r++] = cp;
9886             }
9887             count--;
9888         }
9889
9890     }
9891
9892     /* The loop above increments the index into exactly one of the input lists
9893      * each iteration, and ends when either index gets to its list end.  That
9894      * means the other index is lower than its end, and so something is
9895      * remaining in that one.  We increment 'count', as explained below, if the
9896      * exhausted list was in its set.  (i_a and i_b each currently index the
9897      * element beyond the one we care about.) */
9898     if (   (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9899         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9900     {
9901         count++;
9902     }
9903
9904     /* Above we incremented 'count' if the exhausted list was in its set.  This
9905      * has made it so that 'count' being below 2 means there is nothing left to
9906      * output; otheriwse what's left to add to the intersection is precisely
9907      * that which is left in the non-exhausted input list.
9908      *
9909      * To see why, note first that the exhausted input obviously has nothing
9910      * left to affect the intersection.  If it was in its set at its end, that
9911      * means the set extends from here to the platform's infinity, and hence
9912      * anything in the non-exhausted's list will be in the intersection, and
9913      * anything not in it won't be.  Hence, the rest of the intersection is
9914      * precisely what's in the non-exhausted list  The exhausted set also
9915      * contributed 1 to 'count', meaning 'count' was at least 1.  Incrementing
9916      * it means 'count' is now at least 2.  This is consistent with the
9917      * incremented 'count' being >= 2 means to add the non-exhausted list to
9918      * the intersection.
9919      *
9920      * But if the exhausted input wasn't in its set, it contributed 0 to
9921      * 'count', and the intersection can't include anything further; the
9922      * non-exhausted set is irrelevant.  'count' was at most 1, and doesn't get
9923      * incremented.  This is consistent with 'count' being < 2 meaning nothing
9924      * further to add to the intersection. */
9925     if (count < 2) { /* Nothing left to put in the intersection. */
9926         len_r = i_r;
9927     }
9928     else { /* copy the non-exhausted list, unchanged. */
9929         IV copy_count = len_a - i_a;
9930         if (copy_count > 0) {   /* a is the one with stuff left */
9931             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9932         }
9933         else {  /* b is the one with stuff left */
9934             copy_count = len_b - i_b;
9935             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9936         }
9937         len_r = i_r + copy_count;
9938     }
9939
9940     /* Set the result to the final length, which can change the pointer to
9941      * array_r, so re-find it.  (Note that it is unlikely that this will
9942      * change, as we are shrinking the space, not enlarging it) */
9943     if (len_r != _invlist_len(r)) {
9944         invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9945         invlist_trim(r);
9946         array_r = invlist_array(r);
9947     }
9948
9949     if (*i == NULL) { /* Simply return the calculated intersection */
9950         *i = r;
9951     }
9952     else { /* Otherwise, replace the existing inversion list in '*i'.  We could
9953               instead free '*i', and then set it to 'r', but experience has
9954               shown [perl #127392] that if the input is a mortal, we can get a
9955               huge build-up of these during regex compilation before they get
9956               freed. */
9957         if (len_r) {
9958             invlist_replace_list_destroys_src(*i, r);
9959         }
9960         else {
9961             invlist_clear(*i);
9962         }
9963         SvREFCNT_dec_NN(r);
9964     }
9965
9966     return;
9967 }
9968
9969 SV*
9970 Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end)
9971 {
9972     /* Add the range from 'start' to 'end' inclusive to the inversion list's
9973      * set.  A pointer to the inversion list is returned.  This may actually be
9974      * a new list, in which case the passed in one has been destroyed.  The
9975      * passed-in inversion list can be NULL, in which case a new one is created
9976      * with just the one range in it.  The new list is not necessarily
9977      * NUL-terminated.  Space is not freed if the inversion list shrinks as a
9978      * result of this function.  The gain would not be large, and in many
9979      * cases, this is called multiple times on a single inversion list, so
9980      * anything freed may almost immediately be needed again.
9981      *
9982      * This used to mostly call the 'union' routine, but that is much more
9983      * heavyweight than really needed for a single range addition */
9984
9985     UV* array;              /* The array implementing the inversion list */
9986     UV len;                 /* How many elements in 'array' */
9987     SSize_t i_s;            /* index into the invlist array where 'start'
9988                                should go */
9989     SSize_t i_e = 0;        /* And the index where 'end' should go */
9990     UV cur_highest;         /* The highest code point in the inversion list
9991                                upon entry to this function */
9992
9993     /* This range becomes the whole inversion list if none already existed */
9994     if (invlist == NULL) {
9995         invlist = _new_invlist(2);
9996         _append_range_to_invlist(invlist, start, end);
9997         return invlist;
9998     }
9999
10000     /* Likewise, if the inversion list is currently empty */
10001     len = _invlist_len(invlist);
10002     if (len == 0) {
10003         _append_range_to_invlist(invlist, start, end);
10004         return invlist;
10005     }
10006
10007     /* Starting here, we have to know the internals of the list */
10008     array = invlist_array(invlist);
10009
10010     /* If the new range ends higher than the current highest ... */
10011     cur_highest = invlist_highest(invlist);
10012     if (end > cur_highest) {
10013
10014         /* If the whole range is higher, we can just append it */
10015         if (start > cur_highest) {
10016             _append_range_to_invlist(invlist, start, end);
10017             return invlist;
10018         }
10019
10020         /* Otherwise, add the portion that is higher ... */
10021         _append_range_to_invlist(invlist, cur_highest + 1, end);
10022
10023         /* ... and continue on below to handle the rest.  As a result of the
10024          * above append, we know that the index of the end of the range is the
10025          * final even numbered one of the array.  Recall that the final element
10026          * always starts a range that extends to infinity.  If that range is in
10027          * the set (meaning the set goes from here to infinity), it will be an
10028          * even index, but if it isn't in the set, it's odd, and the final
10029          * range in the set is one less, which is even. */
10030         if (end == UV_MAX) {
10031             i_e = len;
10032         }
10033         else {
10034             i_e = len - 2;
10035         }
10036     }
10037
10038     /* We have dealt with appending, now see about prepending.  If the new
10039      * range starts lower than the current lowest ... */
10040     if (start < array[0]) {
10041
10042         /* Adding something which has 0 in it is somewhat tricky, and uncommon.
10043          * Let the union code handle it, rather than having to know the
10044          * trickiness in two code places.  */
10045         if (UNLIKELY(start == 0)) {
10046             SV* range_invlist;
10047
10048             range_invlist = _new_invlist(2);
10049             _append_range_to_invlist(range_invlist, start, end);
10050
10051             _invlist_union(invlist, range_invlist, &invlist);
10052
10053             SvREFCNT_dec_NN(range_invlist);
10054
10055             return invlist;
10056         }
10057
10058         /* If the whole new range comes before the first entry, and doesn't
10059          * extend it, we have to insert it as an additional range */
10060         if (end < array[0] - 1) {
10061             i_s = i_e = -1;
10062             goto splice_in_new_range;
10063         }
10064
10065         /* Here the new range adjoins the existing first range, extending it
10066          * downwards. */
10067         array[0] = start;
10068
10069         /* And continue on below to handle the rest.  We know that the index of
10070          * the beginning of the range is the first one of the array */
10071         i_s = 0;
10072     }
10073     else { /* Not prepending any part of the new range to the existing list.
10074             * Find where in the list it should go.  This finds i_s, such that:
10075             *     invlist[i_s] <= start < array[i_s+1]
10076             */
10077         i_s = _invlist_search(invlist, start);
10078     }
10079
10080     /* At this point, any extending before the beginning of the inversion list
10081      * and/or after the end has been done.  This has made it so that, in the
10082      * code below, each endpoint of the new range is either in a range that is
10083      * in the set, or is in a gap between two ranges that are.  This means we
10084      * don't have to worry about exceeding the array bounds.
10085      *
10086      * Find where in the list the new range ends (but we can skip this if we
10087      * have already determined what it is, or if it will be the same as i_s,
10088      * which we already have computed) */
10089     if (i_e == 0) {
10090         i_e = (start == end)
10091               ? i_s
10092               : _invlist_search(invlist, end);
10093     }
10094
10095     /* Here generally invlist[i_e] <= end < array[i_e+1].  But if invlist[i_e]
10096      * is a range that goes to infinity there is no element at invlist[i_e+1],
10097      * so only the first relation holds. */
10098
10099     if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10100
10101         /* Here, the ranges on either side of the beginning of the new range
10102          * are in the set, and this range starts in the gap between them.
10103          *
10104          * The new range extends the range above it downwards if the new range
10105          * ends at or above that range's start */
10106         const bool extends_the_range_above = (   end == UV_MAX
10107                                               || end + 1 >= array[i_s+1]);
10108
10109         /* The new range extends the range below it upwards if it begins just
10110          * after where that range ends */
10111         if (start == array[i_s]) {
10112
10113             /* If the new range fills the entire gap between the other ranges,
10114              * they will get merged together.  Other ranges may also get
10115              * merged, depending on how many of them the new range spans.  In
10116              * the general case, we do the merge later, just once, after we
10117              * figure out how many to merge.  But in the case where the new
10118              * range exactly spans just this one gap (possibly extending into
10119              * the one above), we do the merge here, and an early exit.  This
10120              * is done here to avoid having to special case later. */
10121             if (i_e - i_s <= 1) {
10122
10123                 /* If i_e - i_s == 1, it means that the new range terminates
10124                  * within the range above, and hence 'extends_the_range_above'
10125                  * must be true.  (If the range above it extends to infinity,
10126                  * 'i_s+2' will be above the array's limit, but 'len-i_s-2'
10127                  * will be 0, so no harm done.) */
10128                 if (extends_the_range_above) {
10129                     Move(array + i_s + 2, array + i_s, len - i_s - 2, UV);
10130                     invlist_set_len(invlist,
10131                                     len - 2,
10132                                     *(get_invlist_offset_addr(invlist)));
10133                     return invlist;
10134                 }
10135
10136                 /* Here, i_e must == i_s.  We keep them in sync, as they apply
10137                  * to the same range, and below we are about to decrement i_s
10138                  * */
10139                 i_e--;
10140             }
10141
10142             /* Here, the new range is adjacent to the one below.  (It may also
10143              * span beyond the range above, but that will get resolved later.)
10144              * Extend the range below to include this one. */
10145             array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1;
10146             i_s--;
10147             start = array[i_s];
10148         }
10149         else if (extends_the_range_above) {
10150
10151             /* Here the new range only extends the range above it, but not the
10152              * one below.  It merges with the one above.  Again, we keep i_e
10153              * and i_s in sync if they point to the same range */
10154             if (i_e == i_s) {
10155                 i_e++;
10156             }
10157             i_s++;
10158             array[i_s] = start;
10159         }
10160     }
10161
10162     /* Here, we've dealt with the new range start extending any adjoining
10163      * existing ranges.
10164      *
10165      * If the new range extends to infinity, it is now the final one,
10166      * regardless of what was there before */
10167     if (UNLIKELY(end == UV_MAX)) {
10168         invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist)));
10169         return invlist;
10170     }
10171
10172     /* If i_e started as == i_s, it has also been dealt with,
10173      * and been updated to the new i_s, which will fail the following if */
10174     if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) {
10175
10176         /* Here, the ranges on either side of the end of the new range are in
10177          * the set, and this range ends in the gap between them.
10178          *
10179          * If this range is adjacent to (hence extends) the range above it, it
10180          * becomes part of that range; likewise if it extends the range below,
10181          * it becomes part of that range */
10182         if (end + 1 == array[i_e+1]) {
10183             i_e++;
10184             array[i_e] = start;
10185         }
10186         else if (start <= array[i_e]) {
10187             array[i_e] = end + 1;
10188             i_e--;
10189         }
10190     }
10191
10192     if (i_s == i_e) {
10193
10194         /* If the range fits entirely in an existing range (as possibly already
10195          * extended above), it doesn't add anything new */
10196         if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) {
10197             return invlist;
10198         }
10199
10200         /* Here, no part of the range is in the list.  Must add it.  It will
10201          * occupy 2 more slots */
10202       splice_in_new_range:
10203
10204         invlist_extend(invlist, len + 2);
10205         array = invlist_array(invlist);
10206         /* Move the rest of the array down two slots. Don't include any
10207          * trailing NUL */
10208         Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV);
10209
10210         /* Do the actual splice */
10211         array[i_e+1] = start;
10212         array[i_e+2] = end + 1;
10213         invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist)));
10214         return invlist;
10215     }
10216
10217     /* Here the new range crossed the boundaries of a pre-existing range.  The
10218      * code above has adjusted things so that both ends are in ranges that are
10219      * in the set.  This means everything in between must also be in the set.
10220      * Just squash things together */
10221     Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV);
10222     invlist_set_len(invlist,
10223                     len - i_e + i_s,
10224                     *(get_invlist_offset_addr(invlist)));
10225
10226     return invlist;
10227 }
10228
10229 SV*
10230 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
10231                                  UV** other_elements_ptr)
10232 {
10233     /* Create and return an inversion list whose contents are to be populated
10234      * by the caller.  The caller gives the number of elements (in 'size') and
10235      * the very first element ('element0').  This function will set
10236      * '*other_elements_ptr' to an array of UVs, where the remaining elements
10237      * are to be placed.
10238      *
10239      * Obviously there is some trust involved that the caller will properly
10240      * fill in the other elements of the array.
10241      *
10242      * (The first element needs to be passed in, as the underlying code does
10243      * things differently depending on whether it is zero or non-zero) */
10244
10245     SV* invlist = _new_invlist(size);
10246     bool offset;
10247
10248     PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
10249
10250     invlist = add_cp_to_invlist(invlist, element0);
10251     offset = *get_invlist_offset_addr(invlist);
10252
10253     invlist_set_len(invlist, size, offset);
10254     *other_elements_ptr = invlist_array(invlist) + 1;
10255     return invlist;
10256 }
10257
10258 #endif
10259
10260 #ifndef PERL_IN_XSUB_RE
10261 void
10262 Perl__invlist_invert(pTHX_ SV* const invlist)
10263 {
10264     /* Complement the input inversion list.  This adds a 0 if the list didn't
10265      * have a zero; removes it otherwise.  As described above, the data
10266      * structure is set up so that this is very efficient */
10267
10268     PERL_ARGS_ASSERT__INVLIST_INVERT;
10269
10270     assert(! invlist_is_iterating(invlist));
10271
10272     /* The inverse of matching nothing is matching everything */
10273     if (_invlist_len(invlist) == 0) {
10274         _append_range_to_invlist(invlist, 0, UV_MAX);
10275         return;
10276     }
10277
10278     *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
10279 }
10280
10281 SV*
10282 Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist)
10283 {
10284     /* Return a new inversion list that is a copy of the input one, which is
10285      * unchanged.  The new list will not be mortal even if the old one was. */
10286
10287     const STRLEN nominal_length = _invlist_len(invlist);
10288     const STRLEN physical_length = SvCUR(invlist);
10289     const bool offset = *(get_invlist_offset_addr(invlist));
10290
10291     PERL_ARGS_ASSERT_INVLIST_CLONE;
10292
10293     if (new_invlist == NULL) {
10294         new_invlist = _new_invlist(nominal_length);
10295     }
10296     else {
10297         sv_upgrade(new_invlist, SVt_INVLIST);
10298         initialize_invlist_guts(new_invlist, nominal_length);
10299     }
10300
10301     *(get_invlist_offset_addr(new_invlist)) = offset;
10302     invlist_set_len(new_invlist, nominal_length, offset);
10303     Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
10304
10305     return new_invlist;
10306 }
10307
10308 #endif
10309
10310 PERL_STATIC_INLINE UV
10311 S_invlist_lowest(SV* const invlist)
10312 {
10313     /* Returns the lowest code point that matches an inversion list.  This API
10314      * has an ambiguity, as it returns 0 under either the lowest is actually
10315      * 0, or if the list is empty.  If this distinction matters to you, check
10316      * for emptiness before calling this function */
10317
10318     UV len = _invlist_len(invlist);
10319     UV *array;
10320
10321     PERL_ARGS_ASSERT_INVLIST_LOWEST;
10322
10323     if (len == 0) {
10324         return 0;
10325     }
10326
10327     array = invlist_array(invlist);
10328
10329     return array[0];
10330 }
10331
10332 STATIC SV *
10333 S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style)
10334 {
10335     /* Get the contents of an inversion list into a string SV so that they can
10336      * be printed out.  If 'traditional_style' is TRUE, it uses the format
10337      * traditionally done for debug tracing; otherwise it uses a format
10338      * suitable for just copying to the output, with blanks between ranges and
10339      * a dash between range components */
10340
10341     UV start, end;
10342     SV* output;
10343     const char intra_range_delimiter = (traditional_style ? '\t' : '-');
10344     const char inter_range_delimiter = (traditional_style ? '\n' : ' ');
10345
10346     if (traditional_style) {
10347         output = newSVpvs("\n");
10348     }
10349     else {
10350         output = newSVpvs("");
10351     }
10352
10353     PERL_ARGS_ASSERT_INVLIST_CONTENTS;
10354
10355     assert(! invlist_is_iterating(invlist));
10356
10357     invlist_iterinit(invlist);
10358     while (invlist_iternext(invlist, &start, &end)) {
10359         if (end == UV_MAX) {
10360             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c",
10361                                           start, intra_range_delimiter,
10362                                                  inter_range_delimiter);
10363         }
10364         else if (end != start) {
10365             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c",
10366                                           start,
10367                                                    intra_range_delimiter,
10368                                                   end, inter_range_delimiter);
10369         }
10370         else {
10371             Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c",
10372                                           start, inter_range_delimiter);
10373         }
10374     }
10375
10376     if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */
10377         SvCUR_set(output, SvCUR(output) - 1);
10378     }
10379
10380     return output;
10381 }
10382
10383 #ifndef PERL_IN_XSUB_RE
10384 void
10385 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
10386                          const char * const indent, SV* const invlist)
10387 {
10388     /* Designed to be called only by do_sv_dump().  Dumps out the ranges of the
10389      * inversion list 'invlist' to 'file' at 'level'  Each line is prefixed by
10390      * the string 'indent'.  The output looks like this:
10391          [0] 0x000A .. 0x000D
10392          [2] 0x0085
10393          [4] 0x2028 .. 0x2029
10394          [6] 0x3104 .. INFTY
10395      * This means that the first range of code points matched by the list are
10396      * 0xA through 0xD; the second range contains only the single code point
10397      * 0x85, etc.  An inversion list is an array of UVs.  Two array elements
10398      * are used to define each range (except if the final range extends to
10399      * infinity, only a single element is needed).  The array index of the
10400      * first element for the corresponding range is given in brackets. */
10401
10402     UV start, end;
10403     STRLEN count = 0;
10404
10405     PERL_ARGS_ASSERT__INVLIST_DUMP;
10406
10407     if (invlist_is_iterating(invlist)) {
10408         Perl_dump_indent(aTHX_ level, file,
10409              "%sCan't dump inversion list because is in middle of iterating\n",
10410              indent);
10411         return;
10412     }
10413
10414     invlist_iterinit(invlist);
10415     while (invlist_iternext(invlist, &start, &end)) {
10416         if (end == UV_MAX) {
10417             Perl_dump_indent(aTHX_ level, file,
10418                                        "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n",
10419                                    indent, (UV)count, start);
10420         }
10421         else if (end != start) {
10422             Perl_dump_indent(aTHX_ level, file,
10423                                     "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n",
10424                                 indent, (UV)count, start,         end);
10425         }
10426         else {
10427             Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n",
10428                                             indent, (UV)count, start);
10429         }
10430         count += 2;
10431     }
10432 }
10433
10434 #endif
10435
10436 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
10437 bool
10438 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
10439 {
10440     /* Return a boolean as to if the two passed in inversion lists are
10441      * identical.  The final argument, if TRUE, says to take the complement of
10442      * the second inversion list before doing the comparison */
10443
10444     const UV len_a = _invlist_len(a);
10445     UV len_b = _invlist_len(b);
10446
10447     const UV* array_a = NULL;
10448     const UV* array_b = NULL;
10449
10450     PERL_ARGS_ASSERT__INVLISTEQ;
10451
10452     /* This code avoids accessing the arrays unless it knows the length is
10453      * non-zero */
10454
10455     if (len_a == 0) {
10456         if (len_b == 0) {
10457             return ! complement_b;
10458         }
10459     }
10460     else {
10461         array_a = invlist_array(a);
10462     }
10463
10464     if (len_b != 0) {
10465         array_b = invlist_array(b);
10466     }
10467
10468     /* If are to compare 'a' with the complement of b, set it
10469      * up so are looking at b's complement. */
10470     if (complement_b) {
10471
10472         /* The complement of nothing is everything, so <a> would have to have
10473          * just one element, starting at zero (ending at infinity) */
10474         if (len_b == 0) {
10475             return (len_a == 1 && array_a[0] == 0);
10476         }
10477         if (array_b[0] == 0) {
10478
10479             /* Otherwise, to complement, we invert.  Here, the first element is
10480              * 0, just remove it.  To do this, we just pretend the array starts
10481              * one later */
10482
10483             array_b++;
10484             len_b--;
10485         }
10486         else {
10487
10488             /* But if the first element is not zero, we pretend the list starts
10489              * at the 0 that is always stored immediately before the array. */
10490             array_b--;
10491             len_b++;
10492         }
10493     }
10494
10495     return    len_a == len_b
10496            && memEQ(array_a, array_b, len_a * sizeof(array_a[0]));
10497
10498 }
10499 #endif
10500
10501 /*
10502  * As best we can, determine the characters that can match the start of
10503  * the given EXACTF-ish node.  This is for use in creating ssc nodes, so there
10504  * can be false positive matches
10505  *
10506  * Returns the invlist as a new SV*; it is the caller's responsibility to
10507  * call SvREFCNT_dec() when done with it.
10508  */
10509 STATIC SV*
10510 S_make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
10511 {
10512     dVAR;
10513     const U8 * s = (U8*)STRING(node);
10514     SSize_t bytelen = STR_LEN(node);
10515     UV uc;
10516     /* Start out big enough for 2 separate code points */
10517     SV* invlist = _new_invlist(4);
10518
10519     PERL_ARGS_ASSERT_MAKE_EXACTF_INVLIST;
10520
10521     if (! UTF) {
10522         uc = *s;
10523
10524         /* We punt and assume can match anything if the node begins
10525          * with a multi-character fold.  Things are complicated.  For
10526          * example, /ffi/i could match any of:
10527          *  "\N{LATIN SMALL LIGATURE FFI}"
10528          *  "\N{LATIN SMALL LIGATURE FF}I"
10529          *  "F\N{LATIN SMALL LIGATURE FI}"
10530          *  plus several other things; and making sure we have all the
10531          *  possibilities is hard. */
10532         if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
10533             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10534         }
10535         else {
10536             /* Any Latin1 range character can potentially match any
10537              * other depending on the locale, and in Turkic locales, U+130 and
10538              * U+131 */
10539             if (OP(node) == EXACTFL) {
10540                 _invlist_union(invlist, PL_Latin1, &invlist);
10541                 invlist = add_cp_to_invlist(invlist,
10542                                                 LATIN_SMALL_LETTER_DOTLESS_I);
10543                 invlist = add_cp_to_invlist(invlist,
10544                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10545             }
10546             else {
10547                 /* But otherwise, it matches at least itself.  We can
10548                  * quickly tell if it has a distinct fold, and if so,
10549                  * it matches that as well */
10550                 invlist = add_cp_to_invlist(invlist, uc);
10551                 if (IS_IN_SOME_FOLD_L1(uc))
10552                     invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
10553             }
10554
10555             /* Some characters match above-Latin1 ones under /i.  This
10556              * is true of EXACTFL ones when the locale is UTF-8 */
10557             if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
10558                 && (! isASCII(uc) || (OP(node) != EXACTFAA
10559                                     && OP(node) != EXACTFAA_NO_TRIE)))
10560             {
10561                 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
10562             }
10563         }
10564     }
10565     else {  /* Pattern is UTF-8 */
10566         U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
10567         const U8* e = s + bytelen;
10568         IV fc;
10569
10570         fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
10571
10572         /* The only code points that aren't folded in a UTF EXACTFish
10573          * node are are the problematic ones in EXACTFL nodes */
10574         if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
10575             /* We need to check for the possibility that this EXACTFL
10576              * node begins with a multi-char fold.  Therefore we fold
10577              * the first few characters of it so that we can make that
10578              * check */
10579             U8 *d = folded;
10580             int i;
10581
10582             fc = -1;
10583             for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
10584                 if (isASCII(*s)) {
10585                     *(d++) = (U8) toFOLD(*s);
10586                     if (fc < 0) {       /* Save the first fold */
10587                         fc = *(d-1);
10588                     }
10589                     s++;
10590                 }
10591                 else {
10592                     STRLEN len;
10593                     UV fold = toFOLD_utf8_safe(s, e, d, &len);
10594                     if (fc < 0) {       /* Save the first fold */
10595                         fc = fold;
10596                     }
10597                     d += len;
10598                     s += UTF8SKIP(s);
10599                 }
10600             }
10601
10602             /* And set up so the code below that looks in this folded
10603              * buffer instead of the node's string */
10604             e = d;
10605             s = folded;
10606         }
10607
10608         /* When we reach here 's' points to the fold of the first
10609          * character(s) of the node; and 'e' points to far enough along
10610          * the folded string to be just past any possible multi-char
10611          * fold.
10612          *
10613          * Unlike the non-UTF-8 case, the macro for determining if a
10614          * string is a multi-char fold requires all the characters to
10615          * already be folded.  This is because of all the complications
10616          * if not.  Note that they are folded anyway, except in EXACTFL
10617          * nodes.  Like the non-UTF case above, we punt if the node
10618          * begins with a multi-char fold  */
10619
10620         if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
10621             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
10622         }
10623         else {  /* Single char fold */
10624             unsigned int k;
10625             unsigned int first_fold;
10626             const unsigned int * remaining_folds;
10627             Size_t folds_count;
10628
10629             /* It matches itself */
10630             invlist = add_cp_to_invlist(invlist, fc);
10631
10632             /* ... plus all the things that fold to it, which are found in
10633              * PL_utf8_foldclosures */
10634             folds_count = _inverse_folds(fc, &first_fold,
10635                                                 &remaining_folds);
10636             for (k = 0; k < folds_count; k++) {
10637                 UV c = (k == 0) ? first_fold : remaining_folds[k-1];
10638
10639                 /* /aa doesn't allow folds between ASCII and non- */
10640                 if (   (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE)
10641                     && isASCII(c) != isASCII(fc))
10642                 {
10643                     continue;
10644                 }
10645
10646                 invlist = add_cp_to_invlist(invlist, c);
10647             }
10648
10649             if (OP(node) == EXACTFL) {
10650
10651                 /* If either [iI] are present in an EXACTFL node the above code
10652                  * should have added its normal case pair, but under a Turkish
10653                  * locale they could match instead the case pairs from it.  Add
10654                  * those as potential matches as well */
10655                 if (isALPHA_FOLD_EQ(fc, 'I')) {
10656                     invlist = add_cp_to_invlist(invlist,
10657                                                 LATIN_SMALL_LETTER_DOTLESS_I);
10658                     invlist = add_cp_to_invlist(invlist,
10659                                         LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
10660                 }
10661                 else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) {
10662                     invlist = add_cp_to_invlist(invlist, 'I');
10663                 }
10664                 else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10665                     invlist = add_cp_to_invlist(invlist, 'i');
10666                 }
10667             }
10668         }
10669     }
10670
10671     return invlist;
10672 }
10673
10674 #undef HEADER_LENGTH
10675 #undef TO_INTERNAL_SIZE
10676 #undef FROM_INTERNAL_SIZE
10677 #undef INVLIST_VERSION_ID
10678
10679 /* End of inversion list object */
10680
10681 STATIC void
10682 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
10683 {
10684     /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
10685      * constructs, and updates RExC_flags with them.  On input, RExC_parse
10686      * should point to the first flag; it is updated on output to point to the
10687      * final ')' or ':'.  There needs to be at least one flag, or this will
10688      * abort */
10689
10690     /* for (?g), (?gc), and (?o) warnings; warning
10691        about (?c) will warn about (?g) -- japhy    */
10692
10693 #define WASTED_O  0x01
10694 #define WASTED_G  0x02
10695 #define WASTED_C  0x04
10696 #define WASTED_GC (WASTED_G|WASTED_C)
10697     I32 wastedflags = 0x00;
10698     U32 posflags = 0, negflags = 0;
10699     U32 *flagsp = &posflags;
10700     char has_charset_modifier = '\0';
10701     regex_charset cs;
10702     bool has_use_defaults = FALSE;
10703     const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
10704     int x_mod_count = 0;
10705
10706     PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
10707
10708     /* '^' as an initial flag sets certain defaults */
10709     if (UCHARAT(RExC_parse) == '^') {
10710         RExC_parse++;
10711         has_use_defaults = TRUE;
10712         STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
10713         cs = (RExC_uni_semantics)
10714              ? REGEX_UNICODE_CHARSET
10715              : REGEX_DEPENDS_CHARSET;
10716         set_regex_charset(&RExC_flags, cs);
10717     }
10718     else {
10719         cs = get_regex_charset(RExC_flags);
10720         if (   cs == REGEX_DEPENDS_CHARSET
10721             && RExC_uni_semantics)
10722         {
10723             cs = REGEX_UNICODE_CHARSET;
10724         }
10725     }
10726
10727     while (RExC_parse < RExC_end) {
10728         /* && memCHRs("iogcmsx", *RExC_parse) */
10729         /* (?g), (?gc) and (?o) are useless here
10730            and must be globally applied -- japhy */
10731         switch (*RExC_parse) {
10732
10733             /* Code for the imsxn flags */
10734             CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
10735
10736             case LOCALE_PAT_MOD:
10737                 if (has_charset_modifier) {
10738                     goto excess_modifier;
10739                 }
10740                 else if (flagsp == &negflags) {
10741                     goto neg_modifier;
10742                 }
10743                 cs = REGEX_LOCALE_CHARSET;
10744                 has_charset_modifier = LOCALE_PAT_MOD;
10745                 break;
10746             case UNICODE_PAT_MOD:
10747                 if (has_charset_modifier) {
10748                     goto excess_modifier;
10749                 }
10750                 else if (flagsp == &negflags) {
10751                     goto neg_modifier;
10752                 }
10753                 cs = REGEX_UNICODE_CHARSET;
10754                 has_charset_modifier = UNICODE_PAT_MOD;
10755                 break;
10756             case ASCII_RESTRICT_PAT_MOD:
10757                 if (flagsp == &negflags) {
10758                     goto neg_modifier;
10759                 }
10760                 if (has_charset_modifier) {
10761                     if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
10762                         goto excess_modifier;
10763                     }
10764                     /* Doubled modifier implies more restricted */
10765                     cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
10766                 }
10767                 else {
10768                     cs = REGEX_ASCII_RESTRICTED_CHARSET;
10769                 }
10770                 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
10771                 break;
10772             case DEPENDS_PAT_MOD:
10773                 if (has_use_defaults) {
10774                     goto fail_modifiers;
10775                 }
10776                 else if (flagsp == &negflags) {
10777                     goto neg_modifier;
10778                 }
10779                 else if (has_charset_modifier) {
10780                     goto excess_modifier;
10781                 }
10782
10783                 /* The dual charset means unicode semantics if the
10784                  * pattern (or target, not known until runtime) are
10785                  * utf8, or something in the pattern indicates unicode
10786                  * semantics */
10787                 cs = (RExC_uni_semantics)
10788                      ? REGEX_UNICODE_CHARSET
10789                      : REGEX_DEPENDS_CHARSET;
10790                 has_charset_modifier = DEPENDS_PAT_MOD;
10791                 break;
10792               excess_modifier:
10793                 RExC_parse++;
10794                 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
10795                     vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
10796                 }
10797                 else if (has_charset_modifier == *(RExC_parse - 1)) {
10798                     vFAIL2("Regexp modifier \"%c\" may not appear twice",
10799                                         *(RExC_parse - 1));
10800                 }
10801                 else {
10802                     vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
10803                 }
10804                 NOT_REACHED; /*NOTREACHED*/
10805               neg_modifier:
10806                 RExC_parse++;
10807                 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
10808                                     *(RExC_parse - 1));
10809                 NOT_REACHED; /*NOTREACHED*/
10810             case ONCE_PAT_MOD: /* 'o' */
10811             case GLOBAL_PAT_MOD: /* 'g' */
10812                 if (ckWARN(WARN_REGEXP)) {
10813                     const I32 wflagbit = *RExC_parse == 'o'
10814                                          ? WASTED_O
10815                                          : WASTED_G;
10816                     if (! (wastedflags & wflagbit) ) {
10817                         wastedflags |= wflagbit;
10818                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10819                         vWARN5(
10820                             RExC_parse + 1,
10821                             "Useless (%s%c) - %suse /%c modifier",
10822                             flagsp == &negflags ? "?-" : "?",
10823                             *RExC_parse,
10824                             flagsp == &negflags ? "don't " : "",
10825                             *RExC_parse
10826                         );
10827                     }
10828                 }
10829                 break;
10830
10831             case CONTINUE_PAT_MOD: /* 'c' */
10832                 if (ckWARN(WARN_REGEXP)) {
10833                     if (! (wastedflags & WASTED_C) ) {
10834                         wastedflags |= WASTED_GC;
10835                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
10836                         vWARN3(
10837                             RExC_parse + 1,
10838                             "Useless (%sc) - %suse /gc modifier",
10839                             flagsp == &negflags ? "?-" : "?",
10840                             flagsp == &negflags ? "don't " : ""
10841                         );
10842                     }
10843                 }
10844                 break;
10845             case KEEPCOPY_PAT_MOD: /* 'p' */
10846                 if (flagsp == &negflags) {
10847                     ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10848                 } else {
10849                     *flagsp |= RXf_PMf_KEEPCOPY;
10850                 }
10851                 break;
10852             case '-':
10853                 /* A flag is a default iff it is following a minus, so
10854                  * if there is a minus, it means will be trying to
10855                  * re-specify a default which is an error */
10856                 if (has_use_defaults || flagsp == &negflags) {
10857                     goto fail_modifiers;
10858                 }
10859                 flagsp = &negflags;
10860                 wastedflags = 0;  /* reset so (?g-c) warns twice */
10861                 x_mod_count = 0;
10862                 break;
10863             case ':':
10864             case ')':
10865
10866                 if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) {
10867                     negflags |= RXf_PMf_EXTENDED_MORE;
10868                 }
10869                 RExC_flags |= posflags;
10870
10871                 if (negflags & RXf_PMf_EXTENDED) {
10872                     negflags |= RXf_PMf_EXTENDED_MORE;
10873                 }
10874                 RExC_flags &= ~negflags;
10875                 set_regex_charset(&RExC_flags, cs);
10876
10877                 return;
10878             default:
10879               fail_modifiers:
10880                 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
10881                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10882                 vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized",
10883                       UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10884                 NOT_REACHED; /*NOTREACHED*/
10885         }
10886
10887         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10888     }
10889
10890     vFAIL("Sequence (?... not terminated");
10891 }
10892
10893 /*
10894  - reg - regular expression, i.e. main body or parenthesized thing
10895  *
10896  * Caller must absorb opening parenthesis.
10897  *
10898  * Combining parenthesis handling with the base level of regular expression
10899  * is a trifle forced, but the need to tie the tails of the branches to what
10900  * follows makes it hard to avoid.
10901  */
10902 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10903 #ifdef DEBUGGING
10904 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10905 #else
10906 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10907 #endif
10908
10909 PERL_STATIC_INLINE regnode_offset
10910 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10911                              I32 *flagp,
10912                              char * parse_start,
10913                              char ch
10914                       )
10915 {
10916     regnode_offset ret;
10917     char* name_start = RExC_parse;
10918     U32 num = 0;
10919     SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
10920     GET_RE_DEBUG_FLAGS_DECL;
10921
10922     PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
10923
10924     if (RExC_parse == name_start || *RExC_parse != ch) {
10925         /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
10926         vFAIL2("Sequence %.3s... not terminated", parse_start);
10927     }
10928
10929     if (sv_dat) {
10930         num = add_data( pRExC_state, STR_WITH_LEN("S"));
10931         RExC_rxi->data->data[num]=(void*)sv_dat;
10932         SvREFCNT_inc_simple_void_NN(sv_dat);
10933     }
10934     RExC_sawback = 1;
10935     ret = reganode(pRExC_state,
10936                    ((! FOLD)
10937                      ? REFN
10938                      : (ASCII_FOLD_RESTRICTED)
10939                        ? REFFAN
10940                        : (AT_LEAST_UNI_SEMANTICS)
10941                          ? REFFUN
10942                          : (LOC)
10943                            ? REFFLN
10944                            : REFFN),
10945                     num);
10946     *flagp |= HASWIDTH;
10947
10948     Set_Node_Offset(REGNODE_p(ret), parse_start+1);
10949     Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
10950
10951     nextchar(pRExC_state);
10952     return ret;
10953 }
10954
10955 /* On success, returns the offset at which any next node should be placed into
10956  * the regex engine program being compiled.
10957  *
10958  * Returns 0 otherwise, with *flagp set to indicate why:
10959  *  TRYAGAIN        at the end of (?) that only sets flags.
10960  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
10961  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
10962  *  Otherwise would only return 0 if regbranch() returns 0, which cannot
10963  *  happen.  */
10964 STATIC regnode_offset
10965 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth)
10966     /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
10967      * 2 is like 1, but indicates that nextchar() has been called to advance
10968      * RExC_parse beyond the '('.  Things like '(?' are indivisible tokens, and
10969      * this flag alerts us to the need to check for that */
10970 {
10971     regnode_offset ret = 0;    /* Will be the head of the group. */
10972     regnode_offset br;
10973     regnode_offset lastbr;
10974     regnode_offset ender = 0;
10975     I32 parno = 0;
10976     I32 flags;
10977     U32 oregflags = RExC_flags;
10978     bool have_branch = 0;
10979     bool is_open = 0;
10980     I32 freeze_paren = 0;
10981     I32 after_freeze = 0;
10982     I32 num; /* numeric backreferences */
10983     SV * max_open;  /* Max number of unclosed parens */
10984
10985     char * parse_start = RExC_parse; /* MJD */
10986     char * const oregcomp_parse = RExC_parse;
10987
10988     GET_RE_DEBUG_FLAGS_DECL;
10989
10990     PERL_ARGS_ASSERT_REG;
10991     DEBUG_PARSE("reg ");
10992
10993     max_open = get_sv(RE_COMPILE_RECURSION_LIMIT, GV_ADD);
10994     assert(max_open);
10995     if (!SvIOK(max_open)) {
10996         sv_setiv(max_open, RE_COMPILE_RECURSION_INIT);
10997     }
10998     if (depth > 4 * (UV) SvIV(max_open)) { /* We increase depth by 4 for each
10999                                               open paren */
11000         vFAIL("Too many nested open parens");
11001     }
11002
11003     *flagp = 0;                         /* Tentatively. */
11004
11005     if (RExC_in_lookbehind) {
11006         RExC_in_lookbehind++;
11007     }
11008     if (RExC_in_lookahead) {
11009         RExC_in_lookahead++;
11010     }
11011
11012     /* Having this true makes it feasible to have a lot fewer tests for the
11013      * parse pointer being in scope.  For example, we can write
11014      *      while(isFOO(*RExC_parse)) RExC_parse++;
11015      * instead of
11016      *      while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
11017      */
11018     assert(*RExC_end == '\0');
11019
11020     /* Make an OPEN node, if parenthesized. */
11021     if (paren) {
11022
11023         /* Under /x, space and comments can be gobbled up between the '(' and
11024          * here (if paren ==2).  The forms '(*VERB' and '(?...' disallow such
11025          * intervening space, as the sequence is a token, and a token should be
11026          * indivisible */
11027         bool has_intervening_patws = (paren == 2)
11028                                   && *(RExC_parse - 1) != '(';
11029
11030         if (RExC_parse >= RExC_end) {
11031             vFAIL("Unmatched (");
11032         }
11033
11034         if (paren == 'r') {     /* Atomic script run */
11035             paren = '>';
11036             goto parse_rest;
11037         }
11038         else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */
11039             char *start_verb = RExC_parse + 1;
11040             STRLEN verb_len;
11041             char *start_arg = NULL;
11042             unsigned char op = 0;
11043             int arg_required = 0;
11044             int internal_argval = -1; /* if >-1 we are not allowed an argument*/
11045             bool has_upper = FALSE;
11046
11047             if (has_intervening_patws) {
11048                 RExC_parse++;   /* past the '*' */
11049
11050                 /* For strict backwards compatibility, don't change the message
11051                  * now that we also have lowercase operands */
11052                 if (isUPPER(*RExC_parse)) {
11053                     vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
11054                 }
11055                 else {
11056                     vFAIL("In '(*...)', the '(' and '*' must be adjacent");
11057                 }
11058             }
11059             while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
11060                 if ( *RExC_parse == ':' ) {
11061                     start_arg = RExC_parse + 1;
11062                     break;
11063                 }
11064                 else if (! UTF) {
11065                     if (isUPPER(*RExC_parse)) {
11066                         has_upper = TRUE;
11067                     }
11068                     RExC_parse++;
11069                 }
11070                 else {
11071                     RExC_parse += UTF8SKIP(RExC_parse);
11072                 }
11073             }
11074             verb_len = RExC_parse - start_verb;
11075             if ( start_arg ) {
11076                 if (RExC_parse >= RExC_end) {
11077                     goto unterminated_verb_pattern;
11078                 }
11079
11080                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11081                 while ( RExC_parse < RExC_end && *RExC_parse != ')' ) {
11082                     RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11083                 }
11084                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11085                   unterminated_verb_pattern:
11086                     if (has_upper) {
11087                         vFAIL("Unterminated verb pattern argument");
11088                     }
11089                     else {
11090                         vFAIL("Unterminated '(*...' argument");
11091                     }
11092                 }
11093             } else {
11094                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) {
11095                     if (has_upper) {
11096                         vFAIL("Unterminated verb pattern");
11097                     }
11098                     else {
11099                         vFAIL("Unterminated '(*...' construct");
11100                     }
11101                 }
11102             }
11103
11104             /* Here, we know that RExC_parse < RExC_end */
11105
11106             switch ( *start_verb ) {
11107             case 'A':  /* (*ACCEPT) */
11108                 if ( memEQs(start_verb, verb_len,"ACCEPT") ) {
11109                     op = ACCEPT;
11110                     internal_argval = RExC_nestroot;
11111                 }
11112                 break;
11113             case 'C':  /* (*COMMIT) */
11114                 if ( memEQs(start_verb, verb_len,"COMMIT") )
11115                     op = COMMIT;
11116                 break;
11117             case 'F':  /* (*FAIL) */
11118                 if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) {
11119                     op = OPFAIL;
11120                 }
11121                 break;
11122             case ':':  /* (*:NAME) */
11123             case 'M':  /* (*MARK:NAME) */
11124                 if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) {
11125                     op = MARKPOINT;
11126                     arg_required = 1;
11127                 }
11128                 break;
11129             case 'P':  /* (*PRUNE) */
11130                 if ( memEQs(start_verb, verb_len,"PRUNE") )
11131                     op = PRUNE;
11132                 break;
11133             case 'S':   /* (*SKIP) */
11134                 if ( memEQs(start_verb, verb_len,"SKIP") )
11135                     op = SKIP;
11136                 break;
11137             case 'T':  /* (*THEN) */
11138                 /* [19:06] <TimToady> :: is then */
11139                 if ( memEQs(start_verb, verb_len,"THEN") ) {
11140                     op = CUTGROUP;
11141                     RExC_seen |= REG_CUTGROUP_SEEN;
11142                 }
11143                 break;
11144             case 'a':
11145                 if (   memEQs(start_verb, verb_len, "asr")
11146                     || memEQs(start_verb, verb_len, "atomic_script_run"))
11147                 {
11148                     paren = 'r';        /* Mnemonic: recursed run */
11149                     goto script_run;
11150                 }
11151                 else if (memEQs(start_verb, verb_len, "atomic")) {
11152                     paren = 't';    /* AtOMIC */
11153                     goto alpha_assertions;
11154                 }
11155                 break;
11156             case 'p':
11157                 if (   memEQs(start_verb, verb_len, "plb")
11158                     || memEQs(start_verb, verb_len, "positive_lookbehind"))
11159                 {
11160                     paren = 'b';
11161                     goto lookbehind_alpha_assertions;
11162                 }
11163                 else if (   memEQs(start_verb, verb_len, "pla")
11164                          || memEQs(start_verb, verb_len, "positive_lookahead"))
11165                 {
11166                     paren = 'a';
11167                     goto alpha_assertions;
11168                 }
11169                 break;
11170             case 'n':
11171                 if (   memEQs(start_verb, verb_len, "nlb")
11172                     || memEQs(start_verb, verb_len, "negative_lookbehind"))
11173                 {
11174                     paren = 'B';
11175                     goto lookbehind_alpha_assertions;
11176                 }
11177                 else if (   memEQs(start_verb, verb_len, "nla")
11178                          || memEQs(start_verb, verb_len, "negative_lookahead"))
11179                 {
11180                     paren = 'A';
11181                     goto alpha_assertions;
11182                 }
11183                 break;
11184             case 's':
11185                 if (   memEQs(start_verb, verb_len, "sr")
11186                     || memEQs(start_verb, verb_len, "script_run"))
11187                 {
11188                     regnode_offset atomic;
11189
11190                     paren = 's';
11191
11192                    script_run:
11193
11194                     /* This indicates Unicode rules. */
11195                     REQUIRE_UNI_RULES(flagp, 0);
11196
11197                     if (! start_arg) {
11198                         goto no_colon;
11199                     }
11200
11201                     RExC_parse = start_arg;
11202
11203                     if (RExC_in_script_run) {
11204
11205                         /*  Nested script runs are treated as no-ops, because
11206                          *  if the nested one fails, the outer one must as
11207                          *  well.  It could fail sooner, and avoid (??{} with
11208                          *  side effects, but that is explicitly documented as
11209                          *  undefined behavior. */
11210
11211                         ret = 0;
11212
11213                         if (paren == 's') {
11214                             paren = ':';
11215                             goto parse_rest;
11216                         }
11217
11218                         /* But, the atomic part of a nested atomic script run
11219                          * isn't a no-op, but can be treated just like a '(?>'
11220                          * */
11221                         paren = '>';
11222                         goto parse_rest;
11223                     }
11224
11225                     if (paren == 's') {
11226                         /* Here, we're starting a new regular script run */
11227                         ret = reg_node(pRExC_state, SROPEN);
11228                         RExC_in_script_run = 1;
11229                         is_open = 1;
11230                         goto parse_rest;
11231                     }
11232
11233                     /* Here, we are starting an atomic script run.  This is
11234                      * handled by recursing to deal with the atomic portion
11235                      * separately, enclosed in SROPEN ... SRCLOSE nodes */
11236
11237                     ret = reg_node(pRExC_state, SROPEN);
11238
11239                     RExC_in_script_run = 1;
11240
11241                     atomic = reg(pRExC_state, 'r', &flags, depth);
11242                     if (flags & (RESTART_PARSE|NEED_UTF8)) {
11243                         *flagp = flags & (RESTART_PARSE|NEED_UTF8);
11244                         return 0;
11245                     }
11246
11247                     if (! REGTAIL(pRExC_state, ret, atomic)) {
11248                         REQUIRE_BRANCHJ(flagp, 0);
11249                     }
11250
11251                     if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state,
11252                                                                 SRCLOSE)))
11253                     {
11254                         REQUIRE_BRANCHJ(flagp, 0);
11255                     }
11256
11257                     RExC_in_script_run = 0;
11258                     return ret;
11259                 }
11260
11261                 break;
11262
11263             lookbehind_alpha_assertions:
11264                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11265                 RExC_in_lookbehind++;
11266                 /*FALLTHROUGH*/
11267
11268             alpha_assertions:
11269
11270                 RExC_seen_zerolen++;
11271
11272                 if (! start_arg) {
11273                     goto no_colon;
11274                 }
11275
11276                 /* An empty negative lookahead assertion simply is failure */
11277                 if (paren == 'A' && RExC_parse == start_arg) {
11278                     ret=reganode(pRExC_state, OPFAIL, 0);
11279                     nextchar(pRExC_state);
11280                     return ret;
11281                 }
11282
11283                 RExC_parse = start_arg;
11284                 goto parse_rest;
11285
11286               no_colon:
11287                 vFAIL2utf8f(
11288                 "'(*%" UTF8f "' requires a terminating ':'",
11289                 UTF8fARG(UTF, verb_len, start_verb));
11290                 NOT_REACHED; /*NOTREACHED*/
11291
11292             } /* End of switch */
11293             if ( ! op ) {
11294                 RExC_parse += UTF
11295                               ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11296                               : 1;
11297                 if (has_upper || verb_len == 0) {
11298                     vFAIL2utf8f(
11299                     "Unknown verb pattern '%" UTF8f "'",
11300                     UTF8fARG(UTF, verb_len, start_verb));
11301                 }
11302                 else {
11303                     vFAIL2utf8f(
11304                     "Unknown '(*...)' construct '%" UTF8f "'",
11305                     UTF8fARG(UTF, verb_len, start_verb));
11306                 }
11307             }
11308             if ( RExC_parse == start_arg ) {
11309                 start_arg = NULL;
11310             }
11311             if ( arg_required && !start_arg ) {
11312                 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
11313                     verb_len, start_verb);
11314             }
11315             if (internal_argval == -1) {
11316                 ret = reganode(pRExC_state, op, 0);
11317             } else {
11318                 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
11319             }
11320             RExC_seen |= REG_VERBARG_SEEN;
11321             if (start_arg) {
11322                 SV *sv = newSVpvn( start_arg,
11323                                     RExC_parse - start_arg);
11324                 ARG(REGNODE_p(ret)) = add_data( pRExC_state,
11325                                         STR_WITH_LEN("S"));
11326                 RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv;
11327                 FLAGS(REGNODE_p(ret)) = 1;
11328             } else {
11329                 FLAGS(REGNODE_p(ret)) = 0;
11330             }
11331             if ( internal_argval != -1 )
11332                 ARG2L_SET(REGNODE_p(ret), internal_argval);
11333             nextchar(pRExC_state);
11334             return ret;
11335         }
11336         else if (*RExC_parse == '?') { /* (?...) */
11337             bool is_logical = 0;
11338             const char * const seqstart = RExC_parse;
11339             const char * endptr;
11340             if (has_intervening_patws) {
11341                 RExC_parse++;
11342                 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
11343             }
11344
11345             RExC_parse++;           /* past the '?' */
11346             paren = *RExC_parse;    /* might be a trailing NUL, if not
11347                                        well-formed */
11348             RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
11349             if (RExC_parse > RExC_end) {
11350                 paren = '\0';
11351             }
11352             ret = 0;                    /* For look-ahead/behind. */
11353             switch (paren) {
11354
11355             case 'P':   /* (?P...) variants for those used to PCRE/Python */
11356                 paren = *RExC_parse;
11357                 if ( paren == '<') {    /* (?P<...>) named capture */
11358                     RExC_parse++;
11359                     if (RExC_parse >= RExC_end) {
11360                         vFAIL("Sequence (?P<... not terminated");
11361                     }
11362                     goto named_capture;
11363                 }
11364                 else if (paren == '>') {   /* (?P>name) named recursion */
11365                     RExC_parse++;
11366                     if (RExC_parse >= RExC_end) {
11367                         vFAIL("Sequence (?P>... not terminated");
11368                     }
11369                     goto named_recursion;
11370                 }
11371                 else if (paren == '=') {   /* (?P=...)  named backref */
11372                     RExC_parse++;
11373                     return handle_named_backref(pRExC_state, flagp,
11374                                                 parse_start, ')');
11375                 }
11376                 RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11377                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11378                 vFAIL3("Sequence (%.*s...) not recognized",
11379                                 RExC_parse-seqstart, seqstart);
11380                 NOT_REACHED; /*NOTREACHED*/
11381             case '<':           /* (?<...) */
11382                 /* If you want to support (?<*...), first reconcile with GH #17363 */
11383                 if (*RExC_parse == '!')
11384                     paren = ',';
11385                 else if (*RExC_parse != '=')
11386               named_capture:
11387                 {               /* (?<...>) */
11388                     char *name_start;
11389                     SV *svname;
11390                     paren= '>';
11391                 /* FALLTHROUGH */
11392             case '\'':          /* (?'...') */
11393                     name_start = RExC_parse;
11394                     svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME);
11395                     if (   RExC_parse == name_start
11396                         || RExC_parse >= RExC_end
11397                         || *RExC_parse != paren)
11398                     {
11399                         vFAIL2("Sequence (?%c... not terminated",
11400                             paren=='>' ? '<' : paren);
11401                     }
11402                     {
11403                         HE *he_str;
11404                         SV *sv_dat = NULL;
11405                         if (!svname) /* shouldn't happen */
11406                             Perl_croak(aTHX_
11407                                 "panic: reg_scan_name returned NULL");
11408                         if (!RExC_paren_names) {
11409                             RExC_paren_names= newHV();
11410                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
11411 #ifdef DEBUGGING
11412                             RExC_paren_name_list= newAV();
11413                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
11414 #endif
11415                         }
11416                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
11417                         if ( he_str )
11418                             sv_dat = HeVAL(he_str);
11419                         if ( ! sv_dat ) {
11420                             /* croak baby croak */
11421                             Perl_croak(aTHX_
11422                                 "panic: paren_name hash element allocation failed");
11423                         } else if ( SvPOK(sv_dat) ) {
11424                             /* (?|...) can mean we have dupes so scan to check
11425                                its already been stored. Maybe a flag indicating
11426                                we are inside such a construct would be useful,
11427                                but the arrays are likely to be quite small, so
11428                                for now we punt -- dmq */
11429                             IV count = SvIV(sv_dat);
11430                             I32 *pv = (I32*)SvPVX(sv_dat);
11431                             IV i;
11432                             for ( i = 0 ; i < count ; i++ ) {
11433                                 if ( pv[i] == RExC_npar ) {
11434                                     count = 0;
11435                                     break;
11436                                 }
11437                             }
11438                             if ( count ) {
11439                                 pv = (I32*)SvGROW(sv_dat,
11440                                                 SvCUR(sv_dat) + sizeof(I32)+1);
11441                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
11442                                 pv[count] = RExC_npar;
11443                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
11444                             }
11445                         } else {
11446                             (void)SvUPGRADE(sv_dat, SVt_PVNV);
11447                             sv_setpvn(sv_dat, (char *)&(RExC_npar),
11448                                                                 sizeof(I32));
11449                             SvIOK_on(sv_dat);
11450                             SvIV_set(sv_dat, 1);
11451                         }
11452 #ifdef DEBUGGING
11453                         /* Yes this does cause a memory leak in debugging Perls
11454                          * */
11455                         if (!av_store(RExC_paren_name_list,
11456                                       RExC_npar, SvREFCNT_inc_NN(svname)))
11457                             SvREFCNT_dec_NN(svname);
11458 #endif
11459
11460                         /*sv_dump(sv_dat);*/
11461                     }
11462                     nextchar(pRExC_state);
11463                     paren = 1;
11464                     goto capturing_parens;
11465                 }
11466
11467                 RExC_seen |= REG_LOOKBEHIND_SEEN;
11468                 RExC_in_lookbehind++;
11469                 RExC_parse++;
11470                 if (RExC_parse >= RExC_end) {
11471                     vFAIL("Sequence (?... not terminated");
11472                 }
11473                 RExC_seen_zerolen++;
11474                 break;
11475             case '=':           /* (?=...) */
11476                 RExC_seen_zerolen++;
11477                 RExC_in_lookahead++;
11478                 break;
11479             case '!':           /* (?!...) */
11480                 RExC_seen_zerolen++;
11481                 /* check if we're really just a "FAIL" assertion */
11482                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11483                                         FALSE /* Don't force to /x */ );
11484                 if (*RExC_parse == ')') {
11485                     ret=reganode(pRExC_state, OPFAIL, 0);
11486                     nextchar(pRExC_state);
11487                     return ret;
11488                 }
11489                 break;
11490             case '|':           /* (?|...) */
11491                 /* branch reset, behave like a (?:...) except that
11492                    buffers in alternations share the same numbers */
11493                 paren = ':';
11494                 after_freeze = freeze_paren = RExC_npar;
11495
11496                 /* XXX This construct currently requires an extra pass.
11497                  * Investigation would be required to see if that could be
11498                  * changed */
11499                 REQUIRE_PARENS_PASS;
11500                 break;
11501             case ':':           /* (?:...) */
11502             case '>':           /* (?>...) */
11503                 break;
11504             case '$':           /* (?$...) */
11505             case '@':           /* (?@...) */
11506                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
11507                 break;
11508             case '0' :           /* (?0) */
11509             case 'R' :           /* (?R) */
11510                 if (RExC_parse == RExC_end || *RExC_parse != ')')
11511                     FAIL("Sequence (?R) not terminated");
11512                 num = 0;
11513                 RExC_seen |= REG_RECURSE_SEEN;
11514
11515                 /* XXX These constructs currently require an extra pass.
11516                  * It probably could be changed */
11517                 REQUIRE_PARENS_PASS;
11518
11519                 *flagp |= POSTPONED;
11520                 goto gen_recurse_regop;
11521                 /*notreached*/
11522             /* named and numeric backreferences */
11523             case '&':            /* (?&NAME) */
11524                 parse_start = RExC_parse - 1;
11525               named_recursion:
11526                 {
11527                     SV *sv_dat = reg_scan_name(pRExC_state,
11528                                                REG_RSN_RETURN_DATA);
11529                    num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
11530                 }
11531                 if (RExC_parse >= RExC_end || *RExC_parse != ')')
11532                     vFAIL("Sequence (?&... not terminated");
11533                 goto gen_recurse_regop;
11534                 /* NOTREACHED */
11535             case '+':
11536                 if (! inRANGE(RExC_parse[0], '1', '9')) {
11537                     RExC_parse++;
11538                     vFAIL("Illegal pattern");
11539                 }
11540                 goto parse_recursion;
11541                 /* NOTREACHED*/
11542             case '-': /* (?-1) */
11543                 if (! inRANGE(RExC_parse[0], '1', '9')) {
11544                     RExC_parse--; /* rewind to let it be handled later */
11545                     goto parse_flags;
11546                 }
11547                 /* FALLTHROUGH */
11548             case '1': case '2': case '3': case '4': /* (?1) */
11549             case '5': case '6': case '7': case '8': case '9':
11550                 RExC_parse = (char *) seqstart + 1;  /* Point to the digit */
11551               parse_recursion:
11552                 {
11553                     bool is_neg = FALSE;
11554                     UV unum;
11555                     parse_start = RExC_parse - 1; /* MJD */
11556                     if (*RExC_parse == '-') {
11557                         RExC_parse++;
11558                         is_neg = TRUE;
11559                     }
11560                     endptr = RExC_end;
11561                     if (grok_atoUV(RExC_parse, &unum, &endptr)
11562                         && unum <= I32_MAX
11563                     ) {
11564                         num = (I32)unum;
11565                         RExC_parse = (char*)endptr;
11566                     } else
11567                         num = I32_MAX;
11568                     if (is_neg) {
11569                         /* Some limit for num? */
11570                         num = -num;
11571                     }
11572                 }
11573                 if (*RExC_parse!=')')
11574                     vFAIL("Expecting close bracket");
11575
11576               gen_recurse_regop:
11577                 if ( paren == '-' ) {
11578                     /*
11579                     Diagram of capture buffer numbering.
11580                     Top line is the normal capture buffer numbers
11581                     Bottom line is the negative indexing as from
11582                     the X (the (?-2))
11583
11584                     +   1 2    3 4 5 X          6 7
11585                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
11586                     -   5 4    3 2 1 X          x x
11587
11588                     */
11589                     num = RExC_npar + num;
11590                     if (num < 1)  {
11591
11592                         /* It might be a forward reference; we can't fail until
11593                          * we know, by completing the parse to get all the
11594                          * groups, and then reparsing */
11595                         if (ALL_PARENS_COUNTED)  {
11596                             RExC_parse++;
11597                             vFAIL("Reference to nonexistent group");
11598                         }
11599                         else {
11600                             REQUIRE_PARENS_PASS;
11601                         }
11602                     }
11603                 } else if ( paren == '+' ) {
11604                     num = RExC_npar + num - 1;
11605                 }
11606                 /* We keep track how many GOSUB items we have produced.
11607                    To start off the ARG2L() of the GOSUB holds its "id",
11608                    which is used later in conjunction with RExC_recurse
11609                    to calculate the offset we need to jump for the GOSUB,
11610                    which it will store in the final representation.
11611                    We have to defer the actual calculation until much later
11612                    as the regop may move.
11613                  */
11614
11615                 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
11616                 if (num >= RExC_npar) {
11617
11618                     /* It might be a forward reference; we can't fail until we
11619                      * know, by completing the parse to get all the groups, and
11620                      * then reparsing */
11621                     if (ALL_PARENS_COUNTED)  {
11622                         if (num >= RExC_total_parens) {
11623                             RExC_parse++;
11624                             vFAIL("Reference to nonexistent group");
11625                         }
11626                     }
11627                     else {
11628                         REQUIRE_PARENS_PASS;
11629                     }
11630                 }
11631                 RExC_recurse_count++;
11632                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
11633                     "%*s%*s Recurse #%" UVuf " to %" IVdf "\n",
11634                             22, "|    |", (int)(depth * 2 + 1), "",
11635                             (UV)ARG(REGNODE_p(ret)),
11636                             (IV)ARG2L(REGNODE_p(ret))));
11637                 RExC_seen |= REG_RECURSE_SEEN;
11638
11639                 Set_Node_Length(REGNODE_p(ret),
11640                                 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */
11641                 Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */
11642
11643                 *flagp |= POSTPONED;
11644                 assert(*RExC_parse == ')');
11645                 nextchar(pRExC_state);
11646                 return ret;
11647
11648             /* NOTREACHED */
11649
11650             case '?':           /* (??...) */
11651                 is_logical = 1;
11652                 if (*RExC_parse != '{') {
11653                     RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end);
11654                     /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
11655                     vFAIL2utf8f(
11656                         "Sequence (%" UTF8f "...) not recognized",
11657                         UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
11658                     NOT_REACHED; /*NOTREACHED*/
11659                 }
11660                 *flagp |= POSTPONED;
11661                 paren = '{';
11662                 RExC_parse++;
11663                 /* FALLTHROUGH */
11664             case '{':           /* (?{...}) */
11665             {
11666                 U32 n = 0;
11667                 struct reg_code_block *cb;
11668                 OP * o;
11669
11670                 RExC_seen_zerolen++;
11671
11672                 if (   !pRExC_state->code_blocks
11673                     || pRExC_state->code_index
11674                                         >= pRExC_state->code_blocks->count
11675                     || pRExC_state->code_blocks->cb[pRExC_state->code_index].start
11676                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
11677                             - RExC_start)
11678                 ) {
11679                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
11680                         FAIL("panic: Sequence (?{...}): no code block found\n");
11681                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
11682                 }
11683                 /* this is a pre-compiled code block (?{...}) */
11684                 cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index];
11685                 RExC_parse = RExC_start + cb->end;
11686                 o = cb->block;
11687                 if (cb->src_regex) {
11688                     n = add_data(pRExC_state, STR_WITH_LEN("rl"));
11689                     RExC_rxi->data->data[n] =
11690                         (void*)SvREFCNT_inc((SV*)cb->src_regex);
11691                     RExC_rxi->data->data[n+1] = (void*)o;
11692                 }
11693                 else {
11694                     n = add_data(pRExC_state,
11695                             (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
11696                     RExC_rxi->data->data[n] = (void*)o;
11697                 }
11698                 pRExC_state->code_index++;
11699                 nextchar(pRExC_state);
11700
11701                 if (is_logical) {
11702                     regnode_offset eval;
11703                     ret = reg_node(pRExC_state, LOGICAL);
11704
11705                     eval = reg2Lanode(pRExC_state, EVAL,
11706                                        n,
11707
11708                                        /* for later propagation into (??{})
11709                                         * return value */
11710                                        RExC_flags & RXf_PMf_COMPILETIME
11711                                       );
11712                     FLAGS(REGNODE_p(ret)) = 2;
11713                     if (! REGTAIL(pRExC_state, ret, eval)) {
11714                         REQUIRE_BRANCHJ(flagp, 0);
11715                     }
11716                     /* deal with the length of this later - MJD */
11717                     return ret;
11718                 }
11719                 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
11720                 Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1);
11721                 Set_Node_Offset(REGNODE_p(ret), parse_start);
11722                 return ret;
11723             }
11724             case '(':           /* (?(?{...})...) and (?(?=...)...) */
11725             {
11726                 int is_define= 0;
11727                 const int DEFINE_len = sizeof("DEFINE") - 1;
11728                 if (    RExC_parse < RExC_end - 1
11729                     && (   (       RExC_parse[0] == '?'        /* (?(?...)) */
11730                             && (   RExC_parse[1] == '='
11731                                 || RExC_parse[1] == '!'
11732                                 || RExC_parse[1] == '<'
11733                                 || RExC_parse[1] == '{'))
11734                         || (       RExC_parse[0] == '*'        /* (?(*...)) */
11735                             && (   memBEGINs(RExC_parse + 1,
11736                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11737                                          "pla:")
11738                                 || memBEGINs(RExC_parse + 1,
11739                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11740                                          "plb:")
11741                                 || memBEGINs(RExC_parse + 1,
11742                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11743                                          "nla:")
11744                                 || memBEGINs(RExC_parse + 1,
11745                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11746                                          "nlb:")
11747                                 || memBEGINs(RExC_parse + 1,
11748                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11749                                          "positive_lookahead:")
11750                                 || memBEGINs(RExC_parse + 1,
11751                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11752                                          "positive_lookbehind:")
11753                                 || memBEGINs(RExC_parse + 1,
11754                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11755                                          "negative_lookahead:")
11756                                 || memBEGINs(RExC_parse + 1,
11757                                          (Size_t) (RExC_end - (RExC_parse + 1)),
11758                                          "negative_lookbehind:"))))
11759                 ) { /* Lookahead or eval. */
11760                     I32 flag;
11761                     regnode_offset tail;
11762
11763                     ret = reg_node(pRExC_state, LOGICAL);
11764                     FLAGS(REGNODE_p(ret)) = 1;
11765
11766                     tail = reg(pRExC_state, 1, &flag, depth+1);
11767                     RETURN_FAIL_ON_RESTART(flag, flagp);
11768                     if (! REGTAIL(pRExC_state, ret, tail)) {
11769                         REQUIRE_BRANCHJ(flagp, 0);
11770                     }
11771                     goto insert_if;
11772                 }
11773                 else if (   RExC_parse[0] == '<'     /* (?(<NAME>)...) */
11774                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
11775                 {
11776                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
11777                     char *name_start= RExC_parse++;
11778                     U32 num = 0;
11779                     SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA);
11780                     if (   RExC_parse == name_start
11781                         || RExC_parse >= RExC_end
11782                         || *RExC_parse != ch)
11783                     {
11784                         vFAIL2("Sequence (?(%c... not terminated",
11785                             (ch == '>' ? '<' : ch));
11786                     }
11787                     RExC_parse++;
11788                     if (sv_dat) {
11789                         num = add_data( pRExC_state, STR_WITH_LEN("S"));
11790                         RExC_rxi->data->data[num]=(void*)sv_dat;
11791                         SvREFCNT_inc_simple_void_NN(sv_dat);
11792                     }
11793                     ret = reganode(pRExC_state, GROUPPN, num);
11794                     goto insert_if_check_paren;
11795                 }
11796                 else if (memBEGINs(RExC_parse,
11797                                    (STRLEN) (RExC_end - RExC_parse),
11798                                    "DEFINE"))
11799                 {
11800                     ret = reganode(pRExC_state, DEFINEP, 0);
11801                     RExC_parse += DEFINE_len;
11802                     is_define = 1;
11803                     goto insert_if_check_paren;
11804                 }
11805                 else if (RExC_parse[0] == 'R') {
11806                     RExC_parse++;
11807                     /* parno == 0 => /(?(R)YES|NO)/  "in any form of recursion OR eval"
11808                      * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)"
11809                      * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)"
11810                      */
11811                     parno = 0;
11812                     if (RExC_parse[0] == '0') {
11813                         parno = 1;
11814                         RExC_parse++;
11815                     }
11816                     else if (inRANGE(RExC_parse[0], '1', '9')) {
11817                         UV uv;
11818                         endptr = RExC_end;
11819                         if (grok_atoUV(RExC_parse, &uv, &endptr)
11820                             && uv <= I32_MAX
11821                         ) {
11822                             parno = (I32)uv + 1;
11823                             RExC_parse = (char*)endptr;
11824                         }
11825                         /* else "Switch condition not recognized" below */
11826                     } else if (RExC_parse[0] == '&') {
11827                         SV *sv_dat;
11828                         RExC_parse++;
11829                         sv_dat = reg_scan_name(pRExC_state,
11830                                                REG_RSN_RETURN_DATA);
11831                         if (sv_dat)
11832                             parno = 1 + *((I32 *)SvPVX(sv_dat));
11833                     }
11834                     ret = reganode(pRExC_state, INSUBP, parno);
11835                     goto insert_if_check_paren;
11836                 }
11837                 else if (inRANGE(RExC_parse[0], '1', '9')) {
11838                     /* (?(1)...) */
11839                     char c;
11840                     UV uv;
11841                     endptr = RExC_end;
11842                     if (grok_atoUV(RExC_parse, &uv, &endptr)
11843                         && uv <= I32_MAX
11844                     ) {
11845                         parno = (I32)uv;
11846                         RExC_parse = (char*)endptr;
11847                     }
11848                     else {
11849                         vFAIL("panic: grok_atoUV returned FALSE");
11850                     }
11851                     ret = reganode(pRExC_state, GROUPP, parno);
11852
11853                  insert_if_check_paren:
11854                     if (UCHARAT(RExC_parse) != ')') {
11855                         RExC_parse += UTF
11856                                       ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11857                                       : 1;
11858                         vFAIL("Switch condition not recognized");
11859                     }
11860                     nextchar(pRExC_state);
11861                   insert_if:
11862                     if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state,
11863                                                              IFTHEN, 0)))
11864                     {
11865                         REQUIRE_BRANCHJ(flagp, 0);
11866                     }
11867                     br = regbranch(pRExC_state, &flags, 1, depth+1);
11868                     if (br == 0) {
11869                         RETURN_FAIL_ON_RESTART(flags,flagp);
11870                         FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11871                               (UV) flags);
11872                     } else
11873                     if (! REGTAIL(pRExC_state, br, reganode(pRExC_state,
11874                                                              LONGJMP, 0)))
11875                     {
11876                         REQUIRE_BRANCHJ(flagp, 0);
11877                     }
11878                     c = UCHARAT(RExC_parse);
11879                     nextchar(pRExC_state);
11880                     if (flags&HASWIDTH)
11881                         *flagp |= HASWIDTH;
11882                     if (c == '|') {
11883                         if (is_define)
11884                             vFAIL("(?(DEFINE)....) does not allow branches");
11885
11886                         /* Fake one for optimizer.  */
11887                         lastbr = reganode(pRExC_state, IFTHEN, 0);
11888
11889                         if (!regbranch(pRExC_state, &flags, 1, depth+1)) {
11890                             RETURN_FAIL_ON_RESTART(flags, flagp);
11891                             FAIL2("panic: regbranch returned failure, flags=%#" UVxf,
11892                                   (UV) flags);
11893                         }
11894                         if (! REGTAIL(pRExC_state, ret, lastbr)) {
11895                             REQUIRE_BRANCHJ(flagp, 0);
11896                         }
11897                         if (flags&HASWIDTH)
11898                             *flagp |= HASWIDTH;
11899                         c = UCHARAT(RExC_parse);
11900                         nextchar(pRExC_state);
11901                     }
11902                     else
11903                         lastbr = 0;
11904                     if (c != ')') {
11905                         if (RExC_parse >= RExC_end)
11906                             vFAIL("Switch (?(condition)... not terminated");
11907                         else
11908                             vFAIL("Switch (?(condition)... contains too many branches");
11909                     }
11910                     ender = reg_node(pRExC_state, TAIL);
11911                     if (! REGTAIL(pRExC_state, br, ender)) {
11912                         REQUIRE_BRANCHJ(flagp, 0);
11913                     }
11914                     if (lastbr) {
11915                         if (! REGTAIL(pRExC_state, lastbr, ender)) {
11916                             REQUIRE_BRANCHJ(flagp, 0);
11917                         }
11918                         if (! REGTAIL(pRExC_state,
11919                                       REGNODE_OFFSET(
11920                                                  NEXTOPER(
11921                                                  NEXTOPER(REGNODE_p(lastbr)))),
11922                                       ender))
11923                         {
11924                             REQUIRE_BRANCHJ(flagp, 0);
11925                         }
11926                     }
11927                     else
11928                         if (! REGTAIL(pRExC_state, ret, ender)) {
11929                             REQUIRE_BRANCHJ(flagp, 0);
11930                         }
11931 #if 0  /* Removing this doesn't cause failures in the test suite -- khw */
11932                     RExC_size++; /* XXX WHY do we need this?!!
11933                                     For large programs it seems to be required
11934                                     but I can't figure out why. -- dmq*/
11935 #endif
11936                     return ret;
11937                 }
11938                 RExC_parse += UTF
11939                               ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
11940                               : 1;
11941                 vFAIL("Unknown switch condition (?(...))");
11942             }
11943             case '[':           /* (?[ ... ]) */
11944                 return handle_regex_sets(pRExC_state, NULL, flagp, depth+1,
11945                                          oregcomp_parse);
11946             case 0: /* A NUL */
11947                 RExC_parse--; /* for vFAIL to print correctly */
11948                 vFAIL("Sequence (? incomplete");
11949                 break;
11950
11951             case ')':
11952                 if (RExC_strict) {  /* [perl #132851] */
11953                     ckWARNreg(RExC_parse, "Empty (?) without any modifiers");
11954                 }
11955                 /* FALLTHROUGH */
11956             case '*': /* If you want to support (?*...), first reconcile with GH #17363 */
11957             /* FALLTHROUGH */
11958             default: /* e.g., (?i) */
11959                 RExC_parse = (char *) seqstart + 1;
11960               parse_flags:
11961                 parse_lparen_question_flags(pRExC_state);
11962                 if (UCHARAT(RExC_parse) != ':') {
11963                     if (RExC_parse < RExC_end)
11964                         nextchar(pRExC_state);
11965                     *flagp = TRYAGAIN;
11966                     return 0;
11967                 }
11968                 paren = ':';
11969                 nextchar(pRExC_state);
11970                 ret = 0;
11971                 goto parse_rest;
11972             } /* end switch */
11973         }
11974         else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) {   /* (...) */
11975           capturing_parens:
11976             parno = RExC_npar;
11977             RExC_npar++;
11978             if (! ALL_PARENS_COUNTED) {
11979                 /* If we are in our first pass through (and maybe only pass),
11980                  * we  need to allocate memory for the capturing parentheses
11981                  * data structures.
11982                  */
11983
11984                 if (!RExC_parens_buf_size) {
11985                     /* first guess at number of parens we might encounter */
11986                     RExC_parens_buf_size = 10;
11987
11988                     /* setup RExC_open_parens, which holds the address of each
11989                      * OPEN tag, and to make things simpler for the 0 index the
11990                      * start of the program - this is used later for offsets */
11991                     Newxz(RExC_open_parens, RExC_parens_buf_size,
11992                             regnode_offset);
11993                     RExC_open_parens[0] = 1;    /* +1 for REG_MAGIC */
11994
11995                     /* setup RExC_close_parens, which holds the address of each
11996                      * CLOSE tag, and to make things simpler for the 0 index
11997                      * the end of the program - this is used later for offsets
11998                      * */
11999                     Newxz(RExC_close_parens, RExC_parens_buf_size,
12000                             regnode_offset);
12001                     /* we dont know where end op starts yet, so we dont need to
12002                      * set RExC_close_parens[0] like we do RExC_open_parens[0]
12003                      * above */
12004                 }
12005                 else if (RExC_npar > RExC_parens_buf_size) {
12006                     I32 old_size = RExC_parens_buf_size;
12007
12008                     RExC_parens_buf_size *= 2;
12009
12010                     Renew(RExC_open_parens, RExC_parens_buf_size,
12011                             regnode_offset);
12012                     Zero(RExC_open_parens + old_size,
12013                             RExC_parens_buf_size - old_size, regnode_offset);
12014
12015                     Renew(RExC_close_parens, RExC_parens_buf_size,
12016                             regnode_offset);
12017                     Zero(RExC_close_parens + old_size,
12018                             RExC_parens_buf_size - old_size, regnode_offset);
12019                 }
12020             }
12021
12022             ret = reganode(pRExC_state, OPEN, parno);
12023             if (!RExC_nestroot)
12024                 RExC_nestroot = parno;
12025             if (RExC_open_parens && !RExC_open_parens[parno])
12026             {
12027                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12028                     "%*s%*s Setting open paren #%" IVdf " to %d\n",
12029                     22, "|    |", (int)(depth * 2 + 1), "",
12030                     (IV)parno, ret));
12031                 RExC_open_parens[parno]= ret;
12032             }
12033
12034             Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
12035             Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */
12036             is_open = 1;
12037         } else {
12038             /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
12039             paren = ':';
12040             ret = 0;
12041         }
12042     }
12043     else                        /* ! paren */
12044         ret = 0;
12045
12046    parse_rest:
12047     /* Pick up the branches, linking them together. */
12048     parse_start = RExC_parse;   /* MJD */
12049     br = regbranch(pRExC_state, &flags, 1, depth+1);
12050
12051     /*     branch_len = (paren != 0); */
12052
12053     if (br == 0) {
12054         RETURN_FAIL_ON_RESTART(flags, flagp);
12055         FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12056     }
12057     if (*RExC_parse == '|') {
12058         if (RExC_use_BRANCHJ) {
12059             reginsert(pRExC_state, BRANCHJ, br, depth+1);
12060         }
12061         else {                  /* MJD */
12062             reginsert(pRExC_state, BRANCH, br, depth+1);
12063             Set_Node_Length(REGNODE_p(br), paren != 0);
12064             Set_Node_Offset_To_R(br, parse_start-RExC_start);
12065         }
12066         have_branch = 1;
12067     }
12068     else if (paren == ':') {
12069         *flagp |= flags&SIMPLE;
12070     }
12071     if (is_open) {                              /* Starts with OPEN. */
12072         if (! REGTAIL(pRExC_state, ret, br)) {  /* OPEN -> first. */
12073             REQUIRE_BRANCHJ(flagp, 0);
12074         }
12075     }
12076     else if (paren != '?')              /* Not Conditional */
12077         ret = br;
12078     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12079     lastbr = br;
12080     while (*RExC_parse == '|') {
12081         if (RExC_use_BRANCHJ) {
12082             bool shut_gcc_up;
12083
12084             ender = reganode(pRExC_state, LONGJMP, 0);
12085
12086             /* Append to the previous. */
12087             shut_gcc_up = REGTAIL(pRExC_state,
12088                          REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))),
12089                          ender);
12090             PERL_UNUSED_VAR(shut_gcc_up);
12091         }
12092         nextchar(pRExC_state);
12093         if (freeze_paren) {
12094             if (RExC_npar > after_freeze)
12095                 after_freeze = RExC_npar;
12096             RExC_npar = freeze_paren;
12097         }
12098         br = regbranch(pRExC_state, &flags, 0, depth+1);
12099
12100         if (br == 0) {
12101             RETURN_FAIL_ON_RESTART(flags, flagp);
12102             FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags);
12103         }
12104         if (!  REGTAIL(pRExC_state, lastbr, br)) {  /* BRANCH -> BRANCH. */
12105             REQUIRE_BRANCHJ(flagp, 0);
12106         }
12107         lastbr = br;
12108         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
12109     }
12110
12111     if (have_branch || paren != ':') {
12112         regnode * br;
12113
12114         /* Make a closing node, and hook it on the end. */
12115         switch (paren) {
12116         case ':':
12117             ender = reg_node(pRExC_state, TAIL);
12118             break;
12119         case 1: case 2:
12120             ender = reganode(pRExC_state, CLOSE, parno);
12121             if ( RExC_close_parens ) {
12122                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12123                         "%*s%*s Setting close paren #%" IVdf " to %d\n",
12124                         22, "|    |", (int)(depth * 2 + 1), "",
12125                         (IV)parno, ender));
12126                 RExC_close_parens[parno]= ender;
12127                 if (RExC_nestroot == parno)
12128                     RExC_nestroot = 0;
12129             }
12130             Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */
12131             Set_Node_Length(REGNODE_p(ender), 1); /* MJD */
12132             break;
12133         case 's':
12134             ender = reg_node(pRExC_state, SRCLOSE);
12135             RExC_in_script_run = 0;
12136             break;
12137         case '<':
12138         case 'a':
12139         case 'A':
12140         case 'b':
12141         case 'B':
12142         case ',':
12143         case '=':
12144         case '!':
12145             *flagp &= ~HASWIDTH;
12146             /* FALLTHROUGH */
12147         case 't':   /* aTomic */
12148         case '>':
12149             ender = reg_node(pRExC_state, SUCCEED);
12150             break;
12151         case 0:
12152             ender = reg_node(pRExC_state, END);
12153             assert(!RExC_end_op); /* there can only be one! */
12154             RExC_end_op = REGNODE_p(ender);
12155             if (RExC_close_parens) {
12156                 DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_
12157                     "%*s%*s Setting close paren #0 (END) to %d\n",
12158                     22, "|    |", (int)(depth * 2 + 1), "",
12159                     ender));
12160
12161                 RExC_close_parens[0]= ender;
12162             }
12163             break;
12164         }
12165         DEBUG_PARSE_r(
12166             DEBUG_PARSE_MSG("lsbr");
12167             regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state);
12168             regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state);
12169             Perl_re_printf( aTHX_  "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12170                           SvPV_nolen_const(RExC_mysv1),
12171                           (IV)lastbr,
12172                           SvPV_nolen_const(RExC_mysv2),
12173                           (IV)ender,
12174                           (IV)(ender - lastbr)
12175             );
12176         );
12177         if (! REGTAIL(pRExC_state, lastbr, ender)) {
12178             REQUIRE_BRANCHJ(flagp, 0);
12179         }
12180
12181         if (have_branch) {
12182             char is_nothing= 1;
12183             if (depth==1)
12184                 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
12185
12186             /* Hook the tails of the branches to the closing node. */
12187             for (br = REGNODE_p(ret); br; br = regnext(br)) {
12188                 const U8 op = PL_regkind[OP(br)];
12189                 if (op == BRANCH) {
12190                     if (! REGTAIL_STUDY(pRExC_state,
12191                                         REGNODE_OFFSET(NEXTOPER(br)),
12192                                         ender))
12193                     {
12194                         REQUIRE_BRANCHJ(flagp, 0);
12195                     }
12196                     if ( OP(NEXTOPER(br)) != NOTHING
12197                          || regnext(NEXTOPER(br)) != REGNODE_p(ender))
12198                         is_nothing= 0;
12199                 }
12200                 else if (op == BRANCHJ) {
12201                     bool shut_gcc_up = REGTAIL_STUDY(pRExC_state,
12202                                         REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))),
12203                                         ender);
12204                     PERL_UNUSED_VAR(shut_gcc_up);
12205                     /* for now we always disable this optimisation * /
12206                     if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
12207                          || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender))
12208                     */
12209                         is_nothing= 0;
12210                 }
12211             }
12212             if (is_nothing) {
12213                 regnode * ret_as_regnode = REGNODE_p(ret);
12214                 br= PL_regkind[OP(ret_as_regnode)] != BRANCH
12215                                ? regnext(ret_as_regnode)
12216                                : ret_as_regnode;
12217                 DEBUG_PARSE_r(
12218                     DEBUG_PARSE_MSG("NADA");
12219                     regprop(RExC_rx, RExC_mysv1, ret_as_regnode,
12220                                      NULL, pRExC_state);
12221                     regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender),
12222                                      NULL, pRExC_state);
12223                     Perl_re_printf( aTHX_  "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n",
12224                                   SvPV_nolen_const(RExC_mysv1),
12225                                   (IV)REG_NODE_NUM(ret_as_regnode),
12226                                   SvPV_nolen_const(RExC_mysv2),
12227                                   (IV)ender,
12228                                   (IV)(ender - ret)
12229                     );
12230                 );
12231                 OP(br)= NOTHING;
12232                 if (OP(REGNODE_p(ender)) == TAIL) {
12233                     NEXT_OFF(br)= 0;
12234                     RExC_emit= REGNODE_OFFSET(br) + 1;
12235                 } else {
12236                     regnode *opt;
12237                     for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ )
12238                         OP(opt)= OPTIMIZED;
12239                     NEXT_OFF(br)= REGNODE_p(ender) - br;
12240                 }
12241             }
12242         }
12243     }
12244
12245     {
12246         const char *p;
12247          /* Even/odd or x=don't care: 010101x10x */
12248         static const char parens[] = "=!aA<,>Bbt";
12249          /* flag below is set to 0 up through 'A'; 1 for larger */
12250
12251         if (paren && (p = strchr(parens, paren))) {
12252             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
12253             int flag = (p - parens) > 3;
12254
12255             if (paren == '>' || paren == 't') {
12256                 node = SUSPEND, flag = 0;
12257             }
12258
12259             reginsert(pRExC_state, node, ret, depth+1);
12260             Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12261             Set_Node_Offset(REGNODE_p(ret), parse_start + 1);
12262             FLAGS(REGNODE_p(ret)) = flag;
12263             if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL)))
12264             {
12265                 REQUIRE_BRANCHJ(flagp, 0);
12266             }
12267         }
12268     }
12269
12270     /* Check for proper termination. */
12271     if (paren) {
12272         /* restore original flags, but keep (?p) and, if we've encountered
12273          * something in the parse that changes /d rules into /u, keep the /u */
12274         RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
12275         if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
12276             set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
12277         }
12278         if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
12279             RExC_parse = oregcomp_parse;
12280             vFAIL("Unmatched (");
12281         }
12282         nextchar(pRExC_state);
12283     }
12284     else if (!paren && RExC_parse < RExC_end) {
12285         if (*RExC_parse == ')') {
12286             RExC_parse++;
12287             vFAIL("Unmatched )");
12288         }
12289         else
12290             FAIL("Junk on end of regexp");      /* "Can't happen". */
12291         NOT_REACHED; /* NOTREACHED */
12292     }
12293
12294     if (RExC_in_lookbehind) {
12295         RExC_in_lookbehind--;
12296     }
12297     if (RExC_in_lookahead) {
12298         RExC_in_lookahead--;
12299     }
12300     if (after_freeze > RExC_npar)
12301         RExC_npar = after_freeze;
12302     return(ret);
12303 }
12304
12305 /*
12306  - regbranch - one alternative of an | operator
12307  *
12308  * Implements the concatenation operator.
12309  *
12310  * On success, returns the offset at which any next node should be placed into
12311  * the regex engine program being compiled.
12312  *
12313  * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
12314  * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
12315  * UTF-8
12316  */
12317 STATIC regnode_offset
12318 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
12319 {
12320     regnode_offset ret;
12321     regnode_offset chain = 0;
12322     regnode_offset latest;
12323     I32 flags = 0, c = 0;
12324     GET_RE_DEBUG_FLAGS_DECL;
12325
12326     PERL_ARGS_ASSERT_REGBRANCH;
12327
12328     DEBUG_PARSE("brnc");
12329
12330     if (first)
12331         ret = 0;
12332     else {
12333         if (RExC_use_BRANCHJ)
12334             ret = reganode(pRExC_state, BRANCHJ, 0);
12335         else {
12336             ret = reg_node(pRExC_state, BRANCH);
12337             Set_Node_Length(REGNODE_p(ret), 1);
12338         }
12339     }
12340
12341     *flagp = WORST;                     /* Tentatively. */
12342
12343     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12344                             FALSE /* Don't force to /x */ );
12345     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
12346         flags &= ~TRYAGAIN;
12347         latest = regpiece(pRExC_state, &flags, depth+1);
12348         if (latest == 0) {
12349             if (flags & TRYAGAIN)
12350                 continue;
12351             RETURN_FAIL_ON_RESTART(flags, flagp);
12352             FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags);
12353         }
12354         else if (ret == 0)
12355             ret = latest;
12356         *flagp |= flags&(HASWIDTH|POSTPONED);
12357         if (chain == 0)         /* First piece. */
12358             *flagp |= flags&SPSTART;
12359         else {
12360             /* FIXME adding one for every branch after the first is probably
12361              * excessive now we have TRIE support. (hv) */
12362             MARK_NAUGHTY(1);
12363             if (! REGTAIL(pRExC_state, chain, latest)) {
12364                 /* XXX We could just redo this branch, but figuring out what
12365                  * bookkeeping needs to be reset is a pain, and it's likely
12366                  * that other branches that goto END will also be too large */
12367                 REQUIRE_BRANCHJ(flagp, 0);
12368             }
12369         }
12370         chain = latest;
12371         c++;
12372     }
12373     if (chain == 0) {   /* Loop ran zero times. */
12374         chain = reg_node(pRExC_state, NOTHING);
12375         if (ret == 0)
12376             ret = chain;
12377     }
12378     if (c == 1) {
12379         *flagp |= flags&SIMPLE;
12380     }
12381
12382     return ret;
12383 }
12384
12385 /*
12386  - regpiece - something followed by possible quantifier * + ? {n,m}
12387  *
12388  * Note that the branching code sequences used for ? and the general cases
12389  * of * and + are somewhat optimized:  they use the same NOTHING node as
12390  * both the endmarker for their branch list and the body of the last branch.
12391  * It might seem that this node could be dispensed with entirely, but the
12392  * endmarker role is not redundant.
12393  *
12394  * On success, returns the offset at which any next node should be placed into
12395  * the regex engine program being compiled.
12396  *
12397  * Returns 0 otherwise, with *flagp set to indicate why:
12398  *  TRYAGAIN        if regatom() returns 0 with TRYAGAIN.
12399  *  RESTART_PARSE   if the parse needs to be restarted, or'd with
12400  *                  NEED_UTF8 if the pattern needs to be upgraded to UTF-8.
12401  */
12402 STATIC regnode_offset
12403 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12404 {
12405     regnode_offset ret;
12406     char op;
12407     char *next;
12408     I32 flags;
12409     const char * const origparse = RExC_parse;
12410     I32 min;
12411     I32 max = REG_INFTY;
12412 #ifdef RE_TRACK_PATTERN_OFFSETS
12413     char *parse_start;
12414 #endif
12415     const char *maxpos = NULL;
12416     UV uv;
12417
12418     /* Save the original in case we change the emitted regop to a FAIL. */
12419     const regnode_offset orig_emit = RExC_emit;
12420
12421     GET_RE_DEBUG_FLAGS_DECL;
12422
12423     PERL_ARGS_ASSERT_REGPIECE;
12424
12425     DEBUG_PARSE("piec");
12426
12427     ret = regatom(pRExC_state, &flags, depth+1);
12428     if (ret == 0) {
12429         RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN);
12430         FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags);
12431     }
12432
12433     op = *RExC_parse;
12434
12435     if (op == '{' && regcurly(RExC_parse)) {
12436         maxpos = NULL;
12437 #ifdef RE_TRACK_PATTERN_OFFSETS
12438         parse_start = RExC_parse; /* MJD */
12439 #endif
12440         next = RExC_parse + 1;
12441         while (isDIGIT(*next) || *next == ',') {
12442             if (*next == ',') {
12443                 if (maxpos)
12444                     break;
12445                 else
12446                     maxpos = next;
12447             }
12448             next++;
12449         }
12450         if (*next == '}') {             /* got one */
12451             const char* endptr;
12452             if (!maxpos)
12453                 maxpos = next;
12454             RExC_parse++;
12455             if (isDIGIT(*RExC_parse)) {
12456                 endptr = RExC_end;
12457                 if (!grok_atoUV(RExC_parse, &uv, &endptr))
12458                     vFAIL("Invalid quantifier in {,}");
12459                 if (uv >= REG_INFTY)
12460                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12461                 min = (I32)uv;
12462             } else {
12463                 min = 0;
12464             }
12465             if (*maxpos == ',')
12466                 maxpos++;
12467             else
12468                 maxpos = RExC_parse;
12469             if (isDIGIT(*maxpos)) {
12470                 endptr = RExC_end;
12471                 if (!grok_atoUV(maxpos, &uv, &endptr))
12472                     vFAIL("Invalid quantifier in {,}");
12473                 if (uv >= REG_INFTY)
12474                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
12475                 max = (I32)uv;
12476             } else {
12477                 max = REG_INFTY;                /* meaning "infinity" */
12478             }
12479             RExC_parse = next;
12480             nextchar(pRExC_state);
12481             if (max < min) {    /* If can't match, warn and optimize to fail
12482                                    unconditionally */
12483                 reginsert(pRExC_state, OPFAIL, orig_emit, depth+1);
12484                 ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
12485                 NEXT_OFF(REGNODE_p(orig_emit)) =
12486                                     regarglen[OPFAIL] + NODE_STEP_REGNODE;
12487                 return ret;
12488             }
12489             else if (min == max && *RExC_parse == '?')
12490             {
12491                 ckWARN2reg(RExC_parse + 1,
12492                            "Useless use of greediness modifier '%c'",
12493                            *RExC_parse);
12494             }
12495
12496           do_curly:
12497             if ((flags&SIMPLE)) {
12498                 if (min == 0 && max == REG_INFTY) {
12499                     reginsert(pRExC_state, STAR, ret, depth+1);
12500                     MARK_NAUGHTY(4);
12501                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12502                     goto nest_check;
12503                 }
12504                 if (min == 1 && max == REG_INFTY) {
12505                     reginsert(pRExC_state, PLUS, ret, depth+1);
12506                     MARK_NAUGHTY(3);
12507                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12508                     goto nest_check;
12509                 }
12510                 MARK_NAUGHTY_EXP(2, 2);
12511                 reginsert(pRExC_state, CURLY, ret, depth+1);
12512                 Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */
12513                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start);
12514             }
12515             else {
12516                 const regnode_offset w = reg_node(pRExC_state, WHILEM);
12517
12518                 FLAGS(REGNODE_p(w)) = 0;
12519                 if (!  REGTAIL(pRExC_state, ret, w)) {
12520                     REQUIRE_BRANCHJ(flagp, 0);
12521                 }
12522                 if (RExC_use_BRANCHJ) {
12523                     reginsert(pRExC_state, LONGJMP, ret, depth+1);
12524                     reginsert(pRExC_state, NOTHING, ret, depth+1);
12525                     NEXT_OFF(REGNODE_p(ret)) = 3;       /* Go over LONGJMP. */
12526                 }
12527                 reginsert(pRExC_state, CURLYX, ret, depth+1);
12528                                 /* MJD hk */
12529                 Set_Node_Offset(REGNODE_p(ret), parse_start+1);
12530                 Set_Node_Length(REGNODE_p(ret),
12531                                 op == '{' ? (RExC_parse - parse_start) : 1);
12532
12533                 if (RExC_use_BRANCHJ)
12534                     NEXT_OFF(REGNODE_p(ret)) = 3;   /* Go over NOTHING to
12535                                                        LONGJMP. */
12536                 if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state,
12537                                                           NOTHING)))
12538                 {
12539                     REQUIRE_BRANCHJ(flagp, 0);
12540                 }
12541                 RExC_whilem_seen++;
12542                 MARK_NAUGHTY_EXP(1, 4);     /* compound interest */
12543             }
12544             FLAGS(REGNODE_p(ret)) = 0;
12545
12546             if (min > 0)
12547                 *flagp = WORST;
12548             if (max > 0)
12549                 *flagp |= HASWIDTH;
12550             ARG1_SET(REGNODE_p(ret), (U16)min);
12551             ARG2_SET(REGNODE_p(ret), (U16)max);
12552             if (max == REG_INFTY)
12553                 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
12554
12555             goto nest_check;
12556         }
12557     }
12558
12559     if (!ISMULT1(op)) {
12560         *flagp = flags;
12561         return(ret);
12562     }
12563
12564 #if 0                           /* Now runtime fix should be reliable. */
12565
12566     /* if this is reinstated, don't forget to put this back into perldiag:
12567
12568             =item Regexp *+ operand could be empty at {#} in regex m/%s/
12569
12570            (F) The part of the regexp subject to either the * or + quantifier
12571            could match an empty string. The {#} shows in the regular
12572            expression about where the problem was discovered.
12573
12574     */
12575
12576     if (!(flags&HASWIDTH) && op != '?')
12577       vFAIL("Regexp *+ operand could be empty");
12578 #endif
12579
12580 #ifdef RE_TRACK_PATTERN_OFFSETS
12581     parse_start = RExC_parse;
12582 #endif
12583     nextchar(pRExC_state);
12584
12585     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
12586
12587     if (op == '*') {
12588         min = 0;
12589         goto do_curly;
12590     }
12591     else if (op == '+') {
12592         min = 1;
12593         goto do_curly;
12594     }
12595     else if (op == '?') {
12596         min = 0; max = 1;
12597         goto do_curly;
12598     }
12599   nest_check:
12600     if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
12601         ckWARN2reg(RExC_parse,
12602                    "%" UTF8f " matches null string many times",
12603                    UTF8fARG(UTF, (RExC_parse >= origparse
12604                                  ? RExC_parse - origparse
12605                                  : 0),
12606                    origparse));
12607     }
12608
12609     if (*RExC_parse == '?') {
12610         nextchar(pRExC_state);
12611         reginsert(pRExC_state, MINMOD, ret, depth+1);
12612         if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) {
12613             REQUIRE_BRANCHJ(flagp, 0);
12614         }
12615     }
12616     else if (*RExC_parse == '+') {
12617         regnode_offset ender;
12618         nextchar(pRExC_state);
12619         ender = reg_node(pRExC_state, SUCCEED);
12620         if (! REGTAIL(pRExC_state, ret, ender)) {
12621             REQUIRE_BRANCHJ(flagp, 0);
12622         }
12623         reginsert(pRExC_state, SUSPEND, ret, depth+1);
12624         ender = reg_node(pRExC_state, TAIL);
12625         if (! REGTAIL(pRExC_state, ret, ender)) {
12626             REQUIRE_BRANCHJ(flagp, 0);
12627         }
12628     }
12629
12630     if (ISMULT2(RExC_parse)) {
12631         RExC_parse++;
12632         vFAIL("Nested quantifiers");
12633     }
12634
12635     return(ret);
12636 }
12637
12638 STATIC bool
12639 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
12640                 regnode_offset * node_p,
12641                 UV * code_point_p,
12642                 int * cp_count,
12643                 I32 * flagp,
12644                 const bool strict,
12645                 const U32 depth
12646     )
12647 {
12648  /* This routine teases apart the various meanings of \N and returns
12649   * accordingly.  The input parameters constrain which meaning(s) is/are valid
12650   * in the current context.
12651   *
12652   * Exactly one of <node_p> and <code_point_p> must be non-NULL.
12653   *
12654   * If <code_point_p> is not NULL, the context is expecting the result to be a
12655   * single code point.  If this \N instance turns out to a single code point,
12656   * the function returns TRUE and sets *code_point_p to that code point.
12657   *
12658   * If <node_p> is not NULL, the context is expecting the result to be one of
12659   * the things representable by a regnode.  If this \N instance turns out to be
12660   * one such, the function generates the regnode, returns TRUE and sets *node_p
12661   * to point to the offset of that regnode into the regex engine program being
12662   * compiled.
12663   *
12664   * If this instance of \N isn't legal in any context, this function will
12665   * generate a fatal error and not return.
12666   *
12667   * On input, RExC_parse should point to the first char following the \N at the
12668   * time of the call.  On successful return, RExC_parse will have been updated
12669   * to point to just after the sequence identified by this routine.  Also
12670   * *flagp has been updated as needed.
12671   *
12672   * When there is some problem with the current context and this \N instance,
12673   * the function returns FALSE, without advancing RExC_parse, nor setting
12674   * *node_p, nor *code_point_p, nor *flagp.
12675   *
12676   * If <cp_count> is not NULL, the caller wants to know the length (in code
12677   * points) that this \N sequence matches.  This is set, and the input is
12678   * parsed for errors, even if the function returns FALSE, as detailed below.
12679   *
12680   * There are 6 possibilities here, as detailed in the next 6 paragraphs.
12681   *
12682   * Probably the most common case is for the \N to specify a single code point.
12683   * *cp_count will be set to 1, and *code_point_p will be set to that code
12684   * point.
12685   *
12686   * Another possibility is for the input to be an empty \N{}.  This is no
12687   * longer accepted, and will generate a fatal error.
12688   *
12689   * Another possibility is for a custom charnames handler to be in effect which
12690   * translates the input name to an empty string.  *cp_count will be set to 0.
12691   * *node_p will be set to a generated NOTHING node.
12692   *
12693   * Still another possibility is for the \N to mean [^\n]. *cp_count will be
12694   * set to 0. *node_p will be set to a generated REG_ANY node.
12695   *
12696   * The fifth possibility is that \N resolves to a sequence of more than one
12697   * code points.  *cp_count will be set to the number of code points in the
12698   * sequence. *node_p will be set to a generated node returned by this
12699   * function calling S_reg().
12700   *
12701   * The final possibility is that it is premature to be calling this function;
12702   * the parse needs to be restarted.  This can happen when this changes from
12703   * /d to /u rules, or when the pattern needs to be upgraded to UTF-8.  The
12704   * latter occurs only when the fifth possibility would otherwise be in
12705   * effect, and is because one of those code points requires the pattern to be
12706   * recompiled as UTF-8.  The function returns FALSE, and sets the
12707   * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate.  When this
12708   * happens, the caller needs to desist from continuing parsing, and return
12709   * this information to its caller.  This is not set for when there is only one
12710   * code point, as this can be called as part of an ANYOF node, and they can
12711   * store above-Latin1 code points without the pattern having to be in UTF-8.
12712   *
12713   * For non-single-quoted regexes, the tokenizer has resolved character and
12714   * sequence names inside \N{...} into their Unicode values, normalizing the
12715   * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
12716   * hex-represented code points in the sequence.  This is done there because
12717   * the names can vary based on what charnames pragma is in scope at the time,
12718   * so we need a way to take a snapshot of what they resolve to at the time of
12719   * the original parse. [perl #56444].
12720   *
12721   * That parsing is skipped for single-quoted regexes, so here we may get
12722   * '\N{NAME}', which is parsed now.  If the single-quoted regex is something
12723   * like '\N{U+41}', that code point is Unicode, and has to be translated into
12724   * the native character set for non-ASCII platforms.  The other possibilities
12725   * are already native, so no translation is done. */
12726
12727     char * endbrace;    /* points to '}' following the name */
12728     char* p = RExC_parse; /* Temporary */
12729
12730     SV * substitute_parse = NULL;
12731     char *orig_end;
12732     char *save_start;
12733     I32 flags;
12734
12735     GET_RE_DEBUG_FLAGS_DECL;
12736
12737     PERL_ARGS_ASSERT_GROK_BSLASH_N;
12738
12739     GET_RE_DEBUG_FLAGS;
12740
12741     assert(cBOOL(node_p) ^ cBOOL(code_point_p));  /* Exactly one should be set */
12742     assert(! (node_p && cp_count));               /* At most 1 should be set */
12743
12744     if (cp_count) {     /* Initialize return for the most common case */
12745         *cp_count = 1;
12746     }
12747
12748     /* The [^\n] meaning of \N ignores spaces and comments under the /x
12749      * modifier.  The other meanings do not, so use a temporary until we find
12750      * out which we are being called with */
12751     skip_to_be_ignored_text(pRExC_state, &p,
12752                             FALSE /* Don't force to /x */ );
12753
12754     /* Disambiguate between \N meaning a named character versus \N meaning
12755      * [^\n].  The latter is assumed when the {...} following the \N is a legal
12756      * quantifier, or if there is no '{' at all */
12757     if (*p != '{' || regcurly(p)) {
12758         RExC_parse = p;
12759         if (cp_count) {
12760             *cp_count = -1;
12761         }
12762
12763         if (! node_p) {
12764             return FALSE;
12765         }
12766
12767         *node_p = reg_node(pRExC_state, REG_ANY);
12768         *flagp |= HASWIDTH|SIMPLE;
12769         MARK_NAUGHTY(1);
12770         Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */
12771         return TRUE;
12772     }
12773
12774     /* The test above made sure that the next real character is a '{', but
12775      * under the /x modifier, it could be separated by space (or a comment and
12776      * \n) and this is not allowed (for consistency with \x{...} and the
12777      * tokenizer handling of \N{NAME}). */
12778     if (*RExC_parse != '{') {
12779         vFAIL("Missing braces on \\N{}");
12780     }
12781
12782     RExC_parse++;       /* Skip past the '{' */
12783
12784     endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
12785     if (! endbrace) { /* no trailing brace */
12786         vFAIL2("Missing right brace on \\%c{}", 'N');
12787     }
12788
12789     /* Here, we have decided it should be a named character or sequence.  These
12790      * imply Unicode semantics */
12791     REQUIRE_UNI_RULES(flagp, FALSE);
12792
12793     /* \N{_} is what toke.c returns to us to indicate a name that evaluates to
12794      * nothing at all (not allowed under strict) */
12795     if (endbrace - RExC_parse == 1 && *RExC_parse == '_') {
12796         RExC_parse = endbrace;
12797         if (strict) {
12798             RExC_parse++;   /* Position after the "}" */
12799             vFAIL("Zero length \\N{}");
12800         }
12801
12802         if (cp_count) {
12803             *cp_count = 0;
12804         }
12805         nextchar(pRExC_state);
12806         if (! node_p) {
12807             return FALSE;
12808         }
12809
12810         *node_p = reg_node(pRExC_state, NOTHING);
12811         return TRUE;
12812     }
12813
12814     if (endbrace - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) {
12815
12816         /* Here, the name isn't of the form  U+....  This can happen if the
12817          * pattern is single-quoted, so didn't get evaluated in toke.c.  Now
12818          * is the time to find out what the name means */
12819
12820         const STRLEN name_len = endbrace - RExC_parse;
12821         SV *  value_sv;     /* What does this name evaluate to */
12822         SV ** value_svp;
12823         const U8 * value;   /* string of name's value */
12824         STRLEN value_len;   /* and its length */
12825
12826         /*  RExC_unlexed_names is a hash of names that weren't evaluated by
12827          *  toke.c, and their values. Make sure is initialized */
12828         if (! RExC_unlexed_names) {
12829             RExC_unlexed_names = newHV();
12830         }
12831
12832         /* If we have already seen this name in this pattern, use that.  This
12833          * allows us to only call the charnames handler once per name per
12834          * pattern.  A broken or malicious handler could return something
12835          * different each time, which could cause the results to vary depending
12836          * on if something gets added or subtracted from the pattern that
12837          * causes the number of passes to change, for example */
12838         if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse,
12839                                                       name_len, 0)))
12840         {
12841             value_sv = *value_svp;
12842         }
12843         else { /* Otherwise we have to go out and get the name */
12844             const char * error_msg = NULL;
12845             value_sv = get_and_check_backslash_N_name(RExC_parse, endbrace,
12846                                                       UTF,
12847                                                       &error_msg);
12848             if (error_msg) {
12849                 RExC_parse = endbrace;
12850                 vFAIL(error_msg);
12851             }
12852
12853             /* If no error message, should have gotten a valid return */
12854             assert (value_sv);
12855
12856             /* Save the name's meaning for later use */
12857             if (! hv_store(RExC_unlexed_names, RExC_parse, name_len,
12858                            value_sv, 0))
12859             {
12860                 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
12861             }
12862         }
12863
12864         /* Here, we have the value the name evaluates to in 'value_sv' */
12865         value = (U8 *) SvPV(value_sv, value_len);
12866
12867         /* See if the result is one code point vs 0 or multiple */
12868         if (inRANGE(value_len, 1, ((UV) SvUTF8(value_sv)
12869                                   ? UTF8SKIP(value)
12870                                   : 1)))
12871         {
12872             /* Here, exactly one code point.  If that isn't what is wanted,
12873              * fail */
12874             if (! code_point_p) {
12875                 RExC_parse = p;
12876                 return FALSE;
12877             }
12878
12879             /* Convert from string to numeric code point */
12880             *code_point_p = (SvUTF8(value_sv))
12881                             ? valid_utf8_to_uvchr(value, NULL)
12882                             : *value;
12883
12884             /* Have parsed this entire single code point \N{...}.  *cp_count
12885              * has already been set to 1, so don't do it again. */
12886             RExC_parse = endbrace;
12887             nextchar(pRExC_state);
12888             return TRUE;
12889         } /* End of is a single code point */
12890
12891         /* Count the code points, if caller desires.  The API says to do this
12892          * even if we will later return FALSE */
12893         if (cp_count) {
12894             *cp_count = 0;
12895
12896             *cp_count = (SvUTF8(value_sv))
12897                         ? utf8_length(value, value + value_len)
12898                         : value_len;
12899         }
12900
12901         /* Fail if caller doesn't want to handle a multi-code-point sequence.
12902          * But don't back the pointer up if the caller wants to know how many
12903          * code points there are (they need to handle it themselves in this
12904          * case).  */
12905         if (! node_p) {
12906             if (! cp_count) {
12907                 RExC_parse = p;
12908             }
12909             return FALSE;
12910         }
12911
12912         /* Convert this to a sub-pattern of the form "(?: ... )", and then call
12913          * reg recursively to parse it.  That way, it retains its atomicness,
12914          * while not having to worry about any special handling that some code
12915          * points may have. */
12916
12917         substitute_parse = newSVpvs("?:");
12918         sv_catsv(substitute_parse, value_sv);
12919         sv_catpv(substitute_parse, ")");
12920
12921         /* The value should already be native, so no need to convert on EBCDIC
12922          * platforms.*/
12923         assert(! RExC_recode_x_to_native);
12924
12925     }
12926     else {   /* \N{U+...} */
12927         Size_t count = 0;   /* code point count kept internally */
12928
12929         /* We can get to here when the input is \N{U+...} or when toke.c has
12930          * converted a name to the \N{U+...} form.  This include changing a
12931          * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */
12932
12933         RExC_parse += 2;    /* Skip past the 'U+' */
12934
12935         /* Code points are separated by dots.  The '}' terminates the whole
12936          * thing. */
12937
12938         do {    /* Loop until the ending brace */
12939             UV cp = 0;
12940             char * start_digit;     /* The first of the current code point */
12941             if (! isXDIGIT(*RExC_parse)) {
12942                 RExC_parse++;
12943                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
12944             }
12945
12946             start_digit = RExC_parse;
12947             count++;
12948
12949             /* Loop through the hex digits of the current code point */
12950             do {
12951                 /* Adding this digit will shift the result 4 bits.  If that
12952                  * result would be above the legal max, it's overflow */
12953                 if (cp > MAX_LEGAL_CP >> 4) {
12954
12955                     /* Find the end of the code point */
12956                     do {
12957                         RExC_parse ++;
12958                     } while (isXDIGIT(*RExC_parse) || *RExC_parse == '_');
12959
12960                     /* Be sure to synchronize this message with the similar one
12961                      * in utf8.c */
12962                     vFAIL4("Use of code point 0x%.*s is not allowed; the"
12963                         " permissible max is 0x%" UVxf,
12964                         (int) (RExC_parse - start_digit), start_digit,
12965                         MAX_LEGAL_CP);
12966                 }
12967
12968                 /* Accumulate this (valid) digit into the running total */
12969                 cp  = (cp << 4) + READ_XDIGIT(RExC_parse);
12970
12971                 /* READ_XDIGIT advanced the input pointer.  Ignore a single
12972                  * underscore separator */
12973                 if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) {
12974                     RExC_parse++;
12975                 }
12976             } while (isXDIGIT(*RExC_parse));
12977
12978             /* Here, have accumulated the next code point */
12979             if (RExC_parse >= endbrace) {   /* If done ... */
12980                 if (count != 1) {
12981                     goto do_concat;
12982                 }
12983
12984                 /* Here, is a single code point; fail if doesn't want that */
12985                 if (! code_point_p) {
12986                     RExC_parse = p;
12987                     return FALSE;
12988                 }
12989
12990                 /* A single code point is easy to handle; just return it */
12991                 *code_point_p = UNI_TO_NATIVE(cp);
12992                 RExC_parse = endbrace;
12993                 nextchar(pRExC_state);
12994                 return TRUE;
12995             }
12996
12997             /* Here, the only legal thing would be a multiple character
12998              * sequence (of the form "\N{U+c1.c2. ... }".   So the next
12999              * character must be a dot (and the one after that can't be the
13000              * endbrace, or we'd have something like \N{U+100.} ) */
13001             if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) {
13002                 RExC_parse += (RExC_orig_utf8)  /* point to after 1st invalid */
13003                                 ? UTF8SKIP(RExC_parse)
13004                                 : 1;
13005                 if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */
13006                     RExC_parse = endbrace;
13007                 }
13008                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
13009             }
13010
13011             /* Here, looks like its really a multiple character sequence.  Fail
13012              * if that's not what the caller wants.  But continue with counting
13013              * and error checking if they still want a count */
13014             if (! node_p && ! cp_count) {
13015                 return FALSE;
13016             }
13017
13018             /* What is done here is to convert this to a sub-pattern of the
13019              * form \x{char1}\x{char2}...  and then call reg recursively to
13020              * parse it (enclosing in "(?: ... )" ).  That way, it retains its
13021              * atomicness, while not having to worry about special handling
13022              * that some code points may have.  We don't create a subpattern,
13023              * but go through the motions of code point counting and error
13024              * checking, if the caller doesn't want a node returned. */
13025
13026             if (node_p && count == 1) {
13027                 substitute_parse = newSVpvs("?:");
13028             }
13029
13030           do_concat:
13031
13032             if (node_p) {
13033                 /* Convert to notation the rest of the code understands */
13034                 sv_catpvs(substitute_parse, "\\x{");
13035                 sv_catpvn(substitute_parse, start_digit,
13036                                             RExC_parse - start_digit);
13037                 sv_catpvs(substitute_parse, "}");
13038             }
13039
13040             /* Move to after the dot (or ending brace the final time through.)
13041              * */
13042             RExC_parse++;
13043             count++;
13044
13045         } while (RExC_parse < endbrace);
13046
13047         if (! node_p) { /* Doesn't want the node */
13048             assert (cp_count);
13049
13050             *cp_count = count;
13051             return FALSE;
13052         }
13053
13054         sv_catpvs(substitute_parse, ")");
13055
13056         /* The values are Unicode, and therefore have to be converted to native
13057          * on a non-Unicode (meaning non-ASCII) platform. */
13058         SET_recode_x_to_native(1);
13059     }
13060
13061     /* Here, we have the string the name evaluates to, ready to be parsed,
13062      * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}"
13063      * constructs.  This can be called from within a substitute parse already.
13064      * The error reporting mechanism doesn't work for 2 levels of this, but the
13065      * code above has validated this new construct, so there should be no
13066      * errors generated by the below.  And this isn' an exact copy, so the
13067      * mechanism to seamlessly deal with this won't work, so turn off warnings
13068      * during it */
13069     save_start = RExC_start;
13070     orig_end = RExC_end;
13071
13072     RExC_parse = RExC_start = SvPVX(substitute_parse);
13073     RExC_end = RExC_parse + SvCUR(substitute_parse);
13074     TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
13075
13076     *node_p = reg(pRExC_state, 1, &flags, depth+1);
13077
13078     /* Restore the saved values */
13079     RESTORE_WARNINGS;
13080     RExC_start = save_start;
13081     RExC_parse = endbrace;
13082     RExC_end = orig_end;
13083     SET_recode_x_to_native(0);
13084
13085     SvREFCNT_dec_NN(substitute_parse);
13086
13087     if (! *node_p) {
13088         RETURN_FAIL_ON_RESTART(flags, flagp);
13089         FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf,
13090             (UV) flags);
13091     }
13092     *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13093
13094     nextchar(pRExC_state);
13095
13096     return TRUE;
13097 }
13098
13099
13100 PERL_STATIC_INLINE U8
13101 S_compute_EXACTish(RExC_state_t *pRExC_state)
13102 {
13103     U8 op;
13104
13105     PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
13106
13107     if (! FOLD) {
13108         return (LOC)
13109                 ? EXACTL
13110                 : EXACT;
13111     }
13112
13113     op = get_regex_charset(RExC_flags);
13114     if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
13115         op--; /* /a is same as /u, and map /aa's offset to what /a's would have
13116                  been, so there is no hole */
13117     }
13118
13119     return op + EXACTF;
13120 }
13121
13122 STATIC bool
13123 S_new_regcurly(const char *s, const char *e)
13124 {
13125     /* This is a temporary function designed to match the most lenient form of
13126      * a {m,n} quantifier we ever envision, with either number omitted, and
13127      * spaces anywhere between/before/after them.
13128      *
13129      * If this function fails, then the string it matches is very unlikely to
13130      * ever be considered a valid quantifier, so we can allow the '{' that
13131      * begins it to be considered as a literal */
13132
13133     bool has_min = FALSE;
13134     bool has_max = FALSE;
13135
13136     PERL_ARGS_ASSERT_NEW_REGCURLY;
13137
13138     if (s >= e || *s++ != '{')
13139         return FALSE;
13140
13141     while (s < e && isSPACE(*s)) {
13142         s++;
13143     }
13144     while (s < e && isDIGIT(*s)) {
13145         has_min = TRUE;
13146         s++;
13147     }
13148     while (s < e && isSPACE(*s)) {
13149         s++;
13150     }
13151
13152     if (*s == ',') {
13153         s++;
13154         while (s < e && isSPACE(*s)) {
13155             s++;
13156         }
13157         while (s < e && isDIGIT(*s)) {
13158             has_max = TRUE;
13159             s++;
13160         }
13161         while (s < e && isSPACE(*s)) {
13162             s++;
13163         }
13164     }
13165
13166     return s < e && *s == '}' && (has_min || has_max);
13167 }
13168
13169 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
13170  * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
13171
13172 static I32
13173 S_backref_value(char *p, char *e)
13174 {
13175     const char* endptr = e;
13176     UV val;
13177     if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
13178         return (I32)val;
13179     return I32_MAX;
13180 }
13181
13182
13183 /*
13184  - regatom - the lowest level
13185
13186    Try to identify anything special at the start of the current parse position.
13187    If there is, then handle it as required. This may involve generating a
13188    single regop, such as for an assertion; or it may involve recursing, such as
13189    to handle a () structure.
13190
13191    If the string doesn't start with something special then we gobble up
13192    as much literal text as we can.  If we encounter a quantifier, we have to
13193    back off the final literal character, as that quantifier applies to just it
13194    and not to the whole string of literals.
13195
13196    Once we have been able to handle whatever type of thing started the
13197    sequence, we return the offset into the regex engine program being compiled
13198    at which any  next regnode should be placed.
13199
13200    Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN.
13201    Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be
13202    restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
13203    Otherwise does not return 0.
13204
13205    Note: we have to be careful with escapes, as they can be both literal
13206    and special, and in the case of \10 and friends, context determines which.
13207
13208    A summary of the code structure is:
13209
13210    switch (first_byte) {
13211         cases for each special:
13212             handle this special;
13213             break;
13214         case '\\':
13215             switch (2nd byte) {
13216                 cases for each unambiguous special:
13217                     handle this special;
13218                     break;
13219                 cases for each ambigous special/literal:
13220                     disambiguate;
13221                     if (special)  handle here
13222                     else goto defchar;
13223                 default: // unambiguously literal:
13224                     goto defchar;
13225             }
13226         default:  // is a literal char
13227             // FALL THROUGH
13228         defchar:
13229             create EXACTish node for literal;
13230             while (more input and node isn't full) {
13231                 switch (input_byte) {
13232                    cases for each special;
13233                        make sure parse pointer is set so that the next call to
13234                            regatom will see this special first
13235                        goto loopdone; // EXACTish node terminated by prev. char
13236                    default:
13237                        append char to EXACTISH node;
13238                 }
13239                 get next input byte;
13240             }
13241         loopdone:
13242    }
13243    return the generated node;
13244
13245    Specifically there are two separate switches for handling
13246    escape sequences, with the one for handling literal escapes requiring
13247    a dummy entry for all of the special escapes that are actually handled
13248    by the other.
13249
13250 */
13251
13252 STATIC regnode_offset
13253 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
13254 {
13255     dVAR;
13256     regnode_offset ret = 0;
13257     I32 flags = 0;
13258     char *parse_start;
13259     U8 op;
13260     int invert = 0;
13261
13262     GET_RE_DEBUG_FLAGS_DECL;
13263
13264     *flagp = WORST;             /* Tentatively. */
13265
13266     DEBUG_PARSE("atom");
13267
13268     PERL_ARGS_ASSERT_REGATOM;
13269
13270   tryagain:
13271     parse_start = RExC_parse;
13272     assert(RExC_parse < RExC_end);
13273     switch ((U8)*RExC_parse) {
13274     case '^':
13275         RExC_seen_zerolen++;
13276         nextchar(pRExC_state);
13277         if (RExC_flags & RXf_PMf_MULTILINE)
13278             ret = reg_node(pRExC_state, MBOL);
13279         else
13280             ret = reg_node(pRExC_state, SBOL);
13281         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13282         break;
13283     case '$':
13284         nextchar(pRExC_state);
13285         if (*RExC_parse)
13286             RExC_seen_zerolen++;
13287         if (RExC_flags & RXf_PMf_MULTILINE)
13288             ret = reg_node(pRExC_state, MEOL);
13289         else
13290             ret = reg_node(pRExC_state, SEOL);
13291         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13292         break;
13293     case '.':
13294         nextchar(pRExC_state);
13295         if (RExC_flags & RXf_PMf_SINGLELINE)
13296             ret = reg_node(pRExC_state, SANY);
13297         else
13298             ret = reg_node(pRExC_state, REG_ANY);
13299         *flagp |= HASWIDTH|SIMPLE;
13300         MARK_NAUGHTY(1);
13301         Set_Node_Length(REGNODE_p(ret), 1); /* MJD */
13302         break;
13303     case '[':
13304     {
13305         char * const oregcomp_parse = ++RExC_parse;
13306         ret = regclass(pRExC_state, flagp, depth+1,
13307                        FALSE, /* means parse the whole char class */
13308                        TRUE, /* allow multi-char folds */
13309                        FALSE, /* don't silence non-portable warnings. */
13310                        (bool) RExC_strict,
13311                        TRUE, /* Allow an optimized regnode result */
13312                        NULL);
13313         if (ret == 0) {
13314             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13315             FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13316                   (UV) *flagp);
13317         }
13318         if (*RExC_parse != ']') {
13319             RExC_parse = oregcomp_parse;
13320             vFAIL("Unmatched [");
13321         }
13322         nextchar(pRExC_state);
13323         Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */
13324         break;
13325     }
13326     case '(':
13327         nextchar(pRExC_state);
13328         ret = reg(pRExC_state, 2, &flags, depth+1);
13329         if (ret == 0) {
13330                 if (flags & TRYAGAIN) {
13331                     if (RExC_parse >= RExC_end) {
13332                          /* Make parent create an empty node if needed. */
13333                         *flagp |= TRYAGAIN;
13334                         return(0);
13335                     }
13336                     goto tryagain;
13337                 }
13338                 RETURN_FAIL_ON_RESTART(flags, flagp);
13339                 FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf,
13340                                                                  (UV) flags);
13341         }
13342         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
13343         break;
13344     case '|':
13345     case ')':
13346         if (flags & TRYAGAIN) {
13347             *flagp |= TRYAGAIN;
13348             return 0;
13349         }
13350         vFAIL("Internal urp");
13351                                 /* Supposed to be caught earlier. */
13352         break;
13353     case '?':
13354     case '+':
13355     case '*':
13356         RExC_parse++;
13357         vFAIL("Quantifier follows nothing");
13358         break;
13359     case '\\':
13360         /* Special Escapes
13361
13362            This switch handles escape sequences that resolve to some kind
13363            of special regop and not to literal text. Escape sequences that
13364            resolve to literal text are handled below in the switch marked
13365            "Literal Escapes".
13366
13367            Every entry in this switch *must* have a corresponding entry
13368            in the literal escape switch. However, the opposite is not
13369            required, as the default for this switch is to jump to the
13370            literal text handling code.
13371         */
13372         RExC_parse++;
13373         switch ((U8)*RExC_parse) {
13374         /* Special Escapes */
13375         case 'A':
13376             RExC_seen_zerolen++;
13377             ret = reg_node(pRExC_state, SBOL);
13378             /* SBOL is shared with /^/ so we set the flags so we can tell
13379              * /\A/ from /^/ in split. */
13380             FLAGS(REGNODE_p(ret)) = 1;
13381             *flagp |= SIMPLE;
13382             goto finish_meta_pat;
13383         case 'G':
13384             ret = reg_node(pRExC_state, GPOS);
13385             RExC_seen |= REG_GPOS_SEEN;
13386             *flagp |= SIMPLE;
13387             goto finish_meta_pat;
13388         case 'K':
13389             if (!RExC_in_lookbehind && !RExC_in_lookahead) {
13390                 RExC_seen_zerolen++;
13391                 ret = reg_node(pRExC_state, KEEPS);
13392                 *flagp |= SIMPLE;
13393                 /* XXX:dmq : disabling in-place substitution seems to
13394                  * be necessary here to avoid cases of memory corruption, as
13395                  * with: C<$_="x" x 80; s/x\K/y/> -- rgs
13396                  */
13397                 RExC_seen |= REG_LOOKBEHIND_SEEN;
13398                 goto finish_meta_pat;
13399             }
13400             else {
13401                 ++RExC_parse; /* advance past the 'K' */
13402                 vFAIL("\\K not permitted in lookahead/lookbehind");
13403             }
13404         case 'Z':
13405             ret = reg_node(pRExC_state, SEOL);
13406             *flagp |= SIMPLE;
13407             RExC_seen_zerolen++;                /* Do not optimize RE away */
13408             goto finish_meta_pat;
13409         case 'z':
13410             ret = reg_node(pRExC_state, EOS);
13411             *flagp |= SIMPLE;
13412             RExC_seen_zerolen++;                /* Do not optimize RE away */
13413             goto finish_meta_pat;
13414         case 'C':
13415             vFAIL("\\C no longer supported");
13416         case 'X':
13417             ret = reg_node(pRExC_state, CLUMP);
13418             *flagp |= HASWIDTH;
13419             goto finish_meta_pat;
13420
13421         case 'B':
13422             invert = 1;
13423             /* FALLTHROUGH */
13424         case 'b':
13425           {
13426             U8 flags = 0;
13427             regex_charset charset = get_regex_charset(RExC_flags);
13428
13429             RExC_seen_zerolen++;
13430             RExC_seen |= REG_LOOKBEHIND_SEEN;
13431             op = BOUND + charset;
13432
13433             if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
13434                 flags = TRADITIONAL_BOUND;
13435                 if (op > BOUNDA) {  /* /aa is same as /a */
13436                     op = BOUNDA;
13437                 }
13438             }
13439             else {
13440                 STRLEN length;
13441                 char name = *RExC_parse;
13442                 char * endbrace = NULL;
13443                 RExC_parse += 2;
13444                 endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
13445
13446                 if (! endbrace) {
13447                     vFAIL2("Missing right brace on \\%c{}", name);
13448                 }
13449                 /* XXX Need to decide whether to take spaces or not.  Should be
13450                  * consistent with \p{}, but that currently is SPACE, which
13451                  * means vertical too, which seems wrong
13452                  * while (isBLANK(*RExC_parse)) {
13453                     RExC_parse++;
13454                 }*/
13455                 if (endbrace == RExC_parse) {
13456                     RExC_parse++;  /* After the '}' */
13457                     vFAIL2("Empty \\%c{}", name);
13458                 }
13459                 length = endbrace - RExC_parse;
13460                 /*while (isBLANK(*(RExC_parse + length - 1))) {
13461                     length--;
13462                 }*/
13463                 switch (*RExC_parse) {
13464                     case 'g':
13465                         if (    length != 1
13466                             && (memNEs(RExC_parse + 1, length - 1, "cb")))
13467                         {
13468                             goto bad_bound_type;
13469                         }
13470                         flags = GCB_BOUND;
13471                         break;
13472                     case 'l':
13473                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13474                             goto bad_bound_type;
13475                         }
13476                         flags = LB_BOUND;
13477                         break;
13478                     case 's':
13479                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13480                             goto bad_bound_type;
13481                         }
13482                         flags = SB_BOUND;
13483                         break;
13484                     case 'w':
13485                         if (length != 2 || *(RExC_parse + 1) != 'b') {
13486                             goto bad_bound_type;
13487                         }
13488                         flags = WB_BOUND;
13489                         break;
13490                     default:
13491                       bad_bound_type:
13492                         RExC_parse = endbrace;
13493                         vFAIL2utf8f(
13494                             "'%" UTF8f "' is an unknown bound type",
13495                             UTF8fARG(UTF, length, endbrace - length));
13496                         NOT_REACHED; /*NOTREACHED*/
13497                 }
13498                 RExC_parse = endbrace;
13499                 REQUIRE_UNI_RULES(flagp, 0);
13500
13501                 if (op == BOUND) {
13502                     op = BOUNDU;
13503                 }
13504                 else if (op >= BOUNDA) {  /* /aa is same as /a */
13505                     op = BOUNDU;
13506                     length += 4;
13507
13508                     /* Don't have to worry about UTF-8, in this message because
13509                      * to get here the contents of the \b must be ASCII */
13510                     ckWARN4reg(RExC_parse + 1,  /* Include the '}' in msg */
13511                               "Using /u for '%.*s' instead of /%s",
13512                               (unsigned) length,
13513                               endbrace - length + 1,
13514                               (charset == REGEX_ASCII_RESTRICTED_CHARSET)
13515                               ? ASCII_RESTRICT_PAT_MODS
13516                               : ASCII_MORE_RESTRICT_PAT_MODS);
13517                 }
13518             }
13519
13520             if (op == BOUND) {
13521                 RExC_seen_d_op = TRUE;
13522             }
13523             else if (op == BOUNDL) {
13524                 RExC_contains_locale = 1;
13525             }
13526
13527             if (invert) {
13528                 op += NBOUND - BOUND;
13529             }
13530
13531             ret = reg_node(pRExC_state, op);
13532             FLAGS(REGNODE_p(ret)) = flags;
13533
13534             *flagp |= SIMPLE;
13535
13536             goto finish_meta_pat;
13537           }
13538
13539         case 'R':
13540             ret = reg_node(pRExC_state, LNBREAK);
13541             *flagp |= HASWIDTH|SIMPLE;
13542             goto finish_meta_pat;
13543
13544         case 'd':
13545         case 'D':
13546         case 'h':
13547         case 'H':
13548         case 'p':
13549         case 'P':
13550         case 's':
13551         case 'S':
13552         case 'v':
13553         case 'V':
13554         case 'w':
13555         case 'W':
13556             /* These all have the same meaning inside [brackets], and it knows
13557              * how to do the best optimizations for them.  So, pretend we found
13558              * these within brackets, and let it do the work */
13559             RExC_parse--;
13560
13561             ret = regclass(pRExC_state, flagp, depth+1,
13562                            TRUE, /* means just parse this element */
13563                            FALSE, /* don't allow multi-char folds */
13564                            FALSE, /* don't silence non-portable warnings.  It
13565                                      would be a bug if these returned
13566                                      non-portables */
13567                            (bool) RExC_strict,
13568                            TRUE, /* Allow an optimized regnode result */
13569                            NULL);
13570             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13571             /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
13572              * multi-char folds are allowed.  */
13573             if (!ret)
13574                 FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf,
13575                       (UV) *flagp);
13576
13577             RExC_parse--;   /* regclass() leaves this one too far ahead */
13578
13579           finish_meta_pat:
13580                    /* The escapes above that don't take a parameter can't be
13581                     * followed by a '{'.  But 'pX', 'p{foo}' and
13582                     * correspondingly 'P' can be */
13583             if (   RExC_parse - parse_start == 1
13584                 && UCHARAT(RExC_parse + 1) == '{'
13585                 && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end)))
13586             {
13587                 RExC_parse += 2;
13588                 vFAIL("Unescaped left brace in regex is illegal here");
13589             }
13590             Set_Node_Offset(REGNODE_p(ret), parse_start);
13591             Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1); /* MJD */
13592             nextchar(pRExC_state);
13593             break;
13594         case 'N':
13595             /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
13596              * \N{...} evaluates to a sequence of more than one code points).
13597              * The function call below returns a regnode, which is our result.
13598              * The parameters cause it to fail if the \N{} evaluates to a
13599              * single code point; we handle those like any other literal.  The
13600              * reason that the multicharacter case is handled here and not as
13601              * part of the EXACtish code is because of quantifiers.  In
13602              * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
13603              * this way makes that Just Happen. dmq.
13604              * join_exact() will join this up with adjacent EXACTish nodes
13605              * later on, if appropriate. */
13606             ++RExC_parse;
13607             if (grok_bslash_N(pRExC_state,
13608                               &ret,     /* Want a regnode returned */
13609                               NULL,     /* Fail if evaluates to a single code
13610                                            point */
13611                               NULL,     /* Don't need a count of how many code
13612                                            points */
13613                               flagp,
13614                               RExC_strict,
13615                               depth)
13616             ) {
13617                 break;
13618             }
13619
13620             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
13621
13622             /* Here, evaluates to a single code point.  Go get that */
13623             RExC_parse = parse_start;
13624             goto defchar;
13625
13626         case 'k':    /* Handle \k<NAME> and \k'NAME' */
13627       parse_named_seq:
13628         {
13629             char ch;
13630             if (   RExC_parse >= RExC_end - 1
13631                 || ((   ch = RExC_parse[1]) != '<'
13632                                       && ch != '\''
13633                                       && ch != '{'))
13634             {
13635                 RExC_parse++;
13636                 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
13637                 vFAIL2("Sequence %.2s... not terminated", parse_start);
13638             } else {
13639                 RExC_parse += 2;
13640                 ret = handle_named_backref(pRExC_state,
13641                                            flagp,
13642                                            parse_start,
13643                                            (ch == '<')
13644                                            ? '>'
13645                                            : (ch == '{')
13646                                              ? '}'
13647                                              : '\'');
13648             }
13649             break;
13650         }
13651         case 'g':
13652         case '1': case '2': case '3': case '4':
13653         case '5': case '6': case '7': case '8': case '9':
13654             {
13655                 I32 num;
13656                 bool hasbrace = 0;
13657
13658                 if (*RExC_parse == 'g') {
13659                     bool isrel = 0;
13660
13661                     RExC_parse++;
13662                     if (*RExC_parse == '{') {
13663                         RExC_parse++;
13664                         hasbrace = 1;
13665                     }
13666                     if (*RExC_parse == '-') {
13667                         RExC_parse++;
13668                         isrel = 1;
13669                     }
13670                     if (hasbrace && !isDIGIT(*RExC_parse)) {
13671                         if (isrel) RExC_parse--;
13672                         RExC_parse -= 2;
13673                         goto parse_named_seq;
13674                     }
13675
13676                     if (RExC_parse >= RExC_end) {
13677                         goto unterminated_g;
13678                     }
13679                     num = S_backref_value(RExC_parse, RExC_end);
13680                     if (num == 0)
13681                         vFAIL("Reference to invalid group 0");
13682                     else if (num == I32_MAX) {
13683                          if (isDIGIT(*RExC_parse))
13684                             vFAIL("Reference to nonexistent group");
13685                         else
13686                           unterminated_g:
13687                             vFAIL("Unterminated \\g... pattern");
13688                     }
13689
13690                     if (isrel) {
13691                         num = RExC_npar - num;
13692                         if (num < 1)
13693                             vFAIL("Reference to nonexistent or unclosed group");
13694                     }
13695                 }
13696                 else {
13697                     num = S_backref_value(RExC_parse, RExC_end);
13698                     /* bare \NNN might be backref or octal - if it is larger
13699                      * than or equal RExC_npar then it is assumed to be an
13700                      * octal escape. Note RExC_npar is +1 from the actual
13701                      * number of parens. */
13702                     /* Note we do NOT check if num == I32_MAX here, as that is
13703                      * handled by the RExC_npar check */
13704
13705                     if (
13706                         /* any numeric escape < 10 is always a backref */
13707                         num > 9
13708                         /* any numeric escape < RExC_npar is a backref */
13709                         && num >= RExC_npar
13710                         /* cannot be an octal escape if it starts with 8 */
13711                         && *RExC_parse != '8'
13712                         /* cannot be an octal escape if it starts with 9 */
13713                         && *RExC_parse != '9'
13714                     ) {
13715                         /* Probably not meant to be a backref, instead likely
13716                          * to be an octal character escape, e.g. \35 or \777.
13717                          * The above logic should make it obvious why using
13718                          * octal escapes in patterns is problematic. - Yves */
13719                         RExC_parse = parse_start;
13720                         goto defchar;
13721                     }
13722                 }
13723
13724                 /* At this point RExC_parse points at a numeric escape like
13725                  * \12 or \88 or something similar, which we should NOT treat
13726                  * as an octal escape. It may or may not be a valid backref
13727                  * escape. For instance \88888888 is unlikely to be a valid
13728                  * backref. */
13729                 while (isDIGIT(*RExC_parse))
13730                     RExC_parse++;
13731                 if (hasbrace) {
13732                     if (*RExC_parse != '}')
13733                         vFAIL("Unterminated \\g{...} pattern");
13734                     RExC_parse++;
13735                 }
13736                 if (num >= (I32)RExC_npar) {
13737
13738                     /* It might be a forward reference; we can't fail until we
13739                      * know, by completing the parse to get all the groups, and
13740                      * then reparsing */
13741                     if (ALL_PARENS_COUNTED)  {
13742                         if (num >= RExC_total_parens)  {
13743                             vFAIL("Reference to nonexistent group");
13744                         }
13745                     }
13746                     else {
13747                         REQUIRE_PARENS_PASS;
13748                     }
13749                 }
13750                 RExC_sawback = 1;
13751                 ret = reganode(pRExC_state,
13752                                ((! FOLD)
13753                                  ? REF
13754                                  : (ASCII_FOLD_RESTRICTED)
13755                                    ? REFFA
13756                                    : (AT_LEAST_UNI_SEMANTICS)
13757                                      ? REFFU
13758                                      : (LOC)
13759                                        ? REFFL
13760                                        : REFF),
13761                                 num);
13762                 if (OP(REGNODE_p(ret)) == REFF) {
13763                     RExC_seen_d_op = TRUE;
13764                 }
13765                 *flagp |= HASWIDTH;
13766
13767                 /* override incorrect value set in reganode MJD */
13768                 Set_Node_Offset(REGNODE_p(ret), parse_start);
13769                 Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1);
13770                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13771                                         FALSE /* Don't force to /x */ );
13772             }
13773             break;
13774         case '\0':
13775             if (RExC_parse >= RExC_end)
13776                 FAIL("Trailing \\");
13777             /* FALLTHROUGH */
13778         default:
13779             /* Do not generate "unrecognized" warnings here, we fall
13780                back into the quick-grab loop below */
13781             RExC_parse = parse_start;
13782             goto defchar;
13783         } /* end of switch on a \foo sequence */
13784         break;
13785
13786     case '#':
13787
13788         /* '#' comments should have been spaced over before this function was
13789          * called */
13790         assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
13791         /*
13792         if (RExC_flags & RXf_PMf_EXTENDED) {
13793             RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
13794             if (RExC_parse < RExC_end)
13795                 goto tryagain;
13796         }
13797         */
13798
13799         /* FALLTHROUGH */
13800
13801     default:
13802           defchar: {
13803
13804             /* Here, we have determined that the next thing is probably a
13805              * literal character.  RExC_parse points to the first byte of its
13806              * definition.  (It still may be an escape sequence that evaluates
13807              * to a single character) */
13808
13809             STRLEN len = 0;
13810             UV ender = 0;
13811             char *p;
13812             char *s, *old_s = NULL, *old_old_s = NULL;
13813             char *s0;
13814             U32 max_string_len = 255;
13815
13816             /* We may have to reparse the node, artificially stopping filling
13817              * it early, based on info gleaned in the first parse.  This
13818              * variable gives where we stop.  Make it above the normal stopping
13819              * place first time through; otherwise it would stop too early */
13820             U32 upper_fill = max_string_len + 1;
13821
13822             /* We start out as an EXACT node, even if under /i, until we find a
13823              * character which is in a fold.  The algorithm now segregates into
13824              * separate nodes, characters that fold from those that don't under
13825              * /i.  (This hopefully will create nodes that are fixed strings
13826              * even under /i, giving the optimizer something to grab on to.)
13827              * So, if a node has something in it and the next character is in
13828              * the opposite category, that node is closed up, and the function
13829              * returns.  Then regatom is called again, and a new node is
13830              * created for the new category. */
13831             U8 node_type = EXACT;
13832
13833             /* Assume the node will be fully used; the excess is given back at
13834              * the end.  Under /i, we may need to temporarily add the fold of
13835              * an extra character or two at the end to check for splitting
13836              * multi-char folds, so allocate extra space for that.   We can't
13837              * make any other length assumptions, as a byte input sequence
13838              * could shrink down. */
13839             Ptrdiff_t current_string_nodes = STR_SZ(max_string_len
13840                                                  + ((! FOLD)
13841                                                     ? 0
13842                                                     : 2 * ((UTF)
13843                                                            ? UTF8_MAXBYTES_CASE
13844                         /* Max non-UTF-8 expansion is 2 */ : 2)));
13845
13846             bool next_is_quantifier;
13847             char * oldp = NULL;
13848
13849             /* We can convert EXACTF nodes to EXACTFU if they contain only
13850              * characters that match identically regardless of the target
13851              * string's UTF8ness.  The reason to do this is that EXACTF is not
13852              * trie-able, EXACTFU is, and EXACTFU requires fewer operations at
13853              * runtime.
13854              *
13855              * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
13856              * contain only above-Latin1 characters (hence must be in UTF8),
13857              * which don't participate in folds with Latin1-range characters,
13858              * as the latter's folds aren't known until runtime. */
13859             bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
13860
13861             /* Single-character EXACTish nodes are almost always SIMPLE.  This
13862              * allows us to override this as encountered */
13863             U8 maybe_SIMPLE = SIMPLE;
13864
13865             /* Does this node contain something that can't match unless the
13866              * target string is (also) in UTF-8 */
13867             bool requires_utf8_target = FALSE;
13868
13869             /* The sequence 'ss' is problematic in non-UTF-8 patterns. */
13870             bool has_ss = FALSE;
13871
13872             /* So is the MICRO SIGN */
13873             bool has_micro_sign = FALSE;
13874
13875             /* Set when we fill up the current node and there is still more
13876              * text to process */
13877             bool overflowed;
13878
13879             /* Allocate an EXACT node.  The node_type may change below to
13880              * another EXACTish node, but since the size of the node doesn't
13881              * change, it works */
13882             ret = regnode_guts(pRExC_state, node_type, current_string_nodes,
13883                                                                     "exact");
13884             FILL_NODE(ret, node_type);
13885             RExC_emit++;
13886
13887             s = STRING(REGNODE_p(ret));
13888
13889             s0 = s;
13890
13891           reparse:
13892
13893             p = RExC_parse;
13894             len = 0;
13895             s = s0;
13896             node_type = EXACT;
13897             oldp = NULL;
13898             maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC);
13899             maybe_SIMPLE = SIMPLE;
13900             requires_utf8_target = FALSE;
13901             has_ss = FALSE;
13902             has_micro_sign = FALSE;
13903
13904           continue_parse:
13905
13906             /* This breaks under rare circumstances.  If folding, we do not
13907              * want to split a node at a character that is a non-final in a
13908              * multi-char fold, as an input string could just happen to want to
13909              * match across the node boundary.  The code at the end of the loop
13910              * looks for this, and backs off until it finds not such a
13911              * character, but it is possible (though extremely, extremely
13912              * unlikely) for all characters in the node to be non-final fold
13913              * ones, in which case we just leave the node fully filled, and
13914              * hope that it doesn't match the string in just the wrong place */
13915
13916             assert( ! UTF     /* Is at the beginning of a character */
13917                    || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
13918                    || UTF8_IS_START(UCHARAT(RExC_parse)));
13919
13920             overflowed = FALSE;
13921
13922             /* Here, we have a literal character.  Find the maximal string of
13923              * them in the input that we can fit into a single EXACTish node.
13924              * We quit at the first non-literal or when the node gets full, or
13925              * under /i the categorization of folding/non-folding character
13926              * changes */
13927             while (p < RExC_end && len < upper_fill) {
13928
13929                 /* In most cases each iteration adds one byte to the output.
13930                  * The exceptions override this */
13931                 Size_t added_len = 1;
13932
13933                 oldp = p;
13934                 old_old_s = old_s;
13935                 old_s = s;
13936
13937                 /* White space has already been ignored */
13938                 assert(   (RExC_flags & RXf_PMf_EXTENDED) == 0
13939                        || ! is_PATWS_safe((p), RExC_end, UTF));
13940
13941                 switch ((U8)*p) {
13942                 case '^':
13943                 case '$':
13944                 case '.':
13945                 case '[':
13946                 case '(':
13947                 case ')':
13948                 case '|':
13949                     goto loopdone;
13950                 case '\\':
13951                     /* Literal Escapes Switch
13952
13953                        This switch is meant to handle escape sequences that
13954                        resolve to a literal character.
13955
13956                        Every escape sequence that represents something
13957                        else, like an assertion or a char class, is handled
13958                        in the switch marked 'Special Escapes' above in this
13959                        routine, but also has an entry here as anything that
13960                        isn't explicitly mentioned here will be treated as
13961                        an unescaped equivalent literal.
13962                     */
13963
13964                     switch ((U8)*++p) {
13965
13966                     /* These are all the special escapes. */
13967                     case 'A':             /* Start assertion */
13968                     case 'b': case 'B':   /* Word-boundary assertion*/
13969                     case 'C':             /* Single char !DANGEROUS! */
13970                     case 'd': case 'D':   /* digit class */
13971                     case 'g': case 'G':   /* generic-backref, pos assertion */
13972                     case 'h': case 'H':   /* HORIZWS */
13973                     case 'k': case 'K':   /* named backref, keep marker */
13974                     case 'p': case 'P':   /* Unicode property */
13975                               case 'R':   /* LNBREAK */
13976                     case 's': case 'S':   /* space class */
13977                     case 'v': case 'V':   /* VERTWS */
13978                     case 'w': case 'W':   /* word class */
13979                     case 'X':             /* eXtended Unicode "combining
13980                                              character sequence" */
13981                     case 'z': case 'Z':   /* End of line/string assertion */
13982                         --p;
13983                         goto loopdone;
13984
13985                     /* Anything after here is an escape that resolves to a
13986                        literal. (Except digits, which may or may not)
13987                      */
13988                     case 'n':
13989                         ender = '\n';
13990                         p++;
13991                         break;
13992                     case 'N': /* Handle a single-code point named character. */
13993                         RExC_parse = p + 1;
13994                         if (! grok_bslash_N(pRExC_state,
13995                                             NULL,   /* Fail if evaluates to
13996                                                        anything other than a
13997                                                        single code point */
13998                                             &ender, /* The returned single code
13999                                                        point */
14000                                             NULL,   /* Don't need a count of
14001                                                        how many code points */
14002                                             flagp,
14003                                             RExC_strict,
14004                                             depth)
14005                         ) {
14006                             if (*flagp & NEED_UTF8)
14007                                 FAIL("panic: grok_bslash_N set NEED_UTF8");
14008                             RETURN_FAIL_ON_RESTART_FLAGP(flagp);
14009
14010                             /* Here, it wasn't a single code point.  Go close
14011                              * up this EXACTish node.  The switch() prior to
14012                              * this switch handles the other cases */
14013                             RExC_parse = p = oldp;
14014                             goto loopdone;
14015                         }
14016                         p = RExC_parse;
14017                         RExC_parse = parse_start;
14018
14019                         /* The \N{} means the pattern, if previously /d,
14020                          * becomes /u.  That means it can't be an EXACTF node,
14021                          * but an EXACTFU */
14022                         if (node_type == EXACTF) {
14023                             node_type = EXACTFU;
14024
14025                             /* If the node already contains something that
14026                              * differs between EXACTF and EXACTFU, reparse it
14027                              * as EXACTFU */
14028                             if (! maybe_exactfu) {
14029                                 len = 0;
14030                                 s = s0;
14031                                 goto reparse;
14032                             }
14033                         }
14034
14035                         break;
14036                     case 'r':
14037                         ender = '\r';
14038                         p++;
14039                         break;
14040                     case 't':
14041                         ender = '\t';
14042                         p++;
14043                         break;
14044                     case 'f':
14045                         ender = '\f';
14046                         p++;
14047                         break;
14048                     case 'e':
14049                         ender = ESC_NATIVE;
14050                         p++;
14051                         break;
14052                     case 'a':
14053                         ender = '\a';
14054                         p++;
14055                         break;
14056                     case 'o':
14057                         {
14058                             UV result;
14059                             const char* error_msg;
14060
14061                             bool valid = grok_bslash_o(&p,
14062                                                        RExC_end,
14063                                                        &result,
14064                                                        &error_msg,
14065                                                        TO_OUTPUT_WARNINGS(p),
14066                                                        (bool) RExC_strict,
14067                                                        TRUE, /* Output warnings
14068                                                                 for non-
14069                                                                 portables */
14070                                                        UTF);
14071                             if (! valid) {
14072                                 RExC_parse = p; /* going to die anyway; point
14073                                                    to exact spot of failure */
14074                                 vFAIL(error_msg);
14075                             }
14076                             UPDATE_WARNINGS_LOC(p - 1);
14077                             ender = result;
14078                             break;
14079                         }
14080                     case 'x':
14081                         {
14082                             UV result = UV_MAX; /* initialize to erroneous
14083                                                    value */
14084                             const char* error_msg;
14085
14086                             bool valid = grok_bslash_x(&p,
14087                                                        RExC_end,
14088                                                        &result,
14089                                                        &error_msg,
14090                                                        TO_OUTPUT_WARNINGS(p),
14091                                                        (bool) RExC_strict,
14092                                                        TRUE, /* Silence warnings
14093                                                                 for non-
14094                                                                 portables */
14095                                                        UTF);
14096                             if (! valid) {
14097                                 RExC_parse = p; /* going to die anyway; point
14098                                                    to exact spot of failure */
14099                                 vFAIL(error_msg);
14100                             }
14101                             UPDATE_WARNINGS_LOC(p - 1);
14102                             ender = result;
14103
14104 #ifdef EBCDIC
14105                             if (ender < 0x100) {
14106                                 if (RExC_recode_x_to_native) {
14107                                     ender = LATIN1_TO_NATIVE(ender);
14108                                 }
14109                             }
14110 #endif
14111                             break;
14112                         }
14113                     case 'c':
14114                         p++;
14115                         ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p));
14116                         UPDATE_WARNINGS_LOC(p);
14117                         p++;
14118                         break;
14119                     case '8': case '9': /* must be a backreference */
14120                         --p;
14121                         /* we have an escape like \8 which cannot be an octal escape
14122                          * so we exit the loop, and let the outer loop handle this
14123                          * escape which may or may not be a legitimate backref. */
14124                         goto loopdone;
14125                     case '1': case '2': case '3':case '4':
14126                     case '5': case '6': case '7':
14127                         /* When we parse backslash escapes there is ambiguity
14128                          * between backreferences and octal escapes. Any escape
14129                          * from \1 - \9 is a backreference, any multi-digit
14130                          * escape which does not start with 0 and which when
14131                          * evaluated as decimal could refer to an already
14132                          * parsed capture buffer is a back reference. Anything
14133                          * else is octal.
14134                          *
14135                          * Note this implies that \118 could be interpreted as
14136                          * 118 OR as "\11" . "8" depending on whether there
14137                          * were 118 capture buffers defined already in the
14138                          * pattern.  */
14139
14140                         /* NOTE, RExC_npar is 1 more than the actual number of
14141                          * parens we have seen so far, hence the "<" as opposed
14142                          * to "<=" */
14143                         if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar)
14144                         {  /* Not to be treated as an octal constant, go
14145                                    find backref */
14146                             --p;
14147                             goto loopdone;
14148                         }
14149                         /* FALLTHROUGH */
14150                     case '0':
14151                         {
14152                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
14153                             STRLEN numlen = 3;
14154                             ender = grok_oct(p, &numlen, &flags, NULL);
14155                             p += numlen;
14156                             if (   isDIGIT(*p)  /* like \08, \178 */
14157                                 && ckWARN(WARN_REGEXP)
14158                                 && numlen < 3)
14159                             {
14160                                 reg_warn_non_literal_string(
14161                                          p + 1,
14162                                          form_short_octal_warning(p, numlen));
14163                             }
14164                         }
14165                         break;
14166                     case '\0':
14167                         if (p >= RExC_end)
14168                             FAIL("Trailing \\");
14169                         /* FALLTHROUGH */
14170                     default:
14171                         if (isALPHANUMERIC(*p)) {
14172                             /* An alpha followed by '{' is going to fail next
14173                              * iteration, so don't output this warning in that
14174                              * case */
14175                             if (! isALPHA(*p) || *(p + 1) != '{') {
14176                                 ckWARN2reg(p + 1, "Unrecognized escape \\%.1s"
14177                                                   " passed through", p);
14178                             }
14179                         }
14180                         goto normal_default;
14181                     } /* End of switch on '\' */
14182                     break;
14183                 case '{':
14184                     /* Trying to gain new uses for '{' without breaking too
14185                      * much existing code is hard.  The solution currently
14186                      * adopted is:
14187                      *  1)  If there is no ambiguity that a '{' should always
14188                      *      be taken literally, at the start of a construct, we
14189                      *      just do so.
14190                      *  2)  If the literal '{' conflicts with our desired use
14191                      *      of it as a metacharacter, we die.  The deprecation
14192                      *      cycles for this have come and gone.
14193                      *  3)  If there is ambiguity, we raise a simple warning.
14194                      *      This could happen, for example, if the user
14195                      *      intended it to introduce a quantifier, but slightly
14196                      *      misspelled the quantifier.  Without this warning,
14197                      *      the quantifier would silently be taken as a literal
14198                      *      string of characters instead of a meta construct */
14199                     if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) {
14200                         if (      RExC_strict
14201                             || (  p > parse_start + 1
14202                                 && isALPHA_A(*(p - 1))
14203                                 && *(p - 2) == '\\')
14204                             || new_regcurly(p, RExC_end))
14205                         {
14206                             RExC_parse = p + 1;
14207                             vFAIL("Unescaped left brace in regex is "
14208                                   "illegal here");
14209                         }
14210                         ckWARNreg(p + 1, "Unescaped left brace in regex is"
14211                                          " passed through");
14212                     }
14213                     goto normal_default;
14214                 case '}':
14215                 case ']':
14216                     if (p > RExC_parse && RExC_strict) {
14217                         ckWARN2reg(p + 1, "Unescaped literal '%c'", *p);
14218                     }
14219                     /*FALLTHROUGH*/
14220                 default:    /* A literal character */
14221                   normal_default:
14222                     if (! UTF8_IS_INVARIANT(*p) && UTF) {
14223                         STRLEN numlen;
14224                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
14225                                                &numlen, UTF8_ALLOW_DEFAULT);
14226                         p += numlen;
14227                     }
14228                     else
14229                         ender = (U8) *p++;
14230                     break;
14231                 } /* End of switch on the literal */
14232
14233                 /* Here, have looked at the literal character, and <ender>
14234                  * contains its ordinal; <p> points to the character after it.
14235                  * */
14236
14237                 if (ender > 255) {
14238                     REQUIRE_UTF8(flagp);
14239                 }
14240
14241                 /* We need to check if the next non-ignored thing is a
14242                  * quantifier.  Move <p> to after anything that should be
14243                  * ignored, which, as a side effect, positions <p> for the next
14244                  * loop iteration */
14245                 skip_to_be_ignored_text(pRExC_state, &p,
14246                                         FALSE /* Don't force to /x */ );
14247
14248                 /* If the next thing is a quantifier, it applies to this
14249                  * character only, which means that this character has to be in
14250                  * its own node and can't just be appended to the string in an
14251                  * existing node, so if there are already other characters in
14252                  * the node, close the node with just them, and set up to do
14253                  * this character again next time through, when it will be the
14254                  * only thing in its new node */
14255
14256                 next_is_quantifier =    LIKELY(p < RExC_end)
14257                                      && UNLIKELY(ISMULT2(p));
14258
14259                 if (next_is_quantifier && LIKELY(len)) {
14260                     p = oldp;
14261                     goto loopdone;
14262                 }
14263
14264                 /* Ready to add 'ender' to the node */
14265
14266                 if (! FOLD) {  /* The simple case, just append the literal */
14267                   not_fold_common:
14268
14269                     /* Don't output if it would overflow */
14270                     if (UNLIKELY(len > max_string_len - ((UTF)
14271                                                       ? UVCHR_SKIP(ender)
14272                                                       : 1)))
14273                     {
14274                         overflowed = TRUE;
14275                         break;
14276                     }
14277
14278                     if (UVCHR_IS_INVARIANT(ender) || ! UTF) {
14279                         *(s++) = (char) ender;
14280                     }
14281                     else {
14282                         U8 * new_s = uvchr_to_utf8((U8*)s, ender);
14283                         added_len = (char *) new_s - s;
14284                         s = (char *) new_s;
14285
14286                         if (ender > 255)  {
14287                             requires_utf8_target = TRUE;
14288                         }
14289                     }
14290                 }
14291                 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
14292
14293                     /* Here are folding under /l, and the code point is
14294                      * problematic.  If this is the first character in the
14295                      * node, change the node type to folding.   Otherwise, if
14296                      * this is the first problematic character, close up the
14297                      * existing node, so can start a new node with this one */
14298                     if (! len) {
14299                         node_type = EXACTFL;
14300                         RExC_contains_locale = 1;
14301                     }
14302                     else if (node_type == EXACT) {
14303                         p = oldp;
14304                         goto loopdone;
14305                     }
14306
14307                     /* This problematic code point means we can't simplify
14308                      * things */
14309                     maybe_exactfu = FALSE;
14310
14311                     /* Here, we are adding a problematic fold character.
14312                      * "Problematic" in this context means that its fold isn't
14313                      * known until runtime.  (The non-problematic code points
14314                      * are the above-Latin1 ones that fold to also all
14315                      * above-Latin1.  Their folds don't vary no matter what the
14316                      * locale is.) But here we have characters whose fold
14317                      * depends on the locale.  We just add in the unfolded
14318                      * character, and wait until runtime to fold it */
14319                     goto not_fold_common;
14320                 }
14321                 else /* regular fold; see if actually is in a fold */
14322                      if (   (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender))
14323                          || (ender > 255
14324                             && ! _invlist_contains_cp(PL_in_some_fold, ender)))
14325                 {
14326                     /* Here, folding, but the character isn't in a fold.
14327                      *
14328                      * Start a new node if previous characters in the node were
14329                      * folded */
14330                     if (len && node_type != EXACT) {
14331                         p = oldp;
14332                         goto loopdone;
14333                     }
14334
14335                     /* Here, continuing a node with non-folded characters.  Add
14336                      * this one */
14337                     goto not_fold_common;
14338                 }
14339                 else {  /* Here, does participate in some fold */
14340
14341                     /* If this is the first character in the node, change its
14342                      * type to folding.  Otherwise, if this is the first
14343                      * folding character in the node, close up the existing
14344                      * node, so can start a new node with this one.  */
14345                     if (! len) {
14346                         node_type = compute_EXACTish(pRExC_state);
14347                     }
14348                     else if (node_type == EXACT) {
14349                         p = oldp;
14350                         goto loopdone;
14351                     }
14352
14353                     if (UTF) {  /* Alway use the folded value for UTF-8
14354                                    patterns */
14355                         if (UVCHR_IS_INVARIANT(ender)) {
14356                             if (UNLIKELY(len + 1 > max_string_len)) {
14357                                 overflowed = TRUE;
14358                                 break;
14359                             }
14360
14361                             *(s)++ = (U8) toFOLD(ender);
14362                         }
14363                         else {
14364                             UV folded = _to_uni_fold_flags(
14365                                     ender,
14366                                     (U8 *) s,  /* We have allocated extra space
14367                                                   in 's' so can't run off the
14368                                                   end */
14369                                     &added_len,
14370                                     FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14371                                                     ? FOLD_FLAGS_NOMIX_ASCII
14372                                                     : 0));
14373                             if (UNLIKELY(len + added_len > max_string_len)) {
14374                                 overflowed = TRUE;
14375                                 break;
14376                             }
14377
14378                             s += added_len;
14379
14380                             if (   folded > 255
14381                                 && LIKELY(folded != GREEK_SMALL_LETTER_MU))
14382                             {
14383                                 /* U+B5 folds to the MU, so its possible for a
14384                                  * non-UTF-8 target to match it */
14385                                 requires_utf8_target = TRUE;
14386                             }
14387                         }
14388                     }
14389                     else { /* Here is non-UTF8. */
14390
14391                         /* The fold will be one or (rarely) two characters.
14392                          * Check that there's room for at least a single one
14393                          * before setting any flags, etc.  Because otherwise an
14394                          * overflowing character could cause a flag to be set
14395                          * even though it doesn't end up in this node.  (For
14396                          * the two character fold, we check again, before
14397                          * setting any flags) */
14398                         if (UNLIKELY(len + 1 > max_string_len)) {
14399                             overflowed = TRUE;
14400                             break;
14401                         }
14402
14403 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
14404    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
14405                                       || UNICODE_DOT_DOT_VERSION > 0)
14406
14407                         /* On non-ancient Unicodes, check for the only possible
14408                          * multi-char fold  */
14409                         if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
14410
14411                             /* This potential multi-char fold means the node
14412                              * can't be simple (because it could match more
14413                              * than a single char).  And in some cases it will
14414                              * match 'ss', so set that flag */
14415                             maybe_SIMPLE = 0;
14416                             has_ss = TRUE;
14417
14418                             /* It can't change to be an EXACTFU (unless already
14419                              * is one).  We fold it iff under /u rules. */
14420                             if (node_type != EXACTFU) {
14421                                 maybe_exactfu = FALSE;
14422                             }
14423                             else {
14424                                 if (UNLIKELY(len + 2 > max_string_len)) {
14425                                     overflowed = TRUE;
14426                                     break;
14427                                 }
14428
14429                                 *(s++) = 's';
14430                                 *(s++) = 's';
14431                                 added_len = 2;
14432
14433                                 goto done_with_this_char;
14434                             }
14435                         }
14436                         else if (   UNLIKELY(isALPHA_FOLD_EQ(ender, 's'))
14437                                  && LIKELY(len > 0)
14438                                  && UNLIKELY(isALPHA_FOLD_EQ(*(s-1), 's')))
14439                         {
14440                             /* Also, the sequence 'ss' is special when not
14441                              * under /u.  If the target string is UTF-8, it
14442                              * should match SHARP S; otherwise it won't.  So,
14443                              * here we have to exclude the possibility of this
14444                              * node moving to /u.*/
14445                             has_ss = TRUE;
14446                             maybe_exactfu = FALSE;
14447                         }
14448 #endif
14449                         /* Here, the fold will be a single character */
14450
14451                         if (UNLIKELY(ender == MICRO_SIGN)) {
14452                             has_micro_sign = TRUE;
14453                         }
14454                         else if (PL_fold[ender] != PL_fold_latin1[ender]) {
14455
14456                             /* If the character's fold differs between /d and
14457                              * /u, this can't change to be an EXACTFU node */
14458                             maybe_exactfu = FALSE;
14459                         }
14460
14461                         *(s++) = (DEPENDS_SEMANTICS)
14462                                  ? (char) toFOLD(ender)
14463
14464                                    /* Under /u, the fold of any character in
14465                                     * the 0-255 range happens to be its
14466                                     * lowercase equivalent, except for LATIN
14467                                     * SMALL LETTER SHARP S, which was handled
14468                                     * above, and the MICRO SIGN, whose fold
14469                                     * requires UTF-8 to represent.  */
14470                                  : (char) toLOWER_L1(ender);
14471                     }
14472                 } /* End of adding current character to the node */
14473
14474               done_with_this_char:
14475
14476                 len += added_len;
14477
14478                 if (next_is_quantifier) {
14479
14480                     /* Here, the next input is a quantifier, and to get here,
14481                      * the current character is the only one in the node. */
14482                     goto loopdone;
14483                 }
14484
14485             } /* End of loop through literal characters */
14486
14487             /* Here we have either exhausted the input or run out of room in
14488              * the node.  If the former, we are done.  (If we encountered a
14489              * character that can't be in the node, transfer is made directly
14490              * to <loopdone>, and so we wouldn't have fallen off the end of the
14491              * loop.)  */
14492             if (LIKELY(! overflowed)) {
14493                 goto loopdone;
14494             }
14495
14496             /* Here we have run out of room.  We can grow plain EXACT and
14497              * LEXACT nodes.  If the pattern is gigantic enough, though,
14498              * eventually we'll have to artificially chunk the pattern into
14499              * multiple nodes. */
14500             if (! LOC && (node_type == EXACT || node_type == LEXACT)) {
14501                 Size_t overhead = 1 + regarglen[OP(REGNODE_p(ret))];
14502                 Size_t overhead_expansion = 0;
14503                 char temp[256];
14504                 Size_t max_nodes_for_string;
14505                 Size_t achievable;
14506                 SSize_t delta;
14507
14508                 /* Here we couldn't fit the final character in the current
14509                  * node, so it will have to be reparsed, no matter what else we
14510                  * do */
14511                 p = oldp;
14512
14513                 /* If would have overflowed a regular EXACT node, switch
14514                  * instead to an LEXACT.  The code below is structured so that
14515                  * the actual growing code is common to changing from an EXACT
14516                  * or just increasing the LEXACT size.  This means that we have
14517                  * to save the string in the EXACT case before growing, and
14518                  * then copy it afterwards to its new location */
14519                 if (node_type == EXACT) {
14520                     overhead_expansion = regarglen[LEXACT] - regarglen[EXACT];
14521                     RExC_emit += overhead_expansion;
14522                     Copy(s0, temp, len, char);
14523                 }
14524
14525                 /* Ready to grow.  If it was a plain EXACT, the string was
14526                  * saved, and the first few bytes of it overwritten by adding
14527                  * an argument field.  We assume, as we do elsewhere in this
14528                  * file, that one byte of remaining input will translate into
14529                  * one byte of output, and if that's too small, we grow again,
14530                  * if too large the excess memory is freed at the end */
14531
14532                 max_nodes_for_string = U16_MAX - overhead - overhead_expansion;
14533                 achievable = MIN(max_nodes_for_string,
14534                                  current_string_nodes + STR_SZ(RExC_end - p));
14535                 delta = achievable - current_string_nodes;
14536
14537                 /* If there is just no more room, go finish up this chunk of
14538                  * the pattern. */
14539                 if (delta <= 0) {
14540                     goto loopdone;
14541                 }
14542
14543                 change_engine_size(pRExC_state, delta + overhead_expansion);
14544                 current_string_nodes += delta;
14545                 max_string_len
14546                            = sizeof(struct regnode) * current_string_nodes;
14547                 upper_fill = max_string_len + 1;
14548
14549                 /* If the length was small, we know this was originally an
14550                  * EXACT node now converted to LEXACT, and the string has to be
14551                  * restored.  Otherwise the string was untouched.  260 is just
14552                  * a number safely above 255 so don't have to worry about
14553                  * getting it precise */
14554                 if (len < 260) {
14555                     node_type = LEXACT;
14556                     FILL_NODE(ret, node_type);
14557                     s0 = STRING(REGNODE_p(ret));
14558                     Copy(temp, s0, len, char);
14559                     s = s0 + len;
14560                 }
14561
14562                 goto continue_parse;
14563             }
14564             else if (FOLD) {
14565                 bool splittable = FALSE;
14566                 bool backed_up = FALSE;
14567                 char * e;
14568                 char * s_start;
14569
14570                 /* Here is /i.  Running out of room creates a problem if we are
14571                  * folding, and the split happens in the middle of a
14572                  * multi-character fold, as a match that should have occurred,
14573                  * won't, due to the way nodes are matched, and our artificial
14574                  * boundary.  So back off until we aren't splitting such a
14575                  * fold.  If there is no such place to back off to, we end up
14576                  * taking the entire node as-is.  This can happen if the node
14577                  * consists entirely of 'f' or entirely of 's' characters (or
14578                  * things that fold to them) as 'ff' and 'ss' are
14579                  * multi-character folds.
14580                  *
14581                  * The Unicode standard says that multi character folds consist
14582                  * of either two or three characters.  That means we would be
14583                  * splitting one if the final character in the node is at the
14584                  * beginning of either type, or is the second of a three
14585                  * character fold.
14586                  *
14587                  * At this point:
14588                  *  ender     is the code point of the character that won't fit
14589                  *            in the node
14590                  *  s         points to just beyond the final byte in the node.
14591                  *            It's where we would place ender if there were
14592                  *            room, and where in fact we do place ender's fold
14593                  *            in the code below, as we've over-allocated space
14594                  *            for s0 (hence s) to allow for this
14595                  *  e         starts at 's' and advances as we append things.
14596                  *  old_s     is the same as 's'.  (If ender had fit, 's' would
14597                  *            have been advanced to beyond it).
14598                  *  old_old_s points to the beginning byte of the final
14599                  *            character in the node
14600                  *  p         points to the beginning byte in the input of the
14601                  *            character beyond 'ender'.
14602                  *  oldp      points to the beginning byte in the input of
14603                  *            'ender'.
14604                  *
14605                  * In the case of /il, we haven't folded anything that could be
14606                  * affected by the locale.  That means only above-Latin1
14607                  * characters that fold to other above-latin1 characters get
14608                  * folded at compile time.  To check where a good place to
14609                  * split nodes is, everything in it will have to be folded.
14610                  * The boolean 'maybe_exactfu' keeps track in /il if there are
14611                  * any unfolded characters in the node. */
14612                 bool need_to_fold_loc = LOC && ! maybe_exactfu;
14613
14614                 /* If we do need to fold the node, we need a place to store the
14615                  * folded copy, and a way to map back to the unfolded original
14616                  * */
14617                 char * locfold_buf = NULL;
14618                 Size_t * loc_correspondence = NULL;
14619
14620                 if (! need_to_fold_loc) {   /* The normal case.  Just
14621                                                initialize to the actual node */
14622                     e = s;
14623                     s_start = s0;
14624                     s = old_old_s;  /* Point to the beginning of the final char
14625                                        that fits in the node */
14626                 }
14627                 else {
14628
14629                     /* Here, we have filled a /il node, and there are unfolded
14630                      * characters in it.  If the runtime locale turns out to be
14631                      * UTF-8, there are possible multi-character folds, just
14632                      * like when not under /l.  The node hence can't terminate
14633                      * in the middle of such a fold.  To determine this, we
14634                      * have to create a folded copy of this node.  That means
14635                      * reparsing the node, folding everything assuming a UTF-8
14636                      * locale.  (If at runtime it isn't such a locale, the
14637                      * actions here wouldn't have been necessary, but we have
14638                      * to assume the worst case.)  If we find we need to back
14639                      * off the folded string, we do so, and then map that
14640                      * position back to the original unfolded node, which then
14641                      * gets output, truncated at that spot */
14642
14643                     char * redo_p = RExC_parse;
14644                     char * redo_e;
14645                     char * old_redo_e;
14646
14647                     /* Allow enough space assuming a single byte input folds to
14648                      * a single byte output, plus assume that the two unparsed
14649                      * characters (that we may need) fold to the largest number
14650                      * of bytes possible, plus extra for one more worst case
14651                      * scenario.  In the loop below, if we start eating into
14652                      * that final spare space, we enlarge this initial space */
14653                     Size_t size = max_string_len + (3 * UTF8_MAXBYTES_CASE) + 1;
14654
14655                     Newxz(locfold_buf, size, char);
14656                     Newxz(loc_correspondence, size, Size_t);
14657
14658                     /* Redo this node's parse, folding into 'locfold_buf' */
14659                     redo_p = RExC_parse;
14660                     old_redo_e = redo_e = locfold_buf;
14661                     while (redo_p <= oldp) {
14662
14663                         old_redo_e = redo_e;
14664                         loc_correspondence[redo_e - locfold_buf]
14665                                                         = redo_p - RExC_parse;
14666
14667                         if (UTF) {
14668                             Size_t added_len;
14669
14670                             (void) _to_utf8_fold_flags((U8 *) redo_p,
14671                                                        (U8 *) RExC_end,
14672                                                        (U8 *) redo_e,
14673                                                        &added_len,
14674                                                        FOLD_FLAGS_FULL);
14675                             redo_e += added_len;
14676                             redo_p += UTF8SKIP(redo_p);
14677                         }
14678                         else {
14679
14680                             /* Note that if this code is run on some ancient
14681                              * Unicode versions, SHARP S doesn't fold to 'ss',
14682                              * but rather than clutter the code with #ifdef's,
14683                              * as is done above, we ignore that possibility.
14684                              * This is ok because this code doesn't affect what
14685                              * gets matched, but merely where the node gets
14686                              * split */
14687                             if (UCHARAT(redo_p) != LATIN_SMALL_LETTER_SHARP_S) {
14688                                 *redo_e++ = toLOWER_L1(UCHARAT(redo_p));
14689                             }
14690                             else {
14691                                 *redo_e++ = 's';
14692                                 *redo_e++ = 's';
14693                             }
14694                             redo_p++;
14695                         }
14696
14697
14698                         /* If we're getting so close to the end that a
14699                          * worst-case fold in the next character would cause us
14700                          * to overflow, increase, assuming one byte output byte
14701                          * per one byte input one, plus room for another worst
14702                          * case fold */
14703                         if (   redo_p <= oldp
14704                             && redo_e > locfold_buf + size
14705                                                     - (UTF8_MAXBYTES_CASE + 1))
14706                         {
14707                             Size_t new_size = size
14708                                             + (oldp - redo_p)
14709                                             + UTF8_MAXBYTES_CASE + 1;
14710                             Ptrdiff_t e_offset = redo_e - locfold_buf;
14711
14712                             Renew(locfold_buf, new_size, char);
14713                             Renew(loc_correspondence, new_size, Size_t);
14714                             size = new_size;
14715
14716                             redo_e = locfold_buf + e_offset;
14717                         }
14718                     }
14719
14720                     /* Set so that things are in terms of the folded, temporary
14721                      * string */
14722                     s = old_redo_e;
14723                     s_start = locfold_buf;
14724                     e = redo_e;
14725
14726                 }
14727
14728                 /* Here, we have 's', 's_start' and 'e' set up to point to the
14729                  * input that goes into the node, folded.
14730                  *
14731                  * If the final character of the node and the fold of ender
14732                  * form the first two characters of a three character fold, we
14733                  * need to peek ahead at the next (unparsed) character in the
14734                  * input to determine if the three actually do form such a
14735                  * fold.  Just looking at that character is not generally
14736                  * sufficient, as it could be, for example, an escape sequence
14737                  * that evaluates to something else, and it needs to be folded.
14738                  *
14739                  * khw originally thought to just go through the parse loop one
14740                  * extra time, but that doesn't work easily as that iteration
14741                  * could cause things to think that the parse is over and to
14742                  * goto loopdone.  The character could be a '$' for example, or
14743                  * the character beyond could be a quantifier, and other
14744                  * glitches as well.
14745                  *
14746                  * The solution used here for peeking ahead is to look at that
14747                  * next character.  If it isn't ASCII punctuation, then it will
14748                  * be something that continues in an EXACTish node if there
14749                  * were space.  We append the fold of it to s, having reserved
14750                  * enough room in s0 for the purpose.  If we can't reasonably
14751                  * peek ahead, we instead assume the worst case: that it is
14752                  * something that would form the completion of a multi-char
14753                  * fold.
14754                  *
14755                  * If we can't split between s and ender, we work backwards
14756                  * character-by-character down to s0.  At each current point
14757                  * see if we are at the beginning of a multi-char fold.  If so,
14758                  * that means we would be splitting the fold across nodes, and
14759                  * so we back up one and try again.
14760                  *
14761                  * If we're not at the beginning, we still could be at the
14762                  * final two characters of a (rare) three character fold.  We
14763                  * check if the sequence starting at the character before the
14764                  * current position (and including the current and next
14765                  * characters) is a three character fold.  If not, the node can
14766                  * be split here.  If it is, we have to backup two characters
14767                  * and try again.
14768                  *
14769                  * Otherwise, the node can be split at the current position.
14770                  *
14771                  * The same logic is used for UTF-8 patterns and not */
14772                 if (UTF) {
14773                     Size_t added_len;
14774
14775                     /* Append the fold of ender */
14776                     (void) _to_uni_fold_flags(
14777                         ender,
14778                         (U8 *) e,
14779                         &added_len,
14780                         FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14781                                         ? FOLD_FLAGS_NOMIX_ASCII
14782                                         : 0));
14783                     e += added_len;
14784
14785                     /* 's' and the character folded to by ender may be the
14786                      * first two of a three-character fold, in which case the
14787                      * node should not be split here.  That may mean examining
14788                      * the so-far unparsed character starting at 'p'.  But if
14789                      * ender folded to more than one character, we already have
14790                      * three characters to look at.  Also, we first check if
14791                      * the sequence consisting of s and the next character form
14792                      * the first two of some three character fold.  If not,
14793                      * there's no need to peek ahead. */
14794                     if (   added_len <= UTF8SKIP(e - added_len)
14795                         && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_utf8_safe(s, e)))
14796                     {
14797                         /* Here, the two do form the beginning of a potential
14798                          * three character fold.  The unexamined character may
14799                          * or may not complete it.  Peek at it.  It might be
14800                          * something that ends the node or an escape sequence,
14801                          * in which case we don't know without a lot of work
14802                          * what it evaluates to, so we have to assume the worst
14803                          * case: that it does complete the fold, and so we
14804                          * can't split here.  All such instances  will have
14805                          * that character be an ASCII punctuation character,
14806                          * like a backslash.  So, for that case, backup one and
14807                          * drop down to try at that position */
14808                         if (isPUNCT(*p)) {
14809                             s = (char *) utf8_hop_back((U8 *) s, -1,
14810                                        (U8 *) s_start);
14811                             backed_up = TRUE;
14812                         }
14813                         else {
14814                             /* Here, since it's not punctuation, it must be a
14815                              * real character, and we can append its fold to
14816                              * 'e' (having deliberately reserved enough space
14817                              * for this eventuality) and drop down to check if
14818                              * the three actually do form a folded sequence */
14819                             (void) _to_utf8_fold_flags(
14820                                 (U8 *) p, (U8 *) RExC_end,
14821                                 (U8 *) e,
14822                                 &added_len,
14823                                 FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
14824                                                 ? FOLD_FLAGS_NOMIX_ASCII
14825                                                 : 0));
14826                             e += added_len;
14827                         }
14828                     }
14829
14830                     /* Here, we either have three characters available in
14831                      * sequence starting at 's', or we have two characters and
14832                      * know that the following one can't possibly be part of a
14833                      * three character fold.  We go through the node backwards
14834                      * until we find a place where we can split it without
14835                      * breaking apart a multi-character fold.  At any given
14836                      * point we have to worry about if such a fold begins at
14837                      * the current 's', and also if a three-character fold
14838                      * begins at s-1, (containing s and s+1).  Splitting in
14839                      * either case would break apart a fold */
14840                     do {
14841                         char *prev_s = (char *) utf8_hop_back((U8 *) s, -1,
14842                                                             (U8 *) s_start);
14843
14844                         /* If is a multi-char fold, can't split here.  Backup
14845                          * one char and try again */
14846                         if (UNLIKELY(is_MULTI_CHAR_FOLD_utf8_safe(s, e))) {
14847                             s = prev_s;
14848                             backed_up = TRUE;
14849                             continue;
14850                         }
14851
14852                         /* If the two characters beginning at 's' are part of a
14853                          * three character fold starting at the character
14854                          * before s, we can't split either before or after s.
14855                          * Backup two chars and try again */
14856                         if (   LIKELY(s > s_start)
14857                             && UNLIKELY(is_THREE_CHAR_FOLD_utf8_safe(prev_s, e)))
14858                         {
14859                             s = prev_s;
14860                             s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s_start);
14861                             backed_up = TRUE;
14862                             continue;
14863                         }
14864
14865                         /* Here there's no multi-char fold between s and the
14866                          * next character following it.  We can split */
14867                         splittable = TRUE;
14868                         break;
14869
14870                     } while (s > s_start); /* End of loops backing up through the node */
14871
14872                     /* Here we either couldn't find a place to split the node,
14873                      * or else we broke out of the loop setting 'splittable' to
14874                      * true.  In the latter case, the place to split is between
14875                      * the first and second characters in the sequence starting
14876                      * at 's' */
14877                     if (splittable) {
14878                         s += UTF8SKIP(s);
14879                     }
14880                 }
14881                 else {  /* Pattern not UTF-8 */
14882                     if (   ender != LATIN_SMALL_LETTER_SHARP_S
14883                         || ASCII_FOLD_RESTRICTED)
14884                     {
14885                         *e++ = toLOWER_L1(ender);
14886                     }
14887                     else {
14888                         *e++ = 's';
14889                         *e++ = 's';
14890                     }
14891
14892                     if (   e - s  <= 1
14893                         && UNLIKELY(is_THREE_CHAR_FOLD_HEAD_latin1_safe(s, e)))
14894                     {
14895                         if (isPUNCT(*p)) {
14896                             s--;
14897                             backed_up = TRUE;
14898                         }
14899                         else {
14900                             if (   UCHARAT(p) != LATIN_SMALL_LETTER_SHARP_S
14901                                 || ASCII_FOLD_RESTRICTED)
14902                             {
14903                                 *e++ = toLOWER_L1(ender);
14904                             }
14905                             else {
14906                                 *e++ = 's';
14907                                 *e++ = 's';
14908                             }
14909                         }
14910                     }
14911
14912                     do {
14913                         if (UNLIKELY(is_MULTI_CHAR_FOLD_latin1_safe(s, e))) {
14914                             s--;
14915                             backed_up = TRUE;
14916                             continue;
14917                         }
14918
14919                         if (   LIKELY(s > s_start)
14920                             && UNLIKELY(is_THREE_CHAR_FOLD_latin1_safe(s - 1, e)))
14921                         {
14922                             s -= 2;
14923                             backed_up = TRUE;
14924                             continue;
14925                         }
14926
14927                         splittable = TRUE;
14928                         break;
14929
14930                     } while (s > s_start);
14931
14932                     if (splittable) {
14933                         s++;
14934                     }
14935                 }
14936
14937                 /* Here, we are done backing up.  If we didn't backup at all
14938                  * (the likely case), just proceed */
14939                 if (backed_up) {
14940
14941                    /* If we did find a place to split, reparse the entire node
14942                     * stopping where we have calculated. */
14943                     if (splittable) {
14944
14945                        /* If we created a temporary folded string under /l, we
14946                         * have to map that back to the original */
14947                         if (need_to_fold_loc) {
14948                             upper_fill = loc_correspondence[s - s_start];
14949                             Safefree(locfold_buf);
14950                             Safefree(loc_correspondence);
14951
14952                             if (upper_fill == 0) {
14953                                 FAIL2("panic: loc_correspondence[%d] is 0",
14954                                       (int) (s - s_start));
14955                             }
14956                         }
14957                         else {
14958                             upper_fill = s - s0;
14959                         }
14960                         goto reparse;
14961                     }
14962                     else if (need_to_fold_loc) {
14963                         Safefree(locfold_buf);
14964                         Safefree(loc_correspondence);
14965                     }
14966
14967                     /* Here the node consists entirely of non-final multi-char
14968                      * folds.  (Likely it is all 'f's or all 's's.)  There's no
14969                      * decent place to split it, so give up and just take the
14970                      * whole thing */
14971                     len = old_s - s0;
14972                 }
14973             }   /* End of verifying node ends with an appropriate char */
14974
14975             /* We need to start the next node at the character that didn't fit
14976              * in this one */
14977             p = oldp;
14978
14979           loopdone:   /* Jumped to when encounters something that shouldn't be
14980                          in the node */
14981
14982             /* Free up any over-allocated space; cast is to silence bogus
14983              * warning in MS VC */
14984             change_engine_size(pRExC_state,
14985                         - (Ptrdiff_t) (current_string_nodes - STR_SZ(len)));
14986
14987             /* I (khw) don't know if you can get here with zero length, but the
14988              * old code handled this situation by creating a zero-length EXACT
14989              * node.  Might as well be NOTHING instead */
14990             if (len == 0) {
14991                 OP(REGNODE_p(ret)) = NOTHING;
14992             }
14993             else {
14994
14995                 /* If the node type is EXACT here, check to see if it
14996                  * should be EXACTL, or EXACT_REQ8. */
14997                 if (node_type == EXACT) {
14998                     if (LOC) {
14999                         node_type = EXACTL;
15000                     }
15001                     else if (requires_utf8_target) {
15002                         node_type = EXACT_REQ8;
15003                     }
15004                 }
15005                 else if (node_type == LEXACT) {
15006                     if (requires_utf8_target) {
15007                         node_type = LEXACT_REQ8;
15008                     }
15009                 }
15010                 else if (FOLD) {
15011                     if (    UNLIKELY(has_micro_sign || has_ss)
15012                         && (node_type == EXACTFU || (   node_type == EXACTF
15013                                                      && maybe_exactfu)))
15014                     {   /* These two conditions are problematic in non-UTF-8
15015                            EXACTFU nodes. */
15016                         assert(! UTF);
15017                         node_type = EXACTFUP;
15018                     }
15019                     else if (node_type == EXACTFL) {
15020
15021                         /* 'maybe_exactfu' is deliberately set above to
15022                          * indicate this node type, where all code points in it
15023                          * are above 255 */
15024                         if (maybe_exactfu) {
15025                             node_type = EXACTFLU8;
15026                         }
15027                         else if (UNLIKELY(
15028                              _invlist_contains_cp(PL_HasMultiCharFold, ender)))
15029                         {
15030                             /* A character that folds to more than one will
15031                              * match multiple characters, so can't be SIMPLE.
15032                              * We don't have to worry about this with EXACTFLU8
15033                              * nodes just above, as they have already been
15034                              * folded (since the fold doesn't vary at run
15035                              * time).  Here, if the final character in the node
15036                              * folds to multiple, it can't be simple.  (This
15037                              * only has an effect if the node has only a single
15038                              * character, hence the final one, as elsewhere we
15039                              * turn off simple for nodes whose length > 1 */
15040                             maybe_SIMPLE = 0;
15041                         }
15042                     }
15043                     else if (node_type == EXACTF) {  /* Means is /di */
15044
15045                         /* This intermediate variable is needed solely because
15046                          * the asserts in the macro where used exceed Win32's
15047                          * literal string capacity */
15048                         char first_char = * STRING(REGNODE_p(ret));
15049
15050                         /* If 'maybe_exactfu' is clear, then we need to stay
15051                          * /di.  If it is set, it means there are no code
15052                          * points that match differently depending on UTF8ness
15053                          * of the target string, so it can become an EXACTFU
15054                          * node */
15055                         if (! maybe_exactfu) {
15056                             RExC_seen_d_op = TRUE;
15057                         }
15058                         else if (   isALPHA_FOLD_EQ(first_char, 's')
15059                                  || isALPHA_FOLD_EQ(ender, 's'))
15060                         {
15061                             /* But, if the node begins or ends in an 's' we
15062                              * have to defer changing it into an EXACTFU, as
15063                              * the node could later get joined with another one
15064                              * that ends or begins with 's' creating an 'ss'
15065                              * sequence which would then wrongly match the
15066                              * sharp s without the target being UTF-8.  We
15067                              * create a special node that we resolve later when
15068                              * we join nodes together */
15069
15070                             node_type = EXACTFU_S_EDGE;
15071                         }
15072                         else {
15073                             node_type = EXACTFU;
15074                         }
15075                     }
15076
15077                     if (requires_utf8_target && node_type == EXACTFU) {
15078                         node_type = EXACTFU_REQ8;
15079                     }
15080                 }
15081
15082                 OP(REGNODE_p(ret)) = node_type;
15083                 setSTR_LEN(REGNODE_p(ret), len);
15084                 RExC_emit += STR_SZ(len);
15085
15086                 /* If the node isn't a single character, it can't be SIMPLE */
15087                 if (len > (Size_t) ((UTF) ? UTF8SKIP(STRING(REGNODE_p(ret))) : 1)) {
15088                     maybe_SIMPLE = 0;
15089                 }
15090
15091                 *flagp |= HASWIDTH | maybe_SIMPLE;
15092             }
15093
15094             Set_Node_Length(REGNODE_p(ret), p - parse_start - 1);
15095             RExC_parse = p;
15096
15097             {
15098                 /* len is STRLEN which is unsigned, need to copy to signed */
15099                 IV iv = len;
15100                 if (iv < 0)
15101                     vFAIL("Internal disaster");
15102             }
15103
15104         } /* End of label 'defchar:' */
15105         break;
15106     } /* End of giant switch on input character */
15107
15108     /* Position parse to next real character */
15109     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
15110                                             FALSE /* Don't force to /x */ );
15111     if (   *RExC_parse == '{'
15112         && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse))
15113     {
15114         if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) {
15115             RExC_parse++;
15116             vFAIL("Unescaped left brace in regex is illegal here");
15117         }
15118         ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is"
15119                                   " passed through");
15120     }
15121
15122     return(ret);
15123 }
15124
15125
15126 STATIC void
15127 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
15128 {
15129     /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'.  It
15130      * sets up the bitmap and any flags, removing those code points from the
15131      * inversion list, setting it to NULL should it become completely empty */
15132
15133     dVAR;
15134
15135     PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
15136     assert(PL_regkind[OP(node)] == ANYOF);
15137
15138     /* There is no bitmap for this node type */
15139     if (inRANGE(OP(node), ANYOFH, ANYOFRb)) {
15140         return;
15141     }
15142
15143     ANYOF_BITMAP_ZERO(node);
15144     if (*invlist_ptr) {
15145
15146         /* This gets set if we actually need to modify things */
15147         bool change_invlist = FALSE;
15148
15149         UV start, end;
15150
15151         /* Start looking through *invlist_ptr */
15152         invlist_iterinit(*invlist_ptr);
15153         while (invlist_iternext(*invlist_ptr, &start, &end)) {
15154             UV high;
15155             int i;
15156
15157             if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
15158                 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
15159             }
15160
15161             /* Quit if are above what we should change */
15162             if (start >= NUM_ANYOF_CODE_POINTS) {
15163                 break;
15164             }
15165
15166             change_invlist = TRUE;
15167
15168             /* Set all the bits in the range, up to the max that we are doing */
15169             high = (end < NUM_ANYOF_CODE_POINTS - 1)
15170                    ? end
15171                    : NUM_ANYOF_CODE_POINTS - 1;
15172             for (i = start; i <= (int) high; i++) {
15173                 if (! ANYOF_BITMAP_TEST(node, i)) {
15174                     ANYOF_BITMAP_SET(node, i);
15175                 }
15176             }
15177         }
15178         invlist_iterfinish(*invlist_ptr);
15179
15180         /* Done with loop; remove any code points that are in the bitmap from
15181          * *invlist_ptr; similarly for code points above the bitmap if we have
15182          * a flag to match all of them anyways */
15183         if (change_invlist) {
15184             _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
15185         }
15186         if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
15187             _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
15188         }
15189
15190         /* If have completely emptied it, remove it completely */
15191         if (_invlist_len(*invlist_ptr) == 0) {
15192             SvREFCNT_dec_NN(*invlist_ptr);
15193             *invlist_ptr = NULL;
15194         }
15195     }
15196 }
15197
15198 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
15199    Character classes ([:foo:]) can also be negated ([:^foo:]).
15200    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
15201    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
15202    but trigger failures because they are currently unimplemented. */
15203
15204 #define POSIXCC_DONE(c)   ((c) == ':')
15205 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
15206 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
15207 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
15208
15209 #define WARNING_PREFIX              "Assuming NOT a POSIX class since "
15210 #define NO_BLANKS_POSIX_WARNING     "no blanks are allowed in one"
15211 #define SEMI_COLON_POSIX_WARNING    "a semi-colon was found instead of a colon"
15212
15213 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
15214
15215 /* 'posix_warnings' and 'warn_text' are names of variables in the following
15216  * routine. q.v. */
15217 #define ADD_POSIX_WARNING(p, text)  STMT_START {                            \
15218         if (posix_warnings) {                                               \
15219             if (! RExC_warn_text ) RExC_warn_text =                         \
15220                                          (AV *) sv_2mortal((SV *) newAV()); \
15221             av_push(RExC_warn_text, Perl_newSVpvf(aTHX_                     \
15222                                              WARNING_PREFIX                 \
15223                                              text                           \
15224                                              REPORT_LOCATION,               \
15225                                              REPORT_LOCATION_ARGS(p)));     \
15226         }                                                                   \
15227     } STMT_END
15228 #define CLEAR_POSIX_WARNINGS()                                              \
15229     STMT_START {                                                            \
15230         if (posix_warnings && RExC_warn_text)                               \
15231             av_clear(RExC_warn_text);                                       \
15232     } STMT_END
15233
15234 #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret)                                \
15235     STMT_START {                                                            \
15236         CLEAR_POSIX_WARNINGS();                                             \
15237         return ret;                                                         \
15238     } STMT_END
15239
15240 STATIC int
15241 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
15242
15243     const char * const s,      /* Where the putative posix class begins.
15244                                   Normally, this is one past the '['.  This
15245                                   parameter exists so it can be somewhere
15246                                   besides RExC_parse. */
15247     char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
15248                                   NULL */
15249     AV ** posix_warnings,      /* Where to place any generated warnings, or
15250                                   NULL */
15251     const bool check_only      /* Don't die if error */
15252 )
15253 {
15254     /* This parses what the caller thinks may be one of the three POSIX
15255      * constructs:
15256      *  1) a character class, like [:blank:]
15257      *  2) a collating symbol, like [. .]
15258      *  3) an equivalence class, like [= =]
15259      * In the latter two cases, it croaks if it finds a syntactically legal
15260      * one, as these are not handled by Perl.
15261      *
15262      * The main purpose is to look for a POSIX character class.  It returns:
15263      *  a) the class number
15264      *      if it is a completely syntactically and semantically legal class.
15265      *      'updated_parse_ptr', if not NULL, is set to point to just after the
15266      *      closing ']' of the class
15267      *  b) OOB_NAMEDCLASS
15268      *      if it appears that one of the three POSIX constructs was meant, but
15269      *      its specification was somehow defective.  'updated_parse_ptr', if
15270      *      not NULL, is set to point to the character just after the end
15271      *      character of the class.  See below for handling of warnings.
15272      *  c) NOT_MEANT_TO_BE_A_POSIX_CLASS
15273      *      if it  doesn't appear that a POSIX construct was intended.
15274      *      'updated_parse_ptr' is not changed.  No warnings nor errors are
15275      *      raised.
15276      *
15277      * In b) there may be errors or warnings generated.  If 'check_only' is
15278      * TRUE, then any errors are discarded.  Warnings are returned to the
15279      * caller via an AV* created into '*posix_warnings' if it is not NULL.  If
15280      * instead it is NULL, warnings are suppressed.
15281      *
15282      * The reason for this function, and its complexity is that a bracketed
15283      * character class can contain just about anything.  But it's easy to
15284      * mistype the very specific posix class syntax but yielding a valid
15285      * regular bracketed class, so it silently gets compiled into something
15286      * quite unintended.
15287      *
15288      * The solution adopted here maintains backward compatibility except that
15289      * it adds a warning if it looks like a posix class was intended but
15290      * improperly specified.  The warning is not raised unless what is input
15291      * very closely resembles one of the 14 legal posix classes.  To do this,
15292      * it uses fuzzy parsing.  It calculates how many single-character edits it
15293      * would take to transform what was input into a legal posix class.  Only
15294      * if that number is quite small does it think that the intention was a
15295      * posix class.  Obviously these are heuristics, and there will be cases
15296      * where it errs on one side or another, and they can be tweaked as
15297      * experience informs.
15298      *
15299      * The syntax for a legal posix class is:
15300      *
15301      * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/
15302      *
15303      * What this routine considers syntactically to be an intended posix class
15304      * is this (the comments indicate some restrictions that the pattern
15305      * doesn't show):
15306      *
15307      *  qr/(?x: \[?                         # The left bracket, possibly
15308      *                                      # omitted
15309      *          \h*                         # possibly followed by blanks
15310      *          (?: \^ \h* )?               # possibly a misplaced caret
15311      *          [:;]?                       # The opening class character,
15312      *                                      # possibly omitted.  A typo
15313      *                                      # semi-colon can also be used.
15314      *          \h*
15315      *          \^?                         # possibly a correctly placed
15316      *                                      # caret, but not if there was also
15317      *                                      # a misplaced one
15318      *          \h*
15319      *          .{3,15}                     # The class name.  If there are
15320      *                                      # deviations from the legal syntax,
15321      *                                      # its edit distance must be close
15322      *                                      # to a real class name in order
15323      *                                      # for it to be considered to be
15324      *                                      # an intended posix class.
15325      *          \h*
15326      *          [[:punct:]]?                # The closing class character,
15327      *                                      # possibly omitted.  If not a colon
15328      *                                      # nor semi colon, the class name
15329      *                                      # must be even closer to a valid
15330      *                                      # one
15331      *          \h*
15332      *          \]?                         # The right bracket, possibly
15333      *                                      # omitted.
15334      *     )/
15335      *
15336      * In the above, \h must be ASCII-only.
15337      *
15338      * These are heuristics, and can be tweaked as field experience dictates.
15339      * There will be cases when someone didn't intend to specify a posix class
15340      * that this warns as being so.  The goal is to minimize these, while
15341      * maximizing the catching of things intended to be a posix class that
15342      * aren't parsed as such.
15343      */
15344
15345     const char* p             = s;
15346     const char * const e      = RExC_end;
15347     unsigned complement       = 0;      /* If to complement the class */
15348     bool found_problem        = FALSE;  /* Assume OK until proven otherwise */
15349     bool has_opening_bracket  = FALSE;
15350     bool has_opening_colon    = FALSE;
15351     int class_number          = OOB_NAMEDCLASS; /* Out-of-bounds until find
15352                                                    valid class */
15353     const char * possible_end = NULL;   /* used for a 2nd parse pass */
15354     const char* name_start;             /* ptr to class name first char */
15355
15356     /* If the number of single-character typos the input name is away from a
15357      * legal name is no more than this number, it is considered to have meant
15358      * the legal name */
15359     int max_distance          = 2;
15360
15361     /* to store the name.  The size determines the maximum length before we
15362      * decide that no posix class was intended.  Should be at least
15363      * sizeof("alphanumeric") */
15364     UV input_text[15];
15365     STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric");
15366
15367     PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
15368
15369     CLEAR_POSIX_WARNINGS();
15370
15371     if (p >= e) {
15372         return NOT_MEANT_TO_BE_A_POSIX_CLASS;
15373     }
15374
15375     if (*(p - 1) != '[') {
15376         ADD_POSIX_WARNING(p, "it doesn't start with a '['");
15377         found_problem = TRUE;
15378     }
15379     else {
15380         has_opening_bracket = TRUE;
15381     }
15382
15383     /* They could be confused and think you can put spaces between the
15384      * components */
15385     if (isBLANK(*p)) {
15386         found_problem = TRUE;
15387
15388         do {
15389             p++;
15390         } while (p < e && isBLANK(*p));
15391
15392         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15393     }
15394
15395     /* For [. .] and [= =].  These are quite different internally from [: :],
15396      * so they are handled separately.  */
15397     if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']'
15398                                             and 1 for at least one char in it
15399                                           */
15400     {
15401         const char open_char  = *p;
15402         const char * temp_ptr = p + 1;
15403
15404         /* These two constructs are not handled by perl, and if we find a
15405          * syntactically valid one, we croak.  khw, who wrote this code, finds
15406          * this explanation of them very unclear:
15407          * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html
15408          * And searching the rest of the internet wasn't very helpful either.
15409          * It looks like just about any byte can be in these constructs,
15410          * depending on the locale.  But unless the pattern is being compiled
15411          * under /l, which is very rare, Perl runs under the C or POSIX locale.
15412          * In that case, it looks like [= =] isn't allowed at all, and that
15413          * [. .] could be any single code point, but for longer strings the
15414          * constituent characters would have to be the ASCII alphabetics plus
15415          * the minus-hyphen.  Any sensible locale definition would limit itself
15416          * to these.  And any portable one definitely should.  Trying to parse
15417          * the general case is a nightmare (see [perl #127604]).  So, this code
15418          * looks only for interiors of these constructs that match:
15419          *      qr/.|[-\w]{2,}/
15420          * Using \w relaxes the apparent rules a little, without adding much
15421          * danger of mistaking something else for one of these constructs.
15422          *
15423          * [. .] in some implementations described on the internet is usable to
15424          * escape a character that otherwise is special in bracketed character
15425          * classes.  For example [.].] means a literal right bracket instead of
15426          * the ending of the class
15427          *
15428          * [= =] can legitimately contain a [. .] construct, but we don't
15429          * handle this case, as that [. .] construct will later get parsed
15430          * itself and croak then.  And [= =] is checked for even when not under
15431          * /l, as Perl has long done so.
15432          *
15433          * The code below relies on there being a trailing NUL, so it doesn't
15434          * have to keep checking if the parse ptr < e.
15435          */
15436         if (temp_ptr[1] == open_char) {
15437             temp_ptr++;
15438         }
15439         else while (    temp_ptr < e
15440                     && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-'))
15441         {
15442             temp_ptr++;
15443         }
15444
15445         if (*temp_ptr == open_char) {
15446             temp_ptr++;
15447             if (*temp_ptr == ']') {
15448                 temp_ptr++;
15449                 if (! found_problem && ! check_only) {
15450                     RExC_parse = (char *) temp_ptr;
15451                     vFAIL3("POSIX syntax [%c %c] is reserved for future "
15452                             "extensions", open_char, open_char);
15453                 }
15454
15455                 /* Here, the syntax wasn't completely valid, or else the call
15456                  * is to check-only */
15457                 if (updated_parse_ptr) {
15458                     *updated_parse_ptr = (char *) temp_ptr;
15459                 }
15460
15461                 CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS);
15462             }
15463         }
15464
15465         /* If we find something that started out to look like one of these
15466          * constructs, but isn't, we continue below so that it can be checked
15467          * for being a class name with a typo of '.' or '=' instead of a colon.
15468          * */
15469     }
15470
15471     /* Here, we think there is a possibility that a [: :] class was meant, and
15472      * we have the first real character.  It could be they think the '^' comes
15473      * first */
15474     if (*p == '^') {
15475         found_problem = TRUE;
15476         ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
15477         complement = 1;
15478         p++;
15479
15480         if (isBLANK(*p)) {
15481             found_problem = TRUE;
15482
15483             do {
15484                 p++;
15485             } while (p < e && isBLANK(*p));
15486
15487             ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15488         }
15489     }
15490
15491     /* But the first character should be a colon, which they could have easily
15492      * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
15493      * distinguish from a colon, so treat that as a colon).  */
15494     if (*p == ':') {
15495         p++;
15496         has_opening_colon = TRUE;
15497     }
15498     else if (*p == ';') {
15499         found_problem = TRUE;
15500         p++;
15501         ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15502         has_opening_colon = TRUE;
15503     }
15504     else {
15505         found_problem = TRUE;
15506         ADD_POSIX_WARNING(p, "there must be a starting ':'");
15507
15508         /* Consider an initial punctuation (not one of the recognized ones) to
15509          * be a left terminator */
15510         if (*p != '^' && *p != ']' && isPUNCT(*p)) {
15511             p++;
15512         }
15513     }
15514
15515     /* They may think that you can put spaces between the components */
15516     if (isBLANK(*p)) {
15517         found_problem = TRUE;
15518
15519         do {
15520             p++;
15521         } while (p < e && isBLANK(*p));
15522
15523         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15524     }
15525
15526     if (*p == '^') {
15527
15528         /* We consider something like [^:^alnum:]] to not have been intended to
15529          * be a posix class, but XXX maybe we should */
15530         if (complement) {
15531             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15532         }
15533
15534         complement = 1;
15535         p++;
15536     }
15537
15538     /* Again, they may think that you can put spaces between the components */
15539     if (isBLANK(*p)) {
15540         found_problem = TRUE;
15541
15542         do {
15543             p++;
15544         } while (p < e && isBLANK(*p));
15545
15546         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15547     }
15548
15549     if (*p == ']') {
15550
15551         /* XXX This ']' may be a typo, and something else was meant.  But
15552          * treating it as such creates enough complications, that that
15553          * possibility isn't currently considered here.  So we assume that the
15554          * ']' is what is intended, and if we've already found an initial '[',
15555          * this leaves this construct looking like [:] or [:^], which almost
15556          * certainly weren't intended to be posix classes */
15557         if (has_opening_bracket) {
15558             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15559         }
15560
15561         /* But this function can be called when we parse the colon for
15562          * something like qr/[alpha:]]/, so we back up to look for the
15563          * beginning */
15564         p--;
15565
15566         if (*p == ';') {
15567             found_problem = TRUE;
15568             ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15569         }
15570         else if (*p != ':') {
15571
15572             /* XXX We are currently very restrictive here, so this code doesn't
15573              * consider the possibility that, say, /[alpha.]]/ was intended to
15574              * be a posix class. */
15575             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15576         }
15577
15578         /* Here we have something like 'foo:]'.  There was no initial colon,
15579          * and we back up over 'foo.  XXX Unlike the going forward case, we
15580          * don't handle typos of non-word chars in the middle */
15581         has_opening_colon = FALSE;
15582         p--;
15583
15584         while (p > RExC_start && isWORDCHAR(*p)) {
15585             p--;
15586         }
15587         p++;
15588
15589         /* Here, we have positioned ourselves to where we think the first
15590          * character in the potential class is */
15591     }
15592
15593     /* Now the interior really starts.  There are certain key characters that
15594      * can end the interior, or these could just be typos.  To catch both
15595      * cases, we may have to do two passes.  In the first pass, we keep on
15596      * going unless we come to a sequence that matches
15597      *      qr/ [[:punct:]] [[:blank:]]* \] /xa
15598      * This means it takes a sequence to end the pass, so two typos in a row if
15599      * that wasn't what was intended.  If the class is perfectly formed, just
15600      * this one pass is needed.  We also stop if there are too many characters
15601      * being accumulated, but this number is deliberately set higher than any
15602      * real class.  It is set high enough so that someone who thinks that
15603      * 'alphanumeric' is a correct name would get warned that it wasn't.
15604      * While doing the pass, we keep track of where the key characters were in
15605      * it.  If we don't find an end to the class, and one of the key characters
15606      * was found, we redo the pass, but stop when we get to that character.
15607      * Thus the key character was considered a typo in the first pass, but a
15608      * terminator in the second.  If two key characters are found, we stop at
15609      * the second one in the first pass.  Again this can miss two typos, but
15610      * catches a single one
15611      *
15612      * In the first pass, 'possible_end' starts as NULL, and then gets set to
15613      * point to the first key character.  For the second pass, it starts as -1.
15614      * */
15615
15616     name_start = p;
15617   parse_name:
15618     {
15619         bool has_blank               = FALSE;
15620         bool has_upper               = FALSE;
15621         bool has_terminating_colon   = FALSE;
15622         bool has_terminating_bracket = FALSE;
15623         bool has_semi_colon          = FALSE;
15624         unsigned int name_len        = 0;
15625         int punct_count              = 0;
15626
15627         while (p < e) {
15628
15629             /* Squeeze out blanks when looking up the class name below */
15630             if (isBLANK(*p) ) {
15631                 has_blank = TRUE;
15632                 found_problem = TRUE;
15633                 p++;
15634                 continue;
15635             }
15636
15637             /* The name will end with a punctuation */
15638             if (isPUNCT(*p)) {
15639                 const char * peek = p + 1;
15640
15641                 /* Treat any non-']' punctuation followed by a ']' (possibly
15642                  * with intervening blanks) as trying to terminate the class.
15643                  * ']]' is very likely to mean a class was intended (but
15644                  * missing the colon), but the warning message that gets
15645                  * generated shows the error position better if we exit the
15646                  * loop at the bottom (eventually), so skip it here. */
15647                 if (*p != ']') {
15648                     if (peek < e && isBLANK(*peek)) {
15649                         has_blank = TRUE;
15650                         found_problem = TRUE;
15651                         do {
15652                             peek++;
15653                         } while (peek < e && isBLANK(*peek));
15654                     }
15655
15656                     if (peek < e && *peek == ']') {
15657                         has_terminating_bracket = TRUE;
15658                         if (*p == ':') {
15659                             has_terminating_colon = TRUE;
15660                         }
15661                         else if (*p == ';') {
15662                             has_semi_colon = TRUE;
15663                             has_terminating_colon = TRUE;
15664                         }
15665                         else {
15666                             found_problem = TRUE;
15667                         }
15668                         p = peek + 1;
15669                         goto try_posix;
15670                     }
15671                 }
15672
15673                 /* Here we have punctuation we thought didn't end the class.
15674                  * Keep track of the position of the key characters that are
15675                  * more likely to have been class-enders */
15676                 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
15677
15678                     /* Allow just one such possible class-ender not actually
15679                      * ending the class. */
15680                     if (possible_end) {
15681                         break;
15682                     }
15683                     possible_end = p;
15684                 }
15685
15686                 /* If we have too many punctuation characters, no use in
15687                  * keeping going */
15688                 if (++punct_count > max_distance) {
15689                     break;
15690                 }
15691
15692                 /* Treat the punctuation as a typo. */
15693                 input_text[name_len++] = *p;
15694                 p++;
15695             }
15696             else if (isUPPER(*p)) { /* Use lowercase for lookup */
15697                 input_text[name_len++] = toLOWER(*p);
15698                 has_upper = TRUE;
15699                 found_problem = TRUE;
15700                 p++;
15701             } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
15702                 input_text[name_len++] = *p;
15703                 p++;
15704             }
15705             else {
15706                 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
15707                 p+= UTF8SKIP(p);
15708             }
15709
15710             /* The declaration of 'input_text' is how long we allow a potential
15711              * class name to be, before saying they didn't mean a class name at
15712              * all */
15713             if (name_len >= C_ARRAY_LENGTH(input_text)) {
15714                 break;
15715             }
15716         }
15717
15718         /* We get to here when the possible class name hasn't been properly
15719          * terminated before:
15720          *   1) we ran off the end of the pattern; or
15721          *   2) found two characters, each of which might have been intended to
15722          *      be the name's terminator
15723          *   3) found so many punctuation characters in the purported name,
15724          *      that the edit distance to a valid one is exceeded
15725          *   4) we decided it was more characters than anyone could have
15726          *      intended to be one. */
15727
15728         found_problem = TRUE;
15729
15730         /* In the final two cases, we know that looking up what we've
15731          * accumulated won't lead to a match, even a fuzzy one. */
15732         if (   name_len >= C_ARRAY_LENGTH(input_text)
15733             || punct_count > max_distance)
15734         {
15735             /* If there was an intermediate key character that could have been
15736              * an intended end, redo the parse, but stop there */
15737             if (possible_end && possible_end != (char *) -1) {
15738                 possible_end = (char *) -1; /* Special signal value to say
15739                                                we've done a first pass */
15740                 p = name_start;
15741                 goto parse_name;
15742             }
15743
15744             /* Otherwise, it can't have meant to have been a class */
15745             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15746         }
15747
15748         /* If we ran off the end, and the final character was a punctuation
15749          * one, back up one, to look at that final one just below.  Later, we
15750          * will restore the parse pointer if appropriate */
15751         if (name_len && p == e && isPUNCT(*(p-1))) {
15752             p--;
15753             name_len--;
15754         }
15755
15756         if (p < e && isPUNCT(*p)) {
15757             if (*p == ']') {
15758                 has_terminating_bracket = TRUE;
15759
15760                 /* If this is a 2nd ']', and the first one is just below this
15761                  * one, consider that to be the real terminator.  This gives a
15762                  * uniform and better positioning for the warning message  */
15763                 if (   possible_end
15764                     && possible_end != (char *) -1
15765                     && *possible_end == ']'
15766                     && name_len && input_text[name_len - 1] == ']')
15767                 {
15768                     name_len--;
15769                     p = possible_end;
15770
15771                     /* And this is actually equivalent to having done the 2nd
15772                      * pass now, so set it to not try again */
15773                     possible_end = (char *) -1;
15774                 }
15775             }
15776             else {
15777                 if (*p == ':') {
15778                     has_terminating_colon = TRUE;
15779                 }
15780                 else if (*p == ';') {
15781                     has_semi_colon = TRUE;
15782                     has_terminating_colon = TRUE;
15783                 }
15784                 p++;
15785             }
15786         }
15787
15788     try_posix:
15789
15790         /* Here, we have a class name to look up.  We can short circuit the
15791          * stuff below for short names that can't possibly be meant to be a
15792          * class name.  (We can do this on the first pass, as any second pass
15793          * will yield an even shorter name) */
15794         if (name_len < 3) {
15795             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15796         }
15797
15798         /* Find which class it is.  Initially switch on the length of the name.
15799          * */
15800         switch (name_len) {
15801             case 4:
15802                 if (memEQs(name_start, 4, "word")) {
15803                     /* this is not POSIX, this is the Perl \w */
15804                     class_number = ANYOF_WORDCHAR;
15805                 }
15806                 break;
15807             case 5:
15808                 /* Names all of length 5: alnum alpha ascii blank cntrl digit
15809                  *                        graph lower print punct space upper
15810                  * Offset 4 gives the best switch position.  */
15811                 switch (name_start[4]) {
15812                     case 'a':
15813                         if (memBEGINs(name_start, 5, "alph")) /* alpha */
15814                             class_number = ANYOF_ALPHA;
15815                         break;
15816                     case 'e':
15817                         if (memBEGINs(name_start, 5, "spac")) /* space */
15818                             class_number = ANYOF_SPACE;
15819                         break;
15820                     case 'h':
15821                         if (memBEGINs(name_start, 5, "grap")) /* graph */
15822                             class_number = ANYOF_GRAPH;
15823                         break;
15824                     case 'i':
15825                         if (memBEGINs(name_start, 5, "asci")) /* ascii */
15826                             class_number = ANYOF_ASCII;
15827                         break;
15828                     case 'k':
15829                         if (memBEGINs(name_start, 5, "blan")) /* blank */
15830                             class_number = ANYOF_BLANK;
15831                         break;
15832                     case 'l':
15833                         if (memBEGINs(name_start, 5, "cntr")) /* cntrl */
15834                             class_number = ANYOF_CNTRL;
15835                         break;
15836                     case 'm':
15837                         if (memBEGINs(name_start, 5, "alnu")) /* alnum */
15838                             class_number = ANYOF_ALPHANUMERIC;
15839                         break;
15840                     case 'r':
15841                         if (memBEGINs(name_start, 5, "lowe")) /* lower */
15842                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
15843                         else if (memBEGINs(name_start, 5, "uppe")) /* upper */
15844                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
15845                         break;
15846                     case 't':
15847                         if (memBEGINs(name_start, 5, "digi")) /* digit */
15848                             class_number = ANYOF_DIGIT;
15849                         else if (memBEGINs(name_start, 5, "prin")) /* print */
15850                             class_number = ANYOF_PRINT;
15851                         else if (memBEGINs(name_start, 5, "punc")) /* punct */
15852                             class_number = ANYOF_PUNCT;
15853                         break;
15854                 }
15855                 break;
15856             case 6:
15857                 if (memEQs(name_start, 6, "xdigit"))
15858                     class_number = ANYOF_XDIGIT;
15859                 break;
15860         }
15861
15862         /* If the name exactly matches a posix class name the class number will
15863          * here be set to it, and the input almost certainly was meant to be a
15864          * posix class, so we can skip further checking.  If instead the syntax
15865          * is exactly correct, but the name isn't one of the legal ones, we
15866          * will return that as an error below.  But if neither of these apply,
15867          * it could be that no posix class was intended at all, or that one
15868          * was, but there was a typo.  We tease these apart by doing fuzzy
15869          * matching on the name */
15870         if (class_number == OOB_NAMEDCLASS && found_problem) {
15871             const UV posix_names[][6] = {
15872                                                 { 'a', 'l', 'n', 'u', 'm' },
15873                                                 { 'a', 'l', 'p', 'h', 'a' },
15874                                                 { 'a', 's', 'c', 'i', 'i' },
15875                                                 { 'b', 'l', 'a', 'n', 'k' },
15876                                                 { 'c', 'n', 't', 'r', 'l' },
15877                                                 { 'd', 'i', 'g', 'i', 't' },
15878                                                 { 'g', 'r', 'a', 'p', 'h' },
15879                                                 { 'l', 'o', 'w', 'e', 'r' },
15880                                                 { 'p', 'r', 'i', 'n', 't' },
15881                                                 { 'p', 'u', 'n', 'c', 't' },
15882                                                 { 's', 'p', 'a', 'c', 'e' },
15883                                                 { 'u', 'p', 'p', 'e', 'r' },
15884                                                 { 'w', 'o', 'r', 'd' },
15885                                                 { 'x', 'd', 'i', 'g', 'i', 't' }
15886                                             };
15887             /* The names of the above all have added NULs to make them the same
15888              * size, so we need to also have the real lengths */
15889             const UV posix_name_lengths[] = {
15890                                                 sizeof("alnum") - 1,
15891                                                 sizeof("alpha") - 1,
15892                                                 sizeof("ascii") - 1,
15893                                                 sizeof("blank") - 1,
15894                                                 sizeof("cntrl") - 1,
15895                                                 sizeof("digit") - 1,
15896                                                 sizeof("graph") - 1,
15897                                                 sizeof("lower") - 1,
15898                                                 sizeof("print") - 1,
15899                                                 sizeof("punct") - 1,
15900                                                 sizeof("space") - 1,
15901                                                 sizeof("upper") - 1,
15902                                                 sizeof("word")  - 1,
15903                                                 sizeof("xdigit")- 1
15904                                             };
15905             unsigned int i;
15906             int temp_max = max_distance;    /* Use a temporary, so if we
15907                                                reparse, we haven't changed the
15908                                                outer one */
15909
15910             /* Use a smaller max edit distance if we are missing one of the
15911              * delimiters */
15912             if (   has_opening_bracket + has_opening_colon < 2
15913                 || has_terminating_bracket + has_terminating_colon < 2)
15914             {
15915                 temp_max--;
15916             }
15917
15918             /* See if the input name is close to a legal one */
15919             for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
15920
15921                 /* Short circuit call if the lengths are too far apart to be
15922                  * able to match */
15923                 if (abs( (int) (name_len - posix_name_lengths[i]))
15924                     > temp_max)
15925                 {
15926                     continue;
15927                 }
15928
15929                 if (edit_distance(input_text,
15930                                   posix_names[i],
15931                                   name_len,
15932                                   posix_name_lengths[i],
15933                                   temp_max
15934                                  )
15935                     > -1)
15936                 { /* If it is close, it probably was intended to be a class */
15937                     goto probably_meant_to_be;
15938                 }
15939             }
15940
15941             /* Here the input name is not close enough to a valid class name
15942              * for us to consider it to be intended to be a posix class.  If
15943              * we haven't already done so, and the parse found a character that
15944              * could have been terminators for the name, but which we absorbed
15945              * as typos during the first pass, repeat the parse, signalling it
15946              * to stop at that character */
15947             if (possible_end && possible_end != (char *) -1) {
15948                 possible_end = (char *) -1;
15949                 p = name_start;
15950                 goto parse_name;
15951             }
15952
15953             /* Here neither pass found a close-enough class name */
15954             CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS);
15955         }
15956
15957     probably_meant_to_be:
15958
15959         /* Here we think that a posix specification was intended.  Update any
15960          * parse pointer */
15961         if (updated_parse_ptr) {
15962             *updated_parse_ptr = (char *) p;
15963         }
15964
15965         /* If a posix class name was intended but incorrectly specified, we
15966          * output or return the warnings */
15967         if (found_problem) {
15968
15969             /* We set flags for these issues in the parse loop above instead of
15970              * adding them to the list of warnings, because we can parse it
15971              * twice, and we only want one warning instance */
15972             if (has_upper) {
15973                 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
15974             }
15975             if (has_blank) {
15976                 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
15977             }
15978             if (has_semi_colon) {
15979                 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
15980             }
15981             else if (! has_terminating_colon) {
15982                 ADD_POSIX_WARNING(p, "there is no terminating ':'");
15983             }
15984             if (! has_terminating_bracket) {
15985                 ADD_POSIX_WARNING(p, "there is no terminating ']'");
15986             }
15987
15988             if (   posix_warnings
15989                 && RExC_warn_text
15990                 && av_top_index(RExC_warn_text) > -1)
15991             {
15992                 *posix_warnings = RExC_warn_text;
15993             }
15994         }
15995         else if (class_number != OOB_NAMEDCLASS) {
15996             /* If it is a known class, return the class.  The class number
15997              * #defines are structured so each complement is +1 to the normal
15998              * one */
15999             CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement);
16000         }
16001         else if (! check_only) {
16002
16003             /* Here, it is an unrecognized class.  This is an error (unless the
16004             * call is to check only, which we've already handled above) */
16005             const char * const complement_string = (complement)
16006                                                    ? "^"
16007                                                    : "";
16008             RExC_parse = (char *) p;
16009             vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown",
16010                         complement_string,
16011                         UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
16012         }
16013     }
16014
16015     return OOB_NAMEDCLASS;
16016 }
16017 #undef ADD_POSIX_WARNING
16018
16019 STATIC unsigned  int
16020 S_regex_set_precedence(const U8 my_operator) {
16021
16022     /* Returns the precedence in the (?[...]) construct of the input operator,
16023      * specified by its character representation.  The precedence follows
16024      * general Perl rules, but it extends this so that ')' and ']' have (low)
16025      * precedence even though they aren't really operators */
16026
16027     switch (my_operator) {
16028         case '!':
16029             return 5;
16030         case '&':
16031             return 4;
16032         case '^':
16033         case '|':
16034         case '+':
16035         case '-':
16036             return 3;
16037         case ')':
16038             return 2;
16039         case ']':
16040             return 1;
16041     }
16042
16043     NOT_REACHED; /* NOTREACHED */
16044     return 0;   /* Silence compiler warning */
16045 }
16046
16047 STATIC regnode_offset
16048 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
16049                     I32 *flagp, U32 depth,
16050                     char * const oregcomp_parse)
16051 {
16052     /* Handle the (?[...]) construct to do set operations */
16053
16054     U8 curchar;                     /* Current character being parsed */
16055     UV start, end;                  /* End points of code point ranges */
16056     SV* final = NULL;               /* The end result inversion list */
16057     SV* result_string;              /* 'final' stringified */
16058     AV* stack;                      /* stack of operators and operands not yet
16059                                        resolved */
16060     AV* fence_stack = NULL;         /* A stack containing the positions in
16061                                        'stack' of where the undealt-with left
16062                                        parens would be if they were actually
16063                                        put there */
16064     /* The 'volatile' is a workaround for an optimiser bug
16065      * in Solaris Studio 12.3. See RT #127455 */
16066     volatile IV fence = 0;          /* Position of where most recent undealt-
16067                                        with left paren in stack is; -1 if none.
16068                                      */
16069     STRLEN len;                     /* Temporary */
16070     regnode_offset node;                  /* Temporary, and final regnode returned by
16071                                        this function */
16072     const bool save_fold = FOLD;    /* Temporary */
16073     char *save_end, *save_parse;    /* Temporaries */
16074     const bool in_locale = LOC;     /* we turn off /l during processing */
16075
16076     GET_RE_DEBUG_FLAGS_DECL;
16077
16078     PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
16079
16080     DEBUG_PARSE("xcls");
16081
16082     if (in_locale) {
16083         set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
16084     }
16085
16086     /* The use of this operator implies /u.  This is required so that the
16087      * compile time values are valid in all runtime cases */
16088     REQUIRE_UNI_RULES(flagp, 0);
16089
16090     ckWARNexperimental(RExC_parse,
16091                        WARN_EXPERIMENTAL__REGEX_SETS,
16092                        "The regex_sets feature is experimental");
16093
16094     /* Everything in this construct is a metacharacter.  Operands begin with
16095      * either a '\' (for an escape sequence), or a '[' for a bracketed
16096      * character class.  Any other character should be an operator, or
16097      * parenthesis for grouping.  Both types of operands are handled by calling
16098      * regclass() to parse them.  It is called with a parameter to indicate to
16099      * return the computed inversion list.  The parsing here is implemented via
16100      * a stack.  Each entry on the stack is a single character representing one
16101      * of the operators; or else a pointer to an operand inversion list. */
16102
16103 #define IS_OPERATOR(a) SvIOK(a)
16104 #define IS_OPERAND(a)  (! IS_OPERATOR(a))
16105
16106     /* The stack is kept in Łukasiewicz order.  (That's pronounced similar
16107      * to luke-a-shave-itch (or -itz), but people who didn't want to bother
16108      * with pronouncing it called it Reverse Polish instead, but now that YOU
16109      * know how to pronounce it you can use the correct term, thus giving due
16110      * credit to the person who invented it, and impressing your geek friends.
16111      * Wikipedia says that the pronounciation of "Ł" has been changing so that
16112      * it is now more like an English initial W (as in wonk) than an L.)
16113      *
16114      * This means that, for example, 'a | b & c' is stored on the stack as
16115      *
16116      * c  [4]
16117      * b  [3]
16118      * &  [2]
16119      * a  [1]
16120      * |  [0]
16121      *
16122      * where the numbers in brackets give the stack [array] element number.
16123      * In this implementation, parentheses are not stored on the stack.
16124      * Instead a '(' creates a "fence" so that the part of the stack below the
16125      * fence is invisible except to the corresponding ')' (this allows us to
16126      * replace testing for parens, by using instead subtraction of the fence
16127      * position).  As new operands are processed they are pushed onto the stack
16128      * (except as noted in the next paragraph).  New operators of higher
16129      * precedence than the current final one are inserted on the stack before
16130      * the lhs operand (so that when the rhs is pushed next, everything will be
16131      * in the correct positions shown above.  When an operator of equal or
16132      * lower precedence is encountered in parsing, all the stacked operations
16133      * of equal or higher precedence are evaluated, leaving the result as the
16134      * top entry on the stack.  This makes higher precedence operations
16135      * evaluate before lower precedence ones, and causes operations of equal
16136      * precedence to left associate.
16137      *
16138      * The only unary operator '!' is immediately pushed onto the stack when
16139      * encountered.  When an operand is encountered, if the top of the stack is
16140      * a '!", the complement is immediately performed, and the '!' popped.  The
16141      * resulting value is treated as a new operand, and the logic in the
16142      * previous paragraph is executed.  Thus in the expression
16143      *      [a] + ! [b]
16144      * the stack looks like
16145      *
16146      * !
16147      * a
16148      * +
16149      *
16150      * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
16151      * becomes
16152      *
16153      * !b
16154      * a
16155      * +
16156      *
16157      * A ')' is treated as an operator with lower precedence than all the
16158      * aforementioned ones, which causes all operations on the stack above the
16159      * corresponding '(' to be evaluated down to a single resultant operand.
16160      * Then the fence for the '(' is removed, and the operand goes through the
16161      * algorithm above, without the fence.
16162      *
16163      * A separate stack is kept of the fence positions, so that the position of
16164      * the latest so-far unbalanced '(' is at the top of it.
16165      *
16166      * The ']' ending the construct is treated as the lowest operator of all,
16167      * so that everything gets evaluated down to a single operand, which is the
16168      * result */
16169
16170     sv_2mortal((SV *)(stack = newAV()));
16171     sv_2mortal((SV *)(fence_stack = newAV()));
16172
16173     while (RExC_parse < RExC_end) {
16174         I32 top_index;              /* Index of top-most element in 'stack' */
16175         SV** top_ptr;               /* Pointer to top 'stack' element */
16176         SV* current = NULL;         /* To contain the current inversion list
16177                                        operand */
16178         SV* only_to_avoid_leaks;
16179
16180         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
16181                                 TRUE /* Force /x */ );
16182         if (RExC_parse >= RExC_end) {   /* Fail */
16183             break;
16184         }
16185
16186         curchar = UCHARAT(RExC_parse);
16187
16188 redo_curchar:
16189
16190 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16191                     /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */
16192         DEBUG_U(dump_regex_sets_structures(pRExC_state,
16193                                            stack, fence, fence_stack));
16194 #endif
16195
16196         top_index = av_tindex_skip_len_mg(stack);
16197
16198         switch (curchar) {
16199             SV** stacked_ptr;       /* Ptr to something already on 'stack' */
16200             char stacked_operator;  /* The topmost operator on the 'stack'. */
16201             SV* lhs;                /* Operand to the left of the operator */
16202             SV* rhs;                /* Operand to the right of the operator */
16203             SV* fence_ptr;          /* Pointer to top element of the fence
16204                                        stack */
16205
16206             case '(':
16207
16208                 if (   RExC_parse < RExC_end - 2
16209                     && UCHARAT(RExC_parse + 1) == '?'
16210                     && UCHARAT(RExC_parse + 2) == '^')
16211                 {
16212                     /* If is a '(?', could be an embedded '(?^flags:(?[...])'.
16213                      * This happens when we have some thing like
16214                      *
16215                      *   my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
16216                      *   ...
16217                      *   qr/(?[ \p{Digit} & $thai_or_lao ])/;
16218                      *
16219                      * Here we would be handling the interpolated
16220                      * '$thai_or_lao'.  We handle this by a recursive call to
16221                      * ourselves which returns the inversion list the
16222                      * interpolated expression evaluates to.  We use the flags
16223                      * from the interpolated pattern. */
16224                     U32 save_flags = RExC_flags;
16225                     const char * save_parse;
16226
16227                     RExC_parse += 2;        /* Skip past the '(?' */
16228                     save_parse = RExC_parse;
16229
16230                     /* Parse the flags for the '(?'.  We already know the first
16231                      * flag to parse is a '^' */
16232                     parse_lparen_question_flags(pRExC_state);
16233
16234                     if (   RExC_parse >= RExC_end - 4
16235                         || UCHARAT(RExC_parse) != ':'
16236                         || UCHARAT(++RExC_parse) != '('
16237                         || UCHARAT(++RExC_parse) != '?'
16238                         || UCHARAT(++RExC_parse) != '[')
16239                     {
16240
16241                         /* In combination with the above, this moves the
16242                          * pointer to the point just after the first erroneous
16243                          * character. */
16244                         if (RExC_parse >= RExC_end - 4) {
16245                             RExC_parse = RExC_end;
16246                         }
16247                         else if (RExC_parse != save_parse) {
16248                             RExC_parse += (UTF)
16249                                           ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
16250                                           : 1;
16251                         }
16252                         vFAIL("Expecting '(?flags:(?[...'");
16253                     }
16254
16255                     /* Recurse, with the meat of the embedded expression */
16256                     RExC_parse++;
16257                     if (! handle_regex_sets(pRExC_state, &current, flagp,
16258                                                     depth+1, oregcomp_parse))
16259                     {
16260                         RETURN_FAIL_ON_RESTART(*flagp, flagp);
16261                     }
16262
16263                     /* Here, 'current' contains the embedded expression's
16264                      * inversion list, and RExC_parse points to the trailing
16265                      * ']'; the next character should be the ')' */
16266                     RExC_parse++;
16267                     if (UCHARAT(RExC_parse) != ')')
16268                         vFAIL("Expecting close paren for nested extended charclass");
16269
16270                     /* Then the ')' matching the original '(' handled by this
16271                      * case: statement */
16272                     RExC_parse++;
16273                     if (UCHARAT(RExC_parse) != ')')
16274                         vFAIL("Expecting close paren for wrapper for nested extended charclass");
16275
16276                     RExC_flags = save_flags;
16277                     goto handle_operand;
16278                 }
16279
16280                 /* A regular '('.  Look behind for illegal syntax */
16281                 if (top_index - fence >= 0) {
16282                     /* If the top entry on the stack is an operator, it had
16283                      * better be a '!', otherwise the entry below the top
16284                      * operand should be an operator */
16285                     if (   ! (top_ptr = av_fetch(stack, top_index, FALSE))
16286                         || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
16287                         || (   IS_OPERAND(*top_ptr)
16288                             && (   top_index - fence < 1
16289                                 || ! (stacked_ptr = av_fetch(stack,
16290                                                              top_index - 1,
16291                                                              FALSE))
16292                                 || ! IS_OPERATOR(*stacked_ptr))))
16293                     {
16294                         RExC_parse++;
16295                         vFAIL("Unexpected '(' with no preceding operator");
16296                     }
16297                 }
16298
16299                 /* Stack the position of this undealt-with left paren */
16300                 av_push(fence_stack, newSViv(fence));
16301                 fence = top_index + 1;
16302                 break;
16303
16304             case '\\':
16305                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16306                  * multi-char folds are allowed.  */
16307                 if (!regclass(pRExC_state, flagp, depth+1,
16308                               TRUE, /* means parse just the next thing */
16309                               FALSE, /* don't allow multi-char folds */
16310                               FALSE, /* don't silence non-portable warnings.  */
16311                               TRUE,  /* strict */
16312                               FALSE, /* Require return to be an ANYOF */
16313                               &current))
16314                 {
16315                     RETURN_FAIL_ON_RESTART(*flagp, flagp);
16316                     goto regclass_failed;
16317                 }
16318
16319                 /* regclass() will return with parsing just the \ sequence,
16320                  * leaving the parse pointer at the next thing to parse */
16321                 RExC_parse--;
16322                 goto handle_operand;
16323
16324             case '[':   /* Is a bracketed character class */
16325             {
16326                 /* See if this is a [:posix:] class. */
16327                 bool is_posix_class = (OOB_NAMEDCLASS
16328                             < handle_possible_posix(pRExC_state,
16329                                                 RExC_parse + 1,
16330                                                 NULL,
16331                                                 NULL,
16332                                                 TRUE /* checking only */));
16333                 /* If it is a posix class, leave the parse pointer at the '['
16334                  * to fool regclass() into thinking it is part of a
16335                  * '[[:posix:]]'. */
16336                 if (! is_posix_class) {
16337                     RExC_parse++;
16338                 }
16339
16340                 /* regclass() can only return RESTART_PARSE and NEED_UTF8 if
16341                  * multi-char folds are allowed.  */
16342                 if (!regclass(pRExC_state, flagp, depth+1,
16343                                 is_posix_class, /* parse the whole char
16344                                                     class only if not a
16345                                                     posix class */
16346                                 FALSE, /* don't allow multi-char folds */
16347                                 TRUE, /* silence non-portable warnings. */
16348                                 TRUE, /* strict */
16349                                 FALSE, /* Require return to be an ANYOF */
16350                                 &current))
16351                 {
16352                     RETURN_FAIL_ON_RESTART(*flagp, flagp);
16353                     goto regclass_failed;
16354                 }
16355
16356                 if (! current) {
16357                     break;
16358                 }
16359
16360                 /* function call leaves parse pointing to the ']', except if we
16361                  * faked it */
16362                 if (is_posix_class) {
16363                     RExC_parse--;
16364                 }
16365
16366                 goto handle_operand;
16367             }
16368
16369             case ']':
16370                 if (top_index >= 1) {
16371                     goto join_operators;
16372                 }
16373
16374                 /* Only a single operand on the stack: are done */
16375                 goto done;
16376
16377             case ')':
16378                 if (av_tindex_skip_len_mg(fence_stack) < 0) {
16379                     if (UCHARAT(RExC_parse - 1) == ']')  {
16380                         break;
16381                     }
16382                     RExC_parse++;
16383                     vFAIL("Unexpected ')'");
16384                 }
16385
16386                 /* If nothing after the fence, is missing an operand */
16387                 if (top_index - fence < 0) {
16388                     RExC_parse++;
16389                     goto bad_syntax;
16390                 }
16391                 /* If at least two things on the stack, treat this as an
16392                   * operator */
16393                 if (top_index - fence >= 1) {
16394                     goto join_operators;
16395                 }
16396
16397                 /* Here only a single thing on the fenced stack, and there is a
16398                  * fence.  Get rid of it */
16399                 fence_ptr = av_pop(fence_stack);
16400                 assert(fence_ptr);
16401                 fence = SvIV(fence_ptr);
16402                 SvREFCNT_dec_NN(fence_ptr);
16403                 fence_ptr = NULL;
16404
16405                 if (fence < 0) {
16406                     fence = 0;
16407                 }
16408
16409                 /* Having gotten rid of the fence, we pop the operand at the
16410                  * stack top and process it as a newly encountered operand */
16411                 current = av_pop(stack);
16412                 if (IS_OPERAND(current)) {
16413                     goto handle_operand;
16414                 }
16415
16416                 RExC_parse++;
16417                 goto bad_syntax;
16418
16419             case '&':
16420             case '|':
16421             case '+':
16422             case '-':
16423             case '^':
16424
16425                 /* These binary operators should have a left operand already
16426                  * parsed */
16427                 if (   top_index - fence < 0
16428                     || top_index - fence == 1
16429                     || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
16430                     || ! IS_OPERAND(*top_ptr))
16431                 {
16432                     goto unexpected_binary;
16433                 }
16434
16435                 /* If only the one operand is on the part of the stack visible
16436                  * to us, we just place this operator in the proper position */
16437                 if (top_index - fence < 2) {
16438
16439                     /* Place the operator before the operand */
16440
16441                     SV* lhs = av_pop(stack);
16442                     av_push(stack, newSVuv(curchar));
16443                     av_push(stack, lhs);
16444                     break;
16445                 }
16446
16447                 /* But if there is something else on the stack, we need to
16448                  * process it before this new operator if and only if the
16449                  * stacked operation has equal or higher precedence than the
16450                  * new one */
16451
16452              join_operators:
16453
16454                 /* The operator on the stack is supposed to be below both its
16455                  * operands */
16456                 if (   ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
16457                     || IS_OPERAND(*stacked_ptr))
16458                 {
16459                     /* But if not, it's legal and indicates we are completely
16460                      * done if and only if we're currently processing a ']',
16461                      * which should be the final thing in the expression */
16462                     if (curchar == ']') {
16463                         goto done;
16464                     }
16465
16466                   unexpected_binary:
16467                     RExC_parse++;
16468                     vFAIL2("Unexpected binary operator '%c' with no "
16469                            "preceding operand", curchar);
16470                 }
16471                 stacked_operator = (char) SvUV(*stacked_ptr);
16472
16473                 if (regex_set_precedence(curchar)
16474                     > regex_set_precedence(stacked_operator))
16475                 {
16476                     /* Here, the new operator has higher precedence than the
16477                      * stacked one.  This means we need to add the new one to
16478                      * the stack to await its rhs operand (and maybe more
16479                      * stuff).  We put it before the lhs operand, leaving
16480                      * untouched the stacked operator and everything below it
16481                      * */
16482                     lhs = av_pop(stack);
16483                     assert(IS_OPERAND(lhs));
16484
16485                     av_push(stack, newSVuv(curchar));
16486                     av_push(stack, lhs);
16487                     break;
16488                 }
16489
16490                 /* Here, the new operator has equal or lower precedence than
16491                  * what's already there.  This means the operation already
16492                  * there should be performed now, before the new one. */
16493
16494                 rhs = av_pop(stack);
16495                 if (! IS_OPERAND(rhs)) {
16496
16497                     /* This can happen when a ! is not followed by an operand,
16498                      * like in /(?[\t &!])/ */
16499                     goto bad_syntax;
16500                 }
16501
16502                 lhs = av_pop(stack);
16503
16504                 if (! IS_OPERAND(lhs)) {
16505
16506                     /* This can happen when there is an empty (), like in
16507                      * /(?[[0]+()+])/ */
16508                     goto bad_syntax;
16509                 }
16510
16511                 switch (stacked_operator) {
16512                     case '&':
16513                         _invlist_intersection(lhs, rhs, &rhs);
16514                         break;
16515
16516                     case '|':
16517                     case '+':
16518                         _invlist_union(lhs, rhs, &rhs);
16519                         break;
16520
16521                     case '-':
16522                         _invlist_subtract(lhs, rhs, &rhs);
16523                         break;
16524
16525                     case '^':   /* The union minus the intersection */
16526                     {
16527                         SV* i = NULL;
16528                         SV* u = NULL;
16529
16530                         _invlist_union(lhs, rhs, &u);
16531                         _invlist_intersection(lhs, rhs, &i);
16532                         _invlist_subtract(u, i, &rhs);
16533                         SvREFCNT_dec_NN(i);
16534                         SvREFCNT_dec_NN(u);
16535                         break;
16536                     }
16537                 }
16538                 SvREFCNT_dec(lhs);
16539
16540                 /* Here, the higher precedence operation has been done, and the
16541                  * result is in 'rhs'.  We overwrite the stacked operator with
16542                  * the result.  Then we redo this code to either push the new
16543                  * operator onto the stack or perform any higher precedence
16544                  * stacked operation */
16545                 only_to_avoid_leaks = av_pop(stack);
16546                 SvREFCNT_dec(only_to_avoid_leaks);
16547                 av_push(stack, rhs);
16548                 goto redo_curchar;
16549
16550             case '!':   /* Highest priority, right associative */
16551
16552                 /* If what's already at the top of the stack is another '!",
16553                  * they just cancel each other out */
16554                 if (   (top_ptr = av_fetch(stack, top_index, FALSE))
16555                     && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
16556                 {
16557                     only_to_avoid_leaks = av_pop(stack);
16558                     SvREFCNT_dec(only_to_avoid_leaks);
16559                 }
16560                 else { /* Otherwise, since it's right associative, just push
16561                           onto the stack */
16562                     av_push(stack, newSVuv(curchar));
16563                 }
16564                 break;
16565
16566             default:
16567                 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16568                 if (RExC_parse >= RExC_end) {
16569                     break;
16570                 }
16571                 vFAIL("Unexpected character");
16572
16573           handle_operand:
16574
16575             /* Here 'current' is the operand.  If something is already on the
16576              * stack, we have to check if it is a !.  But first, the code above
16577              * may have altered the stack in the time since we earlier set
16578              * 'top_index'.  */
16579
16580             top_index = av_tindex_skip_len_mg(stack);
16581             if (top_index - fence >= 0) {
16582                 /* If the top entry on the stack is an operator, it had better
16583                  * be a '!', otherwise the entry below the top operand should
16584                  * be an operator */
16585                 top_ptr = av_fetch(stack, top_index, FALSE);
16586                 assert(top_ptr);
16587                 if (IS_OPERATOR(*top_ptr)) {
16588
16589                     /* The only permissible operator at the top of the stack is
16590                      * '!', which is applied immediately to this operand. */
16591                     curchar = (char) SvUV(*top_ptr);
16592                     if (curchar != '!') {
16593                         SvREFCNT_dec(current);
16594                         vFAIL2("Unexpected binary operator '%c' with no "
16595                                 "preceding operand", curchar);
16596                     }
16597
16598                     _invlist_invert(current);
16599
16600                     only_to_avoid_leaks = av_pop(stack);
16601                     SvREFCNT_dec(only_to_avoid_leaks);
16602
16603                     /* And we redo with the inverted operand.  This allows
16604                      * handling multiple ! in a row */
16605                     goto handle_operand;
16606                 }
16607                           /* Single operand is ok only for the non-binary ')'
16608                            * operator */
16609                 else if ((top_index - fence == 0 && curchar != ')')
16610                          || (top_index - fence > 0
16611                              && (! (stacked_ptr = av_fetch(stack,
16612                                                            top_index - 1,
16613                                                            FALSE))
16614                                  || IS_OPERAND(*stacked_ptr))))
16615                 {
16616                     SvREFCNT_dec(current);
16617                     vFAIL("Operand with no preceding operator");
16618                 }
16619             }
16620
16621             /* Here there was nothing on the stack or the top element was
16622              * another operand.  Just add this new one */
16623             av_push(stack, current);
16624
16625         } /* End of switch on next parse token */
16626
16627         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
16628     } /* End of loop parsing through the construct */
16629
16630     vFAIL("Syntax error in (?[...])");
16631
16632   done:
16633
16634     if (RExC_parse >= RExC_end || RExC_parse[1] != ')') {
16635         if (RExC_parse < RExC_end) {
16636             RExC_parse++;
16637         }
16638
16639         vFAIL("Unexpected ']' with no following ')' in (?[...");
16640     }
16641
16642     if (av_tindex_skip_len_mg(fence_stack) >= 0) {
16643         vFAIL("Unmatched (");
16644     }
16645
16646     if (av_tindex_skip_len_mg(stack) < 0   /* Was empty */
16647         || ((final = av_pop(stack)) == NULL)
16648         || ! IS_OPERAND(final)
16649         || ! is_invlist(final)
16650         || av_tindex_skip_len_mg(stack) >= 0)  /* More left on stack */
16651     {
16652       bad_syntax:
16653         SvREFCNT_dec(final);
16654         vFAIL("Incomplete expression within '(?[ ])'");
16655     }
16656
16657     /* Here, 'final' is the resultant inversion list from evaluating the
16658      * expression.  Return it if so requested */
16659     if (return_invlist) {
16660         *return_invlist = final;
16661         return END;
16662     }
16663
16664     /* Otherwise generate a resultant node, based on 'final'.  regclass() is
16665      * expecting a string of ranges and individual code points */
16666     invlist_iterinit(final);
16667     result_string = newSVpvs("");
16668     while (invlist_iternext(final, &start, &end)) {
16669         if (start == end) {
16670             Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start);
16671         }
16672         else {
16673             Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}",
16674                                                      start,          end);
16675         }
16676     }
16677
16678     /* About to generate an ANYOF (or similar) node from the inversion list we
16679      * have calculated */
16680     save_parse = RExC_parse;
16681     RExC_parse = SvPV(result_string, len);
16682     save_end = RExC_end;
16683     RExC_end = RExC_parse + len;
16684     TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE;
16685
16686     /* We turn off folding around the call, as the class we have constructed
16687      * already has all folding taken into consideration, and we don't want
16688      * regclass() to add to that */
16689     RExC_flags &= ~RXf_PMf_FOLD;
16690     /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char
16691      * folds are allowed.  */
16692     node = regclass(pRExC_state, flagp, depth+1,
16693                     FALSE, /* means parse the whole char class */
16694                     FALSE, /* don't allow multi-char folds */
16695                     TRUE, /* silence non-portable warnings.  The above may very
16696                              well have generated non-portable code points, but
16697                              they're valid on this machine */
16698                     FALSE, /* similarly, no need for strict */
16699
16700                     /* We can optimize into something besides an ANYOF, except
16701                      * under /l, which needs to be ANYOF because of runtime
16702                      * checks for locale sanity, etc */
16703                   ! in_locale,
16704                     NULL
16705                 );
16706
16707     RESTORE_WARNINGS;
16708     RExC_parse = save_parse + 1;
16709     RExC_end = save_end;
16710     SvREFCNT_dec_NN(final);
16711     SvREFCNT_dec_NN(result_string);
16712
16713     if (save_fold) {
16714         RExC_flags |= RXf_PMf_FOLD;
16715     }
16716
16717     if (!node) {
16718         RETURN_FAIL_ON_RESTART(*flagp, flagp);
16719         goto regclass_failed;
16720     }
16721
16722     /* Fix up the node type if we are in locale.  (We have pretended we are
16723      * under /u for the purposes of regclass(), as this construct will only
16724      * work under UTF-8 locales.  But now we change the opcode to be ANYOFL (so
16725      * as to cause any warnings about bad locales to be output in regexec.c),
16726      * and add the flag that indicates to check if not in a UTF-8 locale.  The
16727      * reason we above forbid optimization into something other than an ANYOF
16728      * node is simply to minimize the number of code changes in regexec.c.
16729      * Otherwise we would have to create new EXACTish node types and deal with
16730      * them.  This decision could be revisited should this construct become
16731      * popular.
16732      *
16733      * (One might think we could look at the resulting ANYOF node and suppress
16734      * the flag if everything is above 255, as those would be UTF-8 only,
16735      * but this isn't true, as the components that led to that result could
16736      * have been locale-affected, and just happen to cancel each other out
16737      * under UTF-8 locales.) */
16738     if (in_locale) {
16739         set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
16740
16741         assert(OP(REGNODE_p(node)) == ANYOF);
16742
16743         OP(REGNODE_p(node)) = ANYOFL;
16744         ANYOF_FLAGS(REGNODE_p(node))
16745                 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16746     }
16747
16748     nextchar(pRExC_state);
16749     Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */
16750     return node;
16751
16752   regclass_failed:
16753     FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf,
16754                                                                 (UV) *flagp);
16755 }
16756
16757 #ifdef ENABLE_REGEX_SETS_DEBUGGING
16758
16759 STATIC void
16760 S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state,
16761                              AV * stack, const IV fence, AV * fence_stack)
16762 {   /* Dumps the stacks in handle_regex_sets() */
16763
16764     const SSize_t stack_top = av_tindex_skip_len_mg(stack);
16765     const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack);
16766     SSize_t i;
16767
16768     PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES;
16769
16770     PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse);
16771
16772     if (stack_top < 0) {
16773         PerlIO_printf(Perl_debug_log, "Nothing on stack\n");
16774     }
16775     else {
16776         PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence);
16777         for (i = stack_top; i >= 0; i--) {
16778             SV ** element_ptr = av_fetch(stack, i, FALSE);
16779             if (! element_ptr) {
16780             }
16781
16782             if (IS_OPERATOR(*element_ptr)) {
16783                 PerlIO_printf(Perl_debug_log, "[%d]: %c\n",
16784                                             (int) i, (int) SvIV(*element_ptr));
16785             }
16786             else {
16787                 PerlIO_printf(Perl_debug_log, "[%d] ", (int) i);
16788                 sv_dump(*element_ptr);
16789             }
16790         }
16791     }
16792
16793     if (fence_stack_top < 0) {
16794         PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n");
16795     }
16796     else {
16797         PerlIO_printf(Perl_debug_log, "Fence_stack: \n");
16798         for (i = fence_stack_top; i >= 0; i--) {
16799             SV ** element_ptr = av_fetch(fence_stack, i, FALSE);
16800             if (! element_ptr) {
16801             }
16802
16803             PerlIO_printf(Perl_debug_log, "[%d]: %d\n",
16804                                             (int) i, (int) SvIV(*element_ptr));
16805         }
16806     }
16807 }
16808
16809 #endif
16810
16811 #undef IS_OPERATOR
16812 #undef IS_OPERAND
16813
16814 STATIC void
16815 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
16816 {
16817     /* This adds the Latin1/above-Latin1 folding rules.
16818      *
16819      * This should be called only for a Latin1-range code points, cp, which is
16820      * known to be involved in a simple fold with other code points above
16821      * Latin1.  It would give false results if /aa has been specified.
16822      * Multi-char folds are outside the scope of this, and must be handled
16823      * specially. */
16824
16825     PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
16826
16827     assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
16828
16829     /* The rules that are valid for all Unicode versions are hard-coded in */
16830     switch (cp) {
16831         case 'k':
16832         case 'K':
16833           *invlist =
16834              add_cp_to_invlist(*invlist, KELVIN_SIGN);
16835             break;
16836         case 's':
16837         case 'S':
16838           *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
16839             break;
16840         case MICRO_SIGN:
16841           *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
16842           *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
16843             break;
16844         case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
16845         case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
16846           *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
16847             break;
16848         case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
16849           *invlist = add_cp_to_invlist(*invlist,
16850                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
16851             break;
16852
16853         default:    /* Other code points are checked against the data for the
16854                        current Unicode version */
16855           {
16856             Size_t folds_count;
16857             unsigned int first_fold;
16858             const unsigned int * remaining_folds;
16859             UV folded_cp;
16860
16861             if (isASCII(cp)) {
16862                 folded_cp = toFOLD(cp);
16863             }
16864             else {
16865                 U8 dummy_fold[UTF8_MAXBYTES_CASE+1];
16866                 Size_t dummy_len;
16867                 folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0);
16868             }
16869
16870             if (folded_cp > 255) {
16871                 *invlist = add_cp_to_invlist(*invlist, folded_cp);
16872             }
16873
16874             folds_count = _inverse_folds(folded_cp, &first_fold,
16875                                                     &remaining_folds);
16876             if (folds_count == 0) {
16877
16878                 /* Use deprecated warning to increase the chances of this being
16879                  * output */
16880                 ckWARN2reg_d(RExC_parse,
16881                         "Perl folding rules are not up-to-date for 0x%02X;"
16882                         " please use the perlbug utility to report;", cp);
16883             }
16884             else {
16885                 unsigned int i;
16886
16887                 if (first_fold > 255) {
16888                     *invlist = add_cp_to_invlist(*invlist, first_fold);
16889                 }
16890                 for (i = 0; i < folds_count - 1; i++) {
16891                     if (remaining_folds[i] > 255) {
16892                         *invlist = add_cp_to_invlist(*invlist,
16893                                                     remaining_folds[i]);
16894                     }
16895                 }
16896             }
16897             break;
16898          }
16899     }
16900 }
16901
16902 STATIC void
16903 S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings)
16904 {
16905     /* Output the elements of the array given by '*posix_warnings' as REGEXP
16906      * warnings. */
16907
16908     SV * msg;
16909     const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP));
16910
16911     PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS;
16912
16913     if (! TO_OUTPUT_WARNINGS(RExC_parse)) {
16914         return;
16915     }
16916
16917     while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
16918         if (first_is_fatal) {           /* Avoid leaking this */
16919             av_undef(posix_warnings);   /* This isn't necessary if the
16920                                             array is mortal, but is a
16921                                             fail-safe */
16922             (void) sv_2mortal(msg);
16923             PREPARE_TO_DIE;
16924         }
16925         Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
16926         SvREFCNT_dec_NN(msg);
16927     }
16928
16929     UPDATE_WARNINGS_LOC(RExC_parse);
16930 }
16931
16932 PERL_STATIC_INLINE Size_t
16933 S_find_first_differing_byte_pos(const U8 * s1, const U8 * s2, const Size_t max)
16934 {
16935     const U8 * const start = s1;
16936     const U8 * const send = start + max;
16937
16938     PERL_ARGS_ASSERT_FIND_FIRST_DIFFERING_BYTE_POS;
16939
16940     while (s1 < send && *s1  == *s2) {
16941         s1++; s2++;
16942     }
16943
16944     return s1 - start;
16945 }
16946
16947
16948 STATIC AV *
16949 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
16950 {
16951     /* This adds the string scalar <multi_string> to the array
16952      * <multi_char_matches>.  <multi_string> is known to have exactly
16953      * <cp_count> code points in it.  This is used when constructing a
16954      * bracketed character class and we find something that needs to match more
16955      * than a single character.
16956      *
16957      * <multi_char_matches> is actually an array of arrays.  Each top-level
16958      * element is an array that contains all the strings known so far that are
16959      * the same length.  And that length (in number of code points) is the same
16960      * as the index of the top-level array.  Hence, the [2] element is an
16961      * array, each element thereof is a string containing TWO code points;
16962      * while element [3] is for strings of THREE characters, and so on.  Since
16963      * this is for multi-char strings there can never be a [0] nor [1] element.
16964      *
16965      * When we rewrite the character class below, we will do so such that the
16966      * longest strings are written first, so that it prefers the longest
16967      * matching strings first.  This is done even if it turns out that any
16968      * quantifier is non-greedy, out of this programmer's (khw) laziness.  Tom
16969      * Christiansen has agreed that this is ok.  This makes the test for the
16970      * ligature 'ffi' come before the test for 'ff', for example */
16971
16972     AV* this_array;
16973     AV** this_array_ptr;
16974
16975     PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
16976
16977     if (! multi_char_matches) {
16978         multi_char_matches = newAV();
16979     }
16980
16981     if (av_exists(multi_char_matches, cp_count)) {
16982         this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
16983         this_array = *this_array_ptr;
16984     }
16985     else {
16986         this_array = newAV();
16987         av_store(multi_char_matches, cp_count,
16988                  (SV*) this_array);
16989     }
16990     av_push(this_array, multi_string);
16991
16992     return multi_char_matches;
16993 }
16994
16995 /* The names of properties whose definitions are not known at compile time are
16996  * stored in this SV, after a constant heading.  So if the length has been
16997  * changed since initialization, then there is a run-time definition. */
16998 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION                            \
16999                                         (SvCUR(listsv) != initial_listsv_len)
17000
17001 /* There is a restricted set of white space characters that are legal when
17002  * ignoring white space in a bracketed character class.  This generates the
17003  * code to skip them.
17004  *
17005  * There is a line below that uses the same white space criteria but is outside
17006  * this macro.  Both here and there must use the same definition */
17007 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p)                          \
17008     STMT_START {                                                        \
17009         if (do_skip) {                                                  \
17010             while (isBLANK_A(UCHARAT(p)))                               \
17011             {                                                           \
17012                 p++;                                                    \
17013             }                                                           \
17014         }                                                               \
17015     } STMT_END
17016
17017 STATIC regnode_offset
17018 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
17019                  const bool stop_at_1,  /* Just parse the next thing, don't
17020                                            look for a full character class */
17021                  bool allow_mutiple_chars,
17022                  const bool silence_non_portable,   /* Don't output warnings
17023                                                        about too large
17024                                                        characters */
17025                  const bool strict,
17026                  bool optimizable,                  /* ? Allow a non-ANYOF return
17027                                                        node */
17028                  SV** ret_invlist  /* Return an inversion list, not a node */
17029           )
17030 {
17031     /* parse a bracketed class specification.  Most of these will produce an
17032      * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
17033      * EXACTFish node; [[:ascii:]], a POSIXA node; etc.  It is more complex
17034      * under /i with multi-character folds: it will be rewritten following the
17035      * paradigm of this example, where the <multi-fold>s are characters which
17036      * fold to multiple character sequences:
17037      *      /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
17038      * gets effectively rewritten as:
17039      *      /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
17040      * reg() gets called (recursively) on the rewritten version, and this
17041      * function will return what it constructs.  (Actually the <multi-fold>s
17042      * aren't physically removed from the [abcdefghi], it's just that they are
17043      * ignored in the recursion by means of a flag:
17044      * <RExC_in_multi_char_class>.)
17045      *
17046      * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
17047      * characters, with the corresponding bit set if that character is in the
17048      * list.  For characters above this, an inversion list is used.  There
17049      * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
17050      * determinable at compile time
17051      *
17052      * On success, returns the offset at which any next node should be placed
17053      * into the regex engine program being compiled.
17054      *
17055      * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs
17056      * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to
17057      * UTF-8
17058      */
17059
17060     dVAR;
17061     UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
17062     IV range = 0;
17063     UV value = OOB_UNICODE, save_value = OOB_UNICODE;
17064     regnode_offset ret = -1;    /* Initialized to an illegal value */
17065     STRLEN numlen;
17066     int namedclass = OOB_NAMEDCLASS;
17067     char *rangebegin = NULL;
17068     SV *listsv = NULL;      /* List of \p{user-defined} whose definitions
17069                                aren't available at the time this was called */
17070     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
17071                                       than just initialized.  */
17072     SV* properties = NULL;    /* Code points that match \p{} \P{} */
17073     SV* posixes = NULL;     /* Code points that match classes like [:word:],
17074                                extended beyond the Latin1 range.  These have to
17075                                be kept separate from other code points for much
17076                                of this function because their handling  is
17077                                different under /i, and for most classes under
17078                                /d as well */
17079     SV* nposixes = NULL;    /* Similarly for [:^word:].  These are kept
17080                                separate for a while from the non-complemented
17081                                versions because of complications with /d
17082                                matching */
17083     SV* simple_posixes = NULL; /* But under some conditions, the classes can be
17084                                   treated more simply than the general case,
17085                                   leading to less compilation and execution
17086                                   work */
17087     UV element_count = 0;   /* Number of distinct elements in the class.
17088                                Optimizations may be possible if this is tiny */
17089     AV * multi_char_matches = NULL; /* Code points that fold to more than one
17090                                        character; used under /i */
17091     UV n;
17092     char * stop_ptr = RExC_end;    /* where to stop parsing */
17093
17094     /* ignore unescaped whitespace? */
17095     const bool skip_white = cBOOL(   ret_invlist
17096                                   || (RExC_flags & RXf_PMf_EXTENDED_MORE));
17097
17098     /* inversion list of code points this node matches only when the target
17099      * string is in UTF-8.  These are all non-ASCII, < 256.  (Because is under
17100      * /d) */
17101     SV* upper_latin1_only_utf8_matches = NULL;
17102
17103     /* Inversion list of code points this node matches regardless of things
17104      * like locale, folding, utf8ness of the target string */
17105     SV* cp_list = NULL;
17106
17107     /* Like cp_list, but code points on this list need to be checked for things
17108      * that fold to/from them under /i */
17109     SV* cp_foldable_list = NULL;
17110
17111     /* Like cp_list, but code points on this list are valid only when the
17112      * runtime locale is UTF-8 */
17113     SV* only_utf8_locale_list = NULL;
17114
17115     /* In a range, if one of the endpoints is non-character-set portable,
17116      * meaning that it hard-codes a code point that may mean a different
17117      * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
17118      * mnemonic '\t' which each mean the same character no matter which
17119      * character set the platform is on. */
17120     unsigned int non_portable_endpoint = 0;
17121
17122     /* Is the range unicode? which means on a platform that isn't 1-1 native
17123      * to Unicode (i.e. non-ASCII), each code point in it should be considered
17124      * to be a Unicode value.  */
17125     bool unicode_range = FALSE;
17126     bool invert = FALSE;    /* Is this class to be complemented */
17127
17128     bool warn_super = ALWAYS_WARN_SUPER;
17129
17130     const char * orig_parse = RExC_parse;
17131
17132     /* This variable is used to mark where the end in the input is of something
17133      * that looks like a POSIX construct but isn't.  During the parse, when
17134      * something looks like it could be such a construct is encountered, it is
17135      * checked for being one, but not if we've already checked this area of the
17136      * input.  Only after this position is reached do we check again */
17137     char *not_posix_region_end = RExC_parse - 1;
17138
17139     AV* posix_warnings = NULL;
17140     const bool do_posix_warnings = ckWARN(WARN_REGEXP);
17141     U8 op = END;    /* The returned node-type, initialized to an impossible
17142                        one.  */
17143     U8 anyof_flags = 0;   /* flag bits if the node is an ANYOF-type */
17144     U32 posixl = 0;       /* bit field of posix classes matched under /l */
17145
17146
17147 /* Flags as to what things aren't knowable until runtime.  (Note that these are
17148  * mutually exclusive.) */
17149 #define HAS_USER_DEFINED_PROPERTY 0x01   /* /u any user-defined properties that
17150                                             haven't been defined as of yet */
17151 #define HAS_D_RUNTIME_DEPENDENCY  0x02   /* /d if the target being matched is
17152                                             UTF-8 or not */
17153 #define HAS_L_RUNTIME_DEPENDENCY   0x04 /* /l what the posix classes match and
17154                                             what gets folded */
17155     U32 has_runtime_dependency = 0;     /* OR of the above flags */
17156
17157     GET_RE_DEBUG_FLAGS_DECL;
17158
17159     PERL_ARGS_ASSERT_REGCLASS;
17160 #ifndef DEBUGGING
17161     PERL_UNUSED_ARG(depth);
17162 #endif
17163
17164
17165     /* If wants an inversion list returned, we can't optimize to something
17166      * else. */
17167     if (ret_invlist) {
17168         optimizable = FALSE;
17169     }
17170
17171     DEBUG_PARSE("clas");
17172
17173 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */      \
17174     || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0          \
17175                                    && UNICODE_DOT_DOT_VERSION == 0)
17176     allow_mutiple_chars = FALSE;
17177 #endif
17178
17179     /* We include the /i status at the beginning of this so that we can
17180      * know it at runtime */
17181     listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD)));
17182     initial_listsv_len = SvCUR(listsv);
17183     SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated.  */
17184
17185     SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17186
17187     assert(RExC_parse <= RExC_end);
17188
17189     if (UCHARAT(RExC_parse) == '^') {   /* Complement the class */
17190         RExC_parse++;
17191         invert = TRUE;
17192         allow_mutiple_chars = FALSE;
17193         MARK_NAUGHTY(1);
17194         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17195     }
17196
17197     /* Check that they didn't say [:posix:] instead of [[:posix:]] */
17198     if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
17199         int maybe_class = handle_possible_posix(pRExC_state,
17200                                                 RExC_parse,
17201                                                 &not_posix_region_end,
17202                                                 NULL,
17203                                                 TRUE /* checking only */);
17204         if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) {
17205             ckWARN4reg(not_posix_region_end,
17206                     "POSIX syntax [%c %c] belongs inside character classes%s",
17207                     *RExC_parse, *RExC_parse,
17208                     (maybe_class == OOB_NAMEDCLASS)
17209                     ? ((POSIXCC_NOTYET(*RExC_parse))
17210                         ? " (but this one isn't implemented)"
17211                         : " (but this one isn't fully valid)")
17212                     : ""
17213                     );
17214         }
17215     }
17216
17217     /* If the caller wants us to just parse a single element, accomplish this
17218      * by faking the loop ending condition */
17219     if (stop_at_1 && RExC_end > RExC_parse) {
17220         stop_ptr = RExC_parse + 1;
17221     }
17222
17223     /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
17224     if (UCHARAT(RExC_parse) == ']')
17225         goto charclassloop;
17226
17227     while (1) {
17228
17229         if (   posix_warnings
17230             && av_tindex_skip_len_mg(posix_warnings) >= 0
17231             && RExC_parse > not_posix_region_end)
17232         {
17233             /* Warnings about posix class issues are considered tentative until
17234              * we are far enough along in the parse that we can no longer
17235              * change our mind, at which point we output them.  This is done
17236              * each time through the loop so that a later class won't zap them
17237              * before they have been dealt with. */
17238             output_posix_warnings(pRExC_state, posix_warnings);
17239         }
17240
17241         if  (RExC_parse >= stop_ptr) {
17242             break;
17243         }
17244
17245         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17246
17247         if  (UCHARAT(RExC_parse) == ']') {
17248             break;
17249         }
17250
17251       charclassloop:
17252
17253         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
17254         save_value = value;
17255         save_prevvalue = prevvalue;
17256
17257         if (!range) {
17258             rangebegin = RExC_parse;
17259             element_count++;
17260             non_portable_endpoint = 0;
17261         }
17262         if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
17263             value = utf8n_to_uvchr((U8*)RExC_parse,
17264                                    RExC_end - RExC_parse,
17265                                    &numlen, UTF8_ALLOW_DEFAULT);
17266             RExC_parse += numlen;
17267         }
17268         else
17269             value = UCHARAT(RExC_parse++);
17270
17271         if (value == '[') {
17272             char * posix_class_end;
17273             namedclass = handle_possible_posix(pRExC_state,
17274                                                RExC_parse,
17275                                                &posix_class_end,
17276                                                do_posix_warnings ? &posix_warnings : NULL,
17277                                                FALSE    /* die if error */);
17278             if (namedclass > OOB_NAMEDCLASS) {
17279
17280                 /* If there was an earlier attempt to parse this particular
17281                  * posix class, and it failed, it was a false alarm, as this
17282                  * successful one proves */
17283                 if (   posix_warnings
17284                     && av_tindex_skip_len_mg(posix_warnings) >= 0
17285                     && not_posix_region_end >= RExC_parse
17286                     && not_posix_region_end <= posix_class_end)
17287                 {
17288                     av_undef(posix_warnings);
17289                 }
17290
17291                 RExC_parse = posix_class_end;
17292             }
17293             else if (namedclass == OOB_NAMEDCLASS) {
17294                 not_posix_region_end = posix_class_end;
17295             }
17296             else {
17297                 namedclass = OOB_NAMEDCLASS;
17298             }
17299         }
17300         else if (   RExC_parse - 1 > not_posix_region_end
17301                  && MAYBE_POSIXCC(value))
17302         {
17303             (void) handle_possible_posix(
17304                         pRExC_state,
17305                         RExC_parse - 1,  /* -1 because parse has already been
17306                                             advanced */
17307                         &not_posix_region_end,
17308                         do_posix_warnings ? &posix_warnings : NULL,
17309                         TRUE /* checking only */);
17310         }
17311         else if (  strict && ! skip_white
17312                  && (   _generic_isCC(value, _CC_VERTSPACE)
17313                      || is_VERTWS_cp_high(value)))
17314         {
17315             vFAIL("Literal vertical space in [] is illegal except under /x");
17316         }
17317         else if (value == '\\') {
17318             /* Is a backslash; get the code point of the char after it */
17319
17320             if (RExC_parse >= RExC_end) {
17321                 vFAIL("Unmatched [");
17322             }
17323
17324             if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
17325                 value = utf8n_to_uvchr((U8*)RExC_parse,
17326                                    RExC_end - RExC_parse,
17327                                    &numlen, UTF8_ALLOW_DEFAULT);
17328                 RExC_parse += numlen;
17329             }
17330             else
17331                 value = UCHARAT(RExC_parse++);
17332
17333             /* Some compilers cannot handle switching on 64-bit integer
17334              * values, therefore value cannot be an UV.  Yes, this will
17335              * be a problem later if we want switch on Unicode.
17336              * A similar issue a little bit later when switching on
17337              * namedclass. --jhi */
17338
17339             /* If the \ is escaping white space when white space is being
17340              * skipped, it means that that white space is wanted literally, and
17341              * is already in 'value'.  Otherwise, need to translate the escape
17342              * into what it signifies. */
17343             if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
17344
17345             case 'w':   namedclass = ANYOF_WORDCHAR;    break;
17346             case 'W':   namedclass = ANYOF_NWORDCHAR;   break;
17347             case 's':   namedclass = ANYOF_SPACE;       break;
17348             case 'S':   namedclass = ANYOF_NSPACE;      break;
17349             case 'd':   namedclass = ANYOF_DIGIT;       break;
17350             case 'D':   namedclass = ANYOF_NDIGIT;      break;
17351             case 'v':   namedclass = ANYOF_VERTWS;      break;
17352             case 'V':   namedclass = ANYOF_NVERTWS;     break;
17353             case 'h':   namedclass = ANYOF_HORIZWS;     break;
17354             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
17355             case 'N':  /* Handle \N{NAME} in class */
17356                 {
17357                     const char * const backslash_N_beg = RExC_parse - 2;
17358                     int cp_count;
17359
17360                     if (! grok_bslash_N(pRExC_state,
17361                                         NULL,      /* No regnode */
17362                                         &value,    /* Yes single value */
17363                                         &cp_count, /* Multiple code pt count */
17364                                         flagp,
17365                                         strict,
17366                                         depth)
17367                     ) {
17368
17369                         if (*flagp & NEED_UTF8)
17370                             FAIL("panic: grok_bslash_N set NEED_UTF8");
17371
17372                         RETURN_FAIL_ON_RESTART_FLAGP(flagp);
17373
17374                         if (cp_count < 0) {
17375                             vFAIL("\\N in a character class must be a named character: \\N{...}");
17376                         }
17377                         else if (cp_count == 0) {
17378                             ckWARNreg(RExC_parse,
17379                               "Ignoring zero length \\N{} in character class");
17380                         }
17381                         else { /* cp_count > 1 */
17382                             assert(cp_count > 1);
17383                             if (! RExC_in_multi_char_class) {
17384                                 if ( ! allow_mutiple_chars
17385                                     || invert
17386                                     || range
17387                                     || *RExC_parse == '-')
17388                                 {
17389                                     if (strict) {
17390                                         RExC_parse--;
17391                                         vFAIL("\\N{} here is restricted to one character");
17392                                     }
17393                                     ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
17394                                     break; /* <value> contains the first code
17395                                               point. Drop out of the switch to
17396                                               process it */
17397                                 }
17398                                 else {
17399                                     SV * multi_char_N = newSVpvn(backslash_N_beg,
17400                                                  RExC_parse - backslash_N_beg);
17401                                     multi_char_matches
17402                                         = add_multi_match(multi_char_matches,
17403                                                           multi_char_N,
17404                                                           cp_count);
17405                                 }
17406                             }
17407                         } /* End of cp_count != 1 */
17408
17409                         /* This element should not be processed further in this
17410                          * class */
17411                         element_count--;
17412                         value = save_value;
17413                         prevvalue = save_prevvalue;
17414                         continue;   /* Back to top of loop to get next char */
17415                     }
17416
17417                     /* Here, is a single code point, and <value> contains it */
17418                     unicode_range = TRUE;   /* \N{} are Unicode */
17419                 }
17420                 break;
17421             case 'p':
17422             case 'P':
17423                 {
17424                 char *e;
17425
17426                 /* \p means they want Unicode semantics */
17427                 REQUIRE_UNI_RULES(flagp, 0);
17428
17429                 if (RExC_parse >= RExC_end)
17430                     vFAIL2("Empty \\%c", (U8)value);
17431                 if (*RExC_parse == '{') {
17432                     const U8 c = (U8)value;
17433                     e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse);
17434                     if (!e) {
17435                         RExC_parse++;
17436                         vFAIL2("Missing right brace on \\%c{}", c);
17437                     }
17438
17439                     RExC_parse++;
17440
17441                     /* White space is allowed adjacent to the braces and after
17442                      * any '^', even when not under /x */
17443                     while (isSPACE(*RExC_parse)) {
17444                          RExC_parse++;
17445                     }
17446
17447                     if (UCHARAT(RExC_parse) == '^') {
17448
17449                         /* toggle.  (The rhs xor gets the single bit that
17450                          * differs between P and p; the other xor inverts just
17451                          * that bit) */
17452                         value ^= 'P' ^ 'p';
17453
17454                         RExC_parse++;
17455                         while (isSPACE(*RExC_parse)) {
17456                             RExC_parse++;
17457                         }
17458                     }
17459
17460                     if (e == RExC_parse)
17461                         vFAIL2("Empty \\%c{}", c);
17462
17463                     n = e - RExC_parse;
17464                     while (isSPACE(*(RExC_parse + n - 1)))
17465                         n--;
17466
17467                 }   /* The \p isn't immediately followed by a '{' */
17468                 else if (! isALPHA(*RExC_parse)) {
17469                     RExC_parse += (UTF)
17470                                   ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17471                                   : 1;
17472                     vFAIL2("Character following \\%c must be '{' or a "
17473                            "single-character Unicode property name",
17474                            (U8) value);
17475                 }
17476                 else {
17477                     e = RExC_parse;
17478                     n = 1;
17479                 }
17480                 {
17481                     char* name = RExC_parse;
17482
17483                     /* Any message returned about expanding the definition */
17484                     SV* msg = newSVpvs_flags("", SVs_TEMP);
17485
17486                     /* If set TRUE, the property is user-defined as opposed to
17487                      * official Unicode */
17488                     bool user_defined = FALSE;
17489
17490                     SV * prop_definition = parse_uniprop_string(
17491                                             name, n, UTF, FOLD,
17492                                             FALSE, /* This is compile-time */
17493
17494                                             /* We can't defer this defn when
17495                                              * the full result is required in
17496                                              * this call */
17497                                             ! cBOOL(ret_invlist),
17498
17499                                             &user_defined,
17500                                             msg,
17501                                             0 /* Base level */
17502                                            );
17503                     if (SvCUR(msg)) {   /* Assumes any error causes a msg */
17504                         assert(prop_definition == NULL);
17505                         RExC_parse = e + 1;
17506                         if (SvUTF8(msg)) {  /* msg being UTF-8 makes the whole
17507                                                thing so, or else the display is
17508                                                mojibake */
17509                             RExC_utf8 = TRUE;
17510                         }
17511                         /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */
17512                         vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg),
17513                                     SvCUR(msg), SvPVX(msg)));
17514                     }
17515
17516                     if (! is_invlist(prop_definition)) {
17517
17518                         /* Here, the definition isn't known, so we have gotten
17519                          * returned a string that will be evaluated if and when
17520                          * encountered at runtime.  We add it to the list of
17521                          * such properties, along with whether it should be
17522                          * complemented or not */
17523                         if (value == 'P') {
17524                             sv_catpvs(listsv, "!");
17525                         }
17526                         else {
17527                             sv_catpvs(listsv, "+");
17528                         }
17529                         sv_catsv(listsv, prop_definition);
17530
17531                         has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY;
17532
17533                         /* We don't know yet what this matches, so have to flag
17534                          * it */
17535                         anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
17536                     }
17537                     else {
17538                         assert (prop_definition && is_invlist(prop_definition));
17539
17540                         /* Here we do have the complete property definition
17541                          *
17542                          * Temporary workaround for [perl #133136].  For this
17543                          * precise input that is in the .t that is failing,
17544                          * load utf8.pm, which is what the test wants, so that
17545                          * that .t passes */
17546                         if (     memEQs(RExC_start, e + 1 - RExC_start,
17547                                         "foo\\p{Alnum}")
17548                             && ! hv_common(GvHVn(PL_incgv),
17549                                            NULL,
17550                                            "utf8.pm", sizeof("utf8.pm") - 1,
17551                                            0, HV_FETCH_ISEXISTS, NULL, 0))
17552                         {
17553                             require_pv("utf8.pm");
17554                         }
17555
17556                         if (! user_defined &&
17557                             /* We warn on matching an above-Unicode code point
17558                              * if the match would return true, except don't
17559                              * warn for \p{All}, which has exactly one element
17560                              * = 0 */
17561                             (_invlist_contains_cp(prop_definition, 0x110000)
17562                                 && (! (_invlist_len(prop_definition) == 1
17563                                        && *invlist_array(prop_definition) == 0))))
17564                         {
17565                             warn_super = TRUE;
17566                         }
17567
17568                         /* Invert if asking for the complement */
17569                         if (value == 'P') {
17570                             _invlist_union_complement_2nd(properties,
17571                                                           prop_definition,
17572                                                           &properties);
17573                         }
17574                         else {
17575                             _invlist_union(properties, prop_definition, &properties);
17576                         }
17577                     }
17578                 }
17579
17580                 RExC_parse = e + 1;
17581                 namedclass = ANYOF_UNIPROP;  /* no official name, but it's
17582                                                 named */
17583                 }
17584                 break;
17585             case 'n':   value = '\n';                   break;
17586             case 'r':   value = '\r';                   break;
17587             case 't':   value = '\t';                   break;
17588             case 'f':   value = '\f';                   break;
17589             case 'b':   value = '\b';                   break;
17590             case 'e':   value = ESC_NATIVE;             break;
17591             case 'a':   value = '\a';                   break;
17592             case 'o':
17593                 RExC_parse--;   /* function expects to be pointed at the 'o' */
17594                 {
17595                     const char* error_msg;
17596                     bool valid = grok_bslash_o(&RExC_parse,
17597                                                RExC_end,
17598                                                &value,
17599                                                &error_msg,
17600                                                TO_OUTPUT_WARNINGS(RExC_parse),
17601                                                strict,
17602                                                silence_non_portable,
17603                                                UTF);
17604                     if (! valid) {
17605                         vFAIL(error_msg);
17606                     }
17607                     UPDATE_WARNINGS_LOC(RExC_parse - 1);
17608                 }
17609                 non_portable_endpoint++;
17610                 break;
17611             case 'x':
17612                 RExC_parse--;   /* function expects to be pointed at the 'x' */
17613                 {
17614                     const char* error_msg;
17615                     bool valid = grok_bslash_x(&RExC_parse,
17616                                                RExC_end,
17617                                                &value,
17618                                                &error_msg,
17619                                                TO_OUTPUT_WARNINGS(RExC_parse),
17620                                                strict,
17621                                                silence_non_portable,
17622                                                UTF);
17623                     if (! valid) {
17624                         vFAIL(error_msg);
17625                     }
17626                     UPDATE_WARNINGS_LOC(RExC_parse - 1);
17627                 }
17628                 non_portable_endpoint++;
17629                 break;
17630             case 'c':
17631                 value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse));
17632                 UPDATE_WARNINGS_LOC(RExC_parse);
17633                 RExC_parse++;
17634                 non_portable_endpoint++;
17635                 break;
17636             case '0': case '1': case '2': case '3': case '4':
17637             case '5': case '6': case '7':
17638                 {
17639                     /* Take 1-3 octal digits */
17640                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
17641                     numlen = (strict) ? 4 : 3;
17642                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
17643                     RExC_parse += numlen;
17644                     if (numlen != 3) {
17645                         if (strict) {
17646                             RExC_parse += (UTF)
17647                                           ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
17648                                           : 1;
17649                             vFAIL("Need exactly 3 octal digits");
17650                         }
17651                         else if (   numlen < 3 /* like \08, \178 */
17652                                  && RExC_parse < RExC_end
17653                                  && isDIGIT(*RExC_parse)
17654                                  && ckWARN(WARN_REGEXP))
17655                         {
17656                             reg_warn_non_literal_string(
17657                                  RExC_parse + 1,
17658                                  form_short_octal_warning(RExC_parse, numlen));
17659                         }
17660                     }
17661                     non_portable_endpoint++;
17662                     break;
17663                 }
17664             default:
17665                 /* Allow \_ to not give an error */
17666                 if (isWORDCHAR(value) && value != '_') {
17667                     if (strict) {
17668                         vFAIL2("Unrecognized escape \\%c in character class",
17669                                (int)value);
17670                     }
17671                     else {
17672                         ckWARN2reg(RExC_parse,
17673                             "Unrecognized escape \\%c in character class passed through",
17674                             (int)value);
17675                     }
17676                 }
17677                 break;
17678             }   /* End of switch on char following backslash */
17679         } /* end of handling backslash escape sequences */
17680
17681         /* Here, we have the current token in 'value' */
17682
17683         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
17684             U8 classnum;
17685
17686             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
17687              * literal, as is the character that began the false range, i.e.
17688              * the 'a' in the examples */
17689             if (range) {
17690                 const int w = (RExC_parse >= rangebegin)
17691                                 ? RExC_parse - rangebegin
17692                                 : 0;
17693                 if (strict) {
17694                     vFAIL2utf8f(
17695                         "False [] range \"%" UTF8f "\"",
17696                         UTF8fARG(UTF, w, rangebegin));
17697                 }
17698                 else {
17699                     ckWARN2reg(RExC_parse,
17700                         "False [] range \"%" UTF8f "\"",
17701                         UTF8fARG(UTF, w, rangebegin));
17702                     cp_list = add_cp_to_invlist(cp_list, '-');
17703                     cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
17704                                                             prevvalue);
17705                 }
17706
17707                 range = 0; /* this was not a true range */
17708                 element_count += 2; /* So counts for three values */
17709             }
17710
17711             classnum = namedclass_to_classnum(namedclass);
17712
17713             if (LOC && namedclass < ANYOF_POSIXL_MAX
17714 #ifndef HAS_ISASCII
17715                 && classnum != _CC_ASCII
17716 #endif
17717             ) {
17718                 SV* scratch_list = NULL;
17719
17720                 /* What the Posix classes (like \w, [:space:]) match isn't
17721                  * generally knowable under locale until actual match time.  A
17722                  * special node is used for these which has extra space for a
17723                  * bitmap, with a bit reserved for each named class that is to
17724                  * be matched against.  (This isn't needed for \p{} and
17725                  * pseudo-classes, as they are not affected by locale, and
17726                  * hence are dealt with separately.)  However, if a named class
17727                  * and its complement are both present, then it matches
17728                  * everything, and there is no runtime dependency.  Odd numbers
17729                  * are the complements of the next lower number, so xor works.
17730                  * (Note that something like [\w\D] should match everything,
17731                  * because \d should be a proper subset of \w.  But rather than
17732                  * trust that the locale is well behaved, we leave this to
17733                  * runtime to sort out) */
17734                 if (POSIXL_TEST(posixl, namedclass ^ 1)) {
17735                     cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX);
17736                     POSIXL_ZERO(posixl);
17737                     has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY;
17738                     anyof_flags &= ~ANYOF_MATCHES_POSIXL;
17739                     continue;   /* We could ignore the rest of the class, but
17740                                    best to parse it for any errors */
17741                 }
17742                 else { /* Here, isn't the complement of any already parsed
17743                           class */
17744                     POSIXL_SET(posixl, namedclass);
17745                     has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
17746                     anyof_flags |= ANYOF_MATCHES_POSIXL;
17747
17748                     /* The above-Latin1 characters are not subject to locale
17749                      * rules.  Just add them to the unconditionally-matched
17750                      * list */
17751
17752                     /* Get the list of the above-Latin1 code points this
17753                      * matches */
17754                     _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
17755                                             PL_XPosix_ptrs[classnum],
17756
17757                                             /* Odd numbers are complements,
17758                                              * like NDIGIT, NASCII, ... */
17759                                             namedclass % 2 != 0,
17760                                             &scratch_list);
17761                     /* Checking if 'cp_list' is NULL first saves an extra
17762                      * clone.  Its reference count will be decremented at the
17763                      * next union, etc, or if this is the only instance, at the
17764                      * end of the routine */
17765                     if (! cp_list) {
17766                         cp_list = scratch_list;
17767                     }
17768                     else {
17769                         _invlist_union(cp_list, scratch_list, &cp_list);
17770                         SvREFCNT_dec_NN(scratch_list);
17771                     }
17772                     continue;   /* Go get next character */
17773                 }
17774             }
17775             else {
17776
17777                 /* Here, is not /l, or is a POSIX class for which /l doesn't
17778                  * matter (or is a Unicode property, which is skipped here). */
17779                 if (namedclass >= ANYOF_POSIXL_MAX) {  /* If a special class */
17780                     if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
17781
17782                         /* Here, should be \h, \H, \v, or \V.  None of /d, /i
17783                          * nor /l make a difference in what these match,
17784                          * therefore we just add what they match to cp_list. */
17785                         if (classnum != _CC_VERTSPACE) {
17786                             assert(   namedclass == ANYOF_HORIZWS
17787                                    || namedclass == ANYOF_NHORIZWS);
17788
17789                             /* It turns out that \h is just a synonym for
17790                              * XPosixBlank */
17791                             classnum = _CC_BLANK;
17792                         }
17793
17794                         _invlist_union_maybe_complement_2nd(
17795                                 cp_list,
17796                                 PL_XPosix_ptrs[classnum],
17797                                 namedclass % 2 != 0,    /* Complement if odd
17798                                                           (NHORIZWS, NVERTWS)
17799                                                         */
17800                                 &cp_list);
17801                     }
17802                 }
17803                 else if (   AT_LEAST_UNI_SEMANTICS
17804                          || classnum == _CC_ASCII
17805                          || (DEPENDS_SEMANTICS && (   classnum == _CC_DIGIT
17806                                                    || classnum == _CC_XDIGIT)))
17807                 {
17808                     /* We usually have to worry about /d affecting what POSIX
17809                      * classes match, with special code needed because we won't
17810                      * know until runtime what all matches.  But there is no
17811                      * extra work needed under /u and /a; and [:ascii:] is
17812                      * unaffected by /d; and :digit: and :xdigit: don't have
17813                      * runtime differences under /d.  So we can special case
17814                      * these, and avoid some extra work below, and at runtime.
17815                      * */
17816                     _invlist_union_maybe_complement_2nd(
17817                                                      simple_posixes,
17818                                                       ((AT_LEAST_ASCII_RESTRICTED)
17819                                                        ? PL_Posix_ptrs[classnum]
17820                                                        : PL_XPosix_ptrs[classnum]),
17821                                                      namedclass % 2 != 0,
17822                                                      &simple_posixes);
17823                 }
17824                 else {  /* Garden variety class.  If is NUPPER, NALPHA, ...
17825                            complement and use nposixes */
17826                     SV** posixes_ptr = namedclass % 2 == 0
17827                                        ? &posixes
17828                                        : &nposixes;
17829                     _invlist_union_maybe_complement_2nd(
17830                                                      *posixes_ptr,
17831                                                      PL_XPosix_ptrs[classnum],
17832                                                      namedclass % 2 != 0,
17833                                                      posixes_ptr);
17834                 }
17835             }
17836         } /* end of namedclass \blah */
17837
17838         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
17839
17840         /* If 'range' is set, 'value' is the ending of a range--check its
17841          * validity.  (If value isn't a single code point in the case of a
17842          * range, we should have figured that out above in the code that
17843          * catches false ranges).  Later, we will handle each individual code
17844          * point in the range.  If 'range' isn't set, this could be the
17845          * beginning of a range, so check for that by looking ahead to see if
17846          * the next real character to be processed is the range indicator--the
17847          * minus sign */
17848
17849         if (range) {
17850 #ifdef EBCDIC
17851             /* For unicode ranges, we have to test that the Unicode as opposed
17852              * to the native values are not decreasing.  (Above 255, there is
17853              * no difference between native and Unicode) */
17854             if (unicode_range && prevvalue < 255 && value < 255) {
17855                 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
17856                     goto backwards_range;
17857                 }
17858             }
17859             else
17860 #endif
17861             if (prevvalue > value) /* b-a */ {
17862                 int w;
17863 #ifdef EBCDIC
17864               backwards_range:
17865 #endif
17866                 w = RExC_parse - rangebegin;
17867                 vFAIL2utf8f(
17868                     "Invalid [] range \"%" UTF8f "\"",
17869                     UTF8fARG(UTF, w, rangebegin));
17870                 NOT_REACHED; /* NOTREACHED */
17871             }
17872         }
17873         else {
17874             prevvalue = value; /* save the beginning of the potential range */
17875             if (! stop_at_1     /* Can't be a range if parsing just one thing */
17876                 && *RExC_parse == '-')
17877             {
17878                 char* next_char_ptr = RExC_parse + 1;
17879
17880                 /* Get the next real char after the '-' */
17881                 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
17882
17883                 /* If the '-' is at the end of the class (just before the ']',
17884                  * it is a literal minus; otherwise it is a range */
17885                 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
17886                     RExC_parse = next_char_ptr;
17887
17888                     /* a bad range like \w-, [:word:]- ? */
17889                     if (namedclass > OOB_NAMEDCLASS) {
17890                         if (strict || ckWARN(WARN_REGEXP)) {
17891                             const int w = RExC_parse >= rangebegin
17892                                           ?  RExC_parse - rangebegin
17893                                           : 0;
17894                             if (strict) {
17895                                 vFAIL4("False [] range \"%*.*s\"",
17896                                     w, w, rangebegin);
17897                             }
17898                             else {
17899                                 vWARN4(RExC_parse,
17900                                     "False [] range \"%*.*s\"",
17901                                     w, w, rangebegin);
17902                             }
17903                         }
17904                         cp_list = add_cp_to_invlist(cp_list, '-');
17905                         element_count++;
17906                     } else
17907                         range = 1;      /* yeah, it's a range! */
17908                     continue;   /* but do it the next time */
17909                 }
17910             }
17911         }
17912
17913         if (namedclass > OOB_NAMEDCLASS) {
17914             continue;
17915         }
17916
17917         /* Here, we have a single value this time through the loop, and
17918          * <prevvalue> is the beginning of the range, if any; or <value> if
17919          * not. */
17920
17921         /* non-Latin1 code point implies unicode semantics. */
17922         if (value > 255) {
17923             REQUIRE_UNI_RULES(flagp, 0);
17924         }
17925
17926         /* Ready to process either the single value, or the completed range.
17927          * For single-valued non-inverted ranges, we consider the possibility
17928          * of multi-char folds.  (We made a conscious decision to not do this
17929          * for the other cases because it can often lead to non-intuitive
17930          * results.  For example, you have the peculiar case that:
17931          *  "s s" =~ /^[^\xDF]+$/i => Y
17932          *  "ss"  =~ /^[^\xDF]+$/i => N
17933          *
17934          * See [perl #89750] */
17935         if (FOLD && allow_mutiple_chars && value == prevvalue) {
17936             if (    value == LATIN_SMALL_LETTER_SHARP_S
17937                 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
17938                                                         value)))
17939             {
17940                 /* Here <value> is indeed a multi-char fold.  Get what it is */
17941
17942                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
17943                 STRLEN foldlen;
17944
17945                 UV folded = _to_uni_fold_flags(
17946                                 value,
17947                                 foldbuf,
17948                                 &foldlen,
17949                                 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
17950                                                    ? FOLD_FLAGS_NOMIX_ASCII
17951                                                    : 0)
17952                                 );
17953
17954                 /* Here, <folded> should be the first character of the
17955                  * multi-char fold of <value>, with <foldbuf> containing the
17956                  * whole thing.  But, if this fold is not allowed (because of
17957                  * the flags), <fold> will be the same as <value>, and should
17958                  * be processed like any other character, so skip the special
17959                  * handling */
17960                 if (folded != value) {
17961
17962                     /* Skip if we are recursed, currently parsing the class
17963                      * again.  Otherwise add this character to the list of
17964                      * multi-char folds. */
17965                     if (! RExC_in_multi_char_class) {
17966                         STRLEN cp_count = utf8_length(foldbuf,
17967                                                       foldbuf + foldlen);
17968                         SV* multi_fold = sv_2mortal(newSVpvs(""));
17969
17970                         Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value);
17971
17972                         multi_char_matches
17973                                         = add_multi_match(multi_char_matches,
17974                                                           multi_fold,
17975                                                           cp_count);
17976
17977                     }
17978
17979                     /* This element should not be processed further in this
17980                      * class */
17981                     element_count--;
17982                     value = save_value;
17983                     prevvalue = save_prevvalue;
17984                     continue;
17985                 }
17986             }
17987         }
17988
17989         if (strict && ckWARN(WARN_REGEXP)) {
17990             if (range) {
17991
17992                 /* If the range starts above 255, everything is portable and
17993                  * likely to be so for any forseeable character set, so don't
17994                  * warn. */
17995                 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
17996                     vWARN(RExC_parse, "Both or neither range ends should be Unicode");
17997                 }
17998                 else if (prevvalue != value) {
17999
18000                     /* Under strict, ranges that stop and/or end in an ASCII
18001                      * printable should have each end point be a portable value
18002                      * for it (preferably like 'A', but we don't warn if it is
18003                      * a (portable) Unicode name or code point), and the range
18004                      * must be be all digits or all letters of the same case.
18005                      * Otherwise, the range is non-portable and unclear as to
18006                      * what it contains */
18007                     if (             (isPRINT_A(prevvalue) || isPRINT_A(value))
18008                         && (          non_portable_endpoint
18009                             || ! (   (isDIGIT_A(prevvalue) && isDIGIT_A(value))
18010                                   || (isLOWER_A(prevvalue) && isLOWER_A(value))
18011                                   || (isUPPER_A(prevvalue) && isUPPER_A(value))
18012                     ))) {
18013                         vWARN(RExC_parse, "Ranges of ASCII printables should"
18014                                           " be some subset of \"0-9\","
18015                                           " \"A-Z\", or \"a-z\"");
18016                     }
18017                     else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) {
18018                         SSize_t index_start;
18019                         SSize_t index_final;
18020
18021                         /* But the nature of Unicode and languages mean we
18022                          * can't do the same checks for above-ASCII ranges,
18023                          * except in the case of digit ones.  These should
18024                          * contain only digits from the same group of 10.  The
18025                          * ASCII case is handled just above.  Hence here, the
18026                          * range could be a range of digits.  First some
18027                          * unlikely special cases.  Grandfather in that a range
18028                          * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad
18029                          * if its starting value is one of the 10 digits prior
18030                          * to it.  This is because it is an alternate way of
18031                          * writing 19D1, and some people may expect it to be in
18032                          * that group.  But it is bad, because it won't give
18033                          * the expected results.  In Unicode 5.2 it was
18034                          * considered to be in that group (of 11, hence), but
18035                          * this was fixed in the next version */
18036
18037                         if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) {
18038                             goto warn_bad_digit_range;
18039                         }
18040                         else if (UNLIKELY(   prevvalue >= 0x1D7CE
18041                                           &&     value <= 0x1D7FF))
18042                         {
18043                             /* This is the only other case currently in Unicode
18044                              * where the algorithm below fails.  The code
18045                              * points just above are the end points of a single
18046                              * range containing only decimal digits.  It is 5
18047                              * different series of 0-9.  All other ranges of
18048                              * digits currently in Unicode are just a single
18049                              * series.  (And mktables will notify us if a later
18050                              * Unicode version breaks this.)
18051                              *
18052                              * If the range being checked is at most 9 long,
18053                              * and the digit values represented are in
18054                              * numerical order, they are from the same series.
18055                              * */
18056                             if (         value - prevvalue > 9
18057                                 ||    (((    value - 0x1D7CE) % 10)
18058                                      <= (prevvalue - 0x1D7CE) % 10))
18059                             {
18060                                 goto warn_bad_digit_range;
18061                             }
18062                         }
18063                         else {
18064
18065                             /* For all other ranges of digits in Unicode, the
18066                              * algorithm is just to check if both end points
18067                              * are in the same series, which is the same range.
18068                              * */
18069                             index_start = _invlist_search(
18070                                                     PL_XPosix_ptrs[_CC_DIGIT],
18071                                                     prevvalue);
18072
18073                             /* Warn if the range starts and ends with a digit,
18074                              * and they are not in the same group of 10. */
18075                             if (   index_start >= 0
18076                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_start)
18077                                 && (index_final =
18078                                     _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
18079                                                     value)) != index_start
18080                                 && index_final >= 0
18081                                 && ELEMENT_RANGE_MATCHES_INVLIST(index_final))
18082                             {
18083                               warn_bad_digit_range:
18084                                 vWARN(RExC_parse, "Ranges of digits should be"
18085                                                   " from the same group of"
18086                                                   " 10");
18087                             }
18088                         }
18089                     }
18090                 }
18091             }
18092             if ((! range || prevvalue == value) && non_portable_endpoint) {
18093                 if (isPRINT_A(value)) {
18094                     char literal[3];
18095                     unsigned d = 0;
18096                     if (isBACKSLASHED_PUNCT(value)) {
18097                         literal[d++] = '\\';
18098                     }
18099                     literal[d++] = (char) value;
18100                     literal[d++] = '\0';
18101
18102                     vWARN4(RExC_parse,
18103                            "\"%.*s\" is more clearly written simply as \"%s\"",
18104                            (int) (RExC_parse - rangebegin),
18105                            rangebegin,
18106                            literal
18107                         );
18108                 }
18109                 else if (isMNEMONIC_CNTRL(value)) {
18110                     vWARN4(RExC_parse,
18111                            "\"%.*s\" is more clearly written simply as \"%s\"",
18112                            (int) (RExC_parse - rangebegin),
18113                            rangebegin,
18114                            cntrl_to_mnemonic((U8) value)
18115                         );
18116                 }
18117             }
18118         }
18119
18120         /* Deal with this element of the class */
18121
18122 #ifndef EBCDIC
18123         cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18124                                                     prevvalue, value);
18125 #else
18126         /* On non-ASCII platforms, for ranges that span all of 0..255, and ones
18127          * that don't require special handling, we can just add the range like
18128          * we do for ASCII platforms */
18129         if ((UNLIKELY(prevvalue == 0) && value >= 255)
18130             || ! (prevvalue < 256
18131                     && (unicode_range
18132                         || (! non_portable_endpoint
18133                             && ((isLOWER_A(prevvalue) && isLOWER_A(value))
18134                                 || (isUPPER_A(prevvalue)
18135                                     && isUPPER_A(value)))))))
18136         {
18137             cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18138                                                         prevvalue, value);
18139         }
18140         else {
18141             /* Here, requires special handling.  This can be because it is a
18142              * range whose code points are considered to be Unicode, and so
18143              * must be individually translated into native, or because its a
18144              * subrange of 'A-Z' or 'a-z' which each aren't contiguous in
18145              * EBCDIC, but we have defined them to include only the "expected"
18146              * upper or lower case ASCII alphabetics.  Subranges above 255 are
18147              * the same in native and Unicode, so can be added as a range */
18148             U8 start = NATIVE_TO_LATIN1(prevvalue);
18149             unsigned j;
18150             U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
18151             for (j = start; j <= end; j++) {
18152                 cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
18153             }
18154             if (value > 255) {
18155                 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
18156                                                             256, value);
18157             }
18158         }
18159 #endif
18160
18161         range = 0; /* this range (if it was one) is done now */
18162     } /* End of loop through all the text within the brackets */
18163
18164     if (   posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) {
18165         output_posix_warnings(pRExC_state, posix_warnings);
18166     }
18167
18168     /* If anything in the class expands to more than one character, we have to
18169      * deal with them by building up a substitute parse string, and recursively
18170      * calling reg() on it, instead of proceeding */
18171     if (multi_char_matches) {
18172         SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
18173         I32 cp_count;
18174         STRLEN len;
18175         char *save_end = RExC_end;
18176         char *save_parse = RExC_parse;
18177         char *save_start = RExC_start;
18178         Size_t constructed_prefix_len = 0; /* This gives the length of the
18179                                               constructed portion of the
18180                                               substitute parse. */
18181         bool first_time = TRUE;     /* First multi-char occurrence doesn't get
18182                                        a "|" */
18183         I32 reg_flags;
18184
18185         assert(! invert);
18186         /* Only one level of recursion allowed */
18187         assert(RExC_copy_start_in_constructed == RExC_precomp);
18188
18189 #if 0   /* Have decided not to deal with multi-char folds in inverted classes,
18190            because too confusing */
18191         if (invert) {
18192             sv_catpvs(substitute_parse, "(?:");
18193         }
18194 #endif
18195
18196         /* Look at the longest folds first */
18197         for (cp_count = av_tindex_skip_len_mg(multi_char_matches);
18198                         cp_count > 0;
18199                         cp_count--)
18200         {
18201
18202             if (av_exists(multi_char_matches, cp_count)) {
18203                 AV** this_array_ptr;
18204                 SV* this_sequence;
18205
18206                 this_array_ptr = (AV**) av_fetch(multi_char_matches,
18207                                                  cp_count, FALSE);
18208                 while ((this_sequence = av_pop(*this_array_ptr)) !=
18209                                                                 &PL_sv_undef)
18210                 {
18211                     if (! first_time) {
18212                         sv_catpvs(substitute_parse, "|");
18213                     }
18214                     first_time = FALSE;
18215
18216                     sv_catpv(substitute_parse, SvPVX(this_sequence));
18217                 }
18218             }
18219         }
18220
18221         /* If the character class contains anything else besides these
18222          * multi-character folds, have to include it in recursive parsing */
18223         if (element_count) {
18224             sv_catpvs(substitute_parse, "|[");
18225             constructed_prefix_len = SvCUR(substitute_parse);
18226             sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
18227
18228             /* Put in a closing ']' only if not going off the end, as otherwise
18229              * we are adding something that really isn't there */
18230             if (RExC_parse < RExC_end) {
18231                 sv_catpvs(substitute_parse, "]");
18232             }
18233         }
18234
18235         sv_catpvs(substitute_parse, ")");
18236 #if 0
18237         if (invert) {
18238             /* This is a way to get the parse to skip forward a whole named
18239              * sequence instead of matching the 2nd character when it fails the
18240              * first */
18241             sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
18242         }
18243 #endif
18244
18245         /* Set up the data structure so that any errors will be properly
18246          * reported.  See the comments at the definition of
18247          * REPORT_LOCATION_ARGS for details */
18248         RExC_copy_start_in_input = (char *) orig_parse;
18249         RExC_start = RExC_parse = SvPV(substitute_parse, len);
18250         RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len;
18251         RExC_end = RExC_parse + len;
18252         RExC_in_multi_char_class = 1;
18253
18254         ret = reg(pRExC_state, 1, &reg_flags, depth+1);
18255
18256         *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8);
18257
18258         /* And restore so can parse the rest of the pattern */
18259         RExC_parse = save_parse;
18260         RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start;
18261         RExC_end = save_end;
18262         RExC_in_multi_char_class = 0;
18263         SvREFCNT_dec_NN(multi_char_matches);
18264         return ret;
18265     }
18266
18267     /* If folding, we calculate all characters that could fold to or from the
18268      * ones already on the list */
18269     if (cp_foldable_list) {
18270         if (FOLD) {
18271             UV start, end;      /* End points of code point ranges */
18272
18273             SV* fold_intersection = NULL;
18274             SV** use_list;
18275
18276             /* Our calculated list will be for Unicode rules.  For locale
18277              * matching, we have to keep a separate list that is consulted at
18278              * runtime only when the locale indicates Unicode rules (and we
18279              * don't include potential matches in the ASCII/Latin1 range, as
18280              * any code point could fold to any other, based on the run-time
18281              * locale).   For non-locale, we just use the general list */
18282             if (LOC) {
18283                 use_list = &only_utf8_locale_list;
18284             }
18285             else {
18286                 use_list = &cp_list;
18287             }
18288
18289             /* Only the characters in this class that participate in folds need
18290              * be checked.  Get the intersection of this class and all the
18291              * possible characters that are foldable.  This can quickly narrow
18292              * down a large class */
18293             _invlist_intersection(PL_in_some_fold, cp_foldable_list,
18294                                   &fold_intersection);
18295
18296             /* Now look at the foldable characters in this class individually */
18297             invlist_iterinit(fold_intersection);
18298             while (invlist_iternext(fold_intersection, &start, &end)) {
18299                 UV j;
18300                 UV folded;
18301
18302                 /* Look at every character in the range */
18303                 for (j = start; j <= end; j++) {
18304                     U8 foldbuf[UTF8_MAXBYTES_CASE+1];
18305                     STRLEN foldlen;
18306                     unsigned int k;
18307                     Size_t folds_count;
18308                     unsigned int first_fold;
18309                     const unsigned int * remaining_folds;
18310
18311                     if (j < 256) {
18312
18313                         /* Under /l, we don't know what code points below 256
18314                          * fold to, except we do know the MICRO SIGN folds to
18315                          * an above-255 character if the locale is UTF-8, so we
18316                          * add it to the special list (in *use_list)  Otherwise
18317                          * we know now what things can match, though some folds
18318                          * are valid under /d only if the target is UTF-8.
18319                          * Those go in a separate list */
18320                         if (      IS_IN_SOME_FOLD_L1(j)
18321                             && ! (LOC && j != MICRO_SIGN))
18322                         {
18323
18324                             /* ASCII is always matched; non-ASCII is matched
18325                              * only under Unicode rules (which could happen
18326                              * under /l if the locale is a UTF-8 one */
18327                             if (isASCII(j) || ! DEPENDS_SEMANTICS) {
18328                                 *use_list = add_cp_to_invlist(*use_list,
18329                                                             PL_fold_latin1[j]);
18330                             }
18331                             else if (j != PL_fold_latin1[j]) {
18332                                 upper_latin1_only_utf8_matches
18333                                         = add_cp_to_invlist(
18334                                                 upper_latin1_only_utf8_matches,
18335                                                 PL_fold_latin1[j]);
18336                             }
18337                         }
18338
18339                         if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
18340                             && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
18341                         {
18342                             add_above_Latin1_folds(pRExC_state,
18343                                                    (U8) j,
18344                                                    use_list);
18345                         }
18346                         continue;
18347                     }
18348
18349                     /* Here is an above Latin1 character.  We don't have the
18350                      * rules hard-coded for it.  First, get its fold.  This is
18351                      * the simple fold, as the multi-character folds have been
18352                      * handled earlier and separated out */
18353                     folded = _to_uni_fold_flags(j, foldbuf, &foldlen,
18354                                                         (ASCII_FOLD_RESTRICTED)
18355                                                         ? FOLD_FLAGS_NOMIX_ASCII
18356                                                         : 0);
18357
18358                     /* Single character fold of above Latin1.  Add everything
18359                      * in its fold closure to the list that this node should
18360                      * match. */
18361                     folds_count = _inverse_folds(folded, &first_fold,
18362                                                     &remaining_folds);
18363                     for (k = 0; k <= folds_count; k++) {
18364                         UV c = (k == 0)     /* First time through use itself */
18365                                 ? folded
18366                                 : (k == 1)  /* 2nd time use, the first fold */
18367                                    ? first_fold
18368
18369                                      /* Then the remaining ones */
18370                                    : remaining_folds[k-2];
18371
18372                         /* /aa doesn't allow folds between ASCII and non- */
18373                         if ((   ASCII_FOLD_RESTRICTED
18374                             && (isASCII(c) != isASCII(j))))
18375                         {
18376                             continue;
18377                         }
18378
18379                         /* Folds under /l which cross the 255/256 boundary are
18380                          * added to a separate list.  (These are valid only
18381                          * when the locale is UTF-8.) */
18382                         if (c < 256 && LOC) {
18383                             *use_list = add_cp_to_invlist(*use_list, c);
18384                             continue;
18385                         }
18386
18387                         if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
18388                         {
18389                             cp_list = add_cp_to_invlist(cp_list, c);
18390                         }
18391                         else {
18392                             /* Similarly folds involving non-ascii Latin1
18393                              * characters under /d are added to their list */
18394                             upper_latin1_only_utf8_matches
18395                                     = add_cp_to_invlist(
18396                                                 upper_latin1_only_utf8_matches,
18397                                                 c);
18398                         }
18399                     }
18400                 }
18401             }
18402             SvREFCNT_dec_NN(fold_intersection);
18403         }
18404
18405         /* Now that we have finished adding all the folds, there is no reason
18406          * to keep the foldable list separate */
18407         _invlist_union(cp_list, cp_foldable_list, &cp_list);
18408         SvREFCNT_dec_NN(cp_foldable_list);
18409     }
18410
18411     /* And combine the result (if any) with any inversion lists from posix
18412      * classes.  The lists are kept separate up to now because we don't want to
18413      * fold the classes */
18414     if (simple_posixes) {   /* These are the classes known to be unaffected by
18415                                /a, /aa, and /d */
18416         if (cp_list) {
18417             _invlist_union(cp_list, simple_posixes, &cp_list);
18418             SvREFCNT_dec_NN(simple_posixes);
18419         }
18420         else {
18421             cp_list = simple_posixes;
18422         }
18423     }
18424     if (posixes || nposixes) {
18425         if (! DEPENDS_SEMANTICS) {
18426
18427             /* For everything but /d, we can just add the current 'posixes' and
18428              * 'nposixes' to the main list */
18429             if (posixes) {
18430                 if (cp_list) {
18431                     _invlist_union(cp_list, posixes, &cp_list);
18432                     SvREFCNT_dec_NN(posixes);
18433                 }
18434                 else {
18435                     cp_list = posixes;
18436                 }
18437             }
18438             if (nposixes) {
18439                 if (cp_list) {
18440                     _invlist_union(cp_list, nposixes, &cp_list);
18441                     SvREFCNT_dec_NN(nposixes);
18442                 }
18443                 else {
18444                     cp_list = nposixes;
18445                 }
18446             }
18447         }
18448         else {
18449             /* Under /d, things like \w match upper Latin1 characters only if
18450              * the target string is in UTF-8.  But things like \W match all the
18451              * upper Latin1 characters if the target string is not in UTF-8.
18452              *
18453              * Handle the case with something like \W separately */
18454             if (nposixes) {
18455                 SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL);
18456
18457                 /* A complemented posix class matches all upper Latin1
18458                  * characters if not in UTF-8.  And it matches just certain
18459                  * ones when in UTF-8.  That means those certain ones are
18460                  * matched regardless, so can just be added to the
18461                  * unconditional list */
18462                 if (cp_list) {
18463                     _invlist_union(cp_list, nposixes, &cp_list);
18464                     SvREFCNT_dec_NN(nposixes);
18465                     nposixes = NULL;
18466                 }
18467                 else {
18468                     cp_list = nposixes;
18469                 }
18470
18471                 /* Likewise for 'posixes' */
18472                 _invlist_union(posixes, cp_list, &cp_list);
18473                 SvREFCNT_dec(posixes);
18474
18475                 /* Likewise for anything else in the range that matched only
18476                  * under UTF-8 */
18477                 if (upper_latin1_only_utf8_matches) {
18478                     _invlist_union(cp_list,
18479                                    upper_latin1_only_utf8_matches,
18480                                    &cp_list);
18481                     SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18482                     upper_latin1_only_utf8_matches = NULL;
18483                 }
18484
18485                 /* If we don't match all the upper Latin1 characters regardless
18486                  * of UTF-8ness, we have to set a flag to match the rest when
18487                  * not in UTF-8 */
18488                 _invlist_subtract(only_non_utf8_list, cp_list,
18489                                   &only_non_utf8_list);
18490                 if (_invlist_len(only_non_utf8_list) != 0) {
18491                     anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18492                 }
18493                 SvREFCNT_dec_NN(only_non_utf8_list);
18494             }
18495             else {
18496                 /* Here there were no complemented posix classes.  That means
18497                  * the upper Latin1 characters in 'posixes' match only when the
18498                  * target string is in UTF-8.  So we have to add them to the
18499                  * list of those types of code points, while adding the
18500                  * remainder to the unconditional list.
18501                  *
18502                  * First calculate what they are */
18503                 SV* nonascii_but_latin1_properties = NULL;
18504                 _invlist_intersection(posixes, PL_UpperLatin1,
18505                                       &nonascii_but_latin1_properties);
18506
18507                 /* And add them to the final list of such characters. */
18508                 _invlist_union(upper_latin1_only_utf8_matches,
18509                                nonascii_but_latin1_properties,
18510                                &upper_latin1_only_utf8_matches);
18511
18512                 /* Remove them from what now becomes the unconditional list */
18513                 _invlist_subtract(posixes, nonascii_but_latin1_properties,
18514                                   &posixes);
18515
18516                 /* And add those unconditional ones to the final list */
18517                 if (cp_list) {
18518                     _invlist_union(cp_list, posixes, &cp_list);
18519                     SvREFCNT_dec_NN(posixes);
18520                     posixes = NULL;
18521                 }
18522                 else {
18523                     cp_list = posixes;
18524                 }
18525
18526                 SvREFCNT_dec(nonascii_but_latin1_properties);
18527
18528                 /* Get rid of any characters from the conditional list that we
18529                  * now know are matched unconditionally, which may make that
18530                  * list empty */
18531                 _invlist_subtract(upper_latin1_only_utf8_matches,
18532                                   cp_list,
18533                                   &upper_latin1_only_utf8_matches);
18534                 if (_invlist_len(upper_latin1_only_utf8_matches) == 0) {
18535                     SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
18536                     upper_latin1_only_utf8_matches = NULL;
18537                 }
18538             }
18539         }
18540     }
18541
18542     /* And combine the result (if any) with any inversion list from properties.
18543      * The lists are kept separate up to now so that we can distinguish the two
18544      * in regards to matching above-Unicode.  A run-time warning is generated
18545      * if a Unicode property is matched against a non-Unicode code point. But,
18546      * we allow user-defined properties to match anything, without any warning,
18547      * and we also suppress the warning if there is a portion of the character
18548      * class that isn't a Unicode property, and which matches above Unicode, \W
18549      * or [\x{110000}] for example.
18550      * (Note that in this case, unlike the Posix one above, there is no
18551      * <upper_latin1_only_utf8_matches>, because having a Unicode property
18552      * forces Unicode semantics */
18553     if (properties) {
18554         if (cp_list) {
18555
18556             /* If it matters to the final outcome, see if a non-property
18557              * component of the class matches above Unicode.  If so, the
18558              * warning gets suppressed.  This is true even if just a single
18559              * such code point is specified, as, though not strictly correct if
18560              * another such code point is matched against, the fact that they
18561              * are using above-Unicode code points indicates they should know
18562              * the issues involved */
18563             if (warn_super) {
18564                 warn_super = ! (invert
18565                                ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
18566             }
18567
18568             _invlist_union(properties, cp_list, &cp_list);
18569             SvREFCNT_dec_NN(properties);
18570         }
18571         else {
18572             cp_list = properties;
18573         }
18574
18575         if (warn_super) {
18576             anyof_flags
18577              |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
18578
18579             /* Because an ANYOF node is the only one that warns, this node
18580              * can't be optimized into something else */
18581             optimizable = FALSE;
18582         }
18583     }
18584
18585     /* Here, we have calculated what code points should be in the character
18586      * class.
18587      *
18588      * Now we can see about various optimizations.  Fold calculation (which we
18589      * did above) needs to take place before inversion.  Otherwise /[^k]/i
18590      * would invert to include K, which under /i would match k, which it
18591      * shouldn't.  Therefore we can't invert folded locale now, as it won't be
18592      * folded until runtime */
18593
18594     /* If we didn't do folding, it's because some information isn't available
18595      * until runtime; set the run-time fold flag for these  We know to set the
18596      * flag if we have a non-NULL list for UTF-8 locales, or the class matches
18597      * at least one 0-255 range code point */
18598     if (LOC && FOLD) {
18599
18600         /* Some things on the list might be unconditionally included because of
18601          * other components.  Remove them, and clean up the list if it goes to
18602          * 0 elements */
18603         if (only_utf8_locale_list && cp_list) {
18604             _invlist_subtract(only_utf8_locale_list, cp_list,
18605                               &only_utf8_locale_list);
18606
18607             if (_invlist_len(only_utf8_locale_list) == 0) {
18608                 SvREFCNT_dec_NN(only_utf8_locale_list);
18609                 only_utf8_locale_list = NULL;
18610             }
18611         }
18612         if (    only_utf8_locale_list
18613             || (cp_list && (   _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)
18614                             || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I))))
18615         {
18616             has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18617             anyof_flags
18618                  |= ANYOFL_FOLD
18619                  |  ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
18620         }
18621         else if (cp_list && invlist_lowest(cp_list) < 256) {
18622             /* If nothing is below 256, has no locale dependency; otherwise it
18623              * does */
18624             anyof_flags |= ANYOFL_FOLD;
18625             has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY;
18626         }
18627     }
18628     else if (   DEPENDS_SEMANTICS
18629              && (    upper_latin1_only_utf8_matches
18630                  || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)))
18631     {
18632         RExC_seen_d_op = TRUE;
18633         has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY;
18634     }
18635
18636     /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at
18637      * compile time. */
18638     if (     cp_list
18639         &&   invert
18640         && ! has_runtime_dependency)
18641     {
18642         _invlist_invert(cp_list);
18643
18644         /* Clear the invert flag since have just done it here */
18645         invert = FALSE;
18646     }
18647
18648     if (ret_invlist) {
18649         *ret_invlist = cp_list;
18650
18651         return RExC_emit;
18652     }
18653
18654     /* All possible optimizations below still have these characteristics.
18655      * (Multi-char folds aren't SIMPLE, but they don't get this far in this
18656      * routine) */
18657     *flagp |= HASWIDTH|SIMPLE;
18658
18659     if (anyof_flags & ANYOF_LOCALE_FLAGS) {
18660         RExC_contains_locale = 1;
18661     }
18662
18663     /* Some character classes are equivalent to other nodes.  Such nodes take
18664      * up less room, and some nodes require fewer operations to execute, than
18665      * ANYOF nodes.  EXACTish nodes may be joinable with adjacent nodes to
18666      * improve efficiency. */
18667
18668     if (optimizable) {
18669         PERL_UINT_FAST8_T i;
18670         UV partial_cp_count = 0;
18671         UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */
18672         UV   end[MAX_FOLD_FROMS+1] = { 0 };
18673         bool single_range = FALSE;
18674
18675         if (cp_list) { /* Count the code points in enough ranges that we would
18676                           see all the ones possible in any fold in this version
18677                           of Unicode */
18678
18679             invlist_iterinit(cp_list);
18680             for (i = 0; i <= MAX_FOLD_FROMS; i++) {
18681                 if (! invlist_iternext(cp_list, &start[i], &end[i])) {
18682                     break;
18683                 }
18684                 partial_cp_count += end[i] - start[i] + 1;
18685             }
18686
18687             if (i == 1) {
18688                 single_range = TRUE;
18689             }
18690             invlist_iterfinish(cp_list);
18691         }
18692
18693         /* If we know at compile time that this matches every possible code
18694          * point, any run-time dependencies don't matter */
18695         if (start[0] == 0 && end[0] == UV_MAX) {
18696             if (invert) {
18697                 ret = reganode(pRExC_state, OPFAIL, 0);
18698             }
18699             else {
18700                 ret = reg_node(pRExC_state, SANY);
18701                 MARK_NAUGHTY(1);
18702             }
18703             goto not_anyof;
18704         }
18705
18706         /* Similarly, for /l posix classes, if both a class and its
18707          * complement match, any run-time dependencies don't matter */
18708         if (posixl) {
18709             for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX;
18710                                                         namedclass += 2)
18711             {
18712                 if (   POSIXL_TEST(posixl, namedclass)      /* class */
18713                     && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */
18714                 {
18715                     if (invert) {
18716                         ret = reganode(pRExC_state, OPFAIL, 0);
18717                     }
18718                     else {
18719                         ret = reg_node(pRExC_state, SANY);
18720                         MARK_NAUGHTY(1);
18721                     }
18722                     goto not_anyof;
18723                 }
18724             }
18725
18726             /* For well-behaved locales, some classes are subsets of others,
18727              * so complementing the subset and including the non-complemented
18728              * superset should match everything, like [\D[:alnum:]], and
18729              * [[:^alpha:][:alnum:]], but some implementations of locales are
18730              * buggy, and khw thinks its a bad idea to have optimization change
18731              * behavior, even if it avoids an OS bug in a given case */
18732
18733 #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n)
18734
18735             /* If is a single posix /l class, can optimize to just that op.
18736              * Such a node will not match anything in the Latin1 range, as that
18737              * is not determinable until runtime, but will match whatever the
18738              * class does outside that range.  (Note that some classes won't
18739              * match anything outside the range, like [:ascii:]) */
18740             if (    isSINGLE_BIT_SET(posixl)
18741                 && (partial_cp_count == 0 || start[0] > 255))
18742             {
18743                 U8 classnum;
18744                 SV * class_above_latin1 = NULL;
18745                 bool already_inverted;
18746                 bool are_equivalent;
18747
18748                 /* Compute which bit is set, which is the same thing as, e.g.,
18749                  * ANYOF_CNTRL.  From
18750                  * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
18751                  * */
18752                 static const int MultiplyDeBruijnBitPosition2[32] =
18753                     {
18754                     0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
18755                     31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
18756                     };
18757
18758                 namedclass = MultiplyDeBruijnBitPosition2[(posixl
18759                                                           * 0x077CB531U) >> 27];
18760                 classnum = namedclass_to_classnum(namedclass);
18761
18762                 /* The named classes are such that the inverted number is one
18763                  * larger than the non-inverted one */
18764                 already_inverted = namedclass
18765                                  - classnum_to_namedclass(classnum);
18766
18767                 /* Create an inversion list of the official property, inverted
18768                  * if the constructed node list is inverted, and restricted to
18769                  * only the above latin1 code points, which are the only ones
18770                  * known at compile time */
18771                 _invlist_intersection_maybe_complement_2nd(
18772                                                     PL_AboveLatin1,
18773                                                     PL_XPosix_ptrs[classnum],
18774                                                     already_inverted,
18775                                                     &class_above_latin1);
18776                 are_equivalent = _invlistEQ(class_above_latin1, cp_list,
18777                                                                         FALSE);
18778                 SvREFCNT_dec_NN(class_above_latin1);
18779
18780                 if (are_equivalent) {
18781
18782                     /* Resolve the run-time inversion flag with this possibly
18783                      * inverted class */
18784                     invert = invert ^ already_inverted;
18785
18786                     ret = reg_node(pRExC_state,
18787                                    POSIXL + invert * (NPOSIXL - POSIXL));
18788                     FLAGS(REGNODE_p(ret)) = classnum;
18789                     goto not_anyof;
18790                 }
18791             }
18792         }
18793
18794         /* khw can't think of any other possible transformation involving
18795          * these. */
18796         if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) {
18797             goto is_anyof;
18798         }
18799
18800         if (! has_runtime_dependency) {
18801
18802             /* If the list is empty, nothing matches.  This happens, for
18803              * example, when a Unicode property that doesn't match anything is
18804              * the only element in the character class (perluniprops.pod notes
18805              * such properties). */
18806             if (partial_cp_count == 0) {
18807                 if (invert) {
18808                     ret = reg_node(pRExC_state, SANY);
18809                 }
18810                 else {
18811                     ret = reganode(pRExC_state, OPFAIL, 0);
18812                 }
18813
18814                 goto not_anyof;
18815             }
18816
18817             /* If matches everything but \n */
18818             if (   start[0] == 0 && end[0] == '\n' - 1
18819                 && start[1] == '\n' + 1 && end[1] == UV_MAX)
18820             {
18821                 assert (! invert);
18822                 ret = reg_node(pRExC_state, REG_ANY);
18823                 MARK_NAUGHTY(1);
18824                 goto not_anyof;
18825             }
18826         }
18827
18828         /* Next see if can optimize classes that contain just a few code points
18829          * into an EXACTish node.  The reason to do this is to let the
18830          * optimizer join this node with adjacent EXACTish ones, and ANYOF
18831          * nodes require conversion to code point from UTF-8.
18832          *
18833          * An EXACTFish node can be generated even if not under /i, and vice
18834          * versa.  But care must be taken.  An EXACTFish node has to be such
18835          * that it only matches precisely the code points in the class, but we
18836          * want to generate the least restrictive one that does that, to
18837          * increase the odds of being able to join with an adjacent node.  For
18838          * example, if the class contains [kK], we have to make it an EXACTFAA
18839          * node to prevent the KELVIN SIGN from matching.  Whether we are under
18840          * /i or not is irrelevant in this case.  Less obvious is the pattern
18841          * qr/[\x{02BC}]n/i.  U+02BC is MODIFIER LETTER APOSTROPHE. That is
18842          * supposed to match the single character U+0149 LATIN SMALL LETTER N
18843          * PRECEDED BY APOSTROPHE.  And so even though there is no simple fold
18844          * that includes \X{02BC}, there is a multi-char fold that does, and so
18845          * the node generated for it must be an EXACTFish one.  On the other
18846          * hand qr/:/i should generate a plain EXACT node since the colon
18847          * participates in no fold whatsoever, and having it EXACT tells the
18848          * optimizer the target string cannot match unless it has a colon in
18849          * it.
18850          */
18851         if (   ! posixl
18852             && ! invert
18853
18854                 /* Only try if there are no more code points in the class than
18855                  * in the max possible fold */
18856             &&   inRANGE(partial_cp_count, 1, MAX_FOLD_FROMS + 1))
18857         {
18858             if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches)
18859             {
18860                 /* We can always make a single code point class into an
18861                  * EXACTish node. */
18862
18863                 if (LOC) {
18864
18865                     /* Here is /l:  Use EXACTL, except if there is a fold not
18866                      * known until runtime so shows as only a single code point
18867                      * here.  For code points above 255, we know which can
18868                      * cause problems by having a potential fold to the Latin1
18869                      * range. */
18870                     if (  ! FOLD
18871                         || (     start[0] > 255
18872                             && ! is_PROBLEMATIC_LOCALE_FOLD_cp(start[0])))
18873                     {
18874                         op = EXACTL;
18875                     }
18876                     else {
18877                         op = EXACTFL;
18878                     }
18879                 }
18880                 else if (! FOLD) { /* Not /l and not /i */
18881                     op = (start[0] < 256) ? EXACT : EXACT_REQ8;
18882                 }
18883                 else if (start[0] < 256) { /* /i, not /l, and the code point is
18884                                               small */
18885
18886                     /* Under /i, it gets a little tricky.  A code point that
18887                      * doesn't participate in a fold should be an EXACT node.
18888                      * We know this one isn't the result of a simple fold, or
18889                      * there'd be more than one code point in the list, but it
18890                      * could be part of a multi- character fold.  In that case
18891                      * we better not create an EXACT node, as we would wrongly
18892                      * be telling the optimizer that this code point must be in
18893                      * the target string, and that is wrong.  This is because
18894                      * if the sequence around this code point forms a
18895                      * multi-char fold, what needs to be in the string could be
18896                      * the code point that folds to the sequence.
18897                      *
18898                      * This handles the case of below-255 code points, as we
18899                      * have an easy look up for those.  The next clause handles
18900                      * the above-256 one */
18901                     op = IS_IN_SOME_FOLD_L1(start[0])
18902                          ? EXACTFU
18903                          : EXACT;
18904                 }
18905                 else {  /* /i, larger code point.  Since we are under /i, and
18906                            have just this code point, we know that it can't
18907                            fold to something else, so PL_InMultiCharFold
18908                            applies to it */
18909                     op = _invlist_contains_cp(PL_InMultiCharFold,
18910                                               start[0])
18911                          ? EXACTFU_REQ8
18912                          : EXACT_REQ8;
18913                 }
18914
18915                 value = start[0];
18916             }
18917             else if (  ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY)
18918                      && _invlist_contains_cp(PL_in_some_fold, start[0]))
18919             {
18920                 /* Here, the only runtime dependency, if any, is from /d, and
18921                  * the class matches more than one code point, and the lowest
18922                  * code point participates in some fold.  It might be that the
18923                  * other code points are /i equivalent to this one, and hence
18924                  * they would representable by an EXACTFish node.  Above, we
18925                  * eliminated classes that contain too many code points to be
18926                  * EXACTFish, with the test for MAX_FOLD_FROMS
18927                  *
18928                  * First, special case the ASCII fold pairs, like 'B' and 'b'.
18929                  * We do this because we have EXACTFAA at our disposal for the
18930                  * ASCII range */
18931                 if (partial_cp_count == 2 && isASCII(start[0])) {
18932
18933                     /* The only ASCII characters that participate in folds are
18934                      * alphabetics */
18935                     assert(isALPHA(start[0]));
18936                     if (   end[0] == start[0]   /* First range is a single
18937                                                    character, so 2nd exists */
18938                         && isALPHA_FOLD_EQ(start[0], start[1]))
18939                     {
18940
18941                         /* Here, is part of an ASCII fold pair */
18942
18943                         if (   ASCII_FOLD_RESTRICTED
18944                             || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0]))
18945                         {
18946                             /* If the second clause just above was true, it
18947                              * means we can't be under /i, or else the list
18948                              * would have included more than this fold pair.
18949                              * Therefore we have to exclude the possibility of
18950                              * whatever else it is that folds to these, by
18951                              * using EXACTFAA */
18952                             op = EXACTFAA;
18953                         }
18954                         else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) {
18955
18956                             /* Here, there's no simple fold that start[0] is part
18957                              * of, but there is a multi-character one.  If we
18958                              * are not under /i, we want to exclude that
18959                              * possibility; if under /i, we want to include it
18960                              * */
18961                             op = (FOLD) ? EXACTFU : EXACTFAA;
18962                         }
18963                         else {
18964
18965                             /* Here, the only possible fold start[0] particpates in
18966                              * is with start[1].  /i or not isn't relevant */
18967                             op = EXACTFU;
18968                         }
18969
18970                         value = toFOLD(start[0]);
18971                     }
18972                 }
18973                 else if (  ! upper_latin1_only_utf8_matches
18974                          || (   _invlist_len(upper_latin1_only_utf8_matches)
18975                                                                           == 2
18976                              && PL_fold_latin1[
18977                                invlist_highest(upper_latin1_only_utf8_matches)]
18978                              == start[0]))
18979                 {
18980                     /* Here, the smallest character is non-ascii or there are
18981                      * more than 2 code points matched by this node.  Also, we
18982                      * either don't have /d UTF-8 dependent matches, or if we
18983                      * do, they look like they could be a single character that
18984                      * is the fold of the lowest one in the always-match list.
18985                      * This test quickly excludes most of the false positives
18986                      * when there are /d UTF-8 depdendent matches.  These are
18987                      * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN
18988                      * SMALL LETTER A WITH GRAVE iff the target string is
18989                      * UTF-8.  (We don't have to worry above about exceeding
18990                      * the array bounds of PL_fold_latin1[] because any code
18991                      * point in 'upper_latin1_only_utf8_matches' is below 256.)
18992                      *
18993                      * EXACTFAA would apply only to pairs (hence exactly 2 code
18994                      * points) in the ASCII range, so we can't use it here to
18995                      * artificially restrict the fold domain, so we check if
18996                      * the class does or does not match some EXACTFish node.
18997                      * Further, if we aren't under /i, and and the folded-to
18998                      * character is part of a multi-character fold, we can't do
18999                      * this optimization, as the sequence around it could be
19000                      * that multi-character fold, and we don't here know the
19001                      * context, so we have to assume it is that multi-char
19002                      * fold, to prevent potential bugs.
19003                      *
19004                      * To do the general case, we first find the fold of the
19005                      * lowest code point (which may be higher than the lowest
19006                      * one), then find everything that folds to it.  (The data
19007                      * structure we have only maps from the folded code points,
19008                      * so we have to do the earlier step.) */
19009
19010                     Size_t foldlen;
19011                     U8 foldbuf[UTF8_MAXBYTES_CASE];
19012                     UV folded = _to_uni_fold_flags(start[0],
19013                                                         foldbuf, &foldlen, 0);
19014                     unsigned int first_fold;
19015                     const unsigned int * remaining_folds;
19016                     Size_t folds_to_this_cp_count = _inverse_folds(
19017                                                             folded,
19018                                                             &first_fold,
19019                                                             &remaining_folds);
19020                     Size_t folds_count = folds_to_this_cp_count + 1;
19021                     SV * fold_list = _new_invlist(folds_count);
19022                     unsigned int i;
19023
19024                     /* If there are UTF-8 dependent matches, create a temporary
19025                      * list of what this node matches, including them. */
19026                     SV * all_cp_list = NULL;
19027                     SV ** use_this_list = &cp_list;
19028
19029                     if (upper_latin1_only_utf8_matches) {
19030                         all_cp_list = _new_invlist(0);
19031                         use_this_list = &all_cp_list;
19032                         _invlist_union(cp_list,
19033                                        upper_latin1_only_utf8_matches,
19034                                        use_this_list);
19035                     }
19036
19037                     /* Having gotten everything that participates in the fold
19038                      * containing the lowest code point, we turn that into an
19039                      * inversion list, making sure everything is included. */
19040                     fold_list = add_cp_to_invlist(fold_list, start[0]);
19041                     fold_list = add_cp_to_invlist(fold_list, folded);
19042                     if (folds_to_this_cp_count > 0) {
19043                         fold_list = add_cp_to_invlist(fold_list, first_fold);
19044                         for (i = 0; i + 1 < folds_to_this_cp_count; i++) {
19045                             fold_list = add_cp_to_invlist(fold_list,
19046                                                         remaining_folds[i]);
19047                         }
19048                     }
19049
19050                     /* If the fold list is identical to what's in this ANYOF
19051                      * node, the node can be represented by an EXACTFish one
19052                      * instead */
19053                     if (_invlistEQ(*use_this_list, fold_list,
19054                                    0 /* Don't complement */ )
19055                     ) {
19056
19057                         /* But, we have to be careful, as mentioned above.
19058                          * Just the right sequence of characters could match
19059                          * this if it is part of a multi-character fold.  That
19060                          * IS what we want if we are under /i.  But it ISN'T
19061                          * what we want if not under /i, as it could match when
19062                          * it shouldn't.  So, when we aren't under /i and this
19063                          * character participates in a multi-char fold, we
19064                          * don't optimize into an EXACTFish node.  So, for each
19065                          * case below we have to check if we are folding
19066                          * and if not, if it is not part of a multi-char fold.
19067                          * */
19068                         if (start[0] > 255) {    /* Highish code point */
19069                             if (FOLD || ! _invlist_contains_cp(
19070                                             PL_InMultiCharFold, folded))
19071                             {
19072                                 op = (LOC)
19073                                      ? EXACTFLU8
19074                                      : (ASCII_FOLD_RESTRICTED)
19075                                        ? EXACTFAA
19076                                        : EXACTFU_REQ8;
19077                                 value = folded;
19078                             }
19079                         }   /* Below, the lowest code point < 256 */
19080                         else if (    FOLD
19081                                  &&  folded == 's'
19082                                  &&  DEPENDS_SEMANTICS)
19083                         {   /* An EXACTF node containing a single character
19084                                 's', can be an EXACTFU if it doesn't get
19085                                 joined with an adjacent 's' */
19086                             op = EXACTFU_S_EDGE;
19087                             value = folded;
19088                         }
19089                         else if (    FOLD
19090                                 || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0]))
19091                         {
19092                             if (upper_latin1_only_utf8_matches) {
19093                                 op = EXACTF;
19094
19095                                 /* We can't use the fold, as that only matches
19096                                  * under UTF-8 */
19097                                 value = start[0];
19098                             }
19099                             else if (     UNLIKELY(start[0] == MICRO_SIGN)
19100                                      && ! UTF)
19101                             {   /* EXACTFUP is a special node for this
19102                                    character */
19103                                 op = (ASCII_FOLD_RESTRICTED)
19104                                      ? EXACTFAA
19105                                      : EXACTFUP;
19106                                 value = MICRO_SIGN;
19107                             }
19108                             else if (     ASCII_FOLD_RESTRICTED
19109                                      && ! isASCII(start[0]))
19110                             {   /* For ASCII under /iaa, we can use EXACTFU
19111                                    below */
19112                                 op = EXACTFAA;
19113                                 value = folded;
19114                             }
19115                             else {
19116                                 op = EXACTFU;
19117                                 value = folded;
19118                             }
19119                         }
19120                     }
19121
19122                     SvREFCNT_dec_NN(fold_list);
19123                     SvREFCNT_dec(all_cp_list);
19124                 }
19125             }
19126
19127             if (op != END) {
19128                 U8 len;
19129
19130                 /* Here, we have calculated what EXACTish node to use.  Have to
19131                  * convert to UTF-8 if not already there */
19132                 if (value > 255) {
19133                     if (! UTF) {
19134                         SvREFCNT_dec(cp_list);;
19135                         REQUIRE_UTF8(flagp);
19136                     }
19137
19138                     /* This is a kludge to the special casing issues with this
19139                      * ligature under /aa.  FB05 should fold to FB06, but the
19140                      * call above to _to_uni_fold_flags() didn't find this, as
19141                      * it didn't use the /aa restriction in order to not miss
19142                      * other folds that would be affected.  This is the only
19143                      * instance likely to ever be a problem in all of Unicode.
19144                      * So special case it. */
19145                     if (   value == LATIN_SMALL_LIGATURE_LONG_S_T
19146                         && ASCII_FOLD_RESTRICTED)
19147                     {
19148                         value = LATIN_SMALL_LIGATURE_ST;
19149                     }
19150                 }
19151
19152                 len = (UTF) ? UVCHR_SKIP(value) : 1;
19153
19154                 ret = regnode_guts(pRExC_state, op, len, "exact");
19155                 FILL_NODE(ret, op);
19156                 RExC_emit += 1 + STR_SZ(len);
19157                 setSTR_LEN(REGNODE_p(ret), len);
19158                 if (len == 1) {
19159                     *STRINGs(REGNODE_p(ret)) = (U8) value;
19160                 }
19161                 else {
19162                     uvchr_to_utf8((U8 *) STRINGs(REGNODE_p(ret)), value);
19163                 }
19164                 goto not_anyof;
19165             }
19166         }
19167
19168         if (! has_runtime_dependency) {
19169
19170             /* See if this can be turned into an ANYOFM node.  Think about the
19171              * bit patterns in two different bytes.  In some positions, the
19172              * bits in each will be 1; and in other positions both will be 0;
19173              * and in some positions the bit will be 1 in one byte, and 0 in
19174              * the other.  Let 'n' be the number of positions where the bits
19175              * differ.  We create a mask which has exactly 'n' 0 bits, each in
19176              * a position where the two bytes differ.  Now take the set of all
19177              * bytes that when ANDed with the mask yield the same result.  That
19178              * set has 2**n elements, and is representable by just two 8 bit
19179              * numbers: the result and the mask.  Importantly, matching the set
19180              * can be vectorized by creating a word full of the result bytes,
19181              * and a word full of the mask bytes, yielding a significant speed
19182              * up.  Here, see if this node matches such a set.  As a concrete
19183              * example consider [01], and the byte representing '0' which is
19184              * 0x30 on ASCII machines.  It has the bits 0011 0000.  Take the
19185              * mask 1111 1110.  If we AND 0x31 and 0x30 with that mask we get
19186              * 0x30.  Any other bytes ANDed yield something else.  So [01],
19187              * which is a common usage, is optimizable into ANYOFM, and can
19188              * benefit from the speed up.  We can only do this on UTF-8
19189              * invariant bytes, because they have the same bit patterns under
19190              * UTF-8 as not. */
19191             PERL_UINT_FAST8_T inverted = 0;
19192 #ifdef EBCDIC
19193             const PERL_UINT_FAST8_T max_permissible = 0xFF;
19194 #else
19195             const PERL_UINT_FAST8_T max_permissible = 0x7F;
19196 #endif
19197             /* If doesn't fit the criteria for ANYOFM, invert and try again.
19198              * If that works we will instead later generate an NANYOFM, and
19199              * invert back when through */
19200             if (invlist_highest(cp_list) > max_permissible) {
19201                 _invlist_invert(cp_list);
19202                 inverted = 1;
19203             }
19204
19205             if (invlist_highest(cp_list) <= max_permissible) {
19206                 UV this_start, this_end;
19207                 UV lowest_cp = UV_MAX;  /* init'ed to suppress compiler warn */
19208                 U8 bits_differing = 0;
19209                 Size_t full_cp_count = 0;
19210                 bool first_time = TRUE;
19211
19212                 /* Go through the bytes and find the bit positions that differ
19213                  * */
19214                 invlist_iterinit(cp_list);
19215                 while (invlist_iternext(cp_list, &this_start, &this_end)) {
19216                     unsigned int i = this_start;
19217
19218                     if (first_time) {
19219                         if (! UVCHR_IS_INVARIANT(i)) {
19220                             goto done_anyofm;
19221                         }
19222
19223                         first_time = FALSE;
19224                         lowest_cp = this_start;
19225
19226                         /* We have set up the code point to compare with.
19227                          * Don't compare it with itself */
19228                         i++;
19229                     }
19230
19231                     /* Find the bit positions that differ from the lowest code
19232                      * point in the node.  Keep track of all such positions by
19233                      * OR'ing */
19234                     for (; i <= this_end; i++) {
19235                         if (! UVCHR_IS_INVARIANT(i)) {
19236                             goto done_anyofm;
19237                         }
19238
19239                         bits_differing  |= i ^ lowest_cp;
19240                     }
19241
19242                     full_cp_count += this_end - this_start + 1;
19243                 }
19244
19245                 /* At the end of the loop, we count how many bits differ from
19246                  * the bits in lowest code point, call the count 'd'.  If the
19247                  * set we found contains 2**d elements, it is the closure of
19248                  * all code points that differ only in those bit positions.  To
19249                  * convince yourself of that, first note that the number in the
19250                  * closure must be a power of 2, which we test for.  The only
19251                  * way we could have that count and it be some differing set,
19252                  * is if we got some code points that don't differ from the
19253                  * lowest code point in any position, but do differ from each
19254                  * other in some other position.  That means one code point has
19255                  * a 1 in that position, and another has a 0.  But that would
19256                  * mean that one of them differs from the lowest code point in
19257                  * that position, which possibility we've already excluded.  */
19258                 if (  (inverted || full_cp_count > 1)
19259                     && full_cp_count == 1U << PL_bitcount[bits_differing])
19260                 {
19261                     U8 ANYOFM_mask;
19262
19263                     op = ANYOFM + inverted;;
19264
19265                     /* We need to make the bits that differ be 0's */
19266                     ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */
19267
19268                     /* The argument is the lowest code point */
19269                     ret = reganode(pRExC_state, op, lowest_cp);
19270                     FLAGS(REGNODE_p(ret)) = ANYOFM_mask;
19271                 }
19272
19273               done_anyofm:
19274                 invlist_iterfinish(cp_list);
19275             }
19276
19277             if (inverted) {
19278                 _invlist_invert(cp_list);
19279             }
19280
19281             if (op != END) {
19282                 goto not_anyof;
19283             }
19284
19285             /* XXX We could create an ANYOFR_LOW node here if we saved above if
19286              * all were invariants, it wasn't inverted, and there is a single
19287              * range.  This would be faster than some of the posix nodes we
19288              * create below like /\d/a, but would be twice the size.  Without
19289              * having actually measured the gain, khw doesn't think the
19290              * tradeoff is really worth it */
19291         }
19292
19293         if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) {
19294             PERL_UINT_FAST8_T type;
19295             SV * intersection = NULL;
19296             SV* d_invlist = NULL;
19297
19298             /* See if this matches any of the POSIX classes.  The POSIXA and
19299              * POSIXD ones are about the same speed as ANYOF ops, but take less
19300              * room; the ones that have above-Latin1 code point matches are
19301              * somewhat faster than ANYOF.  */
19302
19303             for (type = POSIXA; type >= POSIXD; type--) {
19304                 int posix_class;
19305
19306                 if (type == POSIXL) {   /* But not /l posix classes */
19307                     continue;
19308                 }
19309
19310                 for (posix_class = 0;
19311                      posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
19312                      posix_class++)
19313                 {
19314                     SV** our_code_points = &cp_list;
19315                     SV** official_code_points;
19316                     int try_inverted;
19317
19318                     if (type == POSIXA) {
19319                         official_code_points = &PL_Posix_ptrs[posix_class];
19320                     }
19321                     else {
19322                         official_code_points = &PL_XPosix_ptrs[posix_class];
19323                     }
19324
19325                     /* Skip non-existent classes of this type.  e.g. \v only
19326                      * has an entry in PL_XPosix_ptrs */
19327                     if (! *official_code_points) {
19328                         continue;
19329                     }
19330
19331                     /* Try both the regular class, and its inversion */
19332                     for (try_inverted = 0; try_inverted < 2; try_inverted++) {
19333                         bool this_inverted = invert ^ try_inverted;
19334
19335                         if (type != POSIXD) {
19336
19337                             /* This class that isn't /d can't match if we have
19338                              * /d dependencies */
19339                             if (has_runtime_dependency
19340                                                     & HAS_D_RUNTIME_DEPENDENCY)
19341                             {
19342                                 continue;
19343                             }
19344                         }
19345                         else /* is /d */ if (! this_inverted) {
19346
19347                             /* /d classes don't match anything non-ASCII below
19348                              * 256 unconditionally (which cp_list contains) */
19349                             _invlist_intersection(cp_list, PL_UpperLatin1,
19350                                                            &intersection);
19351                             if (_invlist_len(intersection) != 0) {
19352                                 continue;
19353                             }
19354
19355                             SvREFCNT_dec(d_invlist);
19356                             d_invlist = invlist_clone(cp_list, NULL);
19357
19358                             /* But under UTF-8 it turns into using /u rules.
19359                              * Add the things it matches under these conditions
19360                              * so that we check below that these are identical
19361                              * to what the tested class should match */
19362                             if (upper_latin1_only_utf8_matches) {
19363                                 _invlist_union(
19364                                             d_invlist,
19365                                             upper_latin1_only_utf8_matches,
19366                                             &d_invlist);
19367                             }
19368                             our_code_points = &d_invlist;
19369                         }
19370                         else {  /* POSIXD, inverted.  If this doesn't have this
19371                                    flag set, it isn't /d. */
19372                             if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
19373                             {
19374                                 continue;
19375                             }
19376                             our_code_points = &cp_list;
19377                         }
19378
19379                         /* Here, have weeded out some things.  We want to see
19380                          * if the list of characters this node contains
19381                          * ('*our_code_points') precisely matches those of the
19382                          * class we are currently checking against
19383                          * ('*official_code_points'). */
19384                         if (_invlistEQ(*our_code_points,
19385                                        *official_code_points,
19386                                        try_inverted))
19387                         {
19388                             /* Here, they precisely match.  Optimize this ANYOF
19389                              * node into its equivalent POSIX one of the
19390                              * correct type, possibly inverted */
19391                             ret = reg_node(pRExC_state, (try_inverted)
19392                                                         ? type + NPOSIXA
19393                                                                 - POSIXA
19394                                                         : type);
19395                             FLAGS(REGNODE_p(ret)) = posix_class;
19396                             SvREFCNT_dec(d_invlist);
19397                             SvREFCNT_dec(intersection);
19398                             goto not_anyof;
19399                         }
19400                     }
19401                 }
19402             }
19403             SvREFCNT_dec(d_invlist);
19404             SvREFCNT_dec(intersection);
19405         }
19406
19407         /* If it is a single contiguous range, ANYOFR is an efficient regnode,
19408          * both in size and speed.  Currently, a 20 bit range base (smallest
19409          * code point in the range), and a 12 bit maximum delta are packed into
19410          * a 32 bit word.  This allows for using it on all of the Unicode code
19411          * points except for the highest plane, which is only for private use
19412          * code points.  khw doubts that a bigger delta is likely in real world
19413          * applications */
19414         if (     single_range
19415             && ! has_runtime_dependency
19416             &&   anyof_flags == 0
19417             &&   start[0] < (1 << ANYOFR_BASE_BITS)
19418             &&   end[0] - start[0]
19419                     < ((1U << (sizeof(((struct regnode_1 *)NULL)->arg1)
19420                                    * CHARBITS - ANYOFR_BASE_BITS))))
19421
19422         {
19423             U8 low_utf8[UTF8_MAXBYTES+1];
19424             U8 high_utf8[UTF8_MAXBYTES+1];
19425
19426             ret = reganode(pRExC_state, ANYOFR,
19427                         (start[0] | (end[0] - start[0]) << ANYOFR_BASE_BITS));
19428
19429             /* Place the lowest UTF-8 start byte in the flags field, so as to
19430              * allow efficient ruling out at run time of many possible inputs.
19431              * */
19432             (void) uvchr_to_utf8(low_utf8, start[0]);
19433             (void) uvchr_to_utf8(high_utf8, end[0]);
19434
19435             /* If all code points share the same first byte, this can be an
19436              * ANYOFRb.  Otherwise store the lowest UTF-8 start byte which can
19437              * quickly rule out many inputs at run-time without having to
19438              * compute the code point from UTF-8.  For EBCDIC, we use I8, as
19439              * not doing that transformation would not rule out nearly so many
19440              * things */
19441             if (low_utf8[0] == high_utf8[0]) {
19442                 OP(REGNODE_p(ret)) = ANYOFRb;
19443                 ANYOF_FLAGS(REGNODE_p(ret)) = low_utf8[0];
19444             }
19445             else {
19446                 ANYOF_FLAGS(REGNODE_p(ret))
19447                                     = NATIVE_UTF8_TO_I8(low_utf8[0]);
19448             }
19449
19450             goto not_anyof;
19451         }
19452
19453         /* If didn't find an optimization and there is no need for a bitmap,
19454          * optimize to indicate that */
19455         if (     start[0] >= NUM_ANYOF_CODE_POINTS
19456             && ! LOC
19457             && ! upper_latin1_only_utf8_matches
19458             &&   anyof_flags == 0)
19459         {
19460             U8 low_utf8[UTF8_MAXBYTES+1];
19461             UV highest_cp = invlist_highest(cp_list);
19462
19463             /* Currently the maximum allowed code point by the system is
19464              * IV_MAX.  Higher ones are reserved for future internal use.  This
19465              * particular regnode can be used for higher ones, but we can't
19466              * calculate the code point of those.  IV_MAX suffices though, as
19467              * it will be a large first byte */
19468             Size_t low_len = uvchr_to_utf8(low_utf8, MIN(start[0], IV_MAX))
19469                            - low_utf8;
19470
19471             /* We store the lowest possible first byte of the UTF-8
19472              * representation, using the flags field.  This allows for quick
19473              * ruling out of some inputs without having to convert from UTF-8
19474              * to code point.  For EBCDIC, we use I8, as not doing that
19475              * transformation would not rule out nearly so many things */
19476             anyof_flags = NATIVE_UTF8_TO_I8(low_utf8[0]);
19477
19478             op = ANYOFH;
19479
19480             /* If the first UTF-8 start byte for the highest code point in the
19481              * range is suitably small, we may be able to get an upper bound as
19482              * well */
19483             if (highest_cp <= IV_MAX) {
19484                 U8 high_utf8[UTF8_MAXBYTES+1];
19485                 Size_t high_len = uvchr_to_utf8(high_utf8, highest_cp)
19486                                 - high_utf8;
19487
19488                 /* If the lowest and highest are the same, we can get an exact
19489                  * first byte instead of a just minimum or even a sequence of
19490                  * exact leading bytes.  We signal these with different
19491                  * regnodes */
19492                 if (low_utf8[0] == high_utf8[0]) {
19493                     Size_t len = find_first_differing_byte_pos(low_utf8,
19494                                                                high_utf8,
19495                                                        MIN(low_len, high_len));
19496
19497                     if (len == 1) {
19498
19499                         /* No need to convert to I8 for EBCDIC as this is an
19500                          * exact match */
19501                         anyof_flags = low_utf8[0];
19502                         op = ANYOFHb;
19503                     }
19504                     else {
19505                         op = ANYOFHs;
19506                         ret = regnode_guts(pRExC_state, op,
19507                                            regarglen[op] + STR_SZ(len),
19508                                            "anyofhs");
19509                         FILL_NODE(ret, op);
19510                         ((struct regnode_anyofhs *) REGNODE_p(ret))->str_len
19511                                                                         = len;
19512                         Copy(low_utf8,  /* Add the common bytes */
19513                            ((struct regnode_anyofhs *) REGNODE_p(ret))->string,
19514                            len, U8);
19515                         RExC_emit += NODE_SZ_STR(REGNODE_p(ret));
19516                         set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19517                                                   NULL, only_utf8_locale_list);
19518                         goto not_anyof;
19519                     }
19520                 }
19521                 else if (NATIVE_UTF8_TO_I8(high_utf8[0]) <= MAX_ANYOF_HRx_BYTE)
19522                 {
19523
19524                     /* Here, the high byte is not the same as the low, but is
19525                      * small enough that its reasonable to have a loose upper
19526                      * bound, which is packed in with the strict lower bound.
19527                      * See comments at the definition of MAX_ANYOF_HRx_BYTE.
19528                      * On EBCDIC platforms, I8 is used.  On ASCII platforms I8
19529                      * is the same thing as UTF-8 */
19530
19531                     U8 bits = 0;
19532                     U8 max_range_diff = MAX_ANYOF_HRx_BYTE - anyof_flags;
19533                     U8 range_diff = NATIVE_UTF8_TO_I8(high_utf8[0])
19534                                   - anyof_flags;
19535
19536                     if (range_diff <= max_range_diff / 8) {
19537                         bits = 3;
19538                     }
19539                     else if (range_diff <= max_range_diff / 4) {
19540                         bits = 2;
19541                     }
19542                     else if (range_diff <= max_range_diff / 2) {
19543                         bits = 1;
19544                     }
19545                     anyof_flags = (anyof_flags - 0xC0) << 2 | bits;
19546                     op = ANYOFHr;
19547                 }
19548             }
19549
19550             goto done_finding_op;
19551         }
19552     }   /* End of seeing if can optimize it into a different node */
19553
19554   is_anyof: /* It's going to be an ANYOF node. */
19555     op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY)
19556          ? ANYOFD
19557          : ((posixl)
19558             ? ANYOFPOSIXL
19559             : ((LOC)
19560                ? ANYOFL
19561                : ANYOF));
19562
19563   done_finding_op:
19564
19565     ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof");
19566     FILL_NODE(ret, op);        /* We set the argument later */
19567     RExC_emit += 1 + regarglen[op];
19568     ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags;
19569
19570     /* Here, <cp_list> contains all the code points we can determine at
19571      * compile time that match under all conditions.  Go through it, and
19572      * for things that belong in the bitmap, put them there, and delete from
19573      * <cp_list>.  While we are at it, see if everything above 255 is in the
19574      * list, and if so, set a flag to speed up execution */
19575
19576     populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list);
19577
19578     if (posixl) {
19579         ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl);
19580     }
19581
19582     if (invert) {
19583         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT;
19584     }
19585
19586     /* Here, the bitmap has been populated with all the Latin1 code points that
19587      * always match.  Can now add to the overall list those that match only
19588      * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>).
19589      * */
19590     if (upper_latin1_only_utf8_matches) {
19591         if (cp_list) {
19592             _invlist_union(cp_list,
19593                            upper_latin1_only_utf8_matches,
19594                            &cp_list);
19595             SvREFCNT_dec_NN(upper_latin1_only_utf8_matches);
19596         }
19597         else {
19598             cp_list = upper_latin1_only_utf8_matches;
19599         }
19600         ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
19601     }
19602
19603     set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list,
19604                   (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
19605                    ? listsv
19606                    : NULL,
19607                   only_utf8_locale_list);
19608     SvREFCNT_dec(cp_list);;
19609     SvREFCNT_dec(only_utf8_locale_list);
19610     return ret;
19611
19612   not_anyof:
19613
19614     /* Here, the node is getting optimized into something that's not an ANYOF
19615      * one.  Finish up. */
19616
19617     Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start,
19618                                            RExC_parse - orig_parse);;
19619     SvREFCNT_dec(cp_list);;
19620     SvREFCNT_dec(only_utf8_locale_list);
19621     return ret;
19622 }
19623
19624 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
19625
19626 STATIC void
19627 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
19628                 regnode* const node,
19629                 SV* const cp_list,
19630                 SV* const runtime_defns,
19631                 SV* const only_utf8_locale_list)
19632 {
19633     /* Sets the arg field of an ANYOF-type node 'node', using information about
19634      * the node passed-in.  If there is nothing outside the node's bitmap, the
19635      * arg is set to ANYOF_ONLY_HAS_BITMAP.  Otherwise, it sets the argument to
19636      * the count returned by add_data(), having allocated and stored an array,
19637      * av, as follows:
19638      *
19639      *  av[0] stores the inversion list defining this class as far as known at
19640      *        this time, or PL_sv_undef if nothing definite is now known.
19641      *  av[1] stores the inversion list of code points that match only if the
19642      *        current locale is UTF-8, or if none, PL_sv_undef if there is an
19643      *        av[2], or no entry otherwise.
19644      *  av[2] stores the list of user-defined properties whose subroutine
19645      *        definitions aren't known at this time, or no entry if none. */
19646
19647     UV n;
19648
19649     PERL_ARGS_ASSERT_SET_ANYOF_ARG;
19650
19651     if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
19652         assert(! (ANYOF_FLAGS(node)
19653                 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
19654         ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
19655     }
19656     else {
19657         AV * const av = newAV();
19658         SV *rv;
19659
19660         if (cp_list) {
19661             av_store(av, INVLIST_INDEX, SvREFCNT_inc_NN(cp_list));
19662         }
19663
19664         if (only_utf8_locale_list) {
19665             av_store(av, ONLY_LOCALE_MATCHES_INDEX,
19666                                      SvREFCNT_inc_NN(only_utf8_locale_list));
19667         }
19668
19669         if (runtime_defns) {
19670             av_store(av, DEFERRED_USER_DEFINED_INDEX,
19671                          SvREFCNT_inc_NN(runtime_defns));
19672         }
19673
19674         rv = newRV_noinc(MUTABLE_SV(av));
19675         n = add_data(pRExC_state, STR_WITH_LEN("s"));
19676         RExC_rxi->data->data[n] = (void*)rv;
19677         ARG_SET(node, n);
19678     }
19679 }
19680
19681 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
19682 SV *
19683 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
19684                                         const regnode* node,
19685                                         bool doinit,
19686                                         SV** listsvp,
19687                                         SV** only_utf8_locale_ptr,
19688                                         SV** output_invlist)
19689
19690 {
19691     /* For internal core use only.
19692      * Returns the inversion list for the input 'node' in the regex 'prog'.
19693      * If <doinit> is 'true', will attempt to create the inversion list if not
19694      *    already done.
19695      * If <listsvp> is non-null, will return the printable contents of the
19696      *    property definition.  This can be used to get debugging information
19697      *    even before the inversion list exists, by calling this function with
19698      *    'doinit' set to false, in which case the components that will be used
19699      *    to eventually create the inversion list are returned  (in a printable
19700      *    form).
19701      * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to
19702      *    store an inversion list of code points that should match only if the
19703      *    execution-time locale is a UTF-8 one.
19704      * If <output_invlist> is not NULL, it is where this routine is to store an
19705      *    inversion list of the code points that would be instead returned in
19706      *    <listsvp> if this were NULL.  Thus, what gets output in <listsvp>
19707      *    when this parameter is used, is just the non-code point data that
19708      *    will go into creating the inversion list.  This currently should be just
19709      *    user-defined properties whose definitions were not known at compile
19710      *    time.  Using this parameter allows for easier manipulation of the
19711      *    inversion list's data by the caller.  It is illegal to call this
19712      *    function with this parameter set, but not <listsvp>
19713      *
19714      * Tied intimately to how S_set_ANYOF_arg sets up the data structure.  Note
19715      * that, in spite of this function's name, the inversion list it returns
19716      * may include the bitmap data as well */
19717
19718     SV *si  = NULL;         /* Input initialization string */
19719     SV* invlist = NULL;
19720
19721     RXi_GET_DECL(prog, progi);
19722     const struct reg_data * const data = prog ? progi->data : NULL;
19723
19724     PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
19725     assert(! output_invlist || listsvp);
19726
19727     if (data && data->count) {
19728         const U32 n = ARG(node);
19729
19730         if (data->what[n] == 's') {
19731             SV * const rv = MUTABLE_SV(data->data[n]);
19732             AV * const av = MUTABLE_AV(SvRV(rv));
19733             SV **const ary = AvARRAY(av);
19734
19735             invlist = ary[INVLIST_INDEX];
19736
19737             if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) {
19738                 *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX];
19739             }
19740
19741             if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) {
19742                 si = ary[DEFERRED_USER_DEFINED_INDEX];
19743             }
19744
19745             if (doinit && (si || invlist)) {
19746                 if (si) {
19747                     bool user_defined;
19748                     SV * msg = newSVpvs_flags("", SVs_TEMP);
19749
19750                     SV * prop_definition = handle_user_defined_property(
19751                             "", 0, FALSE,   /* There is no \p{}, \P{} */
19752                             SvPVX_const(si)[1] - '0',   /* /i or not has been
19753                                                            stored here for just
19754                                                            this occasion */
19755                             TRUE,           /* run time */
19756                             FALSE,          /* This call must find the defn */
19757                             si,             /* The property definition  */
19758                             &user_defined,
19759                             msg,
19760                             0               /* base level call */
19761                            );
19762
19763                     if (SvCUR(msg)) {
19764                         assert(prop_definition == NULL);
19765
19766                         Perl_croak(aTHX_ "%" UTF8f,
19767                                 UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg)));
19768                     }
19769
19770                     if (invlist) {
19771                         _invlist_union(invlist, prop_definition, &invlist);
19772                         SvREFCNT_dec_NN(prop_definition);
19773                     }
19774                     else {
19775                         invlist = prop_definition;
19776                     }
19777
19778                     STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX);
19779                     STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX);
19780
19781                     ary[INVLIST_INDEX] = invlist;
19782                     av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX])
19783                                  ? ONLY_LOCALE_MATCHES_INDEX
19784                                  : INVLIST_INDEX);
19785                     si = NULL;
19786                 }
19787             }
19788         }
19789     }
19790
19791     /* If requested, return a printable version of what this ANYOF node matches
19792      * */
19793     if (listsvp) {
19794         SV* matches_string = NULL;
19795
19796         /* This function can be called at compile-time, before everything gets
19797          * resolved, in which case we return the currently best available
19798          * information, which is the string that will eventually be used to do
19799          * that resolving, 'si' */
19800         if (si) {
19801             /* Here, we only have 'si' (and possibly some passed-in data in
19802              * 'invlist', which is handled below)  If the caller only wants
19803              * 'si', use that.  */
19804             if (! output_invlist) {
19805                 matches_string = newSVsv(si);
19806             }
19807             else {
19808                 /* But if the caller wants an inversion list of the node, we
19809                  * need to parse 'si' and place as much as possible in the
19810                  * desired output inversion list, making 'matches_string' only
19811                  * contain the currently unresolvable things */
19812                 const char *si_string = SvPVX(si);
19813                 STRLEN remaining = SvCUR(si);
19814                 UV prev_cp = 0;
19815                 U8 count = 0;
19816
19817                 /* Ignore everything before and including the first new-line */
19818                 si_string = (const char *) memchr(si_string, '\n', SvCUR(si));
19819                 assert (si_string != NULL);
19820                 si_string++;
19821                 remaining = SvPVX(si) + SvCUR(si) - si_string;
19822
19823                 while (remaining > 0) {
19824
19825                     /* The data consists of just strings defining user-defined
19826                      * property names, but in prior incarnations, and perhaps
19827                      * somehow from pluggable regex engines, it could still
19828                      * hold hex code point definitions.  Each component of a
19829                      * range would be separated by a tab, and each range by a
19830                      * new-line.  If these are found, instead add them to the
19831                      * inversion list */
19832                     I32 grok_flags =  PERL_SCAN_SILENT_ILLDIGIT
19833                                      |PERL_SCAN_SILENT_NON_PORTABLE;
19834                     STRLEN len = remaining;
19835                     UV cp = grok_hex(si_string, &len, &grok_flags, NULL);
19836
19837                     /* If the hex decode routine found something, it should go
19838                      * up to the next \n */
19839                     if (   *(si_string + len) == '\n') {
19840                         if (count) {    /* 2nd code point on line */
19841                             *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp);
19842                         }
19843                         else {
19844                             *output_invlist = add_cp_to_invlist(*output_invlist, cp);
19845                         }
19846                         count = 0;
19847                         goto prepare_for_next_iteration;
19848                     }
19849
19850                     /* If the hex decode was instead for the lower range limit,
19851                      * save it, and go parse the upper range limit */
19852                     if (*(si_string + len) == '\t') {
19853                         assert(count == 0);
19854
19855                         prev_cp = cp;
19856                         count = 1;
19857                       prepare_for_next_iteration:
19858                         si_string += len + 1;
19859                         remaining -= len + 1;
19860                         continue;
19861                     }
19862
19863                     /* Here, didn't find a legal hex number.  Just add the text
19864                      * from here up to the next \n, omitting any trailing
19865                      * markers. */
19866
19867                     remaining -= len;
19868                     len = strcspn(si_string,
19869                                         DEFERRED_COULD_BE_OFFICIAL_MARKERs "\n");
19870                     remaining -= len;
19871                     if (matches_string) {
19872                         sv_catpvn(matches_string, si_string, len);
19873                     }
19874                     else {
19875                         matches_string = newSVpvn(si_string, len);
19876                     }
19877                     sv_catpvs(matches_string, " ");
19878
19879                     si_string += len;
19880                     if (   remaining
19881                         && UCHARAT(si_string)
19882                                             == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
19883                     {
19884                         si_string++;
19885                         remaining--;
19886                     }
19887                     if (remaining && UCHARAT(si_string) == '\n') {
19888                         si_string++;
19889                         remaining--;
19890                     }
19891                 } /* end of loop through the text */
19892
19893                 assert(matches_string);
19894                 if (SvCUR(matches_string)) {  /* Get rid of trailing blank */
19895                     SvCUR_set(matches_string, SvCUR(matches_string) - 1);
19896                 }
19897             } /* end of has an 'si' */
19898         }
19899
19900         /* Add the stuff that's already known */
19901         if (invlist) {
19902
19903             /* Again, if the caller doesn't want the output inversion list, put
19904              * everything in 'matches-string' */
19905             if (! output_invlist) {
19906                 if ( ! matches_string) {
19907                     matches_string = newSVpvs("\n");
19908                 }
19909                 sv_catsv(matches_string, invlist_contents(invlist,
19910                                                   TRUE /* traditional style */
19911                                                   ));
19912             }
19913             else if (! *output_invlist) {
19914                 *output_invlist = invlist_clone(invlist, NULL);
19915             }
19916             else {
19917                 _invlist_union(*output_invlist, invlist, output_invlist);
19918             }
19919         }
19920
19921         *listsvp = matches_string;
19922     }
19923
19924     return invlist;
19925 }
19926 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
19927
19928 /* reg_skipcomment()
19929
19930    Absorbs an /x style # comment from the input stream,
19931    returning a pointer to the first character beyond the comment, or if the
19932    comment terminates the pattern without anything following it, this returns
19933    one past the final character of the pattern (in other words, RExC_end) and
19934    sets the REG_RUN_ON_COMMENT_SEEN flag.
19935
19936    Note it's the callers responsibility to ensure that we are
19937    actually in /x mode
19938
19939 */
19940
19941 PERL_STATIC_INLINE char*
19942 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
19943 {
19944     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
19945
19946     assert(*p == '#');
19947
19948     while (p < RExC_end) {
19949         if (*(++p) == '\n') {
19950             return p+1;
19951         }
19952     }
19953
19954     /* we ran off the end of the pattern without ending the comment, so we have
19955      * to add an \n when wrapping */
19956     RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
19957     return p;
19958 }
19959
19960 STATIC void
19961 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
19962                                 char ** p,
19963                                 const bool force_to_xmod
19964                          )
19965 {
19966     /* If the text at the current parse position '*p' is a '(?#...)' comment,
19967      * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
19968      * is /x whitespace, advance '*p' so that on exit it points to the first
19969      * byte past all such white space and comments */
19970
19971     const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
19972
19973     PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
19974
19975     assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
19976
19977     for (;;) {
19978         if (RExC_end - (*p) >= 3
19979             && *(*p)     == '('
19980             && *(*p + 1) == '?'
19981             && *(*p + 2) == '#')
19982         {
19983             while (*(*p) != ')') {
19984                 if ((*p) == RExC_end)
19985                     FAIL("Sequence (?#... not terminated");
19986                 (*p)++;
19987             }
19988             (*p)++;
19989             continue;
19990         }
19991
19992         if (use_xmod) {
19993             const char * save_p = *p;
19994             while ((*p) < RExC_end) {
19995                 STRLEN len;
19996                 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
19997                     (*p) += len;
19998                 }
19999                 else if (*(*p) == '#') {
20000                     (*p) = reg_skipcomment(pRExC_state, (*p));
20001                 }
20002                 else {
20003                     break;
20004                 }
20005             }
20006             if (*p != save_p) {
20007                 continue;
20008             }
20009         }
20010
20011         break;
20012     }
20013
20014     return;
20015 }
20016
20017 /* nextchar()
20018
20019    Advances the parse position by one byte, unless that byte is the beginning
20020    of a '(?#...)' style comment, or is /x whitespace and /x is in effect.  In
20021    those two cases, the parse position is advanced beyond all such comments and
20022    white space.
20023
20024    This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
20025 */
20026
20027 STATIC void
20028 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
20029 {
20030     PERL_ARGS_ASSERT_NEXTCHAR;
20031
20032     if (RExC_parse < RExC_end) {
20033         assert(   ! UTF
20034                || UTF8_IS_INVARIANT(*RExC_parse)
20035                || UTF8_IS_START(*RExC_parse));
20036
20037         RExC_parse += (UTF)
20038                       ? UTF8_SAFE_SKIP(RExC_parse, RExC_end)
20039                       : 1;
20040
20041         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
20042                                 FALSE /* Don't force /x */ );
20043     }
20044 }
20045
20046 STATIC void
20047 S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size)
20048 {
20049     /* 'size' is the delta number of smallest regnode equivalents to add or
20050      * subtract from the current memory allocated to the regex engine being
20051      * constructed. */
20052
20053     PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE;
20054
20055     RExC_size += size;
20056
20057     Renewc(RExC_rxi,
20058            sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode),
20059                                                 /* +1 for REG_MAGIC */
20060            char,
20061            regexp_internal);
20062     if ( RExC_rxi == NULL )
20063         FAIL("Regexp out of space");
20064     RXi_SET(RExC_rx, RExC_rxi);
20065
20066     RExC_emit_start = RExC_rxi->program;
20067     if (size > 0) {
20068         Zero(REGNODE_p(RExC_emit), size, regnode);
20069     }
20070
20071 #ifdef RE_TRACK_PATTERN_OFFSETS
20072     Renew(RExC_offsets, 2*RExC_size+1, U32);
20073     if (size > 0) {
20074         Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32);
20075     }
20076     RExC_offsets[0] = RExC_size;
20077 #endif
20078 }
20079
20080 STATIC regnode_offset
20081 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
20082 {
20083     /* Allocate a regnode for 'op', with 'extra_size' extra (smallest) regnode
20084      * equivalents space.  It aligns and increments RExC_size
20085      *
20086      * It returns the regnode's offset into the regex engine program */
20087
20088     const regnode_offset ret = RExC_emit;
20089
20090     GET_RE_DEBUG_FLAGS_DECL;
20091
20092     PERL_ARGS_ASSERT_REGNODE_GUTS;
20093
20094     SIZE_ALIGN(RExC_size);
20095     change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size);
20096     NODE_ALIGN_FILL(REGNODE_p(ret));
20097 #ifndef RE_TRACK_PATTERN_OFFSETS
20098     PERL_UNUSED_ARG(name);
20099     PERL_UNUSED_ARG(op);
20100 #else
20101     assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF);
20102
20103     if (RExC_offsets) {         /* MJD */
20104         MJD_OFFSET_DEBUG(
20105               ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n",
20106               name, __LINE__,
20107               PL_reg_name[op],
20108               (UV)(RExC_emit) > RExC_offsets[0]
20109                 ? "Overwriting end of array!\n" : "OK",
20110               (UV)(RExC_emit),
20111               (UV)(RExC_parse - RExC_start),
20112               (UV)RExC_offsets[0]));
20113         Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END));
20114     }
20115 #endif
20116     return(ret);
20117 }
20118
20119 /*
20120 - reg_node - emit a node
20121 */
20122 STATIC regnode_offset /* Location. */
20123 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
20124 {
20125     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
20126     regnode_offset ptr = ret;
20127
20128     PERL_ARGS_ASSERT_REG_NODE;
20129
20130     assert(regarglen[op] == 0);
20131
20132     FILL_ADVANCE_NODE(ptr, op);
20133     RExC_emit = ptr;
20134     return(ret);
20135 }
20136
20137 /*
20138 - reganode - emit a node with an argument
20139 */
20140 STATIC regnode_offset /* Location. */
20141 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
20142 {
20143     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
20144     regnode_offset ptr = ret;
20145
20146     PERL_ARGS_ASSERT_REGANODE;
20147
20148     /* ANYOF are special cased to allow non-length 1 args */
20149     assert(regarglen[op] == 1);
20150
20151     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
20152     RExC_emit = ptr;
20153     return(ret);
20154 }
20155
20156 STATIC regnode_offset
20157 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
20158 {
20159     /* emit a node with U32 and I32 arguments */
20160
20161     const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
20162     regnode_offset ptr = ret;
20163
20164     PERL_ARGS_ASSERT_REG2LANODE;
20165
20166     assert(regarglen[op] == 2);
20167
20168     FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
20169     RExC_emit = ptr;
20170     return(ret);
20171 }
20172
20173 /*
20174 - reginsert - insert an operator in front of already-emitted operand
20175 *
20176 * That means that on exit 'operand' is the offset of the newly inserted
20177 * operator, and the original operand has been relocated.
20178 *
20179 * IMPORTANT NOTE - it is the *callers* responsibility to correctly
20180 * set up NEXT_OFF() of the inserted node if needed. Something like this:
20181 *
20182 *   reginsert(pRExC, OPFAIL, orig_emit, depth+1);
20183 *   NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE;
20184 *
20185 * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well.
20186 */
20187 STATIC void
20188 S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op,
20189                   const regnode_offset operand, const U32 depth)
20190 {
20191     regnode *src;
20192     regnode *dst;
20193     regnode *place;
20194     const int offset = regarglen[(U8)op];
20195     const int size = NODE_STEP_REGNODE + offset;
20196     GET_RE_DEBUG_FLAGS_DECL;
20197
20198     PERL_ARGS_ASSERT_REGINSERT;
20199     PERL_UNUSED_CONTEXT;
20200     PERL_UNUSED_ARG(depth);
20201 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
20202     DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]);
20203     assert(!RExC_study_started); /* I believe we should never use reginsert once we have started
20204                                     studying. If this is wrong then we need to adjust RExC_recurse
20205                                     below like we do with RExC_open_parens/RExC_close_parens. */
20206     change_engine_size(pRExC_state, (Ptrdiff_t) size);
20207     src = REGNODE_p(RExC_emit);
20208     RExC_emit += size;
20209     dst = REGNODE_p(RExC_emit);
20210
20211     /* If we are in a "count the parentheses" pass, the numbers are unreliable,
20212      * and [perl #133871] shows this can lead to problems, so skip this
20213      * realignment of parens until a later pass when they are reliable */
20214     if (! IN_PARENS_PASS && RExC_open_parens) {
20215         int paren;
20216         /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/
20217         /* remember that RExC_npar is rex->nparens + 1,
20218          * iow it is 1 more than the number of parens seen in
20219          * the pattern so far. */
20220         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
20221             /* note, RExC_open_parens[0] is the start of the
20222              * regex, it can't move. RExC_close_parens[0] is the end
20223              * of the regex, it *can* move. */
20224             if ( paren && RExC_open_parens[paren] >= operand ) {
20225                 /*DEBUG_PARSE_FMT("open"," - %d", size);*/
20226                 RExC_open_parens[paren] += size;
20227             } else {
20228                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
20229             }
20230             if ( RExC_close_parens[paren] >= operand ) {
20231                 /*DEBUG_PARSE_FMT("close"," - %d", size);*/
20232                 RExC_close_parens[paren] += size;
20233             } else {
20234                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
20235             }
20236         }
20237     }
20238     if (RExC_end_op)
20239         RExC_end_op += size;
20240
20241     while (src > REGNODE_p(operand)) {
20242         StructCopy(--src, --dst, regnode);
20243 #ifdef RE_TRACK_PATTERN_OFFSETS
20244         if (RExC_offsets) {     /* MJD 20010112 */
20245             MJD_OFFSET_DEBUG(
20246                  ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n",
20247                   "reginsert",
20248                   __LINE__,
20249                   PL_reg_name[op],
20250                   (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0]
20251                     ? "Overwriting end of array!\n" : "OK",
20252                   (UV)REGNODE_OFFSET(src),
20253                   (UV)REGNODE_OFFSET(dst),
20254                   (UV)RExC_offsets[0]));
20255             Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src));
20256             Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src));
20257         }
20258 #endif
20259     }
20260
20261     place = REGNODE_p(operand); /* Op node, where operand used to be. */
20262 #ifdef RE_TRACK_PATTERN_OFFSETS
20263     if (RExC_offsets) {         /* MJD */
20264         MJD_OFFSET_DEBUG(
20265               ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n",
20266               "reginsert",
20267               __LINE__,
20268               PL_reg_name[op],
20269               (UV)REGNODE_OFFSET(place) > RExC_offsets[0]
20270               ? "Overwriting end of array!\n" : "OK",
20271               (UV)REGNODE_OFFSET(place),
20272               (UV)(RExC_parse - RExC_start),
20273               (UV)RExC_offsets[0]));
20274         Set_Node_Offset(place, RExC_parse);
20275         Set_Node_Length(place, 1);
20276     }
20277 #endif
20278     src = NEXTOPER(place);
20279     FLAGS(place) = 0;
20280     FILL_NODE(operand, op);
20281
20282     /* Zero out any arguments in the new node */
20283     Zero(src, offset, regnode);
20284 }
20285
20286 /*
20287 - regtail - set the next-pointer at the end of a node chain of p to val.  If
20288             that value won't fit in the space available, instead returns FALSE.
20289             (Except asserts if we can't fit in the largest space the regex
20290             engine is designed for.)
20291 - SEE ALSO: regtail_study
20292 */
20293 STATIC bool
20294 S_regtail(pTHX_ RExC_state_t * pRExC_state,
20295                 const regnode_offset p,
20296                 const regnode_offset val,
20297                 const U32 depth)
20298 {
20299     regnode_offset scan;
20300     GET_RE_DEBUG_FLAGS_DECL;
20301
20302     PERL_ARGS_ASSERT_REGTAIL;
20303 #ifndef DEBUGGING
20304     PERL_UNUSED_ARG(depth);
20305 #endif
20306
20307     /* Find last node. */
20308     scan = (regnode_offset) p;
20309     for (;;) {
20310         regnode * const temp = regnext(REGNODE_p(scan));
20311         DEBUG_PARSE_r({
20312             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
20313             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20314             Perl_re_printf( aTHX_  "~ %s (%d) %s %s\n",
20315                 SvPV_nolen_const(RExC_mysv), scan,
20316                     (temp == NULL ? "->" : ""),
20317                     (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "")
20318             );
20319         });
20320         if (temp == NULL)
20321             break;
20322         scan = REGNODE_OFFSET(temp);
20323     }
20324
20325     assert(val >= scan);
20326     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20327         assert((UV) (val - scan) <= U32_MAX);
20328         ARG_SET(REGNODE_p(scan), val - scan);
20329     }
20330     else {
20331         if (val - scan > U16_MAX) {
20332             /* Populate this with something that won't loop and will likely
20333              * lead to a crash if the caller ignores the failure return, and
20334              * execution continues */
20335             NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20336             return FALSE;
20337         }
20338         NEXT_OFF(REGNODE_p(scan)) = val - scan;
20339     }
20340
20341     return TRUE;
20342 }
20343
20344 #ifdef DEBUGGING
20345 /*
20346 - regtail_study - set the next-pointer at the end of a node chain of p to val.
20347 - Look for optimizable sequences at the same time.
20348 - currently only looks for EXACT chains.
20349
20350 This is experimental code. The idea is to use this routine to perform
20351 in place optimizations on branches and groups as they are constructed,
20352 with the long term intention of removing optimization from study_chunk so
20353 that it is purely analytical.
20354
20355 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
20356 to control which is which.
20357
20358 This used to return a value that was ignored.  It was a problem that it is
20359 #ifdef'd to be another function that didn't return a value.  khw has changed it
20360 so both currently return a pass/fail return.
20361
20362 */
20363 /* TODO: All four parms should be const */
20364
20365 STATIC bool
20366 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p,
20367                       const regnode_offset val, U32 depth)
20368 {
20369     regnode_offset scan;
20370     U8 exact = PSEUDO;
20371 #ifdef EXPERIMENTAL_INPLACESCAN
20372     I32 min = 0;
20373 #endif
20374     GET_RE_DEBUG_FLAGS_DECL;
20375
20376     PERL_ARGS_ASSERT_REGTAIL_STUDY;
20377
20378
20379     /* Find last node. */
20380
20381     scan = p;
20382     for (;;) {
20383         regnode * const temp = regnext(REGNODE_p(scan));
20384 #ifdef EXPERIMENTAL_INPLACESCAN
20385         if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) {
20386             bool unfolded_multi_char;   /* Unexamined in this routine */
20387             if (join_exact(pRExC_state, scan, &min,
20388                            &unfolded_multi_char, 1, REGNODE_p(val), depth+1))
20389                 return TRUE; /* Was return EXACT */
20390         }
20391 #endif
20392         if ( exact ) {
20393             switch (OP(REGNODE_p(scan))) {
20394                 case LEXACT:
20395                 case EXACT:
20396                 case LEXACT_REQ8:
20397                 case EXACT_REQ8:
20398                 case EXACTL:
20399                 case EXACTF:
20400                 case EXACTFU_S_EDGE:
20401                 case EXACTFAA_NO_TRIE:
20402                 case EXACTFAA:
20403                 case EXACTFU:
20404                 case EXACTFU_REQ8:
20405                 case EXACTFLU8:
20406                 case EXACTFUP:
20407                 case EXACTFL:
20408                         if( exact == PSEUDO )
20409                             exact= OP(REGNODE_p(scan));
20410                         else if ( exact != OP(REGNODE_p(scan)) )
20411                             exact= 0;
20412                 case NOTHING:
20413                     break;
20414                 default:
20415                     exact= 0;
20416             }
20417         }
20418         DEBUG_PARSE_r({
20419             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
20420             regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state);
20421             Perl_re_printf( aTHX_  "~ %s (%d) -> %s\n",
20422                 SvPV_nolen_const(RExC_mysv),
20423                 scan,
20424                 PL_reg_name[exact]);
20425         });
20426         if (temp == NULL)
20427             break;
20428         scan = REGNODE_OFFSET(temp);
20429     }
20430     DEBUG_PARSE_r({
20431         DEBUG_PARSE_MSG("");
20432         regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state);
20433         Perl_re_printf( aTHX_
20434                       "~ attach to %s (%" IVdf ") offset to %" IVdf "\n",
20435                       SvPV_nolen_const(RExC_mysv),
20436                       (IV)val,
20437                       (IV)(val - scan)
20438         );
20439     });
20440     if (reg_off_by_arg[OP(REGNODE_p(scan))]) {
20441         assert((UV) (val - scan) <= U32_MAX);
20442         ARG_SET(REGNODE_p(scan), val - scan);
20443     }
20444     else {
20445         if (val - scan > U16_MAX) {
20446             /* Populate this with something that won't loop and will likely
20447              * lead to a crash if the caller ignores the failure return, and
20448              * execution continues */
20449             NEXT_OFF(REGNODE_p(scan)) = U16_MAX;
20450             return FALSE;
20451         }
20452         NEXT_OFF(REGNODE_p(scan)) = val - scan;
20453     }
20454
20455     return TRUE; /* Was 'return exact' */
20456 }
20457 #endif
20458
20459 STATIC SV*
20460 S_get_ANYOFM_contents(pTHX_ const regnode * n) {
20461
20462     /* Returns an inversion list of all the code points matched by the
20463      * ANYOFM/NANYOFM node 'n' */
20464
20465     SV * cp_list = _new_invlist(-1);
20466     const U8 lowest = (U8) ARG(n);
20467     unsigned int i;
20468     U8 count = 0;
20469     U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)];
20470
20471     PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS;
20472
20473     /* Starting with the lowest code point, any code point that ANDed with the
20474      * mask yields the lowest code point is in the set */
20475     for (i = lowest; i <= 0xFF; i++) {
20476         if ((i & FLAGS(n)) == ARG(n)) {
20477             cp_list = add_cp_to_invlist(cp_list, i);
20478             count++;
20479
20480             /* We know how many code points (a power of two) that are in the
20481              * set.  No use looking once we've got that number */
20482             if (count >= needed) break;
20483         }
20484     }
20485
20486     if (OP(n) == NANYOFM) {
20487         _invlist_invert(cp_list);
20488     }
20489     return cp_list;
20490 }
20491
20492 /*
20493  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
20494  */
20495 #ifdef DEBUGGING
20496
20497 static void
20498 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
20499 {
20500     int bit;
20501     int set=0;
20502
20503     ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20504
20505     for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
20506         if (flags & (1<<bit)) {
20507             if (!set++ && lead)
20508                 Perl_re_printf( aTHX_  "%s", lead);
20509             Perl_re_printf( aTHX_  "%s ", PL_reg_intflags_name[bit]);
20510         }
20511     }
20512     if (lead)  {
20513         if (set)
20514             Perl_re_printf( aTHX_  "\n");
20515         else
20516             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
20517     }
20518 }
20519
20520 static void
20521 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
20522 {
20523     int bit;
20524     int set=0;
20525     regex_charset cs;
20526
20527     ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
20528
20529     for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
20530         if (flags & (1<<bit)) {
20531             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
20532                 continue;
20533             }
20534             if (!set++ && lead)
20535                 Perl_re_printf( aTHX_  "%s", lead);
20536             Perl_re_printf( aTHX_  "%s ", PL_reg_extflags_name[bit]);
20537         }
20538     }
20539     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
20540             if (!set++ && lead) {
20541                 Perl_re_printf( aTHX_  "%s", lead);
20542             }
20543             switch (cs) {
20544                 case REGEX_UNICODE_CHARSET:
20545                     Perl_re_printf( aTHX_  "UNICODE");
20546                     break;
20547                 case REGEX_LOCALE_CHARSET:
20548                     Perl_re_printf( aTHX_  "LOCALE");
20549                     break;
20550                 case REGEX_ASCII_RESTRICTED_CHARSET:
20551                     Perl_re_printf( aTHX_  "ASCII-RESTRICTED");
20552                     break;
20553                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
20554                     Perl_re_printf( aTHX_  "ASCII-MORE_RESTRICTED");
20555                     break;
20556                 default:
20557                     Perl_re_printf( aTHX_  "UNKNOWN CHARACTER SET");
20558                     break;
20559             }
20560     }
20561     if (lead)  {
20562         if (set)
20563             Perl_re_printf( aTHX_  "\n");
20564         else
20565             Perl_re_printf( aTHX_  "%s[none-set]\n", lead);
20566     }
20567 }
20568 #endif
20569
20570 void
20571 Perl_regdump(pTHX_ const regexp *r)
20572 {
20573 #ifdef DEBUGGING
20574     int i;
20575     SV * const sv = sv_newmortal();
20576     SV *dsv= sv_newmortal();
20577     RXi_GET_DECL(r, ri);
20578     GET_RE_DEBUG_FLAGS_DECL;
20579
20580     PERL_ARGS_ASSERT_REGDUMP;
20581
20582     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
20583
20584     /* Header fields of interest. */
20585     for (i = 0; i < 2; i++) {
20586         if (r->substrs->data[i].substr) {
20587             RE_PV_QUOTED_DECL(s, 0, dsv,
20588                             SvPVX_const(r->substrs->data[i].substr),
20589                             RE_SV_DUMPLEN(r->substrs->data[i].substr),
20590                             PL_dump_re_max_len);
20591             Perl_re_printf( aTHX_
20592                           "%s %s%s at %" IVdf "..%" UVuf " ",
20593                           i ? "floating" : "anchored",
20594                           s,
20595                           RE_SV_TAIL(r->substrs->data[i].substr),
20596                           (IV)r->substrs->data[i].min_offset,
20597                           (UV)r->substrs->data[i].max_offset);
20598         }
20599         else if (r->substrs->data[i].utf8_substr) {
20600             RE_PV_QUOTED_DECL(s, 1, dsv,
20601                             SvPVX_const(r->substrs->data[i].utf8_substr),
20602                             RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr),
20603                             30);
20604             Perl_re_printf( aTHX_
20605                           "%s utf8 %s%s at %" IVdf "..%" UVuf " ",
20606                           i ? "floating" : "anchored",
20607                           s,
20608                           RE_SV_TAIL(r->substrs->data[i].utf8_substr),
20609                           (IV)r->substrs->data[i].min_offset,
20610                           (UV)r->substrs->data[i].max_offset);
20611         }
20612     }
20613
20614     if (r->check_substr || r->check_utf8)
20615         Perl_re_printf( aTHX_
20616                       (const char *)
20617                       (   r->check_substr == r->substrs->data[1].substr
20618                        && r->check_utf8   == r->substrs->data[1].utf8_substr
20619                        ? "(checking floating" : "(checking anchored"));
20620     if (r->intflags & PREGf_NOSCAN)
20621         Perl_re_printf( aTHX_  " noscan");
20622     if (r->extflags & RXf_CHECK_ALL)
20623         Perl_re_printf( aTHX_  " isall");
20624     if (r->check_substr || r->check_utf8)
20625         Perl_re_printf( aTHX_  ") ");
20626
20627     if (ri->regstclass) {
20628         regprop(r, sv, ri->regstclass, NULL, NULL);
20629         Perl_re_printf( aTHX_  "stclass %s ", SvPVX_const(sv));
20630     }
20631     if (r->intflags & PREGf_ANCH) {
20632         Perl_re_printf( aTHX_  "anchored");
20633         if (r->intflags & PREGf_ANCH_MBOL)
20634             Perl_re_printf( aTHX_  "(MBOL)");
20635         if (r->intflags & PREGf_ANCH_SBOL)
20636             Perl_re_printf( aTHX_  "(SBOL)");
20637         if (r->intflags & PREGf_ANCH_GPOS)
20638             Perl_re_printf( aTHX_  "(GPOS)");
20639         Perl_re_printf( aTHX_ " ");
20640     }
20641     if (r->intflags & PREGf_GPOS_SEEN)
20642         Perl_re_printf( aTHX_  "GPOS:%" UVuf " ", (UV)r->gofs);
20643     if (r->intflags & PREGf_SKIP)
20644         Perl_re_printf( aTHX_  "plus ");
20645     if (r->intflags & PREGf_IMPLICIT)
20646         Perl_re_printf( aTHX_  "implicit ");
20647     Perl_re_printf( aTHX_  "minlen %" IVdf " ", (IV)r->minlen);
20648     if (r->extflags & RXf_EVAL_SEEN)
20649         Perl_re_printf( aTHX_  "with eval ");
20650     Perl_re_printf( aTHX_  "\n");
20651     DEBUG_FLAGS_r({
20652         regdump_extflags("r->extflags: ", r->extflags);
20653         regdump_intflags("r->intflags: ", r->intflags);
20654     });
20655 #else
20656     PERL_ARGS_ASSERT_REGDUMP;
20657     PERL_UNUSED_CONTEXT;
20658     PERL_UNUSED_ARG(r);
20659 #endif  /* DEBUGGING */
20660 }
20661
20662 /* Should be synchronized with ANYOF_ #defines in regcomp.h */
20663 #ifdef DEBUGGING
20664
20665 #  if   _CC_WORDCHAR != 0 || _CC_DIGIT != 1        || _CC_ALPHA != 2    \
20666      || _CC_LOWER != 3    || _CC_UPPER != 4        || _CC_PUNCT != 5    \
20667      || _CC_PRINT != 6    || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8    \
20668      || _CC_CASED != 9    || _CC_SPACE != 10       || _CC_BLANK != 11   \
20669      || _CC_XDIGIT != 12  || _CC_CNTRL != 13       || _CC_ASCII != 14   \
20670      || _CC_VERTSPACE != 15
20671 #   error Need to adjust order of anyofs[]
20672 #  endif
20673 static const char * const anyofs[] = {
20674     "\\w",
20675     "\\W",
20676     "\\d",
20677     "\\D",
20678     "[:alpha:]",
20679     "[:^alpha:]",
20680     "[:lower:]",
20681     "[:^lower:]",
20682     "[:upper:]",
20683     "[:^upper:]",
20684     "[:punct:]",
20685     "[:^punct:]",
20686     "[:print:]",
20687     "[:^print:]",
20688     "[:alnum:]",
20689     "[:^alnum:]",
20690     "[:graph:]",
20691     "[:^graph:]",
20692     "[:cased:]",
20693     "[:^cased:]",
20694     "\\s",
20695     "\\S",
20696     "[:blank:]",
20697     "[:^blank:]",
20698     "[:xdigit:]",
20699     "[:^xdigit:]",
20700     "[:cntrl:]",
20701     "[:^cntrl:]",
20702     "[:ascii:]",
20703     "[:^ascii:]",
20704     "\\v",
20705     "\\V"
20706 };
20707 #endif
20708
20709 /*
20710 - regprop - printable representation of opcode, with run time support
20711 */
20712
20713 void
20714 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
20715 {
20716 #ifdef DEBUGGING
20717     dVAR;
20718     int k;
20719     RXi_GET_DECL(prog, progi);
20720     GET_RE_DEBUG_FLAGS_DECL;
20721
20722     PERL_ARGS_ASSERT_REGPROP;
20723
20724     SvPVCLEAR(sv);
20725
20726     if (OP(o) > REGNODE_MAX) {          /* regnode.type is unsigned */
20727         if (pRExC_state) {  /* This gives more info, if we have it */
20728             FAIL3("panic: corrupted regexp opcode %d > %d",
20729                   (int)OP(o), (int)REGNODE_MAX);
20730         }
20731         else {
20732             Perl_croak(aTHX_ "panic: corrupted regexp opcode %d > %d",
20733                              (int)OP(o), (int)REGNODE_MAX);
20734         }
20735     }
20736     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
20737
20738     k = PL_regkind[OP(o)];
20739
20740     if (k == EXACT) {
20741         sv_catpvs(sv, " ");
20742         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
20743          * is a crude hack but it may be the best for now since
20744          * we have no flag "this EXACTish node was UTF-8"
20745          * --jhi */
20746         pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len,
20747                   PL_colors[0], PL_colors[1],
20748                   PERL_PV_ESCAPE_UNI_DETECT |
20749                   PERL_PV_ESCAPE_NONASCII   |
20750                   PERL_PV_PRETTY_ELLIPSES   |
20751                   PERL_PV_PRETTY_LTGT       |
20752                   PERL_PV_PRETTY_NOCLEAR
20753                   );
20754     } else if (k == TRIE) {
20755         /* print the details of the trie in dumpuntil instead, as
20756          * progi->data isn't available here */
20757         const char op = OP(o);
20758         const U32 n = ARG(o);
20759         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
20760                (reg_ac_data *)progi->data->data[n] :
20761                NULL;
20762         const reg_trie_data * const trie
20763             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
20764
20765         Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]);
20766         DEBUG_TRIE_COMPILE_r({
20767           if (trie->jump)
20768             sv_catpvs(sv, "(JUMP)");
20769           Perl_sv_catpvf(aTHX_ sv,
20770             "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">",
20771             (UV)trie->startstate,
20772             (IV)trie->statecount-1, /* -1 because of the unused 0 element */
20773             (UV)trie->wordcount,
20774             (UV)trie->minlen,
20775             (UV)trie->maxlen,
20776             (UV)TRIE_CHARCOUNT(trie),
20777             (UV)trie->uniquecharcount
20778           );
20779         });
20780         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
20781             sv_catpvs(sv, "[");
20782             (void) put_charclass_bitmap_innards(sv,
20783                                                 ((IS_ANYOF_TRIE(op))
20784                                                  ? ANYOF_BITMAP(o)
20785                                                  : TRIE_BITMAP(trie)),
20786                                                 NULL,
20787                                                 NULL,
20788                                                 NULL,
20789                                                 0,
20790                                                 FALSE
20791                                                );
20792             sv_catpvs(sv, "]");
20793         }
20794     } else if (k == CURLY) {
20795         U32 lo = ARG1(o), hi = ARG2(o);
20796         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
20797             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
20798         Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
20799         if (hi == REG_INFTY)
20800             sv_catpvs(sv, "INFTY");
20801         else
20802             Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
20803         sv_catpvs(sv, "}");
20804     }
20805     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
20806         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
20807     else if (k == REF || k == OPEN || k == CLOSE
20808              || k == GROUPP || OP(o)==ACCEPT)
20809     {
20810         AV *name_list= NULL;
20811         U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
20812         Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno);        /* Parenth number */
20813         if ( RXp_PAREN_NAMES(prog) ) {
20814             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
20815         } else if ( pRExC_state ) {
20816             name_list= RExC_paren_name_list;
20817         }
20818         if (name_list) {
20819             if ( k != REF || (OP(o) < REFN)) {
20820                 SV **name= av_fetch(name_list, parno, 0 );
20821                 if (name)
20822                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20823             }
20824             else {
20825                 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
20826                 I32 *nums=(I32*)SvPVX(sv_dat);
20827                 SV **name= av_fetch(name_list, nums[0], 0 );
20828                 I32 n;
20829                 if (name) {
20830                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
20831                         Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf,
20832                                     (n ? "," : ""), (IV)nums[n]);
20833                     }
20834                     Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20835                 }
20836             }
20837         }
20838         if ( k == REF && reginfo) {
20839             U32 n = ARG(o);  /* which paren pair */
20840             I32 ln = prog->offs[n].start;
20841             if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1)
20842                 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
20843             else if (ln == prog->offs[n].end)
20844                 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
20845             else {
20846                 const char *s = reginfo->strbeg + ln;
20847                 Perl_sv_catpvf(aTHX_ sv, ": ");
20848                 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
20849                     PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
20850             }
20851         }
20852     } else if (k == GOSUB) {
20853         AV *name_list= NULL;
20854         if ( RXp_PAREN_NAMES(prog) ) {
20855             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
20856         } else if ( pRExC_state ) {
20857             name_list= RExC_paren_name_list;
20858         }
20859
20860         /* Paren and offset */
20861         Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o),
20862                 (int)((o + (int)ARG2L(o)) - progi->program) );
20863         if (name_list) {
20864             SV **name= av_fetch(name_list, ARG(o), 0 );
20865             if (name)
20866                 Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name));
20867         }
20868     }
20869     else if (k == LOGICAL)
20870         /* 2: embedded, otherwise 1 */
20871         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
20872     else if (k == ANYOF || k == ANYOFR) {
20873         U8 flags;
20874         char * bitmap;
20875         U32 arg;
20876         bool do_sep = FALSE;    /* Do we need to separate various components of
20877                                    the output? */
20878         /* Set if there is still an unresolved user-defined property */
20879         SV *unresolved                = NULL;
20880
20881         /* Things that are ignored except when the runtime locale is UTF-8 */
20882         SV *only_utf8_locale_invlist = NULL;
20883
20884         /* Code points that don't fit in the bitmap */
20885         SV *nonbitmap_invlist = NULL;
20886
20887         /* And things that aren't in the bitmap, but are small enough to be */
20888         SV* bitmap_range_not_in_bitmap = NULL;
20889
20890         bool inverted;
20891
20892         if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
20893             flags = 0;
20894             bitmap = NULL;
20895             arg = 0;
20896         }
20897         else {
20898             flags = ANYOF_FLAGS(o);
20899             bitmap = ANYOF_BITMAP(o);
20900             arg = ARG(o);
20901         }
20902
20903         if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) {
20904             if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
20905                 sv_catpvs(sv, "{utf8-locale-reqd}");
20906             }
20907             if (flags & ANYOFL_FOLD) {
20908                 sv_catpvs(sv, "{i}");
20909             }
20910         }
20911
20912         inverted = flags & ANYOF_INVERT;
20913
20914         /* If there is stuff outside the bitmap, get it */
20915         if (arg != ANYOF_ONLY_HAS_BITMAP) {
20916             if (inRANGE(OP(o), ANYOFR, ANYOFRb)) {
20917                 nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
20918                                             ANYOFRbase(o),
20919                                             ANYOFRbase(o) + ANYOFRdelta(o));
20920             }
20921             else {
20922                 (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
20923                                                 &unresolved,
20924                                                 &only_utf8_locale_invlist,
20925                                                 &nonbitmap_invlist);
20926             }
20927
20928             /* The non-bitmap data may contain stuff that could fit in the
20929              * bitmap.  This could come from a user-defined property being
20930              * finally resolved when this call was done; or much more likely
20931              * because there are matches that require UTF-8 to be valid, and so
20932              * aren't in the bitmap (or ANYOFR).  This is teased apart later */
20933             _invlist_intersection(nonbitmap_invlist,
20934                                   PL_InBitmap,
20935                                   &bitmap_range_not_in_bitmap);
20936             /* Leave just the things that don't fit into the bitmap */
20937             _invlist_subtract(nonbitmap_invlist,
20938                               PL_InBitmap,
20939                               &nonbitmap_invlist);
20940         }
20941
20942         /* Obey this flag to add all above-the-bitmap code points */
20943         if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
20944             nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist,
20945                                                       NUM_ANYOF_CODE_POINTS,
20946                                                       UV_MAX);
20947         }
20948
20949         /* Ready to start outputting.  First, the initial left bracket */
20950         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
20951
20952         /* ANYOFH by definition doesn't have anything that will fit inside the
20953          * bitmap;  ANYOFR may or may not. */
20954         if (  ! inRANGE(OP(o), ANYOFH, ANYOFHr)
20955             && (   ! inRANGE(OP(o), ANYOFR, ANYOFRb)
20956                 ||   ANYOFRbase(o) < NUM_ANYOF_CODE_POINTS))
20957         {
20958             /* Then all the things that could fit in the bitmap */
20959             do_sep = put_charclass_bitmap_innards(sv,
20960                                                   bitmap,
20961                                                   bitmap_range_not_in_bitmap,
20962                                                   only_utf8_locale_invlist,
20963                                                   o,
20964                                                   flags,
20965
20966                                                   /* Can't try inverting for a
20967                                                    * better display if there
20968                                                    * are things that haven't
20969                                                    * been resolved */
20970                                                   unresolved != NULL
20971                                             || inRANGE(OP(o), ANYOFR, ANYOFRb));
20972             SvREFCNT_dec(bitmap_range_not_in_bitmap);
20973
20974             /* If there are user-defined properties which haven't been defined
20975              * yet, output them.  If the result is not to be inverted, it is
20976              * clearest to output them in a separate [] from the bitmap range
20977              * stuff.  If the result is to be complemented, we have to show
20978              * everything in one [], as the inversion applies to the whole
20979              * thing.  Use {braces} to separate them from anything in the
20980              * bitmap and anything above the bitmap. */
20981             if (unresolved) {
20982                 if (inverted) {
20983                     if (! do_sep) { /* If didn't output anything in the bitmap
20984                                      */
20985                         sv_catpvs(sv, "^");
20986                     }
20987                     sv_catpvs(sv, "{");
20988                 }
20989                 else if (do_sep) {
20990                     Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1],
20991                                                       PL_colors[0]);
20992                 }
20993                 sv_catsv(sv, unresolved);
20994                 if (inverted) {
20995                     sv_catpvs(sv, "}");
20996                 }
20997                 do_sep = ! inverted;
20998             }
20999         }
21000
21001         /* And, finally, add the above-the-bitmap stuff */
21002         if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) {
21003             SV* contents;
21004
21005             /* See if truncation size is overridden */
21006             const STRLEN dump_len = (PL_dump_re_max_len > 256)
21007                                     ? PL_dump_re_max_len
21008                                     : 256;
21009
21010             /* This is output in a separate [] */
21011             if (do_sep) {
21012                 Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]);
21013             }
21014
21015             /* And, for easy of understanding, it is shown in the
21016              * uncomplemented form if possible.  The one exception being if
21017              * there are unresolved items, where the inversion has to be
21018              * delayed until runtime */
21019             if (inverted && ! unresolved) {
21020                 _invlist_invert(nonbitmap_invlist);
21021                 _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist);
21022             }
21023
21024             contents = invlist_contents(nonbitmap_invlist,
21025                                         FALSE /* output suitable for catsv */
21026                                        );
21027
21028             /* If the output is shorter than the permissible maximum, just do it. */
21029             if (SvCUR(contents) <= dump_len) {
21030                 sv_catsv(sv, contents);
21031             }
21032             else {
21033                 const char * contents_string = SvPVX(contents);
21034                 STRLEN i = dump_len;
21035
21036                 /* Otherwise, start at the permissible max and work back to the
21037                  * first break possibility */
21038                 while (i > 0 && contents_string[i] != ' ') {
21039                     i--;
21040                 }
21041                 if (i == 0) {       /* Fail-safe.  Use the max if we couldn't
21042                                        find a legal break */
21043                     i = dump_len;
21044                 }
21045
21046                 sv_catpvn(sv, contents_string, i);
21047                 sv_catpvs(sv, "...");
21048             }
21049
21050             SvREFCNT_dec_NN(contents);
21051             SvREFCNT_dec_NN(nonbitmap_invlist);
21052         }
21053
21054         /* And finally the matching, closing ']' */
21055         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21056
21057         if (OP(o) == ANYOFHs) {
21058             Perl_sv_catpvf(aTHX_ sv, " (Leading UTF-8 bytes=%s", _byte_dump_string((U8 *) ((struct regnode_anyofhs *) o)->string, FLAGS(o), 1));
21059         }
21060         else if (inRANGE(OP(o), ANYOFH, ANYOFRb)) {
21061             U8 lowest = (OP(o) != ANYOFHr)
21062                          ? FLAGS(o)
21063                          : LOWEST_ANYOF_HRx_BYTE(FLAGS(o));
21064             U8 highest = (OP(o) == ANYOFHr)
21065                          ? HIGHEST_ANYOF_HRx_BYTE(FLAGS(o))
21066                          : (OP(o) == ANYOFH || OP(o) == ANYOFR)
21067                            ? 0xFF
21068                            : lowest;
21069             Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=%02X", lowest);
21070             if (lowest != highest) {
21071                 Perl_sv_catpvf(aTHX_ sv, "-%02X", highest);
21072             }
21073             Perl_sv_catpvf(aTHX_ sv, ")");
21074         }
21075
21076         SvREFCNT_dec(unresolved);
21077     }
21078     else if (k == ANYOFM) {
21079         SV * cp_list = get_ANYOFM_contents(o);
21080
21081         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
21082         if (OP(o) == NANYOFM) {
21083             _invlist_invert(cp_list);
21084         }
21085
21086         put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, 0, TRUE);
21087         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
21088
21089         SvREFCNT_dec(cp_list);
21090     }
21091     else if (k == POSIXD || k == NPOSIXD) {
21092         U8 index = FLAGS(o) * 2;
21093         if (index < C_ARRAY_LENGTH(anyofs)) {
21094             if (*anyofs[index] != '[')  {
21095                 sv_catpvs(sv, "[");
21096             }
21097             sv_catpv(sv, anyofs[index]);
21098             if (*anyofs[index] != '[')  {
21099                 sv_catpvs(sv, "]");
21100             }
21101         }
21102         else {
21103             Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
21104         }
21105     }
21106     else if (k == BOUND || k == NBOUND) {
21107         /* Must be synced with order of 'bound_type' in regcomp.h */
21108         const char * const bounds[] = {
21109             "",      /* Traditional */
21110             "{gcb}",
21111             "{lb}",
21112             "{sb}",
21113             "{wb}"
21114         };
21115         assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
21116         sv_catpv(sv, bounds[FLAGS(o)]);
21117     }
21118     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) {
21119         Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags));
21120         if (o->next_off) {
21121             Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off);
21122         }
21123         Perl_sv_catpvf(aTHX_ sv, "]");
21124     }
21125     else if (OP(o) == SBOL)
21126         Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
21127
21128     /* add on the verb argument if there is one */
21129     if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
21130         if ( ARG(o) )
21131             Perl_sv_catpvf(aTHX_ sv, ":%" SVf,
21132                        SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
21133         else
21134             sv_catpvs(sv, ":NULL");
21135     }
21136 #else
21137     PERL_UNUSED_CONTEXT;
21138     PERL_UNUSED_ARG(sv);
21139     PERL_UNUSED_ARG(o);
21140     PERL_UNUSED_ARG(prog);
21141     PERL_UNUSED_ARG(reginfo);
21142     PERL_UNUSED_ARG(pRExC_state);
21143 #endif  /* DEBUGGING */
21144 }
21145
21146
21147
21148 SV *
21149 Perl_re_intuit_string(pTHX_ REGEXP * const r)
21150 {                               /* Assume that RE_INTUIT is set */
21151     struct regexp *const prog = ReANY(r);
21152     GET_RE_DEBUG_FLAGS_DECL;
21153
21154     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
21155     PERL_UNUSED_CONTEXT;
21156
21157     DEBUG_COMPILE_r(
21158         {
21159             const char * const s = SvPV_nolen_const(RX_UTF8(r)
21160                       ? prog->check_utf8 : prog->check_substr);
21161
21162             if (!PL_colorset) reginitcolors();
21163             Perl_re_printf( aTHX_
21164                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
21165                       PL_colors[4],
21166                       RX_UTF8(r) ? "utf8 " : "",
21167                       PL_colors[5], PL_colors[0],
21168                       s,
21169                       PL_colors[1],
21170                       (strlen(s) > PL_dump_re_max_len ? "..." : ""));
21171         } );
21172
21173     /* use UTF8 check substring if regexp pattern itself is in UTF8 */
21174     return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
21175 }
21176
21177 /*
21178    pregfree()
21179
21180    handles refcounting and freeing the perl core regexp structure. When
21181    it is necessary to actually free the structure the first thing it
21182    does is call the 'free' method of the regexp_engine associated to
21183    the regexp, allowing the handling of the void *pprivate; member
21184    first. (This routine is not overridable by extensions, which is why
21185    the extensions free is called first.)
21186
21187    See regdupe and regdupe_internal if you change anything here.
21188 */
21189 #ifndef PERL_IN_XSUB_RE
21190 void
21191 Perl_pregfree(pTHX_ REGEXP *r)
21192 {
21193     SvREFCNT_dec(r);
21194 }
21195
21196 void
21197 Perl_pregfree2(pTHX_ REGEXP *rx)
21198 {
21199     struct regexp *const r = ReANY(rx);
21200     GET_RE_DEBUG_FLAGS_DECL;
21201
21202     PERL_ARGS_ASSERT_PREGFREE2;
21203
21204     if (! r)
21205         return;
21206
21207     if (r->mother_re) {
21208         ReREFCNT_dec(r->mother_re);
21209     } else {
21210         CALLREGFREE_PVT(rx); /* free the private data */
21211         SvREFCNT_dec(RXp_PAREN_NAMES(r));
21212     }
21213     if (r->substrs) {
21214         int i;
21215         for (i = 0; i < 2; i++) {
21216             SvREFCNT_dec(r->substrs->data[i].substr);
21217             SvREFCNT_dec(r->substrs->data[i].utf8_substr);
21218         }
21219         Safefree(r->substrs);
21220     }
21221     RX_MATCH_COPY_FREE(rx);
21222 #ifdef PERL_ANY_COW
21223     SvREFCNT_dec(r->saved_copy);
21224 #endif
21225     Safefree(r->offs);
21226     SvREFCNT_dec(r->qr_anoncv);
21227     if (r->recurse_locinput)
21228         Safefree(r->recurse_locinput);
21229 }
21230
21231
21232 /*  reg_temp_copy()
21233
21234     Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV,
21235     except that dsv will be created if NULL.
21236
21237     This function is used in two main ways. First to implement
21238         $r = qr/....; $s = $$r;
21239
21240     Secondly, it is used as a hacky workaround to the structural issue of
21241     match results
21242     being stored in the regexp structure which is in turn stored in
21243     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
21244     could be PL_curpm in multiple contexts, and could require multiple
21245     result sets being associated with the pattern simultaneously, such
21246     as when doing a recursive match with (??{$qr})
21247
21248     The solution is to make a lightweight copy of the regexp structure
21249     when a qr// is returned from the code executed by (??{$qr}) this
21250     lightweight copy doesn't actually own any of its data except for
21251     the starp/end and the actual regexp structure itself.
21252
21253 */
21254
21255
21256 REGEXP *
21257 Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv)
21258 {
21259     struct regexp *drx;
21260     struct regexp *const srx = ReANY(ssv);
21261     const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV;
21262
21263     PERL_ARGS_ASSERT_REG_TEMP_COPY;
21264
21265     if (!dsv)
21266         dsv = (REGEXP*) newSV_type(SVt_REGEXP);
21267     else {
21268         assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV));
21269
21270         /* our only valid caller, sv_setsv_flags(), should have done
21271          * a SV_CHECK_THINKFIRST_COW_DROP() by now */
21272         assert(!SvOOK(dsv));
21273         assert(!SvIsCOW(dsv));
21274         assert(!SvROK(dsv));
21275
21276         if (SvPVX_const(dsv)) {
21277             if (SvLEN(dsv))
21278                 Safefree(SvPVX(dsv));
21279             SvPVX(dsv) = NULL;
21280         }
21281         SvLEN_set(dsv, 0);
21282         SvCUR_set(dsv, 0);
21283         SvOK_off((SV *)dsv);
21284
21285         if (islv) {
21286             /* For PVLVs, the head (sv_any) points to an XPVLV, while
21287              * the LV's xpvlenu_rx will point to a regexp body, which
21288              * we allocate here */
21289             REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
21290             assert(!SvPVX(dsv));
21291             ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any;
21292             temp->sv_any = NULL;
21293             SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
21294             SvREFCNT_dec_NN(temp);
21295             /* SvCUR still resides in the xpvlv struct, so the regexp copy-
21296                ing below will not set it. */
21297             SvCUR_set(dsv, SvCUR(ssv));
21298         }
21299     }
21300     /* This ensures that SvTHINKFIRST(sv) is true, and hence that
21301        sv_force_normal(sv) is called.  */
21302     SvFAKE_on(dsv);
21303     drx = ReANY(dsv);
21304
21305     SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8);
21306     SvPV_set(dsv, RX_WRAPPED(ssv));
21307     /* We share the same string buffer as the original regexp, on which we
21308        hold a reference count, incremented when mother_re is set below.
21309        The string pointer is copied here, being part of the regexp struct.
21310      */
21311     memcpy(&(drx->xpv_cur), &(srx->xpv_cur),
21312            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
21313     if (!islv)
21314         SvLEN_set(dsv, 0);
21315     if (srx->offs) {
21316         const I32 npar = srx->nparens+1;
21317         Newx(drx->offs, npar, regexp_paren_pair);
21318         Copy(srx->offs, drx->offs, npar, regexp_paren_pair);
21319     }
21320     if (srx->substrs) {
21321         int i;
21322         Newx(drx->substrs, 1, struct reg_substr_data);
21323         StructCopy(srx->substrs, drx->substrs, struct reg_substr_data);
21324
21325         for (i = 0; i < 2; i++) {
21326             SvREFCNT_inc_void(drx->substrs->data[i].substr);
21327             SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr);
21328         }
21329
21330         /* check_substr and check_utf8, if non-NULL, point to either their
21331            anchored or float namesakes, and don't hold a second reference.  */
21332     }
21333     RX_MATCH_COPIED_off(dsv);
21334 #ifdef PERL_ANY_COW
21335     drx->saved_copy = NULL;
21336 #endif
21337     drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv);
21338     SvREFCNT_inc_void(drx->qr_anoncv);
21339     if (srx->recurse_locinput)
21340         Newx(drx->recurse_locinput, srx->nparens + 1, char *);
21341
21342     return dsv;
21343 }
21344 #endif
21345
21346
21347 /* regfree_internal()
21348
21349    Free the private data in a regexp. This is overloadable by
21350    extensions. Perl takes care of the regexp structure in pregfree(),
21351    this covers the *pprivate pointer which technically perl doesn't
21352    know about, however of course we have to handle the
21353    regexp_internal structure when no extension is in use.
21354
21355    Note this is called before freeing anything in the regexp
21356    structure.
21357  */
21358
21359 void
21360 Perl_regfree_internal(pTHX_ REGEXP * const rx)
21361 {
21362     struct regexp *const r = ReANY(rx);
21363     RXi_GET_DECL(r, ri);
21364     GET_RE_DEBUG_FLAGS_DECL;
21365
21366     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
21367
21368     if (! ri) {
21369         return;
21370     }
21371
21372     DEBUG_COMPILE_r({
21373         if (!PL_colorset)
21374             reginitcolors();
21375         {
21376             SV *dsv= sv_newmortal();
21377             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
21378                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len);
21379             Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n",
21380                 PL_colors[4], PL_colors[5], s);
21381         }
21382     });
21383
21384 #ifdef RE_TRACK_PATTERN_OFFSETS
21385     if (ri->u.offsets)
21386         Safefree(ri->u.offsets);             /* 20010421 MJD */
21387 #endif
21388     if (ri->code_blocks)
21389         S_free_codeblocks(aTHX_ ri->code_blocks);
21390
21391     if (ri->data) {
21392         int n = ri->data->count;
21393
21394         while (--n >= 0) {
21395           /* If you add a ->what type here, update the comment in regcomp.h */
21396             switch (ri->data->what[n]) {
21397             case 'a':
21398             case 'r':
21399             case 's':
21400             case 'S':
21401             case 'u':
21402                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
21403                 break;
21404             case 'f':
21405                 Safefree(ri->data->data[n]);
21406                 break;
21407             case 'l':
21408             case 'L':
21409                 break;
21410             case 'T':
21411                 { /* Aho Corasick add-on structure for a trie node.
21412                      Used in stclass optimization only */
21413                     U32 refcount;
21414                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
21415 #ifdef USE_ITHREADS
21416                     dVAR;
21417 #endif
21418                     OP_REFCNT_LOCK;
21419                     refcount = --aho->refcount;
21420                     OP_REFCNT_UNLOCK;
21421                     if ( !refcount ) {
21422                         PerlMemShared_free(aho->states);
21423                         PerlMemShared_free(aho->fail);
21424                          /* do this last!!!! */
21425                         PerlMemShared_free(ri->data->data[n]);
21426                         /* we should only ever get called once, so
21427                          * assert as much, and also guard the free
21428                          * which /might/ happen twice. At the least
21429                          * it will make code anlyzers happy and it
21430                          * doesn't cost much. - Yves */
21431                         assert(ri->regstclass);
21432                         if (ri->regstclass) {
21433                             PerlMemShared_free(ri->regstclass);
21434                             ri->regstclass = 0;
21435                         }
21436                     }
21437                 }
21438                 break;
21439             case 't':
21440                 {
21441                     /* trie structure. */
21442                     U32 refcount;
21443                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
21444 #ifdef USE_ITHREADS
21445                     dVAR;
21446 #endif
21447                     OP_REFCNT_LOCK;
21448                     refcount = --trie->refcount;
21449                     OP_REFCNT_UNLOCK;
21450                     if ( !refcount ) {
21451                         PerlMemShared_free(trie->charmap);
21452                         PerlMemShared_free(trie->states);
21453                         PerlMemShared_free(trie->trans);
21454                         if (trie->bitmap)
21455                             PerlMemShared_free(trie->bitmap);
21456                         if (trie->jump)
21457                             PerlMemShared_free(trie->jump);
21458                         PerlMemShared_free(trie->wordinfo);
21459                         /* do this last!!!! */
21460                         PerlMemShared_free(ri->data->data[n]);
21461                     }
21462                 }
21463                 break;
21464             default:
21465                 Perl_croak(aTHX_ "panic: regfree data code '%c'",
21466                                                     ri->data->what[n]);
21467             }
21468         }
21469         Safefree(ri->data->what);
21470         Safefree(ri->data);
21471     }
21472
21473     Safefree(ri);
21474 }
21475
21476 #define av_dup_inc(s, t)        MUTABLE_AV(sv_dup_inc((const SV *)s, t))
21477 #define hv_dup_inc(s, t)        MUTABLE_HV(sv_dup_inc((const SV *)s, t))
21478 #define SAVEPVN(p, n)   ((p) ? savepvn(p, n) : NULL)
21479
21480 /*
21481    re_dup_guts - duplicate a regexp.
21482
21483    This routine is expected to clone a given regexp structure. It is only
21484    compiled under USE_ITHREADS.
21485
21486    After all of the core data stored in struct regexp is duplicated
21487    the regexp_engine.dupe method is used to copy any private data
21488    stored in the *pprivate pointer. This allows extensions to handle
21489    any duplication it needs to do.
21490
21491    See pregfree() and regfree_internal() if you change anything here.
21492 */
21493 #if defined(USE_ITHREADS)
21494 #ifndef PERL_IN_XSUB_RE
21495 void
21496 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
21497 {
21498     dVAR;
21499     I32 npar;
21500     const struct regexp *r = ReANY(sstr);
21501     struct regexp *ret = ReANY(dstr);
21502
21503     PERL_ARGS_ASSERT_RE_DUP_GUTS;
21504
21505     npar = r->nparens+1;
21506     Newx(ret->offs, npar, regexp_paren_pair);
21507     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
21508
21509     if (ret->substrs) {
21510         /* Do it this way to avoid reading from *r after the StructCopy().
21511            That way, if any of the sv_dup_inc()s dislodge *r from the L1
21512            cache, it doesn't matter.  */
21513         int i;
21514         const bool anchored = r->check_substr
21515             ? r->check_substr == r->substrs->data[0].substr
21516             : r->check_utf8   == r->substrs->data[0].utf8_substr;
21517         Newx(ret->substrs, 1, struct reg_substr_data);
21518         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
21519
21520         for (i = 0; i < 2; i++) {
21521             ret->substrs->data[i].substr =
21522                         sv_dup_inc(ret->substrs->data[i].substr, param);
21523             ret->substrs->data[i].utf8_substr =
21524                         sv_dup_inc(ret->substrs->data[i].utf8_substr, param);
21525         }
21526
21527         /* check_substr and check_utf8, if non-NULL, point to either their
21528            anchored or float namesakes, and don't hold a second reference.  */
21529
21530         if (ret->check_substr) {
21531             if (anchored) {
21532                 assert(r->check_utf8 == r->substrs->data[0].utf8_substr);
21533
21534                 ret->check_substr = ret->substrs->data[0].substr;
21535                 ret->check_utf8   = ret->substrs->data[0].utf8_substr;
21536             } else {
21537                 assert(r->check_substr == r->substrs->data[1].substr);
21538                 assert(r->check_utf8   == r->substrs->data[1].utf8_substr);
21539
21540                 ret->check_substr = ret->substrs->data[1].substr;
21541                 ret->check_utf8   = ret->substrs->data[1].utf8_substr;
21542             }
21543         } else if (ret->check_utf8) {
21544             if (anchored) {
21545                 ret->check_utf8 = ret->substrs->data[0].utf8_substr;
21546             } else {
21547                 ret->check_utf8 = ret->substrs->data[1].utf8_substr;
21548             }
21549         }
21550     }
21551
21552     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
21553     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
21554     if (r->recurse_locinput)
21555         Newx(ret->recurse_locinput, r->nparens + 1, char *);
21556
21557     if (ret->pprivate)
21558         RXi_SET(ret, CALLREGDUPE_PVT(dstr, param));
21559
21560     if (RX_MATCH_COPIED(dstr))
21561         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
21562     else
21563         ret->subbeg = NULL;
21564 #ifdef PERL_ANY_COW
21565     ret->saved_copy = NULL;
21566 #endif
21567
21568     /* Whether mother_re be set or no, we need to copy the string.  We
21569        cannot refrain from copying it when the storage points directly to
21570        our mother regexp, because that's
21571                1: a buffer in a different thread
21572                2: something we no longer hold a reference on
21573                so we need to copy it locally.  */
21574     RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1);
21575     /* set malloced length to a non-zero value so it will be freed
21576      * (otherwise in combination with SVf_FAKE it looks like an alien
21577      * buffer). It doesn't have to be the actual malloced size, since it
21578      * should never be grown */
21579     SvLEN_set(dstr, SvCUR(sstr)+1);
21580     ret->mother_re   = NULL;
21581 }
21582 #endif /* PERL_IN_XSUB_RE */
21583
21584 /*
21585    regdupe_internal()
21586
21587    This is the internal complement to regdupe() which is used to copy
21588    the structure pointed to by the *pprivate pointer in the regexp.
21589    This is the core version of the extension overridable cloning hook.
21590    The regexp structure being duplicated will be copied by perl prior
21591    to this and will be provided as the regexp *r argument, however
21592    with the /old/ structures pprivate pointer value. Thus this routine
21593    may override any copying normally done by perl.
21594
21595    It returns a pointer to the new regexp_internal structure.
21596 */
21597
21598 void *
21599 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
21600 {
21601     dVAR;
21602     struct regexp *const r = ReANY(rx);
21603     regexp_internal *reti;
21604     int len;
21605     RXi_GET_DECL(r, ri);
21606
21607     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
21608
21609     len = ProgLen(ri);
21610
21611     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
21612           char, regexp_internal);
21613     Copy(ri->program, reti->program, len+1, regnode);
21614
21615
21616     if (ri->code_blocks) {
21617         int n;
21618         Newx(reti->code_blocks, 1, struct reg_code_blocks);
21619         Newx(reti->code_blocks->cb, ri->code_blocks->count,
21620                     struct reg_code_block);
21621         Copy(ri->code_blocks->cb, reti->code_blocks->cb,
21622              ri->code_blocks->count, struct reg_code_block);
21623         for (n = 0; n < ri->code_blocks->count; n++)
21624              reti->code_blocks->cb[n].src_regex = (REGEXP*)
21625                     sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param);
21626         reti->code_blocks->count = ri->code_blocks->count;
21627         reti->code_blocks->refcnt = 1;
21628     }
21629     else
21630         reti->code_blocks = NULL;
21631
21632     reti->regstclass = NULL;
21633
21634     if (ri->data) {
21635         struct reg_data *d;
21636         const int count = ri->data->count;
21637         int i;
21638
21639         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
21640                 char, struct reg_data);
21641         Newx(d->what, count, U8);
21642
21643         d->count = count;
21644         for (i = 0; i < count; i++) {
21645             d->what[i] = ri->data->what[i];
21646             switch (d->what[i]) {
21647                 /* see also regcomp.h and regfree_internal() */
21648             case 'a': /* actually an AV, but the dup function is identical.
21649                          values seem to be "plain sv's" generally. */
21650             case 'r': /* a compiled regex (but still just another SV) */
21651             case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code)
21652                          this use case should go away, the code could have used
21653                          'a' instead - see S_set_ANYOF_arg() for array contents. */
21654             case 'S': /* actually an SV, but the dup function is identical.  */
21655             case 'u': /* actually an HV, but the dup function is identical.
21656                          values are "plain sv's" */
21657                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
21658                 break;
21659             case 'f':
21660                 /* Synthetic Start Class - "Fake" charclass we generate to optimize
21661                  * patterns which could start with several different things. Pre-TRIE
21662                  * this was more important than it is now, however this still helps
21663                  * in some places, for instance /x?a+/ might produce a SSC equivalent
21664                  * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass()
21665                  * in regexec.c
21666                  */
21667                 /* This is cheating. */
21668                 Newx(d->data[i], 1, regnode_ssc);
21669                 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
21670                 reti->regstclass = (regnode*)d->data[i];
21671                 break;
21672             case 'T':
21673                 /* AHO-CORASICK fail table */
21674                 /* Trie stclasses are readonly and can thus be shared
21675                  * without duplication. We free the stclass in pregfree
21676                  * when the corresponding reg_ac_data struct is freed.
21677                  */
21678                 reti->regstclass= ri->regstclass;
21679                 /* FALLTHROUGH */
21680             case 't':
21681                 /* TRIE transition table */
21682                 OP_REFCNT_LOCK;
21683                 ((reg_trie_data*)ri->data->data[i])->refcount++;
21684                 OP_REFCNT_UNLOCK;
21685                 /* FALLTHROUGH */
21686             case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */
21687             case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code
21688                          is not from another regexp */
21689                 d->data[i] = ri->data->data[i];
21690                 break;
21691             default:
21692                 Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'",
21693                                                            ri->data->what[i]);
21694             }
21695         }
21696
21697         reti->data = d;
21698     }
21699     else
21700         reti->data = NULL;
21701
21702     reti->name_list_idx = ri->name_list_idx;
21703
21704 #ifdef RE_TRACK_PATTERN_OFFSETS
21705     if (ri->u.offsets) {
21706         Newx(reti->u.offsets, 2*len+1, U32);
21707         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
21708     }
21709 #else
21710     SetProgLen(reti, len);
21711 #endif
21712
21713     return (void*)reti;
21714 }
21715
21716 #endif    /* USE_ITHREADS */
21717
21718 #ifndef PERL_IN_XSUB_RE
21719
21720 /*
21721  - regnext - dig the "next" pointer out of a node
21722  */
21723 regnode *
21724 Perl_regnext(pTHX_ regnode *p)
21725 {
21726     I32 offset;
21727
21728     if (!p)
21729         return(NULL);
21730
21731     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
21732         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
21733                                                 (int)OP(p), (int)REGNODE_MAX);
21734     }
21735
21736     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
21737     if (offset == 0)
21738         return(NULL);
21739
21740     return(p+offset);
21741 }
21742
21743 #endif
21744
21745 STATIC void
21746 S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...)
21747 {
21748     va_list args;
21749     STRLEN l1 = strlen(pat1);
21750     STRLEN l2 = strlen(pat2);
21751     char buf[512];
21752     SV *msv;
21753     const char *message;
21754
21755     PERL_ARGS_ASSERT_RE_CROAK2;
21756
21757     if (l1 > 510)
21758         l1 = 510;
21759     if (l1 + l2 > 510)
21760         l2 = 510 - l1;
21761     Copy(pat1, buf, l1 , char);
21762     Copy(pat2, buf + l1, l2 , char);
21763     buf[l1 + l2] = '\n';
21764     buf[l1 + l2 + 1] = '\0';
21765     va_start(args, pat2);
21766     msv = vmess(buf, &args);
21767     va_end(args);
21768     message = SvPV_const(msv, l1);
21769     if (l1 > 512)
21770         l1 = 512;
21771     Copy(message, buf, l1 , char);
21772     /* l1-1 to avoid \n */
21773     Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf));
21774 }
21775
21776 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
21777
21778 #ifndef PERL_IN_XSUB_RE
21779 void
21780 Perl_save_re_context(pTHX)
21781 {
21782     I32 nparens = -1;
21783     I32 i;
21784
21785     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
21786
21787     if (PL_curpm) {
21788         const REGEXP * const rx = PM_GETRE(PL_curpm);
21789         if (rx)
21790             nparens = RX_NPARENS(rx);
21791     }
21792
21793     /* RT #124109. This is a complete hack; in the SWASHNEW case we know
21794      * that PL_curpm will be null, but that utf8.pm and the modules it
21795      * loads will only use $1..$3.
21796      * The t/porting/re_context.t test file checks this assumption.
21797      */
21798     if (nparens == -1)
21799         nparens = 3;
21800
21801     for (i = 1; i <= nparens; i++) {
21802         char digits[TYPE_CHARS(long)];
21803         const STRLEN len = my_snprintf(digits, sizeof(digits),
21804                                        "%lu", (long)i);
21805         GV *const *const gvp
21806             = (GV**)hv_fetch(PL_defstash, digits, len, 0);
21807
21808         if (gvp) {
21809             GV * const gv = *gvp;
21810             if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
21811                 save_scalar(gv);
21812         }
21813     }
21814 }
21815 #endif
21816
21817 #ifdef DEBUGGING
21818
21819 STATIC void
21820 S_put_code_point(pTHX_ SV *sv, UV c)
21821 {
21822     PERL_ARGS_ASSERT_PUT_CODE_POINT;
21823
21824     if (c > 255) {
21825         Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c);
21826     }
21827     else if (isPRINT(c)) {
21828         const char string = (char) c;
21829
21830         /* We use {phrase} as metanotation in the class, so also escape literal
21831          * braces */
21832         if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}')
21833             sv_catpvs(sv, "\\");
21834         sv_catpvn(sv, &string, 1);
21835     }
21836     else if (isMNEMONIC_CNTRL(c)) {
21837         Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c));
21838     }
21839     else {
21840         Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c);
21841     }
21842 }
21843
21844 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
21845
21846 STATIC void
21847 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
21848 {
21849     /* Appends to 'sv' a displayable version of the range of code points from
21850      * 'start' to 'end'.  Mnemonics (like '\r') are used for the few controls
21851      * that have them, when they occur at the beginning or end of the range.
21852      * It uses hex to output the remaining code points, unless 'allow_literals'
21853      * is true, in which case the printable ASCII ones are output as-is (though
21854      * some of these will be escaped by put_code_point()).
21855      *
21856      * NOTE:  This is designed only for printing ranges of code points that fit
21857      *        inside an ANYOF bitmap.  Higher code points are simply suppressed
21858      */
21859
21860     const unsigned int min_range_count = 3;
21861
21862     assert(start <= end);
21863
21864     PERL_ARGS_ASSERT_PUT_RANGE;
21865
21866     while (start <= end) {
21867         UV this_end;
21868         const char * format;
21869
21870         if (end - start < min_range_count) {
21871
21872             /* Output chars individually when they occur in short ranges */
21873             for (; start <= end; start++) {
21874                 put_code_point(sv, start);
21875             }
21876             break;
21877         }
21878
21879         /* If permitted by the input options, and there is a possibility that
21880          * this range contains a printable literal, look to see if there is
21881          * one. */
21882         if (allow_literals && start <= MAX_PRINT_A) {
21883
21884             /* If the character at the beginning of the range isn't an ASCII
21885              * printable, effectively split the range into two parts:
21886              *  1) the portion before the first such printable,
21887              *  2) the rest
21888              * and output them separately. */
21889             if (! isPRINT_A(start)) {
21890                 UV temp_end = start + 1;
21891
21892                 /* There is no point looking beyond the final possible
21893                  * printable, in MAX_PRINT_A */
21894                 UV max = MIN(end, MAX_PRINT_A);
21895
21896                 while (temp_end <= max && ! isPRINT_A(temp_end)) {
21897                     temp_end++;
21898                 }
21899
21900                 /* Here, temp_end points to one beyond the first printable if
21901                  * found, or to one beyond 'max' if not.  If none found, make
21902                  * sure that we use the entire range */
21903                 if (temp_end > MAX_PRINT_A) {
21904                     temp_end = end + 1;
21905                 }
21906
21907                 /* Output the first part of the split range: the part that
21908                  * doesn't have printables, with the parameter set to not look
21909                  * for literals (otherwise we would infinitely recurse) */
21910                 put_range(sv, start, temp_end - 1, FALSE);
21911
21912                 /* The 2nd part of the range (if any) starts here. */
21913                 start = temp_end;
21914
21915                 /* We do a continue, instead of dropping down, because even if
21916                  * the 2nd part is non-empty, it could be so short that we want
21917                  * to output it as individual characters, as tested for at the
21918                  * top of this loop.  */
21919                 continue;
21920             }
21921
21922             /* Here, 'start' is a printable ASCII.  If it is an alphanumeric,
21923              * output a sub-range of just the digits or letters, then process
21924              * the remaining portion as usual. */
21925             if (isALPHANUMERIC_A(start)) {
21926                 UV mask = (isDIGIT_A(start))
21927                            ? _CC_DIGIT
21928                              : isUPPER_A(start)
21929                                ? _CC_UPPER
21930                                : _CC_LOWER;
21931                 UV temp_end = start + 1;
21932
21933                 /* Find the end of the sub-range that includes just the
21934                  * characters in the same class as the first character in it */
21935                 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
21936                     temp_end++;
21937                 }
21938                 temp_end--;
21939
21940                 /* For short ranges, don't duplicate the code above to output
21941                  * them; just call recursively */
21942                 if (temp_end - start < min_range_count) {
21943                     put_range(sv, start, temp_end, FALSE);
21944                 }
21945                 else {  /* Output as a range */
21946                     put_code_point(sv, start);
21947                     sv_catpvs(sv, "-");
21948                     put_code_point(sv, temp_end);
21949                 }
21950                 start = temp_end + 1;
21951                 continue;
21952             }
21953
21954             /* We output any other printables as individual characters */
21955             if (isPUNCT_A(start) || isSPACE_A(start)) {
21956                 while (start <= end && (isPUNCT_A(start)
21957                                         || isSPACE_A(start)))
21958                 {
21959                     put_code_point(sv, start);
21960                     start++;
21961                 }
21962                 continue;
21963             }
21964         } /* End of looking for literals */
21965
21966         /* Here is not to output as a literal.  Some control characters have
21967          * mnemonic names.  Split off any of those at the beginning and end of
21968          * the range to print mnemonically.  It isn't possible for many of
21969          * these to be in a row, so this won't overwhelm with output */
21970         if (   start <= end
21971             && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end)))
21972         {
21973             while (isMNEMONIC_CNTRL(start) && start <= end) {
21974                 put_code_point(sv, start);
21975                 start++;
21976             }
21977
21978             /* If this didn't take care of the whole range ... */
21979             if (start <= end) {
21980
21981                 /* Look backwards from the end to find the final non-mnemonic
21982                  * */
21983                 UV temp_end = end;
21984                 while (isMNEMONIC_CNTRL(temp_end)) {
21985                     temp_end--;
21986                 }
21987
21988                 /* And separately output the interior range that doesn't start
21989                  * or end with mnemonics */
21990                 put_range(sv, start, temp_end, FALSE);
21991
21992                 /* Then output the mnemonic trailing controls */
21993                 start = temp_end + 1;
21994                 while (start <= end) {
21995                     put_code_point(sv, start);
21996                     start++;
21997                 }
21998                 break;
21999             }
22000         }
22001
22002         /* As a final resort, output the range or subrange as hex. */
22003
22004         if (start >= NUM_ANYOF_CODE_POINTS) {
22005             this_end = end;
22006         }
22007         else {  /* Have to split range at the bitmap boundary */
22008             this_end = (end < NUM_ANYOF_CODE_POINTS)
22009                         ? end
22010                         : NUM_ANYOF_CODE_POINTS - 1;
22011         }
22012 #if NUM_ANYOF_CODE_POINTS > 256
22013         format = (this_end < 256)
22014                  ? "\\x%02" UVXf "-\\x%02" UVXf
22015                  : "\\x{%04" UVXf "}-\\x{%04" UVXf "}";
22016 #else
22017         format = "\\x%02" UVXf "-\\x%02" UVXf;
22018 #endif
22019         GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
22020         Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
22021         GCC_DIAG_RESTORE_STMT;
22022         break;
22023     }
22024 }
22025
22026 STATIC void
22027 S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist)
22028 {
22029     /* Concatenate onto the PV in 'sv' a displayable form of the inversion list
22030      * 'invlist' */
22031
22032     UV start, end;
22033     bool allow_literals = TRUE;
22034
22035     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST;
22036
22037     /* Generally, it is more readable if printable characters are output as
22038      * literals, but if a range (nearly) spans all of them, it's best to output
22039      * it as a single range.  This code will use a single range if all but 2
22040      * ASCII printables are in it */
22041     invlist_iterinit(invlist);
22042     while (invlist_iternext(invlist, &start, &end)) {
22043
22044         /* If the range starts beyond the final printable, it doesn't have any
22045          * in it */
22046         if (start > MAX_PRINT_A) {
22047             break;
22048         }
22049
22050         /* In both ASCII and EBCDIC, a SPACE is the lowest printable.  To span
22051          * all but two, the range must start and end no later than 2 from
22052          * either end */
22053         if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
22054             if (end > MAX_PRINT_A) {
22055                 end = MAX_PRINT_A;
22056             }
22057             if (start < ' ') {
22058                 start = ' ';
22059             }
22060             if (end - start >= MAX_PRINT_A - ' ' - 2) {
22061                 allow_literals = FALSE;
22062             }
22063             break;
22064         }
22065     }
22066     invlist_iterfinish(invlist);
22067
22068     /* Here we have figured things out.  Output each range */
22069     invlist_iterinit(invlist);
22070     while (invlist_iternext(invlist, &start, &end)) {
22071         if (start >= NUM_ANYOF_CODE_POINTS) {
22072             break;
22073         }
22074         put_range(sv, start, end, allow_literals);
22075     }
22076     invlist_iterfinish(invlist);
22077
22078     return;
22079 }
22080
22081 STATIC SV*
22082 S_put_charclass_bitmap_innards_common(pTHX_
22083         SV* invlist,            /* The bitmap */
22084         SV* posixes,            /* Under /l, things like [:word:], \S */
22085         SV* only_utf8,          /* Under /d, matches iff the target is UTF-8 */
22086         SV* not_utf8,           /* /d, matches iff the target isn't UTF-8 */
22087         SV* only_utf8_locale,   /* Under /l, matches if the locale is UTF-8 */
22088         const bool invert       /* Is the result to be inverted? */
22089 )
22090 {
22091     /* Create and return an SV containing a displayable version of the bitmap
22092      * and associated information determined by the input parameters.  If the
22093      * output would have been only the inversion indicator '^', NULL is instead
22094      * returned. */
22095
22096     dVAR;
22097     SV * output;
22098
22099     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON;
22100
22101     if (invert) {
22102         output = newSVpvs("^");
22103     }
22104     else {
22105         output = newSVpvs("");
22106     }
22107
22108     /* First, the code points in the bitmap that are unconditionally there */
22109     put_charclass_bitmap_innards_invlist(output, invlist);
22110
22111     /* Traditionally, these have been placed after the main code points */
22112     if (posixes) {
22113         sv_catsv(output, posixes);
22114     }
22115
22116     if (only_utf8 && _invlist_len(only_utf8)) {
22117         Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]);
22118         put_charclass_bitmap_innards_invlist(output, only_utf8);
22119     }
22120
22121     if (not_utf8 && _invlist_len(not_utf8)) {
22122         Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]);
22123         put_charclass_bitmap_innards_invlist(output, not_utf8);
22124     }
22125
22126     if (only_utf8_locale && _invlist_len(only_utf8_locale)) {
22127         Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]);
22128         put_charclass_bitmap_innards_invlist(output, only_utf8_locale);
22129
22130         /* This is the only list in this routine that can legally contain code
22131          * points outside the bitmap range.  The call just above to
22132          * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so
22133          * output them here.  There's about a half-dozen possible, and none in
22134          * contiguous ranges longer than 2 */
22135         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22136             UV start, end;
22137             SV* above_bitmap = NULL;
22138
22139             _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap);
22140
22141             invlist_iterinit(above_bitmap);
22142             while (invlist_iternext(above_bitmap, &start, &end)) {
22143                 UV i;
22144
22145                 for (i = start; i <= end; i++) {
22146                     put_code_point(output, i);
22147                 }
22148             }
22149             invlist_iterfinish(above_bitmap);
22150             SvREFCNT_dec_NN(above_bitmap);
22151         }
22152     }
22153
22154     if (invert && SvCUR(output) == 1) {
22155         return NULL;
22156     }
22157
22158     return output;
22159 }
22160
22161 STATIC bool
22162 S_put_charclass_bitmap_innards(pTHX_ SV *sv,
22163                                      char *bitmap,
22164                                      SV *nonbitmap_invlist,
22165                                      SV *only_utf8_locale_invlist,
22166                                      const regnode * const node,
22167                                      const U8 flags,
22168                                      const bool force_as_is_display)
22169 {
22170     /* Appends to 'sv' a displayable version of the innards of the bracketed
22171      * character class defined by the other arguments:
22172      *  'bitmap' points to the bitmap, or NULL if to ignore that.
22173      *  'nonbitmap_invlist' is an inversion list of the code points that are in
22174      *      the bitmap range, but for some reason aren't in the bitmap; NULL if
22175      *      none.  The reasons for this could be that they require some
22176      *      condition such as the target string being or not being in UTF-8
22177      *      (under /d), or because they came from a user-defined property that
22178      *      was not resolved at the time of the regex compilation (under /u)
22179      *  'only_utf8_locale_invlist' is an inversion list of the code points that
22180      *      are valid only if the runtime locale is a UTF-8 one; NULL if none
22181      *  'node' is the regex pattern ANYOF node.  It is needed only when the
22182      *      above two parameters are not null, and is passed so that this
22183      *      routine can tease apart the various reasons for them.
22184      *  'flags' is the flags field of 'node'
22185      *  'force_as_is_display' is TRUE if this routine should definitely NOT try
22186      *      to invert things to see if that leads to a cleaner display.  If
22187      *      FALSE, this routine is free to use its judgment about doing this.
22188      *
22189      * It returns TRUE if there was actually something output.  (It may be that
22190      * the bitmap, etc is empty.)
22191      *
22192      * When called for outputting the bitmap of a non-ANYOF node, just pass the
22193      * bitmap, with the succeeding parameters set to NULL, and the final one to
22194      * FALSE.
22195      */
22196
22197     /* In general, it tries to display the 'cleanest' representation of the
22198      * innards, choosing whether to display them inverted or not, regardless of
22199      * whether the class itself is to be inverted.  However,  there are some
22200      * cases where it can't try inverting, as what actually matches isn't known
22201      * until runtime, and hence the inversion isn't either. */
22202
22203     dVAR;
22204     bool inverting_allowed = ! force_as_is_display;
22205
22206     int i;
22207     STRLEN orig_sv_cur = SvCUR(sv);
22208
22209     SV* invlist;            /* Inversion list we accumulate of code points that
22210                                are unconditionally matched */
22211     SV* only_utf8 = NULL;   /* Under /d, list of matches iff the target is
22212                                UTF-8 */
22213     SV* not_utf8 =  NULL;   /* /d, list of matches iff the target isn't UTF-8
22214                              */
22215     SV* posixes = NULL;     /* Under /l, string of things like [:word:], \D */
22216     SV* only_utf8_locale = NULL;    /* Under /l, list of matches if the locale
22217                                        is UTF-8 */
22218
22219     SV* as_is_display;      /* The output string when we take the inputs
22220                                literally */
22221     SV* inverted_display;   /* The output string when we invert the inputs */
22222
22223     bool invert = cBOOL(flags & ANYOF_INVERT);  /* Is the input to be inverted
22224                                                    to match? */
22225     /* We are biased in favor of displaying things without them being inverted,
22226      * as that is generally easier to understand */
22227     const int bias = 5;
22228
22229     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
22230
22231     /* Start off with whatever code points are passed in.  (We clone, so we
22232      * don't change the caller's list) */
22233     if (nonbitmap_invlist) {
22234         assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS);
22235         invlist = invlist_clone(nonbitmap_invlist, NULL);
22236     }
22237     else {  /* Worst case size is every other code point is matched */
22238         invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
22239     }
22240
22241     if (flags) {
22242         if (OP(node) == ANYOFD) {
22243
22244             /* This flag indicates that the code points below 0x100 in the
22245              * nonbitmap list are precisely the ones that match only when the
22246              * target is UTF-8 (they should all be non-ASCII). */
22247             if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
22248             {
22249                 _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8);
22250                 _invlist_subtract(invlist, only_utf8, &invlist);
22251             }
22252
22253             /* And this flag for matching all non-ASCII 0xFF and below */
22254             if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
22255             {
22256                 not_utf8 = invlist_clone(PL_UpperLatin1, NULL);
22257             }
22258         }
22259         else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) {
22260
22261             /* If either of these flags are set, what matches isn't
22262              * determinable except during execution, so don't know enough here
22263              * to invert */
22264             if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) {
22265                 inverting_allowed = FALSE;
22266             }
22267
22268             /* What the posix classes match also varies at runtime, so these
22269              * will be output symbolically. */
22270             if (ANYOF_POSIXL_TEST_ANY_SET(node)) {
22271                 int i;
22272
22273                 posixes = newSVpvs("");
22274                 for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
22275                     if (ANYOF_POSIXL_TEST(node, i)) {
22276                         sv_catpv(posixes, anyofs[i]);
22277                     }
22278                 }
22279             }
22280         }
22281     }
22282
22283     /* Accumulate the bit map into the unconditional match list */
22284     if (bitmap) {
22285         for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
22286             if (BITMAP_TEST(bitmap, i)) {
22287                 int start = i++;
22288                 for (;
22289                      i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i);
22290                      i++)
22291                 { /* empty */ }
22292                 invlist = _add_range_to_invlist(invlist, start, i-1);
22293             }
22294         }
22295     }
22296
22297     /* Make sure that the conditional match lists don't have anything in them
22298      * that match unconditionally; otherwise the output is quite confusing.
22299      * This could happen if the code that populates these misses some
22300      * duplication. */
22301     if (only_utf8) {
22302         _invlist_subtract(only_utf8, invlist, &only_utf8);
22303     }
22304     if (not_utf8) {
22305         _invlist_subtract(not_utf8, invlist, &not_utf8);
22306     }
22307
22308     if (only_utf8_locale_invlist) {
22309
22310         /* Since this list is passed in, we have to make a copy before
22311          * modifying it */
22312         only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL);
22313
22314         _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale);
22315
22316         /* And, it can get really weird for us to try outputting an inverted
22317          * form of this list when it has things above the bitmap, so don't even
22318          * try */
22319         if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) {
22320             inverting_allowed = FALSE;
22321         }
22322     }
22323
22324     /* Calculate what the output would be if we take the input as-is */
22325     as_is_display = put_charclass_bitmap_innards_common(invlist,
22326                                                     posixes,
22327                                                     only_utf8,
22328                                                     not_utf8,
22329                                                     only_utf8_locale,
22330                                                     invert);
22331
22332     /* If have to take the output as-is, just do that */
22333     if (! inverting_allowed) {
22334         if (as_is_display) {
22335             sv_catsv(sv, as_is_display);
22336             SvREFCNT_dec_NN(as_is_display);
22337         }
22338     }
22339     else { /* But otherwise, create the output again on the inverted input, and
22340               use whichever version is shorter */
22341
22342         int inverted_bias, as_is_bias;
22343
22344         /* We will apply our bias to whichever of the the results doesn't have
22345          * the '^' */
22346         if (invert) {
22347             invert = FALSE;
22348             as_is_bias = bias;
22349             inverted_bias = 0;
22350         }
22351         else {
22352             invert = TRUE;
22353             as_is_bias = 0;
22354             inverted_bias = bias;
22355         }
22356
22357         /* Now invert each of the lists that contribute to the output,
22358          * excluding from the result things outside the possible range */
22359
22360         /* For the unconditional inversion list, we have to add in all the
22361          * conditional code points, so that when inverted, they will be gone
22362          * from it */
22363         _invlist_union(only_utf8, invlist, &invlist);
22364         _invlist_union(not_utf8, invlist, &invlist);
22365         _invlist_union(only_utf8_locale, invlist, &invlist);
22366         _invlist_invert(invlist);
22367         _invlist_intersection(invlist, PL_InBitmap, &invlist);
22368
22369         if (only_utf8) {
22370             _invlist_invert(only_utf8);
22371             _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8);
22372         }
22373         else if (not_utf8) {
22374
22375             /* If a code point matches iff the target string is not in UTF-8,
22376              * then complementing the result has it not match iff not in UTF-8,
22377              * which is the same thing as matching iff it is UTF-8. */
22378             only_utf8 = not_utf8;
22379             not_utf8 = NULL;
22380         }
22381
22382         if (only_utf8_locale) {
22383             _invlist_invert(only_utf8_locale);
22384             _invlist_intersection(only_utf8_locale,
22385                                   PL_InBitmap,
22386                                   &only_utf8_locale);
22387         }
22388
22389         inverted_display = put_charclass_bitmap_innards_common(
22390                                             invlist,
22391                                             posixes,
22392                                             only_utf8,
22393                                             not_utf8,
22394                                             only_utf8_locale, invert);
22395
22396         /* Use the shortest representation, taking into account our bias
22397          * against showing it inverted */
22398         if (   inverted_display
22399             && (   ! as_is_display
22400                 || (  SvCUR(inverted_display) + inverted_bias
22401                     < SvCUR(as_is_display)    + as_is_bias)))
22402         {
22403             sv_catsv(sv, inverted_display);
22404         }
22405         else if (as_is_display) {
22406             sv_catsv(sv, as_is_display);
22407         }
22408
22409         SvREFCNT_dec(as_is_display);
22410         SvREFCNT_dec(inverted_display);
22411     }
22412
22413     SvREFCNT_dec_NN(invlist);
22414     SvREFCNT_dec(only_utf8);
22415     SvREFCNT_dec(not_utf8);
22416     SvREFCNT_dec(posixes);
22417     SvREFCNT_dec(only_utf8_locale);
22418
22419     return SvCUR(sv) > orig_sv_cur;
22420 }
22421
22422 #define CLEAR_OPTSTART                                                       \
22423     if (optstart) STMT_START {                                               \
22424         DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_                                           \
22425                               " (%" IVdf " nodes)\n", (IV)(node - optstart))); \
22426         optstart=NULL;                                                       \
22427     } STMT_END
22428
22429 #define DUMPUNTIL(b,e)                                                       \
22430                     CLEAR_OPTSTART;                                          \
22431                     node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
22432
22433 STATIC const regnode *
22434 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
22435             const regnode *last, const regnode *plast,
22436             SV* sv, I32 indent, U32 depth)
22437 {
22438     U8 op = PSEUDO;     /* Arbitrary non-END op. */
22439     const regnode *next;
22440     const regnode *optstart= NULL;
22441
22442     RXi_GET_DECL(r, ri);
22443     GET_RE_DEBUG_FLAGS_DECL;
22444
22445     PERL_ARGS_ASSERT_DUMPUNTIL;
22446
22447 #ifdef DEBUG_DUMPUNTIL
22448     Perl_re_printf( aTHX_  "--- %d : %d - %d - %d\n", indent, node-start,
22449         last ? last-start : 0, plast ? plast-start : 0);
22450 #endif
22451
22452     if (plast && plast < last)
22453         last= plast;
22454
22455     while (PL_regkind[op] != END && (!last || node < last)) {
22456         assert(node);
22457         /* While that wasn't END last time... */
22458         NODE_ALIGN(node);
22459         op = OP(node);
22460         if (op == CLOSE || op == SRCLOSE || op == WHILEM)
22461             indent--;
22462         next = regnext((regnode *)node);
22463
22464         /* Where, what. */
22465         if (OP(node) == OPTIMIZED) {
22466             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
22467                 optstart = node;
22468             else
22469                 goto after_print;
22470         } else
22471             CLEAR_OPTSTART;
22472
22473         regprop(r, sv, node, NULL, NULL);
22474         Perl_re_printf( aTHX_  "%4" IVdf ":%*s%s", (IV)(node - start),
22475                       (int)(2*indent + 1), "", SvPVX_const(sv));
22476
22477         if (OP(node) != OPTIMIZED) {
22478             if (next == NULL)           /* Next ptr. */
22479                 Perl_re_printf( aTHX_  " (0)");
22480             else if (PL_regkind[(U8)op] == BRANCH
22481                      && PL_regkind[OP(next)] != BRANCH )
22482                 Perl_re_printf( aTHX_  " (FAIL)");
22483             else
22484                 Perl_re_printf( aTHX_  " (%" IVdf ")", (IV)(next - start));
22485             Perl_re_printf( aTHX_ "\n");
22486         }
22487
22488       after_print:
22489         if (PL_regkind[(U8)op] == BRANCHJ) {
22490             assert(next);
22491             {
22492                 const regnode *nnode = (OP(next) == LONGJMP
22493                                        ? regnext((regnode *)next)
22494                                        : next);
22495                 if (last && nnode > last)
22496                     nnode = last;
22497                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
22498             }
22499         }
22500         else if (PL_regkind[(U8)op] == BRANCH) {
22501             assert(next);
22502             DUMPUNTIL(NEXTOPER(node), next);
22503         }
22504         else if ( PL_regkind[(U8)op]  == TRIE ) {
22505             const regnode *this_trie = node;
22506             const char op = OP(node);
22507             const U32 n = ARG(node);
22508             const reg_ac_data * const ac = op>=AHOCORASICK ?
22509                (reg_ac_data *)ri->data->data[n] :
22510                NULL;
22511             const reg_trie_data * const trie =
22512                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
22513 #ifdef DEBUGGING
22514             AV *const trie_words
22515                            = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
22516 #endif
22517             const regnode *nextbranch= NULL;
22518             I32 word_idx;
22519             SvPVCLEAR(sv);
22520             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
22521                 SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0);
22522
22523                 Perl_re_indentf( aTHX_  "%s ",
22524                     indent+3,
22525                     elem_ptr
22526                     ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
22527                                 SvCUR(*elem_ptr), PL_dump_re_max_len,
22528                                 PL_colors[0], PL_colors[1],
22529                                 (SvUTF8(*elem_ptr)
22530                                  ? PERL_PV_ESCAPE_UNI
22531                                  : 0)
22532                                 | PERL_PV_PRETTY_ELLIPSES
22533                                 | PERL_PV_PRETTY_LTGT
22534                             )
22535                     : "???"
22536                 );
22537                 if (trie->jump) {
22538                     U16 dist= trie->jump[word_idx+1];
22539                     Perl_re_printf( aTHX_  "(%" UVuf ")\n",
22540                                (UV)((dist ? this_trie + dist : next) - start));
22541                     if (dist) {
22542                         if (!nextbranch)
22543                             nextbranch= this_trie + trie->jump[0];
22544                         DUMPUNTIL(this_trie + dist, nextbranch);
22545                     }
22546                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
22547                         nextbranch= regnext((regnode *)nextbranch);
22548                 } else {
22549                     Perl_re_printf( aTHX_  "\n");
22550                 }
22551             }
22552             if (last && next > last)
22553                 node= last;
22554             else
22555                 node= next;
22556         }
22557         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
22558             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
22559                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
22560         }
22561         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
22562             assert(next);
22563             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
22564         }
22565         else if ( op == PLUS || op == STAR) {
22566             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
22567         }
22568         else if (PL_regkind[(U8)op] == EXACT || op == ANYOFHs) {
22569             /* Literal string, where present. */
22570             node += NODE_SZ_STR(node) - 1;
22571             node = NEXTOPER(node);
22572         }
22573         else {
22574             node = NEXTOPER(node);
22575             node += regarglen[(U8)op];
22576         }
22577         if (op == CURLYX || op == OPEN || op == SROPEN)
22578             indent++;
22579     }
22580     CLEAR_OPTSTART;
22581 #ifdef DEBUG_DUMPUNTIL
22582     Perl_re_printf( aTHX_  "--- %d\n", (int)indent);
22583 #endif
22584     return node;
22585 }
22586
22587 #endif  /* DEBUGGING */
22588
22589 #ifndef PERL_IN_XSUB_RE
22590
22591 #include "uni_keywords.h"
22592
22593 void
22594 Perl_init_uniprops(pTHX)
22595 {
22596     dVAR;
22597
22598 #ifdef DEBUGGING
22599     char * dump_len_string;
22600
22601     dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN");
22602     if (   ! dump_len_string
22603         || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL))
22604     {
22605         PL_dump_re_max_len = 60;    /* A reasonable default */
22606     }
22607 #endif
22608
22609     PL_user_def_props = newHV();
22610
22611 #ifdef USE_ITHREADS
22612
22613     HvSHAREKEYS_off(PL_user_def_props);
22614     PL_user_def_props_aTHX = aTHX;
22615
22616 #endif
22617
22618     /* Set up the inversion list interpreter-level variables */
22619
22620     PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
22621     PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]);
22622     PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]);
22623     PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]);
22624     PL_XPosix_ptrs[_CC_CASED] =  _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]);
22625     PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]);
22626     PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]);
22627     PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]);
22628     PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]);
22629     PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]);
22630     PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]);
22631     PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]);
22632     PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]);
22633     PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]);
22634     PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]);
22635     PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]);
22636
22637     PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]);
22638     PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]);
22639     PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]);
22640     PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]);
22641     PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA];
22642     PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]);
22643     PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]);
22644     PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]);
22645     PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]);
22646     PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]);
22647     PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]);
22648     PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]);
22649     PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]);
22650     PL_Posix_ptrs[_CC_VERTSPACE] = NULL;
22651     PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]);
22652     PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]);
22653
22654     PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist);
22655     PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist);
22656     PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist);
22657     PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist);
22658     PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist);
22659
22660     PL_InBitmap = _new_invlist_C_array(InBitmap_invlist);
22661     PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
22662     PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
22663     PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
22664
22665     PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]);
22666
22667     PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]);
22668     PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]);
22669
22670     PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]);
22671     PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]);
22672
22673     PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]);
22674     PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
22675                                             UNI__PERL_FOLDS_TO_MULTI_CHAR]);
22676     PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[
22677                                             UNI__PERL_IS_IN_MULTI_CHAR_FOLD]);
22678     PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist);
22679     PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist);
22680     PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist);
22681     PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist);
22682     PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist);
22683     PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist);
22684     PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]);
22685     PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist);
22686     PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]);
22687
22688 #ifdef UNI_XIDC
22689     /* The below are used only by deprecated functions.  They could be removed */
22690     PL_utf8_xidcont  = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]);
22691     PL_utf8_idcont   = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]);
22692     PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]);
22693 #endif
22694 }
22695
22696 #if 0
22697
22698 This code was mainly added for backcompat to give a warning for non-portable
22699 code points in user-defined properties.  But experiments showed that the
22700 warning in earlier perls were only omitted on overflow, which should be an
22701 error, so there really isnt a backcompat issue, and actually adding the
22702 warning when none was present before might cause breakage, for little gain.  So
22703 khw left this code in, but not enabled.  Tests were never added.
22704
22705 embed.fnc entry:
22706 Ei      |const char *|get_extended_utf8_msg|const UV cp
22707
22708 PERL_STATIC_INLINE const char *
22709 S_get_extended_utf8_msg(pTHX_ const UV cp)
22710 {
22711     U8 dummy[UTF8_MAXBYTES + 1];
22712     HV *msgs;
22713     SV **msg;
22714
22715     uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED,
22716                              &msgs);
22717
22718     msg = hv_fetchs(msgs, "text", 0);
22719     assert(msg);
22720
22721     (void) sv_2mortal((SV *) msgs);
22722
22723     return SvPVX(*msg);
22724 }
22725
22726 #endif
22727
22728 SV *
22729 Perl_handle_user_defined_property(pTHX_
22730
22731     /* Parses the contents of a user-defined property definition; returning the
22732      * expanded definition if possible.  If so, the return is an inversion
22733      * list.
22734      *
22735      * If there are subroutines that are part of the expansion and which aren't
22736      * known at the time of the call to this function, this returns what
22737      * parse_uniprop_string() returned for the first one encountered.
22738      *
22739      * If an error was found, NULL is returned, and 'msg' gets a suitable
22740      * message appended to it.  (Appending allows the back trace of how we got
22741      * to the faulty definition to be displayed through nested calls of
22742      * user-defined subs.)
22743      *
22744      * The caller IS responsible for freeing any returned SV.
22745      *
22746      * The syntax of the contents is pretty much described in perlunicode.pod,
22747      * but we also allow comments on each line */
22748
22749     const char * name,          /* Name of property */
22750     const STRLEN name_len,      /* The name's length in bytes */
22751     const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
22752     const bool to_fold,         /* ? Is this under /i */
22753     const bool runtime,         /* ? Are we in compile- or run-time */
22754     const bool deferrable,      /* Is it ok for this property's full definition
22755                                    to be deferred until later? */
22756     SV* contents,               /* The property's definition */
22757     bool *user_defined_ptr,     /* This will be set TRUE as we wouldn't be
22758                                    getting called unless this is thought to be
22759                                    a user-defined property */
22760     SV * msg,                   /* Any error or warning msg(s) are appended to
22761                                    this */
22762     const STRLEN level)         /* Recursion level of this call */
22763 {
22764     STRLEN len;
22765     const char * string         = SvPV_const(contents, len);
22766     const char * const e        = string + len;
22767     const bool is_contents_utf8 = cBOOL(SvUTF8(contents));
22768     const STRLEN msgs_length_on_entry = SvCUR(msg);
22769
22770     const char * s0 = string;   /* Points to first byte in the current line
22771                                    being parsed in 'string' */
22772     const char overflow_msg[] = "Code point too large in \"";
22773     SV* running_definition = NULL;
22774
22775     PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY;
22776
22777     *user_defined_ptr = TRUE;
22778
22779     /* Look at each line */
22780     while (s0 < e) {
22781         const char * s;     /* Current byte */
22782         char op = '+';      /* Default operation is 'union' */
22783         IV   min = 0;       /* range begin code point */
22784         IV   max = -1;      /* and range end */
22785         SV* this_definition;
22786
22787         /* Skip comment lines */
22788         if (*s0 == '#') {
22789             s0 = strchr(s0, '\n');
22790             if (s0 == NULL) {
22791                 break;
22792             }
22793             s0++;
22794             continue;
22795         }
22796
22797         /* For backcompat, allow an empty first line */
22798         if (*s0 == '\n') {
22799             s0++;
22800             continue;
22801         }
22802
22803         /* First character in the line may optionally be the operation */
22804         if (   *s0 == '+'
22805             || *s0 == '!'
22806             || *s0 == '-'
22807             || *s0 == '&')
22808         {
22809             op = *s0++;
22810         }
22811
22812         /* If the line is one or two hex digits separated by blank space, its
22813          * a range; otherwise it is either another user-defined property or an
22814          * error */
22815
22816         s = s0;
22817
22818         if (! isXDIGIT(*s)) {
22819             goto check_if_property;
22820         }
22821
22822         do { /* Each new hex digit will add 4 bits. */
22823             if (min > ( (IV) MAX_LEGAL_CP >> 4)) {
22824                 s = strchr(s, '\n');
22825                 if (s == NULL) {
22826                     s = e;
22827                 }
22828                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22829                 sv_catpv(msg, overflow_msg);
22830                 Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22831                                      UTF8fARG(is_contents_utf8, s - s0, s0));
22832                 sv_catpvs(msg, "\"");
22833                 goto return_failure;
22834             }
22835
22836             /* Accumulate this digit into the value */
22837             min = (min << 4) + READ_XDIGIT(s);
22838         } while (isXDIGIT(*s));
22839
22840         while (isBLANK(*s)) { s++; }
22841
22842         /* We allow comments at the end of the line */
22843         if (*s == '#') {
22844             s = strchr(s, '\n');
22845             if (s == NULL) {
22846                 s = e;
22847             }
22848             s++;
22849         }
22850         else if (s < e && *s != '\n') {
22851             if (! isXDIGIT(*s)) {
22852                 goto check_if_property;
22853             }
22854
22855             /* Look for the high point of the range */
22856             max = 0;
22857             do {
22858                 if (max > ( (IV) MAX_LEGAL_CP >> 4)) {
22859                     s = strchr(s, '\n');
22860                     if (s == NULL) {
22861                         s = e;
22862                     }
22863                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22864                     sv_catpv(msg, overflow_msg);
22865                     Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22866                                       UTF8fARG(is_contents_utf8, s - s0, s0));
22867                     sv_catpvs(msg, "\"");
22868                     goto return_failure;
22869                 }
22870
22871                 max = (max << 4) + READ_XDIGIT(s);
22872             } while (isXDIGIT(*s));
22873
22874             while (isBLANK(*s)) { s++; }
22875
22876             if (*s == '#') {
22877                 s = strchr(s, '\n');
22878                 if (s == NULL) {
22879                     s = e;
22880                 }
22881             }
22882             else if (s < e && *s != '\n') {
22883                 goto check_if_property;
22884             }
22885         }
22886
22887         if (max == -1) {    /* The line only had one entry */
22888             max = min;
22889         }
22890         else if (max < min) {
22891             if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22892             sv_catpvs(msg, "Illegal range in \"");
22893             Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22894                                 UTF8fARG(is_contents_utf8, s - s0, s0));
22895             sv_catpvs(msg, "\"");
22896             goto return_failure;
22897         }
22898
22899 #if 0   /* See explanation at definition above of get_extended_utf8_msg() */
22900
22901         if (   UNICODE_IS_PERL_EXTENDED(min)
22902             || UNICODE_IS_PERL_EXTENDED(max))
22903         {
22904             if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
22905
22906             /* If both code points are non-portable, warn only on the lower
22907              * one. */
22908             sv_catpv(msg, get_extended_utf8_msg(
22909                                             (UNICODE_IS_PERL_EXTENDED(min))
22910                                             ? min : max));
22911             sv_catpvs(msg, " in \"");
22912             Perl_sv_catpvf(aTHX_ msg, "%" UTF8f,
22913                                  UTF8fARG(is_contents_utf8, s - s0, s0));
22914             sv_catpvs(msg, "\"");
22915         }
22916
22917 #endif
22918
22919         /* Here, this line contains a legal range */
22920         this_definition = sv_2mortal(_new_invlist(2));
22921         this_definition = _add_range_to_invlist(this_definition, min, max);
22922         goto calculate;
22923
22924       check_if_property:
22925
22926         /* Here it isn't a legal range line.  See if it is a legal property
22927          * line.  First find the end of the meat of the line */
22928         s = strpbrk(s, "#\n");
22929         if (s == NULL) {
22930             s = e;
22931         }
22932
22933         /* Ignore trailing blanks in keeping with the requirements of
22934          * parse_uniprop_string() */
22935         s--;
22936         while (s > s0 && isBLANK_A(*s)) {
22937             s--;
22938         }
22939         s++;
22940
22941         this_definition = parse_uniprop_string(s0, s - s0,
22942                                                is_utf8, to_fold, runtime,
22943                                                deferrable,
22944                                                user_defined_ptr, msg,
22945                                                (name_len == 0)
22946                                                 ? level /* Don't increase level
22947                                                            if input is empty */
22948                                                 : level + 1
22949                                               );
22950         if (this_definition == NULL) {
22951             goto return_failure;    /* 'msg' should have had the reason
22952                                        appended to it by the above call */
22953         }
22954
22955         if (! is_invlist(this_definition)) {    /* Unknown at this time */
22956             return newSVsv(this_definition);
22957         }
22958
22959         if (*s != '\n') {
22960             s = strchr(s, '\n');
22961             if (s == NULL) {
22962                 s = e;
22963             }
22964         }
22965
22966       calculate:
22967
22968         switch (op) {
22969             case '+':
22970                 _invlist_union(running_definition, this_definition,
22971                                                         &running_definition);
22972                 break;
22973             case '-':
22974                 _invlist_subtract(running_definition, this_definition,
22975                                                         &running_definition);
22976                 break;
22977             case '&':
22978                 _invlist_intersection(running_definition, this_definition,
22979                                                         &running_definition);
22980                 break;
22981             case '!':
22982                 _invlist_union_complement_2nd(running_definition,
22983                                         this_definition, &running_definition);
22984                 break;
22985             default:
22986                 Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d",
22987                                  __FILE__, __LINE__, op);
22988                 break;
22989         }
22990
22991         /* Position past the '\n' */
22992         s0 = s + 1;
22993     }   /* End of loop through the lines of 'contents' */
22994
22995     /* Here, we processed all the lines in 'contents' without error.  If we
22996      * didn't add any warnings, simply return success */
22997     if (msgs_length_on_entry == SvCUR(msg)) {
22998
22999         /* If the expansion was empty, the answer isn't nothing: its an empty
23000          * inversion list */
23001         if (running_definition == NULL) {
23002             running_definition = _new_invlist(1);
23003         }
23004
23005         return running_definition;
23006     }
23007
23008     /* Otherwise, add some explanatory text, but we will return success */
23009     goto return_msg;
23010
23011   return_failure:
23012     running_definition = NULL;
23013
23014   return_msg:
23015
23016     if (name_len > 0) {
23017         sv_catpvs(msg, " in expansion of ");
23018         Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
23019     }
23020
23021     return running_definition;
23022 }
23023
23024 /* As explained below, certain operations need to take place in the first
23025  * thread created.  These macros switch contexts */
23026 #ifdef USE_ITHREADS
23027 #  define DECLARATION_FOR_GLOBAL_CONTEXT                                    \
23028                                         PerlInterpreter * save_aTHX = aTHX;
23029 #  define SWITCH_TO_GLOBAL_CONTEXT                                          \
23030                            PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX))
23031 #  define RESTORE_CONTEXT  PERL_SET_CONTEXT((aTHX = save_aTHX));
23032 #  define CUR_CONTEXT      aTHX
23033 #  define ORIGINAL_CONTEXT save_aTHX
23034 #else
23035 #  define DECLARATION_FOR_GLOBAL_CONTEXT
23036 #  define SWITCH_TO_GLOBAL_CONTEXT          NOOP
23037 #  define RESTORE_CONTEXT                   NOOP
23038 #  define CUR_CONTEXT                       NULL
23039 #  define ORIGINAL_CONTEXT                  NULL
23040 #endif
23041
23042 STATIC void
23043 S_delete_recursion_entry(pTHX_ void *key)
23044 {
23045     /* Deletes the entry used to detect recursion when expanding user-defined
23046      * properties.  This is a function so it can be set up to be called even if
23047      * the program unexpectedly quits */
23048
23049     dVAR;
23050     SV ** current_entry;
23051     const STRLEN key_len = strlen((const char *) key);
23052     DECLARATION_FOR_GLOBAL_CONTEXT;
23053
23054     SWITCH_TO_GLOBAL_CONTEXT;
23055
23056     /* If the entry is one of these types, it is a permanent entry, and not the
23057      * one used to detect recursions.  This function should delete only the
23058      * recursion entry */
23059     current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0);
23060     if (     current_entry
23061         && ! is_invlist(*current_entry)
23062         && ! SvPOK(*current_entry))
23063     {
23064         (void) hv_delete(PL_user_def_props, (const char *) key, key_len,
23065                                                                     G_DISCARD);
23066     }
23067
23068     RESTORE_CONTEXT;
23069 }
23070
23071 STATIC SV *
23072 S_get_fq_name(pTHX_
23073               const char * const name,    /* The first non-blank in the \p{}, \P{} */
23074               const Size_t name_len,      /* Its length in bytes, not including any trailing space */
23075               const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
23076               const bool has_colon_colon
23077              )
23078 {
23079     /* Returns a mortal SV containing the fully qualified version of the input
23080      * name */
23081
23082     SV * fq_name;
23083
23084     fq_name = newSVpvs_flags("", SVs_TEMP);
23085
23086     /* Use the current package if it wasn't included in our input */
23087     if (! has_colon_colon) {
23088         const HV * pkg = (IN_PERL_COMPILETIME)
23089                          ? PL_curstash
23090                          : CopSTASH(PL_curcop);
23091         const char* pkgname = HvNAME(pkg);
23092
23093         Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23094                       UTF8fARG(is_utf8, strlen(pkgname), pkgname));
23095         sv_catpvs(fq_name, "::");
23096     }
23097
23098     Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f,
23099                          UTF8fARG(is_utf8, name_len, name));
23100     return fq_name;
23101 }
23102
23103 SV *
23104 Perl_parse_uniprop_string(pTHX_
23105
23106     /* Parse the interior of a \p{}, \P{}.  Returns its definition if knowable
23107      * now.  If so, the return is an inversion list.
23108      *
23109      * If the property is user-defined, it is a subroutine, which in turn
23110      * may call other subroutines.  This function will call the whole nest of
23111      * them to get the definition they return; if some aren't known at the time
23112      * of the call to this function, the fully qualified name of the highest
23113      * level sub is returned.  It is an error to call this function at runtime
23114      * without every sub defined.
23115      *
23116      * If an error was found, NULL is returned, and 'msg' gets a suitable
23117      * message appended to it.  (Appending allows the back trace of how we got
23118      * to the faulty definition to be displayed through nested calls of
23119      * user-defined subs.)
23120      *
23121      * The caller should NOT try to free any returned inversion list.
23122      *
23123      * Other parameters will be set on return as described below */
23124
23125     const char * const name,    /* The first non-blank in the \p{}, \P{} */
23126     Size_t name_len,            /* Its length in bytes, not including any
23127                                    trailing space */
23128     const bool is_utf8,         /* ? Is 'name' encoded in UTF-8 */
23129     const bool to_fold,         /* ? Is this under /i */
23130     const bool runtime,         /* TRUE if this is being called at run time */
23131     const bool deferrable,      /* TRUE if it's ok for the definition to not be
23132                                    known at this call */
23133     bool *user_defined_ptr,     /* Upon return from this function it will be
23134                                    set to TRUE if any component is a
23135                                    user-defined property */
23136     SV * msg,                   /* Any error or warning msg(s) are appended to
23137                                    this */
23138    const STRLEN level)          /* Recursion level of this call */
23139 {
23140     dVAR;
23141     char* lookup_name;          /* normalized name for lookup in our tables */
23142     unsigned lookup_len;        /* Its length */
23143     bool stricter = FALSE;      /* Some properties have stricter name
23144                                    normalization rules, which we decide upon
23145                                    based on parsing */
23146
23147     /* nv= or numeric_value=, or possibly one of the cjk numeric properties
23148      * (though it requires extra effort to download them from Unicode and
23149      * compile perl to know about them) */
23150     bool is_nv_type = FALSE;
23151
23152     unsigned int i, j = 0;
23153     int equals_pos = -1;    /* Where the '=' is found, or negative if none */
23154     int slash_pos  = -1;    /* Where the '/' is found, or negative if none */
23155     int table_index = 0;    /* The entry number for this property in the table
23156                                of all Unicode property names */
23157     bool starts_with_Is = FALSE;  /* ? Does the name start with 'Is' */
23158     Size_t lookup_offset = 0;   /* Used to ignore the first few characters of
23159                                    the normalized name in certain situations */
23160     Size_t non_pkg_begin = 0;   /* Offset of first byte in 'name' that isn't
23161                                    part of a package name */
23162     Size_t lun_non_pkg_begin = 0;   /* Similarly for 'lookup_name' */
23163     bool could_be_user_defined = TRUE;  /* ? Could this be a user-defined
23164                                              property rather than a Unicode
23165                                              one. */
23166     SV * prop_definition = NULL;  /* The returned definition of 'name' or NULL
23167                                      if an error.  If it is an inversion list,
23168                                      it is the definition.  Otherwise it is a
23169                                      string containing the fully qualified sub
23170                                      name of 'name' */
23171     SV * fq_name = NULL;        /* For user-defined properties, the fully
23172                                    qualified name */
23173     bool invert_return = FALSE; /* ? Do we need to complement the result before
23174                                      returning it */
23175     bool stripped_utf8_pkg = FALSE; /* Set TRUE if the input includes an
23176                                        explicit utf8:: package that we strip
23177                                        off  */
23178     /* The expansion of properties that could be either user-defined or
23179      * official unicode ones is deferred until runtime, including a marker for
23180      * those that might be in the latter category.  This boolean indicates if
23181      * we've seen that marker.  If not, what we're parsing can't be such an
23182      * official Unicode property whose expansion was deferred */
23183     bool could_be_deferred_official = FALSE;
23184
23185     PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING;
23186
23187     /* The input will be normalized into 'lookup_name' */
23188     Newx(lookup_name, name_len, char);
23189     SAVEFREEPV(lookup_name);
23190
23191     /* Parse the input. */
23192     for (i = 0; i < name_len; i++) {
23193         char cur = name[i];
23194
23195         /* Most of the characters in the input will be of this ilk, being parts
23196          * of a name */
23197         if (isIDCONT_A(cur)) {
23198
23199             /* Case differences are ignored.  Our lookup routine assumes
23200              * everything is lowercase, so normalize to that */
23201             if (isUPPER_A(cur)) {
23202                 lookup_name[j++] = toLOWER_A(cur);
23203                 continue;
23204             }
23205
23206             if (cur == '_') { /* Don't include these in the normalized name */
23207                 continue;
23208             }
23209
23210             lookup_name[j++] = cur;
23211
23212             /* The first character in a user-defined name must be of this type.
23213              * */
23214             if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) {
23215                 could_be_user_defined = FALSE;
23216             }
23217
23218             continue;
23219         }
23220
23221         /* Here, the character is not something typically in a name,  But these
23222          * two types of characters (and the '_' above) can be freely ignored in
23223          * most situations.  Later it may turn out we shouldn't have ignored
23224          * them, and we have to reparse, but we don't have enough information
23225          * yet to make that decision */
23226         if (cur == '-' || isSPACE_A(cur)) {
23227             could_be_user_defined = FALSE;
23228             continue;
23229         }
23230
23231         /* An equals sign or single colon mark the end of the first part of
23232          * the property name */
23233         if (    cur == '='
23234             || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':')))
23235         {
23236             lookup_name[j++] = '='; /* Treat the colon as an '=' */
23237             equals_pos = j; /* Note where it occurred in the input */
23238             could_be_user_defined = FALSE;
23239             break;
23240         }
23241
23242         /* If this looks like it is a marker we inserted at compile time,
23243          * set a flag and otherwise ignore it.  If it isn't in the final
23244          * position, keep it as it would have been user input. */
23245         if (     UNLIKELY(cur == DEFERRED_COULD_BE_OFFICIAL_MARKERc)
23246             && ! deferrable
23247             &&   could_be_user_defined
23248             &&   i == name_len - 1)
23249         {
23250             name_len--;
23251             could_be_deferred_official = TRUE;
23252             continue;
23253         }
23254
23255         /* Otherwise, this character is part of the name. */
23256         lookup_name[j++] = cur;
23257
23258         /* Here it isn't a single colon, so if it is a colon, it must be a
23259          * double colon */
23260         if (cur == ':') {
23261
23262             /* A double colon should be a package qualifier.  We note its
23263              * position and continue.  Note that one could have
23264              *      pkg1::pkg2::...::foo
23265              * so that the position at the end of the loop will be just after
23266              * the final qualifier */
23267
23268             i++;
23269             non_pkg_begin = i + 1;
23270             lookup_name[j++] = ':';
23271             lun_non_pkg_begin = j;
23272         }
23273         else { /* Only word chars (and '::') can be in a user-defined name */
23274             could_be_user_defined = FALSE;
23275         }
23276     } /* End of parsing through the lhs of the property name (or all of it if
23277          no rhs) */
23278
23279 #define STRLENs(s)  (sizeof("" s "") - 1)
23280
23281     /* If there is a single package name 'utf8::', it is ambiguous.  It could
23282      * be for a user-defined property, or it could be a Unicode property, as
23283      * all of them are considered to be for that package.  For the purposes of
23284      * parsing the rest of the property, strip it off */
23285     if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) {
23286         lookup_name +=  STRLENs("utf8::");
23287         j -=  STRLENs("utf8::");
23288         equals_pos -=  STRLENs("utf8::");
23289         stripped_utf8_pkg = TRUE;
23290     }
23291
23292     /* Here, we are either done with the whole property name, if it was simple;
23293      * or are positioned just after the '=' if it is compound. */
23294
23295     if (equals_pos >= 0) {
23296         assert(! stricter); /* We shouldn't have set this yet */
23297
23298         /* Space immediately after the '=' is ignored */
23299         i++;
23300         for (; i < name_len; i++) {
23301             if (! isSPACE_A(name[i])) {
23302                 break;
23303             }
23304         }
23305
23306         /* Most punctuation after the equals indicates a subpattern, like
23307          * \p{foo=/bar/} */
23308         if (   isPUNCT_A(name[i])
23309             &&  name[i] != '-'
23310             &&  name[i] != '+'
23311             &&  name[i] != '_'
23312             &&  name[i] != '{'
23313                 /* A backslash means the real delimitter is the next character,
23314                  * but it must be punctuation */
23315             && (name[i] != '\\' || (i < name_len && isPUNCT_A(name[i+1]))))
23316         {
23317             /* Find the property.  The table includes the equals sign, so we
23318              * use 'j' as-is */
23319             table_index = match_uniprop((U8 *) lookup_name, j);
23320             if (table_index) {
23321                 const char * const * prop_values
23322                                             = UNI_prop_value_ptrs[table_index];
23323                 SV * subpattern;
23324                 Size_t subpattern_len;
23325                 REGEXP * subpattern_re;
23326                 char open = name[i++];
23327                 char close;
23328                 const char * pos_in_brackets;
23329                 bool escaped = 0;
23330
23331                 /* Backslash => delimitter is the character following.  We
23332                  * already checked that it is punctuation */
23333                 if (open == '\\') {
23334                     open = name[i++];
23335                     escaped = 1;
23336                 }
23337
23338                 /* This data structure is constructed so that the matching
23339                  * closing bracket is 3 past its matching opening.  The second
23340                  * set of closing is so that if the opening is something like
23341                  * ']', the closing will be that as well.  Something similar is
23342                  * done in toke.c */
23343                 pos_in_brackets = memCHRs("([<)]>)]>", open);
23344                 close = (pos_in_brackets) ? pos_in_brackets[3] : open;
23345
23346                 if (    i >= name_len
23347                     ||  name[name_len-1] != close
23348                     || (escaped && name[name_len-2] != '\\')
23349                         /* Also make sure that there are enough characters.
23350                          * e.g., '\\\' would show up incorrectly as legal even
23351                          * though it is too short */
23352                     || (SSize_t) (name_len - i - 1 - escaped) < 0)
23353                 {
23354                     sv_catpvs(msg, "Unicode property wildcard not terminated");
23355                     goto append_name_to_msg;
23356                 }
23357
23358                 Perl_ck_warner_d(aTHX_
23359                     packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS),
23360                     "The Unicode property wildcards feature is experimental");
23361
23362                 /* Now create and compile the wildcard subpattern.  Use /iaa
23363                  * because nothing outside of ASCII will match, and it the
23364                  * property values should all match /i.  Note that when the
23365                  * pattern fails to compile, our added text to the user's
23366                  * pattern will be displayed to the user, which is not so
23367                  * desirable. */
23368                 subpattern_len = name_len - i - 1 - escaped;
23369                 subpattern = Perl_newSVpvf(aTHX_ "(?iaa:%.*s)",
23370                                               (unsigned) subpattern_len,
23371                                               name + i);
23372                 subpattern = sv_2mortal(subpattern);
23373                 subpattern_re = re_compile(subpattern, 0);
23374                 assert(subpattern_re);  /* Should have died if didn't compile
23375                                          successfully */
23376
23377                 /* For each legal property value, see if the supplied pattern
23378                  * matches it. */
23379                 while (*prop_values) {
23380                     const char * const entry = *prop_values;
23381                     const Size_t len = strlen(entry);
23382                     SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP);
23383
23384                     if (pregexec(subpattern_re,
23385                                  (char *) entry,
23386                                  (char *) entry + len,
23387                                  (char *) entry, 0,
23388                                  entry_sv,
23389                                  0))
23390                     { /* Here, matched.  Add to the returned list */
23391                         Size_t total_len = j + len;
23392                         SV * sub_invlist = NULL;
23393                         char * this_string;
23394
23395                         /* We know this is a legal \p{property=value}.  Call
23396                          * the function to return the list of code points that
23397                          * match it */
23398                         Newxz(this_string, total_len + 1, char);
23399                         Copy(lookup_name, this_string, j, char);
23400                         my_strlcat(this_string, entry, total_len + 1);
23401                         SAVEFREEPV(this_string);
23402                         sub_invlist = parse_uniprop_string(this_string,
23403                                                            total_len,
23404                                                            is_utf8,
23405                                                            to_fold,
23406                                                            runtime,
23407                                                            deferrable,
23408                                                            user_defined_ptr,
23409                                                            msg,
23410                                                            level + 1);
23411                         _invlist_union(prop_definition, sub_invlist,
23412                                        &prop_definition);
23413                     }
23414
23415                     prop_values++;  /* Next iteration, look at next propvalue */
23416                 } /* End of looking through property values; (the data
23417                      structure is terminated by a NULL ptr) */
23418
23419                 SvREFCNT_dec_NN(subpattern_re);
23420
23421                 if (prop_definition) {
23422                     return prop_definition;
23423                 }
23424
23425                 sv_catpvs(msg, "No Unicode property value wildcard matches:");
23426                 goto append_name_to_msg;
23427             }
23428
23429             /* Here's how khw thinks we should proceed to handle the properties
23430              * not yet done:    Bidi Mirroring Glyph
23431                                 Bidi Paired Bracket
23432                                 Case Folding  (both full and simple)
23433                                 Decomposition Mapping
23434                                 Equivalent Unified Ideograph
23435                                 Name
23436                                 Name Alias
23437                                 Lowercase Mapping  (both full and simple)
23438                                 NFKC Case Fold
23439                                 Titlecase Mapping  (both full and simple)
23440                                 Uppercase Mapping  (both full and simple)
23441              * Move the part that looks at the property values into a perl
23442              * script, like utf8_heavy.pl was done.  This makes things somewhat
23443              * easier, but most importantly, it avoids always adding all these
23444              * strings to the memory usage when the feature is little-used.
23445              *
23446              * The property values would all be concatenated into a single
23447              * string per property with each value on a separate line, and the
23448              * code point it's for on alternating lines.  Then we match the
23449              * user's input pattern m//mg, without having to worry about their
23450              * uses of '^' and '$'.  Only the values that aren't the default
23451              * would be in the strings.  Code points would be in UTF-8.  The
23452              * search pattern that we would construct would look like
23453              * (?: \n (code-point_re) \n (?aam: user-re ) \n )
23454              * And so $1 would contain the code point that matched the user-re.
23455              * For properties where the default is the code point itself, such
23456              * as any of the case changing mappings, the string would otherwise
23457              * consist of all Unicode code points in UTF-8 strung together.
23458              * This would be impractical.  So instead, examine their compiled
23459              * pattern, looking at the ssc.  If none, reject the pattern as an
23460              * error.  Otherwise run the pattern against every code point in
23461              * the ssc.  The ssc is kind of like tr18's 3.9 Possible Match Sets
23462              * And it might be good to create an API to return the ssc.
23463              *
23464              * For the name properties, a new function could be created in
23465              * charnames which essentially does the same thing as above,
23466              * sharing Name.pl with the other charname functions.  Don't know
23467              * about loose name matching, or algorithmically determined names.
23468              * Decomposition.pl similarly.
23469              *
23470              * It might be that a new pattern modifier would have to be
23471              * created, like /t for resTricTed, which changed the behavior of
23472              * some constructs in their subpattern, like \A. */
23473         } /* End of is a wildcard subppattern */
23474
23475
23476         /* Certain properties whose values are numeric need special handling.
23477          * They may optionally be prefixed by 'is'.  Ignore that prefix for the
23478          * purposes of checking if this is one of those properties */
23479         if (memBEGINPs(lookup_name, j, "is")) {
23480             lookup_offset = 2;
23481         }
23482
23483         /* Then check if it is one of these specially-handled properties.  The
23484          * possibilities are hard-coded because easier this way, and the list
23485          * is unlikely to change.
23486          *
23487          * All numeric value type properties are of this ilk, and are also
23488          * special in a different way later on.  So find those first.  There
23489          * are several numeric value type properties in the Unihan DB (which is
23490          * unlikely to be compiled with perl, but we handle it here in case it
23491          * does get compiled).  They all end with 'numeric'.  The interiors
23492          * aren't checked for the precise property.  This would stop working if
23493          * a cjk property were to be created that ended with 'numeric' and
23494          * wasn't a numeric type */
23495         is_nv_type = memEQs(lookup_name + lookup_offset,
23496                        j - 1 - lookup_offset, "numericvalue")
23497                   || memEQs(lookup_name + lookup_offset,
23498                       j - 1 - lookup_offset, "nv")
23499                   || (   memENDPs(lookup_name + lookup_offset,
23500                             j - 1 - lookup_offset, "numeric")
23501                       && (   memBEGINPs(lookup_name + lookup_offset,
23502                                       j - 1 - lookup_offset, "cjk")
23503                           || memBEGINPs(lookup_name + lookup_offset,
23504                                       j - 1 - lookup_offset, "k")));
23505         if (   is_nv_type
23506             || memEQs(lookup_name + lookup_offset,
23507                       j - 1 - lookup_offset, "canonicalcombiningclass")
23508             || memEQs(lookup_name + lookup_offset,
23509                       j - 1 - lookup_offset, "ccc")
23510             || memEQs(lookup_name + lookup_offset,
23511                       j - 1 - lookup_offset, "age")
23512             || memEQs(lookup_name + lookup_offset,
23513                       j - 1 - lookup_offset, "in")
23514             || memEQs(lookup_name + lookup_offset,
23515                       j - 1 - lookup_offset, "presentin"))
23516         {
23517             unsigned int k;
23518
23519             /* Since the stuff after the '=' is a number, we can't throw away
23520              * '-' willy-nilly, as those could be a minus sign.  Other stricter
23521              * rules also apply.  However, these properties all can have the
23522              * rhs not be a number, in which case they contain at least one
23523              * alphabetic.  In those cases, the stricter rules don't apply.
23524              * But the numeric type properties can have the alphas [Ee] to
23525              * signify an exponent, and it is still a number with stricter
23526              * rules.  So look for an alpha that signifies not-strict */
23527             stricter = TRUE;
23528             for (k = i; k < name_len; k++) {
23529                 if (   isALPHA_A(name[k])
23530                     && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E')))
23531                 {
23532                     stricter = FALSE;
23533                     break;
23534                 }
23535             }
23536         }
23537
23538         if (stricter) {
23539
23540             /* A number may have a leading '+' or '-'.  The latter is retained
23541              * */
23542             if (name[i] == '+') {
23543                 i++;
23544             }
23545             else if (name[i] == '-') {
23546                 lookup_name[j++] = '-';
23547                 i++;
23548             }
23549
23550             /* Skip leading zeros including single underscores separating the
23551              * zeros, or between the final leading zero and the first other
23552              * digit */
23553             for (; i < name_len - 1; i++) {
23554                 if (    name[i] != '0'
23555                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
23556                 {
23557                     break;
23558                 }
23559             }
23560         }
23561     }
23562     else {  /* No '=' */
23563
23564        /* Only a few properties without an '=' should be parsed with stricter
23565         * rules.  The list is unlikely to change. */
23566         if (   memBEGINPs(lookup_name, j, "perl")
23567             && memNEs(lookup_name + 4, j - 4, "space")
23568             && memNEs(lookup_name + 4, j - 4, "word"))
23569         {
23570             stricter = TRUE;
23571
23572             /* We set the inputs back to 0 and the code below will reparse,
23573              * using strict */
23574             i = j = 0;
23575         }
23576     }
23577
23578     /* Here, we have either finished the property, or are positioned to parse
23579      * the remainder, and we know if stricter rules apply.  Finish out, if not
23580      * already done */
23581     for (; i < name_len; i++) {
23582         char cur = name[i];
23583
23584         /* In all instances, case differences are ignored, and we normalize to
23585          * lowercase */
23586         if (isUPPER_A(cur)) {
23587             lookup_name[j++] = toLOWER(cur);
23588             continue;
23589         }
23590
23591         /* An underscore is skipped, but not under strict rules unless it
23592          * separates two digits */
23593         if (cur == '_') {
23594             if (    stricter
23595                 && (     i == 0 || (int) i == equals_pos || i == name_len- 1
23596                     || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1])))
23597             {
23598                 lookup_name[j++] = '_';
23599             }
23600             continue;
23601         }
23602
23603         /* Hyphens are skipped except under strict */
23604         if (cur == '-' && ! stricter) {
23605             continue;
23606         }
23607
23608         /* XXX Bug in documentation.  It says white space skipped adjacent to
23609          * non-word char.  Maybe we should, but shouldn't skip it next to a dot
23610          * in a number */
23611         if (isSPACE_A(cur) && ! stricter) {
23612             continue;
23613         }
23614
23615         lookup_name[j++] = cur;
23616
23617         /* Unless this is a non-trailing slash, we are done with it */
23618         if (i >= name_len - 1 || cur != '/') {
23619             continue;
23620         }
23621
23622         slash_pos = j;
23623
23624         /* A slash in the 'numeric value' property indicates that what follows
23625          * is a denominator.  It can have a leading '+' and '0's that should be
23626          * skipped.  But we have never allowed a negative denominator, so treat
23627          * a minus like every other character.  (No need to rule out a second
23628          * '/', as that won't match anything anyway */
23629         if (is_nv_type) {
23630             i++;
23631             if (i < name_len && name[i] == '+') {
23632                 i++;
23633             }
23634
23635             /* Skip leading zeros including underscores separating digits */
23636             for (; i < name_len - 1; i++) {
23637                 if (   name[i] != '0'
23638                     && (name[i] != '_' || ! isDIGIT_A(name[i+1])))
23639                 {
23640                     break;
23641                 }
23642             }
23643
23644             /* Store the first real character in the denominator */
23645             if (i < name_len) {
23646                 lookup_name[j++] = name[i];
23647             }
23648         }
23649     }
23650
23651     /* Here are completely done parsing the input 'name', and 'lookup_name'
23652      * contains a copy, normalized.
23653      *
23654      * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and
23655      * different from without the underscores.  */
23656     if (  (   UNLIKELY(memEQs(lookup_name, j, "l"))
23657            || UNLIKELY(memEQs(lookup_name, j, "gc=l")))
23658         && UNLIKELY(name[name_len-1] == '_'))
23659     {
23660         lookup_name[j++] = '&';
23661     }
23662
23663     /* If the original input began with 'In' or 'Is', it could be a subroutine
23664      * call to a user-defined property instead of a Unicode property name. */
23665     if (    name_len - non_pkg_begin > 2
23666         &&  name[non_pkg_begin+0] == 'I'
23667         && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's'))
23668     {
23669         /* Names that start with In have different characterstics than those
23670          * that start with Is */
23671         if (name[non_pkg_begin+1] == 's') {
23672             starts_with_Is = TRUE;
23673         }
23674     }
23675     else {
23676         could_be_user_defined = FALSE;
23677     }
23678
23679     if (could_be_user_defined) {
23680         CV* user_sub;
23681
23682         /* If the user defined property returns the empty string, it could
23683          * easily be because the pattern is being compiled before the data it
23684          * actually needs to compile is available.  This could be argued to be
23685          * a bug in the perl code, but this is a change of behavior for Perl,
23686          * so we handle it.  This means that intentionally returning nothing
23687          * will not be resolved until runtime */
23688         bool empty_return = FALSE;
23689
23690         /* Here, the name could be for a user defined property, which are
23691          * implemented as subs. */
23692         user_sub = get_cvn_flags(name, name_len, 0);
23693         if (! user_sub) {
23694
23695             /* Here, the property name could be a user-defined one, but there
23696              * is no subroutine to handle it (as of now).   Defer handling it
23697              * until runtime.  Otherwise, a block defined by Unicode in a later
23698              * release would get the synonym InFoo added for it, and existing
23699              * code that used that name would suddenly break if it referred to
23700              * the property before the sub was declared.  See [perl #134146] */
23701             if (deferrable) {
23702                 goto definition_deferred;
23703             }
23704
23705             /* Here, we are at runtime, and didn't find the user property.  It
23706              * could be an official property, but only if no package was
23707              * specified, or just the utf8:: package. */
23708             if (could_be_deferred_official) {
23709                 lookup_name += lun_non_pkg_begin;
23710                 j -= lun_non_pkg_begin;
23711             }
23712             else if (! stripped_utf8_pkg) {
23713                 goto unknown_user_defined;
23714             }
23715
23716             /* Drop down to look up in the official properties */
23717         }
23718         else {
23719             const char insecure[] = "Insecure user-defined property";
23720
23721             /* Here, there is a sub by the correct name.  Normally we call it
23722              * to get the property definition */
23723             dSP;
23724             SV * user_sub_sv = MUTABLE_SV(user_sub);
23725             SV * error;     /* Any error returned by calling 'user_sub' */
23726             SV * key;       /* The key into the hash of user defined sub names
23727                              */
23728             SV * placeholder;
23729             SV ** saved_user_prop_ptr;      /* Hash entry for this property */
23730
23731             /* How many times to retry when another thread is in the middle of
23732              * expanding the same definition we want */
23733             PERL_INT_FAST8_T retry_countdown = 10;
23734
23735             DECLARATION_FOR_GLOBAL_CONTEXT;
23736
23737             /* If we get here, we know this property is user-defined */
23738             *user_defined_ptr = TRUE;
23739
23740             /* We refuse to call a potentially tainted subroutine; returning an
23741              * error instead */
23742             if (TAINT_get) {
23743                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23744                 sv_catpvn(msg, insecure, sizeof(insecure) - 1);
23745                 goto append_name_to_msg;
23746             }
23747
23748             /* In principal, we only call each subroutine property definition
23749              * once during the life of the program.  This guarantees that the
23750              * property definition never changes.  The results of the single
23751              * sub call are stored in a hash, which is used instead for future
23752              * references to this property.  The property definition is thus
23753              * immutable.  But, to allow the user to have a /i-dependent
23754              * definition, we call the sub once for non-/i, and once for /i,
23755              * should the need arise, passing the /i status as a parameter.
23756              *
23757              * We start by constructing the hash key name, consisting of the
23758              * fully qualified subroutine name, preceded by the /i status, so
23759              * that there is a key for /i and a different key for non-/i */
23760             key = newSVpvn(((to_fold) ? "1" : "0"), 1);
23761             fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
23762                                           non_pkg_begin != 0);
23763             sv_catsv(key, fq_name);
23764             sv_2mortal(key);
23765
23766             /* We only call the sub once throughout the life of the program
23767              * (with the /i, non-/i exception noted above).  That means the
23768              * hash must be global and accessible to all threads.  It is
23769              * created at program start-up, before any threads are created, so
23770              * is accessible to all children.  But this creates some
23771              * complications.
23772              *
23773              * 1) The keys can't be shared, or else problems arise; sharing is
23774              *    turned off at hash creation time
23775              * 2) All SVs in it are there for the remainder of the life of the
23776              *    program, and must be created in the same interpreter context
23777              *    as the hash, or else they will be freed from the wrong pool
23778              *    at global destruction time.  This is handled by switching to
23779              *    the hash's context to create each SV going into it, and then
23780              *    immediately switching back
23781              * 3) All accesses to the hash must be controlled by a mutex, to
23782              *    prevent two threads from getting an unstable state should
23783              *    they simultaneously be accessing it.  The code below is
23784              *    crafted so that the mutex is locked whenever there is an
23785              *    access and unlocked only when the next stable state is
23786              *    achieved.
23787              *
23788              * The hash stores either the definition of the property if it was
23789              * valid, or, if invalid, the error message that was raised.  We
23790              * use the type of SV to distinguish.
23791              *
23792              * There's also the need to guard against the definition expansion
23793              * from infinitely recursing.  This is handled by storing the aTHX
23794              * of the expanding thread during the expansion.  Again the SV type
23795              * is used to distinguish this from the other two cases.  If we
23796              * come to here and the hash entry for this property is our aTHX,
23797              * it means we have recursed, and the code assumes that we would
23798              * infinitely recurse, so instead stops and raises an error.
23799              * (Any recursion has always been treated as infinite recursion in
23800              * this feature.)
23801              *
23802              * If instead, the entry is for a different aTHX, it means that
23803              * that thread has gotten here first, and hasn't finished expanding
23804              * the definition yet.  We just have to wait until it is done.  We
23805              * sleep and retry a few times, returning an error if the other
23806              * thread doesn't complete. */
23807
23808           re_fetch:
23809             USER_PROP_MUTEX_LOCK;
23810
23811             /* If we have an entry for this key, the subroutine has already
23812              * been called once with this /i status. */
23813             saved_user_prop_ptr = hv_fetch(PL_user_def_props,
23814                                                    SvPVX(key), SvCUR(key), 0);
23815             if (saved_user_prop_ptr) {
23816
23817                 /* If the saved result is an inversion list, it is the valid
23818                  * definition of this property */
23819                 if (is_invlist(*saved_user_prop_ptr)) {
23820                     prop_definition = *saved_user_prop_ptr;
23821
23822                     /* The SV in the hash won't be removed until global
23823                      * destruction, so it is stable and we can unlock */
23824                     USER_PROP_MUTEX_UNLOCK;
23825
23826                     /* The caller shouldn't try to free this SV */
23827                     return prop_definition;
23828                 }
23829
23830                 /* Otherwise, if it is a string, it is the error message
23831                  * that was returned when we first tried to evaluate this
23832                  * property.  Fail, and append the message */
23833                 if (SvPOK(*saved_user_prop_ptr)) {
23834                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23835                     sv_catsv(msg, *saved_user_prop_ptr);
23836
23837                     /* The SV in the hash won't be removed until global
23838                      * destruction, so it is stable and we can unlock */
23839                     USER_PROP_MUTEX_UNLOCK;
23840
23841                     return NULL;
23842                 }
23843
23844                 assert(SvIOK(*saved_user_prop_ptr));
23845
23846                 /* Here, we have an unstable entry in the hash.  Either another
23847                  * thread is in the middle of expanding the property's
23848                  * definition, or we are ourselves recursing.  We use the aTHX
23849                  * in it to distinguish */
23850                 if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) {
23851
23852                     /* Here, it's another thread doing the expanding.  We've
23853                      * looked as much as we are going to at the contents of the
23854                      * hash entry.  It's safe to unlock. */
23855                     USER_PROP_MUTEX_UNLOCK;
23856
23857                     /* Retry a few times */
23858                     if (retry_countdown-- > 0) {
23859                         PerlProc_sleep(1);
23860                         goto re_fetch;
23861                     }
23862
23863                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23864                     sv_catpvs(msg, "Timeout waiting for another thread to "
23865                                    "define");
23866                     goto append_name_to_msg;
23867                 }
23868
23869                 /* Here, we are recursing; don't dig any deeper */
23870                 USER_PROP_MUTEX_UNLOCK;
23871
23872                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23873                 sv_catpvs(msg,
23874                           "Infinite recursion in user-defined property");
23875                 goto append_name_to_msg;
23876             }
23877
23878             /* Here, this thread has exclusive control, and there is no entry
23879              * for this property in the hash.  So we have the go ahead to
23880              * expand the definition ourselves. */
23881
23882             PUSHSTACKi(PERLSI_MAGIC);
23883             ENTER;
23884
23885             /* Create a temporary placeholder in the hash to detect recursion
23886              * */
23887             SWITCH_TO_GLOBAL_CONTEXT;
23888             placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT));
23889             (void) hv_store_ent(PL_user_def_props, key, placeholder, 0);
23890             RESTORE_CONTEXT;
23891
23892             /* Now that we have a placeholder, we can let other threads
23893              * continue */
23894             USER_PROP_MUTEX_UNLOCK;
23895
23896             /* Make sure the placeholder always gets destroyed */
23897             SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key));
23898
23899             PUSHMARK(SP);
23900             SAVETMPS;
23901
23902             /* Call the user's function, with the /i status as a parameter.
23903              * Note that we have gone to a lot of trouble to keep this call
23904              * from being within the locked mutex region. */
23905             XPUSHs(boolSV(to_fold));
23906             PUTBACK;
23907
23908             /* The following block was taken from swash_init().  Presumably
23909              * they apply to here as well, though we no longer use a swash --
23910              * khw */
23911             SAVEHINTS();
23912             save_re_context();
23913             /* We might get here via a subroutine signature which uses a utf8
23914              * parameter name, at which point PL_subname will have been set
23915              * but not yet used. */
23916             save_item(PL_subname);
23917
23918             (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR);
23919
23920             SPAGAIN;
23921
23922             error = ERRSV;
23923             if (TAINT_get || SvTRUE(error)) {
23924                 if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
23925                 if (SvTRUE(error)) {
23926                     sv_catpvs(msg, "Error \"");
23927                     sv_catsv(msg, error);
23928                     sv_catpvs(msg, "\"");
23929                 }
23930                 if (TAINT_get) {
23931                     if (SvTRUE(error)) sv_catpvs(msg, "; ");
23932                     sv_catpvn(msg, insecure, sizeof(insecure) - 1);
23933                 }
23934
23935                 if (name_len > 0) {
23936                     sv_catpvs(msg, " in expansion of ");
23937                     Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8,
23938                                                                   name_len,
23939                                                                   name));
23940                 }
23941
23942                 (void) POPs;
23943                 prop_definition = NULL;
23944             }
23945             else {  /* G_SCALAR guarantees a single return value */
23946                 SV * contents = POPs;
23947
23948                 /* The contents is supposed to be the expansion of the property
23949                  * definition.  If the definition is deferrable, and we got an
23950                  * empty string back, set a flag to later defer it (after clean
23951                  * up below). */
23952                 if (      deferrable
23953                     && (! SvPOK(contents) || SvCUR(contents) == 0))
23954                 {
23955                         empty_return = TRUE;
23956                 }
23957                 else { /* Otherwise, call a function to check for valid syntax,
23958                           and handle it */
23959
23960                     prop_definition = handle_user_defined_property(
23961                                                     name, name_len,
23962                                                     is_utf8, to_fold, runtime,
23963                                                     deferrable,
23964                                                     contents, user_defined_ptr,
23965                                                     msg,
23966                                                     level);
23967                 }
23968             }
23969
23970             /* Here, we have the results of the expansion.  Delete the
23971              * placeholder, and if the definition is now known, replace it with
23972              * that definition.  We need exclusive access to the hash, and we
23973              * can't let anyone else in, between when we delete the placeholder
23974              * and add the permanent entry */
23975             USER_PROP_MUTEX_LOCK;
23976
23977             S_delete_recursion_entry(aTHX_ SvPVX(key));
23978
23979             if (    ! empty_return
23980                 && (! prop_definition || is_invlist(prop_definition)))
23981             {
23982                 /* If we got success we use the inversion list defining the
23983                  * property; otherwise use the error message */
23984                 SWITCH_TO_GLOBAL_CONTEXT;
23985                 (void) hv_store_ent(PL_user_def_props,
23986                                     key,
23987                                     ((prop_definition)
23988                                      ? newSVsv(prop_definition)
23989                                      : newSVsv(msg)),
23990                                     0);
23991                 RESTORE_CONTEXT;
23992             }
23993
23994             /* All done, and the hash now has a permanent entry for this
23995              * property.  Give up exclusive control */
23996             USER_PROP_MUTEX_UNLOCK;
23997
23998             FREETMPS;
23999             LEAVE;
24000             POPSTACK;
24001
24002             if (empty_return) {
24003                 goto definition_deferred;
24004             }
24005
24006             if (prop_definition) {
24007
24008                 /* If the definition is for something not known at this time,
24009                  * we toss it, and go return the main property name, as that's
24010                  * the one the user will be aware of */
24011                 if (! is_invlist(prop_definition)) {
24012                     SvREFCNT_dec_NN(prop_definition);
24013                     goto definition_deferred;
24014                 }
24015
24016                 sv_2mortal(prop_definition);
24017             }
24018
24019             /* And return */
24020             return prop_definition;
24021
24022         }   /* End of calling the subroutine for the user-defined property */
24023     }       /* End of it could be a user-defined property */
24024
24025     /* Here it wasn't a user-defined property that is known at this time.  See
24026      * if it is a Unicode property */
24027
24028     lookup_len = j;     /* This is a more mnemonic name than 'j' */
24029
24030     /* Get the index into our pointer table of the inversion list corresponding
24031      * to the property */
24032     table_index = match_uniprop((U8 *) lookup_name, lookup_len);
24033
24034     /* If it didn't find the property ... */
24035     if (table_index == 0) {
24036
24037         /* Try again stripping off any initial 'Is'.  This is because we
24038          * promise that an initial Is is optional.  The same isn't true of
24039          * names that start with 'In'.  Those can match only blocks, and the
24040          * lookup table already has those accounted for. */
24041         if (starts_with_Is) {
24042             lookup_name += 2;
24043             lookup_len -= 2;
24044             equals_pos -= 2;
24045             slash_pos -= 2;
24046
24047             table_index = match_uniprop((U8 *) lookup_name, lookup_len);
24048         }
24049
24050         if (table_index == 0) {
24051             char * canonical;
24052
24053             /* Here, we didn't find it.  If not a numeric type property, and
24054              * can't be a user-defined one, it isn't a legal property */
24055             if (! is_nv_type) {
24056                 if (! could_be_user_defined) {
24057                     goto failed;
24058                 }
24059
24060                 /* Here, the property name is legal as a user-defined one.   At
24061                  * compile time, it might just be that the subroutine for that
24062                  * property hasn't been encountered yet, but at runtime, it's
24063                  * an error to try to use an undefined one */
24064                 if (! deferrable) {
24065                     goto unknown_user_defined;;
24066                 }
24067
24068                 goto definition_deferred;
24069             } /* End of isn't a numeric type property */
24070
24071             /* The numeric type properties need more work to decide.  What we
24072              * do is make sure we have the number in canonical form and look
24073              * that up. */
24074
24075             if (slash_pos < 0) {    /* No slash */
24076
24077                 /* When it isn't a rational, take the input, convert it to a
24078                  * NV, then create a canonical string representation of that
24079                  * NV. */
24080
24081                 NV value;
24082                 SSize_t value_len = lookup_len - equals_pos;
24083
24084                 /* Get the value */
24085                 if (   value_len <= 0
24086                     || my_atof3(lookup_name + equals_pos, &value,
24087                                 value_len)
24088                           != lookup_name + lookup_len)
24089                 {
24090                     goto failed;
24091                 }
24092
24093                 /* If the value is an integer, the canonical value is integral
24094                  * */
24095                 if (Perl_ceil(value) == value) {
24096                     canonical = Perl_form(aTHX_ "%.*s%.0" NVff,
24097                                             equals_pos, lookup_name, value);
24098                 }
24099                 else {  /* Otherwise, it is %e with a known precision */
24100                     char * exp_ptr;
24101
24102                     canonical = Perl_form(aTHX_ "%.*s%.*" NVef,
24103                                                 equals_pos, lookup_name,
24104                                                 PL_E_FORMAT_PRECISION, value);
24105
24106                     /* The exponent generated is expecting two digits, whereas
24107                      * %e on some systems will generate three.  Remove leading
24108                      * zeros in excess of 2 from the exponent.  We start
24109                      * looking for them after the '=' */
24110                     exp_ptr = strchr(canonical + equals_pos, 'e');
24111                     if (exp_ptr) {
24112                         char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */
24113                         SSize_t excess_exponent_len = strlen(cur_ptr) - 2;
24114
24115                         assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+');
24116
24117                         if (excess_exponent_len > 0) {
24118                             SSize_t leading_zeros = strspn(cur_ptr, "0");
24119                             SSize_t excess_leading_zeros
24120                                     = MIN(leading_zeros, excess_exponent_len);
24121                             if (excess_leading_zeros > 0) {
24122                                 Move(cur_ptr + excess_leading_zeros,
24123                                      cur_ptr,
24124                                      strlen(cur_ptr) - excess_leading_zeros
24125                                        + 1,  /* Copy the NUL as well */
24126                                      char);
24127                             }
24128                         }
24129                     }
24130                 }
24131             }
24132             else {  /* Has a slash.  Create a rational in canonical form  */
24133                 UV numerator, denominator, gcd, trial;
24134                 const char * end_ptr;
24135                 const char * sign = "";
24136
24137                 /* We can't just find the numerator, denominator, and do the
24138                  * division, then use the method above, because that is
24139                  * inexact.  And the input could be a rational that is within
24140                  * epsilon (given our precision) of a valid rational, and would
24141                  * then incorrectly compare valid.
24142                  *
24143                  * We're only interested in the part after the '=' */
24144                 const char * this_lookup_name = lookup_name + equals_pos;
24145                 lookup_len -= equals_pos;
24146                 slash_pos -= equals_pos;
24147
24148                 /* Handle any leading minus */
24149                 if (this_lookup_name[0] == '-') {
24150                     sign = "-";
24151                     this_lookup_name++;
24152                     lookup_len--;
24153                     slash_pos--;
24154                 }
24155
24156                 /* Convert the numerator to numeric */
24157                 end_ptr = this_lookup_name + slash_pos;
24158                 if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) {
24159                     goto failed;
24160                 }
24161
24162                 /* It better have included all characters before the slash */
24163                 if (*end_ptr != '/') {
24164                     goto failed;
24165                 }
24166
24167                 /* Set to look at just the denominator */
24168                 this_lookup_name += slash_pos;
24169                 lookup_len -= slash_pos;
24170                 end_ptr = this_lookup_name + lookup_len;
24171
24172                 /* Convert the denominator to numeric */
24173                 if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) {
24174                     goto failed;
24175                 }
24176
24177                 /* It better be the rest of the characters, and don't divide by
24178                  * 0 */
24179                 if (   end_ptr != this_lookup_name + lookup_len
24180                     || denominator == 0)
24181                 {
24182                     goto failed;
24183                 }
24184
24185                 /* Get the greatest common denominator using
24186                    http://en.wikipedia.org/wiki/Euclidean_algorithm */
24187                 gcd = numerator;
24188                 trial = denominator;
24189                 while (trial != 0) {
24190                     UV temp = trial;
24191                     trial = gcd % trial;
24192                     gcd = temp;
24193                 }
24194
24195                 /* If already in lowest possible terms, we have already tried
24196                  * looking this up */
24197                 if (gcd == 1) {
24198                     goto failed;
24199                 }
24200
24201                 /* Reduce the rational, which should put it in canonical form
24202                  * */
24203                 numerator /= gcd;
24204                 denominator /= gcd;
24205
24206                 canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf,
24207                         equals_pos, lookup_name, sign, numerator, denominator);
24208             }
24209
24210             /* Here, we have the number in canonical form.  Try that */
24211             table_index = match_uniprop((U8 *) canonical, strlen(canonical));
24212             if (table_index == 0) {
24213                 goto failed;
24214             }
24215         }   /* End of still didn't find the property in our table */
24216     }       /* End of       didn't find the property in our table */
24217
24218     /* Here, we have a non-zero return, which is an index into a table of ptrs.
24219      * A negative return signifies that the real index is the absolute value,
24220      * but the result needs to be inverted */
24221     if (table_index < 0) {
24222         invert_return = TRUE;
24223         table_index = -table_index;
24224     }
24225
24226     /* Out-of band indices indicate a deprecated property.  The proper index is
24227      * modulo it with the table size.  And dividing by the table size yields
24228      * an offset into a table constructed by regen/mk_invlists.pl to contain
24229      * the corresponding warning message */
24230     if (table_index > MAX_UNI_KEYWORD_INDEX) {
24231         Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX;
24232         table_index %= MAX_UNI_KEYWORD_INDEX;
24233         Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
24234                 "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s",
24235                 (int) name_len, name, deprecated_property_msgs[warning_offset]);
24236     }
24237
24238     /* In a few properties, a different property is used under /i.  These are
24239      * unlikely to change, so are hard-coded here. */
24240     if (to_fold) {
24241         if (   table_index == UNI_XPOSIXUPPER
24242             || table_index == UNI_XPOSIXLOWER
24243             || table_index == UNI_TITLE)
24244         {
24245             table_index = UNI_CASED;
24246         }
24247         else if (   table_index == UNI_UPPERCASELETTER
24248                  || table_index == UNI_LOWERCASELETTER
24249 #  ifdef UNI_TITLECASELETTER   /* Missing from early Unicodes */
24250                  || table_index == UNI_TITLECASELETTER
24251 #  endif
24252         ) {
24253             table_index = UNI_CASEDLETTER;
24254         }
24255         else if (  table_index == UNI_POSIXUPPER
24256                 || table_index == UNI_POSIXLOWER)
24257         {
24258             table_index = UNI_POSIXALPHA;
24259         }
24260     }
24261
24262     /* Create and return the inversion list */
24263     prop_definition =_new_invlist_C_array(uni_prop_ptrs[table_index]);
24264     sv_2mortal(prop_definition);
24265
24266
24267     /* See if there is a private use override to add to this definition */
24268     {
24269         COPHH * hinthash = (IN_PERL_COMPILETIME)
24270                            ? CopHINTHASH_get(&PL_compiling)
24271                            : CopHINTHASH_get(PL_curcop);
24272         SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0);
24273
24274         if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) {
24275
24276             /* See if there is an element in the hints hash for this table */
24277             SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index);
24278             const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup));
24279
24280             if (pos) {
24281                 bool dummy;
24282                 SV * pu_definition;
24283                 SV * pu_invlist;
24284                 SV * expanded_prop_definition =
24285                             sv_2mortal(invlist_clone(prop_definition, NULL));
24286
24287                 /* If so, it's definition is the string from here to the next
24288                  * \a character.  And its format is the same as a user-defined
24289                  * property */
24290                 pos += SvCUR(pu_lookup);
24291                 pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos);
24292                 pu_invlist = handle_user_defined_property(lookup_name,
24293                                                           lookup_len,
24294                                                           0, /* Not UTF-8 */
24295                                                           0, /* Not folded */
24296                                                           runtime,
24297                                                           deferrable,
24298                                                           pu_definition,
24299                                                           &dummy,
24300                                                           msg,
24301                                                           level);
24302                 if (TAINT_get) {
24303                     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24304                     sv_catpvs(msg, "Insecure private-use override");
24305                     goto append_name_to_msg;
24306                 }
24307
24308                 /* For now, as a safety measure, make sure that it doesn't
24309                  * override non-private use code points */
24310                 _invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist);
24311
24312                 /* Add it to the list to be returned */
24313                 _invlist_union(prop_definition, pu_invlist,
24314                                &expanded_prop_definition);
24315                 prop_definition = expanded_prop_definition;
24316                 Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental");
24317             }
24318         }
24319     }
24320
24321     if (invert_return) {
24322         _invlist_invert(prop_definition);
24323     }
24324     return prop_definition;
24325
24326   unknown_user_defined:
24327     if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24328     sv_catpvs(msg, "Unknown user-defined property name");
24329     goto append_name_to_msg;
24330
24331   failed:
24332     if (non_pkg_begin != 0) {
24333         if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24334         sv_catpvs(msg, "Illegal user-defined property name");
24335     }
24336     else {
24337         if (SvCUR(msg) > 0) sv_catpvs(msg, "; ");
24338         sv_catpvs(msg, "Can't find Unicode property definition");
24339     }
24340     /* FALLTHROUGH */
24341
24342   append_name_to_msg:
24343     {
24344         const char * prefix = (runtime && level == 0) ?  " \\p{" : " \"";
24345         const char * suffix = (runtime && level == 0) ?  "}" : "\"";
24346
24347         sv_catpv(msg, prefix);
24348         Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name));
24349         sv_catpv(msg, suffix);
24350     }
24351
24352     return NULL;
24353
24354   definition_deferred:
24355
24356     {
24357         bool is_qualified = non_pkg_begin != 0;  /* If has "::" */
24358
24359         /* Here it could yet to be defined, so defer evaluation of this until
24360          * its needed at runtime.  We need the fully qualified property name to
24361          * avoid ambiguity */
24362         if (! fq_name) {
24363             fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8,
24364                                                                 is_qualified);
24365         }
24366
24367         /* If it didn't come with a package, or the package is utf8::, this
24368          * actually could be an official Unicode property whose inclusion we
24369          * are deferring until runtime to make sure that it isn't overridden by
24370          * a user-defined property of the same name (which we haven't
24371          * encountered yet).  Add a marker to indicate this possibility, for
24372          * use at such time when we first need the definition during pattern
24373          * matching execution */
24374         if (! is_qualified || memBEGINPs(name, non_pkg_begin, "utf8::")) {
24375             sv_catpvs(fq_name, DEFERRED_COULD_BE_OFFICIAL_MARKERs);
24376         }
24377
24378         /* We also need a trailing newline */
24379         sv_catpvs(fq_name, "\n");
24380
24381         *user_defined_ptr = TRUE;
24382         return fq_name;
24383     }
24384 }
24385
24386 #endif
24387
24388 /*
24389  * ex: set ts=8 sts=4 sw=4 et:
24390  */