This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perldelta for f94c6c536844091ca6a005e3e0398db8e1cc212e
[perl5.git] / regcomp.c
1 /*    regcomp.c
2  */
3
4 /*
5  * 'A fair jaw-cracker dwarf-language must be.'            --Samwise Gamgee
6  *
7  *     [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
8  */
9
10 /* This file contains functions for compiling a regular expression.  See
11  * also regexec.c which funnily enough, contains functions for executing
12  * a regular expression.
13  *
14  * This file is also copied at build time to ext/re/re_comp.c, where
15  * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
16  * This causes the main functions to be compiled under new names and with
17  * debugging support added, which makes "use re 'debug'" work.
18  */
19
20 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
21  * confused with the original package (see point 3 below).  Thanks, Henry!
22  */
23
24 /* Additional note: this code is very heavily munged from Henry's version
25  * in places.  In some spots I've traded clarity for efficiency, so don't
26  * blame Henry for some of the lack of readability.
27  */
28
29 /* The names of the functions have been changed from regcomp and
30  * regexec to pregcomp and pregexec in order to avoid conflicts
31  * with the POSIX routines of the same names.
32 */
33
34 #ifdef PERL_EXT_RE_BUILD
35 #include "re_top.h"
36 #endif
37
38 /*
39  * pregcomp and pregexec -- regsub and regerror are not used in perl
40  *
41  *      Copyright (c) 1986 by University of Toronto.
42  *      Written by Henry Spencer.  Not derived from licensed software.
43  *
44  *      Permission is granted to anyone to use this software for any
45  *      purpose on any computer system, and to redistribute it freely,
46  *      subject to the following restrictions:
47  *
48  *      1. The author is not responsible for the consequences of use of
49  *              this software, no matter how awful, even if they arise
50  *              from defects in it.
51  *
52  *      2. The origin of this software must not be misrepresented, either
53  *              by explicit claim or by omission.
54  *
55  *      3. Altered versions must be plainly marked as such, and must not
56  *              be misrepresented as being the original software.
57  *
58  *
59  ****    Alterations to Henry's code are...
60  ****
61  ****    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
62  ****    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
63  ****    by Larry Wall and others
64  ****
65  ****    You may distribute under the terms of either the GNU General Public
66  ****    License or the Artistic License, as specified in the README file.
67
68  *
69  * Beware that some of this code is subtly aware of the way operator
70  * precedence is structured in regular expressions.  Serious changes in
71  * regular-expression syntax might require a total rethink.
72  */
73 #include "EXTERN.h"
74 #define PERL_IN_REGCOMP_C
75 #include "perl.h"
76
77 #ifndef PERL_IN_XSUB_RE
78 #  include "INTERN.h"
79 #endif
80
81 #define REG_COMP_C
82 #ifdef PERL_IN_XSUB_RE
83 #  include "re_comp.h"
84 EXTERN_C const struct regexp_engine my_reg_engine;
85 #else
86 #  include "regcomp.h"
87 #endif
88
89 #include "dquote_inline.h"
90 #include "invlist_inline.h"
91 #include "unicode_constants.h"
92
93 #define HAS_NONLATIN1_FOLD_CLOSURE(i) \
94  _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
95 #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \
96  _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
97 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
98 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
99
100 #ifndef STATIC
101 #define STATIC  static
102 #endif
103
104 #ifndef MIN
105 #define MIN(a,b) ((a) < (b) ? (a) : (b))
106 #endif
107
108 /* this is a chain of data about sub patterns we are processing that
109    need to be handled separately/specially in study_chunk. Its so
110    we can simulate recursion without losing state.  */
111 struct scan_frame;
112 typedef struct scan_frame {
113     regnode *last_regnode;      /* last node to process in this frame */
114     regnode *next_regnode;      /* next node to process when last is reached */
115     U32 prev_recursed_depth;
116     I32 stopparen;              /* what stopparen do we use */
117     U32 is_top_frame;           /* what flags do we use? */
118
119     struct scan_frame *this_prev_frame; /* this previous frame */
120     struct scan_frame *prev_frame;      /* previous frame */
121     struct scan_frame *next_frame;      /* next frame */
122 } scan_frame;
123
124 /* Certain characters are output as a sequence with the first being a
125  * backslash. */
126 #define isBACKSLASHED_PUNCT(c)                                              \
127                     ((c) == '-' || (c) == ']' || (c) == '\\' || (c) == '^')
128
129
130 struct RExC_state_t {
131     U32         flags;                  /* RXf_* are we folding, multilining? */
132     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
133     char        *precomp;               /* uncompiled string. */
134     char        *precomp_end;           /* pointer to end of uncompiled string. */
135     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
136     regexp      *rx;                    /* perl core regexp structure */
137     regexp_internal     *rxi;           /* internal data for regexp object
138                                            pprivate field */
139     char        *start;                 /* Start of input for compile */
140     char        *end;                   /* End of input for compile */
141     char        *parse;                 /* Input-scan pointer. */
142     char        *adjusted_start;        /* 'start', adjusted.  See code use */
143     STRLEN      precomp_adj;            /* an offset beyond precomp.  See code use */
144     SSize_t     whilem_seen;            /* number of WHILEM in this expr */
145     regnode     *emit_start;            /* Start of emitted-code area */
146     regnode     *emit_bound;            /* First regnode outside of the
147                                            allocated space */
148     regnode     *emit;                  /* Code-emit pointer; if = &emit_dummy,
149                                            implies compiling, so don't emit */
150     regnode_ssc emit_dummy;             /* placeholder for emit to point to;
151                                            large enough for the largest
152                                            non-EXACTish node, so can use it as
153                                            scratch in pass1 */
154     I32         naughty;                /* How bad is this pattern? */
155     I32         sawback;                /* Did we see \1, ...? */
156     U32         seen;
157     SSize_t     size;                   /* Code size. */
158     I32                npar;            /* Capture buffer count, (OPEN) plus
159                                            one. ("par" 0 is the whole
160                                            pattern)*/
161     I32         nestroot;               /* root parens we are in - used by
162                                            accept */
163     I32         extralen;
164     I32         seen_zerolen;
165     regnode     **open_parens;          /* pointers to open parens */
166     regnode     **close_parens;         /* pointers to close parens */
167     regnode     *opend;                 /* END node in program */
168     I32         utf8;           /* whether the pattern is utf8 or not */
169     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
170                                 /* XXX use this for future optimisation of case
171                                  * where pattern must be upgraded to utf8. */
172     I32         uni_semantics;  /* If a d charset modifier should use unicode
173                                    rules, even if the pattern is not in
174                                    utf8 */
175     HV          *paren_names;           /* Paren names */
176
177     regnode     **recurse;              /* Recurse regops */
178     I32         recurse_count;          /* Number of recurse regops */
179     U8          *study_chunk_recursed;  /* bitmap of which subs we have moved
180                                            through */
181     U32         study_chunk_recursed_bytes;  /* bytes in bitmap */
182     I32         in_lookbehind;
183     I32         contains_locale;
184     I32         contains_i;
185     I32         override_recoding;
186 #ifdef EBCDIC
187     I32         recode_x_to_native;
188 #endif
189     I32         in_multi_char_class;
190     struct reg_code_block *code_blocks; /* positions of literal (?{})
191                                             within pattern */
192     int         num_code_blocks;        /* size of code_blocks[] */
193     int         code_index;             /* next code_blocks[] slot */
194     SSize_t     maxlen;                        /* mininum possible number of chars in string to match */
195     scan_frame *frame_head;
196     scan_frame *frame_last;
197     U32         frame_count;
198     U32         strict;
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 #define RExC_lastparse  (pRExC_state->lastparse)
212 #define RExC_lastnum    (pRExC_state->lastnum)
213 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
214 #define RExC_study_chunk_recursed_count    (pRExC_state->study_chunk_recursed_count)
215 #define RExC_mysv       (pRExC_state->mysv1)
216 #define RExC_mysv1      (pRExC_state->mysv1)
217 #define RExC_mysv2      (pRExC_state->mysv2)
218
219 #endif
220     bool        seen_unfolded_sharp_s;
221 };
222
223 #define RExC_flags      (pRExC_state->flags)
224 #define RExC_pm_flags   (pRExC_state->pm_flags)
225 #define RExC_precomp    (pRExC_state->precomp)
226 #define RExC_precomp_adj (pRExC_state->precomp_adj)
227 #define RExC_adjusted_start  (pRExC_state->adjusted_start)
228 #define RExC_precomp_end (pRExC_state->precomp_end)
229 #define RExC_rx_sv      (pRExC_state->rx_sv)
230 #define RExC_rx         (pRExC_state->rx)
231 #define RExC_rxi        (pRExC_state->rxi)
232 #define RExC_start      (pRExC_state->start)
233 #define RExC_end        (pRExC_state->end)
234 #define RExC_parse      (pRExC_state->parse)
235 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
236
237 /* Set during the sizing pass when there is a LATIN SMALL LETTER SHARP S in any
238  * EXACTF node, hence was parsed under /di rules.  If later in the parse,
239  * something forces the pattern into using /ui rules, the sharp s should be
240  * folded into the sequence 'ss', which takes up more space than previously
241  * calculated.  This means that the sizing pass needs to be restarted.  (The
242  * node also becomes an EXACTFU_SS.)  For all other characters, an EXACTF node
243  * that gets converted to /ui (and EXACTFU) occupies the same amount of space,
244  * so there is no need to resize [perl #125990]. */
245 #define RExC_seen_unfolded_sharp_s (pRExC_state->seen_unfolded_sharp_s)
246
247 #ifdef RE_TRACK_PATTERN_OFFSETS
248 #define RExC_offsets    (pRExC_state->rxi->u.offsets) /* I am not like the
249                                                          others */
250 #endif
251 #define RExC_emit       (pRExC_state->emit)
252 #define RExC_emit_dummy (pRExC_state->emit_dummy)
253 #define RExC_emit_start (pRExC_state->emit_start)
254 #define RExC_emit_bound (pRExC_state->emit_bound)
255 #define RExC_sawback    (pRExC_state->sawback)
256 #define RExC_seen       (pRExC_state->seen)
257 #define RExC_size       (pRExC_state->size)
258 #define RExC_maxlen        (pRExC_state->maxlen)
259 #define RExC_npar       (pRExC_state->npar)
260 #define RExC_nestroot   (pRExC_state->nestroot)
261 #define RExC_extralen   (pRExC_state->extralen)
262 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
263 #define RExC_utf8       (pRExC_state->utf8)
264 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
265 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
266 #define RExC_open_parens        (pRExC_state->open_parens)
267 #define RExC_close_parens       (pRExC_state->close_parens)
268 #define RExC_opend      (pRExC_state->opend)
269 #define RExC_paren_names        (pRExC_state->paren_names)
270 #define RExC_recurse    (pRExC_state->recurse)
271 #define RExC_recurse_count      (pRExC_state->recurse_count)
272 #define RExC_study_chunk_recursed        (pRExC_state->study_chunk_recursed)
273 #define RExC_study_chunk_recursed_bytes  \
274                                    (pRExC_state->study_chunk_recursed_bytes)
275 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
276 #define RExC_contains_locale    (pRExC_state->contains_locale)
277 #define RExC_contains_i (pRExC_state->contains_i)
278 #define RExC_override_recoding (pRExC_state->override_recoding)
279 #ifdef EBCDIC
280 #   define RExC_recode_x_to_native (pRExC_state->recode_x_to_native)
281 #endif
282 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
283 #define RExC_frame_head (pRExC_state->frame_head)
284 #define RExC_frame_last (pRExC_state->frame_last)
285 #define RExC_frame_count (pRExC_state->frame_count)
286 #define RExC_strict (pRExC_state->strict)
287
288 /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set
289  * a flag to disable back-off on the fixed/floating substrings - if it's
290  * a high complexity pattern we assume the benefit of avoiding a full match
291  * is worth the cost of checking for the substrings even if they rarely help.
292  */
293 #define RExC_naughty    (pRExC_state->naughty)
294 #define TOO_NAUGHTY (10)
295 #define MARK_NAUGHTY(add) \
296     if (RExC_naughty < TOO_NAUGHTY) \
297         RExC_naughty += (add)
298 #define MARK_NAUGHTY_EXP(exp, add) \
299     if (RExC_naughty < TOO_NAUGHTY) \
300         RExC_naughty += RExC_naughty / (exp) + (add)
301
302 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
303 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
304         ((*s) == '{' && regcurly(s)))
305
306 /*
307  * Flags to be passed up and down.
308  */
309 #define WORST           0       /* Worst case. */
310 #define HASWIDTH        0x01    /* Known to match non-null strings. */
311
312 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
313  * character.  (There needs to be a case: in the switch statement in regexec.c
314  * for any node marked SIMPLE.)  Note that this is not the same thing as
315  * REGNODE_SIMPLE */
316 #define SIMPLE          0x02
317 #define SPSTART         0x04    /* Starts with * or + */
318 #define POSTPONED       0x08    /* (?1),(?&name), (??{...}) or similar */
319 #define TRYAGAIN        0x10    /* Weeded out a declaration. */
320 #define RESTART_PASS1   0x20    /* Need to restart sizing pass */
321 #define NEED_UTF8       0x40    /* In conjunction with RESTART_PASS1, need to
322                                    calcuate sizes as UTF-8 */
323
324 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
325
326 /* whether trie related optimizations are enabled */
327 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
328 #define TRIE_STUDY_OPT
329 #define FULL_TRIE_STUDY
330 #define TRIE_STCLASS
331 #endif
332
333
334
335 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
336 #define PBITVAL(paren) (1 << ((paren) & 7))
337 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
338 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
339 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
340
341 #define REQUIRE_UTF8(flagp) STMT_START {                                   \
342                                      if (!UTF) {                           \
343                                          assert(PASS1);                    \
344                                          *flagp = RESTART_PASS1|NEED_UTF8; \
345                                          return NULL;                      \
346                                      }                                     \
347                              } STMT_END
348
349 /* Change from /d into /u rules, and restart the parse if we've already seen
350  * something whose size would increase as a result, by setting *flagp and
351  * returning 'restart_retval'.  RExC_uni_semantics is a flag that indicates
352  * we've change to /u during the parse.  */
353 #define REQUIRE_UNI_RULES(flagp, restart_retval)                            \
354     STMT_START {                                                            \
355             if (DEPENDS_SEMANTICS) {                                        \
356                 assert(PASS1);                                              \
357                 set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);      \
358                 RExC_uni_semantics = 1;                                     \
359                 if (RExC_seen_unfolded_sharp_s) {                           \
360                     *flagp |= RESTART_PASS1;                                \
361                     return restart_retval;                                  \
362                 }                                                           \
363             }                                                               \
364     } STMT_END
365
366 /* This converts the named class defined in regcomp.h to its equivalent class
367  * number defined in handy.h. */
368 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
369 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
370
371 #define _invlist_union_complement_2nd(a, b, output) \
372                         _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
373 #define _invlist_intersection_complement_2nd(a, b, output) \
374                  _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output)
375
376 /* About scan_data_t.
377
378   During optimisation we recurse through the regexp program performing
379   various inplace (keyhole style) optimisations. In addition study_chunk
380   and scan_commit populate this data structure with information about
381   what strings MUST appear in the pattern. We look for the longest
382   string that must appear at a fixed location, and we look for the
383   longest string that may appear at a floating location. So for instance
384   in the pattern:
385
386     /FOO[xX]A.*B[xX]BAR/
387
388   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
389   strings (because they follow a .* construct). study_chunk will identify
390   both FOO and BAR as being the longest fixed and floating strings respectively.
391
392   The strings can be composites, for instance
393
394      /(f)(o)(o)/
395
396   will result in a composite fixed substring 'foo'.
397
398   For each string some basic information is maintained:
399
400   - offset or min_offset
401     This is the position the string must appear at, or not before.
402     It also implicitly (when combined with minlenp) tells us how many
403     characters must match before the string we are searching for.
404     Likewise when combined with minlenp and the length of the string it
405     tells us how many characters must appear after the string we have
406     found.
407
408   - max_offset
409     Only used for floating strings. This is the rightmost point that
410     the string can appear at. If set to SSize_t_MAX it indicates that the
411     string can occur infinitely far to the right.
412
413   - minlenp
414     A pointer to the minimum number of characters of the pattern that the
415     string was found inside. This is important as in the case of positive
416     lookahead or positive lookbehind we can have multiple patterns
417     involved. Consider
418
419     /(?=FOO).*F/
420
421     The minimum length of the pattern overall is 3, the minimum length
422     of the lookahead part is 3, but the minimum length of the part that
423     will actually match is 1. So 'FOO's minimum length is 3, but the
424     minimum length for the F is 1. This is important as the minimum length
425     is used to determine offsets in front of and behind the string being
426     looked for.  Since strings can be composites this is the length of the
427     pattern at the time it was committed with a scan_commit. Note that
428     the length is calculated by study_chunk, so that the minimum lengths
429     are not known until the full pattern has been compiled, thus the
430     pointer to the value.
431
432   - lookbehind
433
434     In the case of lookbehind the string being searched for can be
435     offset past the start point of the final matching string.
436     If this value was just blithely removed from the min_offset it would
437     invalidate some of the calculations for how many chars must match
438     before or after (as they are derived from min_offset and minlen and
439     the length of the string being searched for).
440     When the final pattern is compiled and the data is moved from the
441     scan_data_t structure into the regexp structure the information
442     about lookbehind is factored in, with the information that would
443     have been lost precalculated in the end_shift field for the
444     associated string.
445
446   The fields pos_min and pos_delta are used to store the minimum offset
447   and the delta to the maximum offset at the current point in the pattern.
448
449 */
450
451 typedef struct scan_data_t {
452     /*I32 len_min;      unused */
453     /*I32 len_delta;    unused */
454     SSize_t pos_min;
455     SSize_t pos_delta;
456     SV *last_found;
457     SSize_t last_end;       /* min value, <0 unless valid. */
458     SSize_t last_start_min;
459     SSize_t last_start_max;
460     SV **longest;           /* Either &l_fixed, or &l_float. */
461     SV *longest_fixed;      /* longest fixed string found in pattern */
462     SSize_t offset_fixed;   /* offset where it starts */
463     SSize_t *minlen_fixed;  /* pointer to the minlen relevant to the string */
464     I32 lookbehind_fixed;   /* is the position of the string modfied by LB */
465     SV *longest_float;      /* longest floating string found in pattern */
466     SSize_t offset_float_min; /* earliest point in string it can appear */
467     SSize_t offset_float_max; /* latest point in string it can appear */
468     SSize_t *minlen_float;  /* pointer to the minlen relevant to the string */
469     SSize_t lookbehind_float; /* is the pos of the string modified by LB */
470     I32 flags;
471     I32 whilem_c;
472     SSize_t *last_closep;
473     regnode_ssc *start_class;
474 } scan_data_t;
475
476 /*
477  * Forward declarations for pregcomp()'s friends.
478  */
479
480 static const scan_data_t zero_scan_data =
481   { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
482
483 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
484 #define SF_BEFORE_SEOL          0x0001
485 #define SF_BEFORE_MEOL          0x0002
486 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
487 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
488
489 #define SF_FIX_SHIFT_EOL        (+2)
490 #define SF_FL_SHIFT_EOL         (+4)
491
492 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
493 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
494
495 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
496 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
497 #define SF_IS_INF               0x0040
498 #define SF_HAS_PAR              0x0080
499 #define SF_IN_PAR               0x0100
500 #define SF_HAS_EVAL             0x0200
501 #define SCF_DO_SUBSTR           0x0400
502 #define SCF_DO_STCLASS_AND      0x0800
503 #define SCF_DO_STCLASS_OR       0x1000
504 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
505 #define SCF_WHILEM_VISITED_POS  0x2000
506
507 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
508 #define SCF_SEEN_ACCEPT         0x8000
509 #define SCF_TRIE_DOING_RESTUDY 0x10000
510 #define SCF_IN_DEFINE          0x20000
511
512
513
514
515 #define UTF cBOOL(RExC_utf8)
516
517 /* The enums for all these are ordered so things work out correctly */
518 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
519 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags)                    \
520                                                      == REGEX_DEPENDS_CHARSET)
521 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
522 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags)                \
523                                                      >= REGEX_UNICODE_CHARSET)
524 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags)                      \
525                                             == REGEX_ASCII_RESTRICTED_CHARSET)
526 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags)             \
527                                             >= REGEX_ASCII_RESTRICTED_CHARSET)
528 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags)                 \
529                                         == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
530
531 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
532
533 /* For programs that want to be strictly Unicode compatible by dying if any
534  * attempt is made to match a non-Unicode code point against a Unicode
535  * property.  */
536 #define ALWAYS_WARN_SUPER  ckDEAD(packWARN(WARN_NON_UNICODE))
537
538 #define OOB_NAMEDCLASS          -1
539
540 /* There is no code point that is out-of-bounds, so this is problematic.  But
541  * its only current use is to initialize a variable that is always set before
542  * looked at. */
543 #define OOB_UNICODE             0xDEADBEEF
544
545 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
546 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
547
548
549 /* length of regex to show in messages that don't mark a position within */
550 #define RegexLengthToShowInErrorMessages 127
551
552 /*
553  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
554  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
555  * op/pragma/warn/regcomp.
556  */
557 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
558 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
559
560 #define REPORT_LOCATION " in regex; marked by " MARKER1    \
561                         " in m/%"UTF8f MARKER2 "%"UTF8f"/"
562
563 /* The code in this file in places uses one level of recursion with parsing
564  * rebased to an alternate string constructed by us in memory.  This can take
565  * the form of something that is completely different from the input, or
566  * something that uses the input as part of the alternate.  In the first case,
567  * there should be no possibility of an error, as we are in complete control of
568  * the alternate string.  But in the second case we don't control the input
569  * portion, so there may be errors in that.  Here's an example:
570  *      /[abc\x{DF}def]/ui
571  * is handled specially because \x{df} folds to a sequence of more than one
572  * character, 'ss'.  What is done is to create and parse an alternate string,
573  * which looks like this:
574  *      /(?:\x{DF}|[abc\x{DF}def])/ui
575  * where it uses the input unchanged in the middle of something it constructs,
576  * which is a branch for the DF outside the character class, and clustering
577  * parens around the whole thing. (It knows enough to skip the DF inside the
578  * class while in this substitute parse.) 'abc' and 'def' may have errors that
579  * need to be reported.  The general situation looks like this:
580  *
581  *              sI                       tI               xI       eI
582  * Input:       ----------------------------------------------------
583  * Constructed:         ---------------------------------------------------
584  *                      sC               tC               xC       eC     EC
585  *
586  * The input string sI..eI is the input pattern.  The string sC..EC is the
587  * constructed substitute parse string.  The portions sC..tC and eC..EC are
588  * constructed by us.  The portion tC..eC is an exact duplicate of the input
589  * pattern tI..eI.  In the diagram, these are vertically aligned.  Suppose that
590  * while parsing, we find an error at xC.  We want to display a message showing
591  * the real input string.  Thus we need to find the point xI in it which
592  * corresponds to xC.  xC >= tC, since the portion of the string sC..tC has
593  * been constructed by us, and so shouldn't have errors.  We get:
594  *
595  *      xI = sI + (tI - sI) + (xC - tC)
596  *
597  * and, the offset into sI is:
598  *
599  *      (xI - sI) = (tI - sI) + (xC - tC)
600  *
601  * When the substitute is constructed, we save (tI -sI) as RExC_precomp_adj,
602  * and we save tC as RExC_adjusted_start.
603  *
604  * During normal processing of the input pattern, everything points to that,
605  * with RExC_precomp_adj set to 0, and RExC_adjusted_start set to sI.
606  */
607
608 #define tI_sI           RExC_precomp_adj
609 #define tC              RExC_adjusted_start
610 #define sC              RExC_precomp
611 #define xI_offset(xC)   ((IV) (tI_sI + (xC - tC)))
612 #define xI(xC)          (sC + xI_offset(xC))
613 #define eC              RExC_precomp_end
614
615 #define REPORT_LOCATION_ARGS(xC)                                            \
616     UTF8fARG(UTF,                                                           \
617              (xI(xC) > eC) /* Don't run off end */                          \
618               ? eC - sC   /* Length before the <--HERE */                   \
619               : xI_offset(xC),                                              \
620              sC),         /* The input pattern printed up to the <--HERE */ \
621     UTF8fARG(UTF,                                                           \
622              (xI(xC) > eC) ? 0 : eC - xI(xC), /* Length after <--HERE */    \
623              (xI(xC) > eC) ? eC : xI(xC))     /* pattern after <--HERE */
624
625 /* Used to point after bad bytes for an error message, but avoid skipping
626  * past a nul byte. */
627 #define SKIP_IF_CHAR(s) (!*(s) ? 0 : UTF ? UTF8SKIP(s) : 1)
628
629 /*
630  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
631  * arg. Show regex, up to a maximum length. If it's too long, chop and add
632  * "...".
633  */
634 #define _FAIL(code) STMT_START {                                        \
635     const char *ellipses = "";                                          \
636     IV len = RExC_precomp_end - RExC_precomp;                                   \
637                                                                         \
638     if (!SIZE_ONLY)                                                     \
639         SAVEFREESV(RExC_rx_sv);                                         \
640     if (len > RegexLengthToShowInErrorMessages) {                       \
641         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
642         len = RegexLengthToShowInErrorMessages - 10;                    \
643         ellipses = "...";                                               \
644     }                                                                   \
645     code;                                                               \
646 } STMT_END
647
648 #define FAIL(msg) _FAIL(                            \
649     Perl_croak(aTHX_ "%s in regex m/%"UTF8f"%s/",           \
650             msg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
651
652 #define FAIL2(msg,arg) _FAIL(                       \
653     Perl_croak(aTHX_ msg " in regex m/%"UTF8f"%s/",         \
654             arg, UTF8fARG(UTF, len, RExC_precomp), ellipses))
655
656 /*
657  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
658  */
659 #define Simple_vFAIL(m) STMT_START {                                    \
660     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
661             m, REPORT_LOCATION_ARGS(RExC_parse));                       \
662 } STMT_END
663
664 /*
665  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
666  */
667 #define vFAIL(m) STMT_START {                           \
668     if (!SIZE_ONLY)                                     \
669         SAVEFREESV(RExC_rx_sv);                         \
670     Simple_vFAIL(m);                                    \
671 } STMT_END
672
673 /*
674  * Like Simple_vFAIL(), but accepts two arguments.
675  */
676 #define Simple_vFAIL2(m,a1) STMT_START {                        \
677     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,              \
678                       REPORT_LOCATION_ARGS(RExC_parse));        \
679 } STMT_END
680
681 /*
682  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
683  */
684 #define vFAIL2(m,a1) STMT_START {                       \
685     if (!SIZE_ONLY)                                     \
686         SAVEFREESV(RExC_rx_sv);                         \
687     Simple_vFAIL2(m, a1);                               \
688 } STMT_END
689
690
691 /*
692  * Like Simple_vFAIL(), but accepts three arguments.
693  */
694 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
695     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,          \
696             REPORT_LOCATION_ARGS(RExC_parse));                  \
697 } STMT_END
698
699 /*
700  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
701  */
702 #define vFAIL3(m,a1,a2) STMT_START {                    \
703     if (!SIZE_ONLY)                                     \
704         SAVEFREESV(RExC_rx_sv);                         \
705     Simple_vFAIL3(m, a1, a2);                           \
706 } STMT_END
707
708 /*
709  * Like Simple_vFAIL(), but accepts four arguments.
710  */
711 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
712     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3,      \
713             REPORT_LOCATION_ARGS(RExC_parse));                  \
714 } STMT_END
715
716 #define vFAIL4(m,a1,a2,a3) STMT_START {                 \
717     if (!SIZE_ONLY)                                     \
718         SAVEFREESV(RExC_rx_sv);                         \
719     Simple_vFAIL4(m, a1, a2, a3);                       \
720 } STMT_END
721
722 /* A specialized version of vFAIL2 that works with UTF8f */
723 #define vFAIL2utf8f(m, a1) STMT_START {             \
724     if (!SIZE_ONLY)                                 \
725         SAVEFREESV(RExC_rx_sv);                     \
726     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1,  \
727             REPORT_LOCATION_ARGS(RExC_parse));      \
728 } STMT_END
729
730 #define vFAIL3utf8f(m, a1, a2) STMT_START {             \
731     if (!SIZE_ONLY)                                     \
732         SAVEFREESV(RExC_rx_sv);                         \
733     S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2,  \
734             REPORT_LOCATION_ARGS(RExC_parse));          \
735 } STMT_END
736
737 /* These have asserts in them because of [perl #122671] Many warnings in
738  * regcomp.c can occur twice.  If they get output in pass1 and later in that
739  * pass, the pattern has to be converted to UTF-8 and the pass restarted, they
740  * would get output again.  So they should be output in pass2, and these
741  * asserts make sure new warnings follow that paradigm. */
742
743 /* m is not necessarily a "literal string", in this macro */
744 #define reg_warn_non_literal_string(loc, m) STMT_START {                \
745     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),           \
746                                        "%s" REPORT_LOCATION,            \
747                                   m, REPORT_LOCATION_ARGS(loc));        \
748 } STMT_END
749
750 #define ckWARNreg(loc,m) STMT_START {                                   \
751     __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),        \
752                                           m REPORT_LOCATION,            \
753                                           REPORT_LOCATION_ARGS(loc));   \
754 } STMT_END
755
756 #define vWARN(loc, m) STMT_START {                                      \
757     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),           \
758                                        m REPORT_LOCATION,               \
759                                        REPORT_LOCATION_ARGS(loc));      \
760 } STMT_END
761
762 #define vWARN_dep(loc, m) STMT_START {                                  \
763     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),       \
764                                        m REPORT_LOCATION,               \
765                                        REPORT_LOCATION_ARGS(loc));      \
766 } STMT_END
767
768 #define ckWARNdep(loc,m) STMT_START {                                   \
769     __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),  \
770                                             m REPORT_LOCATION,          \
771                                             REPORT_LOCATION_ARGS(loc)); \
772 } STMT_END
773
774 #define ckWARNregdep(loc,m) STMT_START {                                    \
775     __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED,      \
776                                                       WARN_REGEXP),         \
777                                              m REPORT_LOCATION,             \
778                                              REPORT_LOCATION_ARGS(loc));    \
779 } STMT_END
780
781 #define ckWARN2reg_d(loc,m, a1) STMT_START {                                \
782     __ASSERT_(PASS2) Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP),          \
783                                             m REPORT_LOCATION,              \
784                                             a1, REPORT_LOCATION_ARGS(loc)); \
785 } STMT_END
786
787 #define ckWARN2reg(loc, m, a1) STMT_START {                                 \
788     __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),            \
789                                           m REPORT_LOCATION,                \
790                                           a1, REPORT_LOCATION_ARGS(loc));   \
791 } STMT_END
792
793 #define vWARN3(loc, m, a1, a2) STMT_START {                                 \
794     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),               \
795                                        m REPORT_LOCATION,                   \
796                                        a1, a2, REPORT_LOCATION_ARGS(loc));  \
797 } STMT_END
798
799 #define ckWARN3reg(loc, m, a1, a2) STMT_START {                             \
800     __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),            \
801                                           m REPORT_LOCATION,                \
802                                           a1, a2,                           \
803                                           REPORT_LOCATION_ARGS(loc));       \
804 } STMT_END
805
806 #define vWARN4(loc, m, a1, a2, a3) STMT_START {                         \
807     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),           \
808                                        m REPORT_LOCATION,               \
809                                        a1, a2, a3,                      \
810                                        REPORT_LOCATION_ARGS(loc));      \
811 } STMT_END
812
813 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START {                     \
814     __ASSERT_(PASS2) Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),        \
815                                           m REPORT_LOCATION,            \
816                                           a1, a2, a3,                   \
817                                           REPORT_LOCATION_ARGS(loc));   \
818 } STMT_END
819
820 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START {                     \
821     __ASSERT_(PASS2) Perl_warner(aTHX_ packWARN(WARN_REGEXP),           \
822                                        m REPORT_LOCATION,               \
823                                        a1, a2, a3, a4,                  \
824                                        REPORT_LOCATION_ARGS(loc));      \
825 } STMT_END
826
827 /* Macros for recording node offsets.   20001227 mjd@plover.com
828  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
829  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
830  * Element 0 holds the number n.
831  * Position is 1 indexed.
832  */
833 #ifndef RE_TRACK_PATTERN_OFFSETS
834 #define Set_Node_Offset_To_R(node,byte)
835 #define Set_Node_Offset(node,byte)
836 #define Set_Cur_Node_Offset
837 #define Set_Node_Length_To_R(node,len)
838 #define Set_Node_Length(node,len)
839 #define Set_Node_Cur_Length(node,start)
840 #define Node_Offset(n)
841 #define Node_Length(n)
842 #define Set_Node_Offset_Length(node,offset,len)
843 #define ProgLen(ri) ri->u.proglen
844 #define SetProgLen(ri,x) ri->u.proglen = x
845 #else
846 #define ProgLen(ri) ri->u.offsets[0]
847 #define SetProgLen(ri,x) ri->u.offsets[0] = x
848 #define Set_Node_Offset_To_R(node,byte) STMT_START {                    \
849     if (! SIZE_ONLY) {                                                  \
850         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
851                     __LINE__, (int)(node), (int)(byte)));               \
852         if((node) < 0) {                                                \
853             Perl_croak(aTHX_ "value of node is %d in Offset macro",     \
854                                          (int)(node));                  \
855         } else {                                                        \
856             RExC_offsets[2*(node)-1] = (byte);                          \
857         }                                                               \
858     }                                                                   \
859 } STMT_END
860
861 #define Set_Node_Offset(node,byte) \
862     Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
863 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
864
865 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
866     if (! SIZE_ONLY) {                                                  \
867         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
868                 __LINE__, (int)(node), (int)(len)));                    \
869         if((node) < 0) {                                                \
870             Perl_croak(aTHX_ "value of node is %d in Length macro",     \
871                                          (int)(node));                  \
872         } else {                                                        \
873             RExC_offsets[2*(node)] = (len);                             \
874         }                                                               \
875     }                                                                   \
876 } STMT_END
877
878 #define Set_Node_Length(node,len) \
879     Set_Node_Length_To_R((node)-RExC_emit_start, len)
880 #define Set_Node_Cur_Length(node, start)                \
881     Set_Node_Length(node, RExC_parse - start)
882
883 /* Get offsets and lengths */
884 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
885 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
886
887 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
888     Set_Node_Offset_To_R((node)-RExC_emit_start, (offset));     \
889     Set_Node_Length_To_R((node)-RExC_emit_start, (len));        \
890 } STMT_END
891 #endif
892
893 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
894 #define EXPERIMENTAL_INPLACESCAN
895 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
896
897 #define DEBUG_RExC_seen() \
898         DEBUG_OPTIMISE_MORE_r({                                             \
899             PerlIO_printf(Perl_debug_log,"RExC_seen: ");                    \
900                                                                             \
901             if (RExC_seen & REG_ZERO_LEN_SEEN)                              \
902                 PerlIO_printf(Perl_debug_log,"REG_ZERO_LEN_SEEN ");         \
903                                                                             \
904             if (RExC_seen & REG_LOOKBEHIND_SEEN)                            \
905                 PerlIO_printf(Perl_debug_log,"REG_LOOKBEHIND_SEEN ");       \
906                                                                             \
907             if (RExC_seen & REG_GPOS_SEEN)                                  \
908                 PerlIO_printf(Perl_debug_log,"REG_GPOS_SEEN ");             \
909                                                                             \
910             if (RExC_seen & REG_RECURSE_SEEN)                               \
911                 PerlIO_printf(Perl_debug_log,"REG_RECURSE_SEEN ");          \
912                                                                             \
913             if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)                         \
914                 PerlIO_printf(Perl_debug_log,"REG_TOP_LEVEL_BRANCHES_SEEN ");    \
915                                                                             \
916             if (RExC_seen & REG_VERBARG_SEEN)                               \
917                 PerlIO_printf(Perl_debug_log,"REG_VERBARG_SEEN ");          \
918                                                                             \
919             if (RExC_seen & REG_CUTGROUP_SEEN)                              \
920                 PerlIO_printf(Perl_debug_log,"REG_CUTGROUP_SEEN ");         \
921                                                                             \
922             if (RExC_seen & REG_RUN_ON_COMMENT_SEEN)                        \
923                 PerlIO_printf(Perl_debug_log,"REG_RUN_ON_COMMENT_SEEN ");   \
924                                                                             \
925             if (RExC_seen & REG_UNFOLDED_MULTI_SEEN)                        \
926                 PerlIO_printf(Perl_debug_log,"REG_UNFOLDED_MULTI_SEEN ");   \
927                                                                             \
928             if (RExC_seen & REG_GOSTART_SEEN)                               \
929                 PerlIO_printf(Perl_debug_log,"REG_GOSTART_SEEN ");          \
930                                                                             \
931             if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)                               \
932                 PerlIO_printf(Perl_debug_log,"REG_UNBOUNDED_QUANTIFIER_SEEN ");          \
933                                                                             \
934             PerlIO_printf(Perl_debug_log,"\n");                             \
935         });
936
937 #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \
938   if ((flags) & flag) PerlIO_printf(Perl_debug_log, "%s ", #flag)
939
940 #define DEBUG_SHOW_STUDY_FLAGS(flags,open_str,close_str)                    \
941     if ( ( flags ) ) {                                                      \
942         PerlIO_printf(Perl_debug_log, "%s", open_str);                      \
943         DEBUG_SHOW_STUDY_FLAG(flags,SF_FL_BEFORE_SEOL);                     \
944         DEBUG_SHOW_STUDY_FLAG(flags,SF_FL_BEFORE_MEOL);                     \
945         DEBUG_SHOW_STUDY_FLAG(flags,SF_IS_INF);                             \
946         DEBUG_SHOW_STUDY_FLAG(flags,SF_HAS_PAR);                            \
947         DEBUG_SHOW_STUDY_FLAG(flags,SF_IN_PAR);                             \
948         DEBUG_SHOW_STUDY_FLAG(flags,SF_HAS_EVAL);                           \
949         DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_SUBSTR);                         \
950         DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS_AND);                    \
951         DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS_OR);                     \
952         DEBUG_SHOW_STUDY_FLAG(flags,SCF_DO_STCLASS);                        \
953         DEBUG_SHOW_STUDY_FLAG(flags,SCF_WHILEM_VISITED_POS);                \
954         DEBUG_SHOW_STUDY_FLAG(flags,SCF_TRIE_RESTUDY);                      \
955         DEBUG_SHOW_STUDY_FLAG(flags,SCF_SEEN_ACCEPT);                       \
956         DEBUG_SHOW_STUDY_FLAG(flags,SCF_TRIE_DOING_RESTUDY);                \
957         DEBUG_SHOW_STUDY_FLAG(flags,SCF_IN_DEFINE);                         \
958         PerlIO_printf(Perl_debug_log, "%s", close_str);                     \
959     }
960
961
962 #define DEBUG_STUDYDATA(str,data,depth)                              \
963 DEBUG_OPTIMISE_MORE_r(if(data){                                      \
964     PerlIO_printf(Perl_debug_log,                                    \
965         "%*s" str "Pos:%"IVdf"/%"IVdf                                \
966         " Flags: 0x%"UVXf,                                           \
967         (int)(depth)*2, "",                                          \
968         (IV)((data)->pos_min),                                       \
969         (IV)((data)->pos_delta),                                     \
970         (UV)((data)->flags)                                          \
971     );                                                               \
972     DEBUG_SHOW_STUDY_FLAGS((data)->flags," [ ","]");                 \
973     PerlIO_printf(Perl_debug_log,                                    \
974         " Whilem_c: %"IVdf" Lcp: %"IVdf" %s",                        \
975         (IV)((data)->whilem_c),                                      \
976         (IV)((data)->last_closep ? *((data)->last_closep) : -1),     \
977         is_inf ? "INF " : ""                                         \
978     );                                                               \
979     if ((data)->last_found)                                          \
980         PerlIO_printf(Perl_debug_log,                                \
981             "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
982             " %sFloat: '%s' @ %"IVdf"/%"IVdf"",                      \
983             SvPVX_const((data)->last_found),                         \
984             (IV)((data)->last_end),                                  \
985             (IV)((data)->last_start_min),                            \
986             (IV)((data)->last_start_max),                            \
987             ((data)->longest &&                                      \
988              (data)->longest==&((data)->longest_fixed)) ? "*" : "",  \
989             SvPVX_const((data)->longest_fixed),                      \
990             (IV)((data)->offset_fixed),                              \
991             ((data)->longest &&                                      \
992              (data)->longest==&((data)->longest_float)) ? "*" : "",  \
993             SvPVX_const((data)->longest_float),                      \
994             (IV)((data)->offset_float_min),                          \
995             (IV)((data)->offset_float_max)                           \
996         );                                                           \
997     PerlIO_printf(Perl_debug_log,"\n");                              \
998 });
999
1000 /* =========================================================
1001  * BEGIN edit_distance stuff.
1002  *
1003  * This calculates how many single character changes of any type are needed to
1004  * transform a string into another one.  It is taken from version 3.1 of
1005  *
1006  * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS
1007  */
1008
1009 /* Our unsorted dictionary linked list.   */
1010 /* Note we use UVs, not chars. */
1011
1012 struct dictionary{
1013   UV key;
1014   UV value;
1015   struct dictionary* next;
1016 };
1017 typedef struct dictionary item;
1018
1019
1020 PERL_STATIC_INLINE item*
1021 push(UV key,item* curr)
1022 {
1023     item* head;
1024     Newxz(head, 1, item);
1025     head->key = key;
1026     head->value = 0;
1027     head->next = curr;
1028     return head;
1029 }
1030
1031
1032 PERL_STATIC_INLINE item*
1033 find(item* head, UV key)
1034 {
1035     item* iterator = head;
1036     while (iterator){
1037         if (iterator->key == key){
1038             return iterator;
1039         }
1040         iterator = iterator->next;
1041     }
1042
1043     return NULL;
1044 }
1045
1046 PERL_STATIC_INLINE item*
1047 uniquePush(item* head,UV key)
1048 {
1049     item* iterator = head;
1050
1051     while (iterator){
1052         if (iterator->key == key) {
1053             return head;
1054         }
1055         iterator = iterator->next;
1056     }
1057
1058     return push(key,head);
1059 }
1060
1061 PERL_STATIC_INLINE void
1062 dict_free(item* head)
1063 {
1064     item* iterator = head;
1065
1066     while (iterator) {
1067         item* temp = iterator;
1068         iterator = iterator->next;
1069         Safefree(temp);
1070     }
1071
1072     head = NULL;
1073 }
1074
1075 /* End of Dictionary Stuff */
1076
1077 /* All calculations/work are done here */
1078 STATIC int
1079 S_edit_distance(const UV* src,
1080                 const UV* tgt,
1081                 const STRLEN x,             /* length of src[] */
1082                 const STRLEN y,             /* length of tgt[] */
1083                 const SSize_t maxDistance
1084 )
1085 {
1086     item *head = NULL;
1087     UV swapCount,swapScore,targetCharCount,i,j;
1088     UV *scores;
1089     UV score_ceil = x + y;
1090
1091     PERL_ARGS_ASSERT_EDIT_DISTANCE;
1092
1093     /* intialize matrix start values */
1094     Newxz(scores, ( (x + 2) * (y + 2)), UV);
1095     scores[0] = score_ceil;
1096     scores[1 * (y + 2) + 0] = score_ceil;
1097     scores[0 * (y + 2) + 1] = score_ceil;
1098     scores[1 * (y + 2) + 1] = 0;
1099     head = uniquePush(uniquePush(head,src[0]),tgt[0]);
1100
1101     /* work loops    */
1102     /* i = src index */
1103     /* j = tgt index */
1104     for (i=1;i<=x;i++) {
1105         if (i < x)
1106             head = uniquePush(head,src[i]);
1107         scores[(i+1) * (y + 2) + 1] = i;
1108         scores[(i+1) * (y + 2) + 0] = score_ceil;
1109         swapCount = 0;
1110
1111         for (j=1;j<=y;j++) {
1112             if (i == 1) {
1113                 if(j < y)
1114                 head = uniquePush(head,tgt[j]);
1115                 scores[1 * (y + 2) + (j + 1)] = j;
1116                 scores[0 * (y + 2) + (j + 1)] = score_ceil;
1117             }
1118
1119             targetCharCount = find(head,tgt[j-1])->value;
1120             swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount;
1121
1122             if (src[i-1] != tgt[j-1]){
1123                 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));
1124             }
1125             else {
1126                 swapCount = j;
1127                 scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore);
1128             }
1129         }
1130
1131         find(head,src[i-1])->value = i;
1132     }
1133
1134     {
1135         IV score = scores[(x+1) * (y + 2) + (y + 1)];
1136         dict_free(head);
1137         Safefree(scores);
1138         return (maxDistance != 0 && maxDistance < score)?(-1):score;
1139     }
1140 }
1141
1142 /* END of edit_distance() stuff
1143  * ========================================================= */
1144
1145 /* is c a control character for which we have a mnemonic? */
1146 #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
1147
1148 STATIC const char *
1149 S_cntrl_to_mnemonic(const U8 c)
1150 {
1151     /* Returns the mnemonic string that represents character 'c', if one
1152      * exists; NULL otherwise.  The only ones that exist for the purposes of
1153      * this routine are a few control characters */
1154
1155     switch (c) {
1156         case '\a':       return "\\a";
1157         case '\b':       return "\\b";
1158         case ESC_NATIVE: return "\\e";
1159         case '\f':       return "\\f";
1160         case '\n':       return "\\n";
1161         case '\r':       return "\\r";
1162         case '\t':       return "\\t";
1163     }
1164
1165     return NULL;
1166 }
1167
1168 /* Mark that we cannot extend a found fixed substring at this point.
1169    Update the longest found anchored substring and the longest found
1170    floating substrings if needed. */
1171
1172 STATIC void
1173 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data,
1174                     SSize_t *minlenp, int is_inf)
1175 {
1176     const STRLEN l = CHR_SVLEN(data->last_found);
1177     const STRLEN old_l = CHR_SVLEN(*data->longest);
1178     GET_RE_DEBUG_FLAGS_DECL;
1179
1180     PERL_ARGS_ASSERT_SCAN_COMMIT;
1181
1182     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
1183         SvSetMagicSV(*data->longest, data->last_found);
1184         if (*data->longest == data->longest_fixed) {
1185             data->offset_fixed = l ? data->last_start_min : data->pos_min;
1186             if (data->flags & SF_BEFORE_EOL)
1187                 data->flags
1188                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
1189             else
1190                 data->flags &= ~SF_FIX_BEFORE_EOL;
1191             data->minlen_fixed=minlenp;
1192             data->lookbehind_fixed=0;
1193         }
1194         else { /* *data->longest == data->longest_float */
1195             data->offset_float_min = l ? data->last_start_min : data->pos_min;
1196             data->offset_float_max = (l
1197                           ? data->last_start_max
1198                           : (data->pos_delta > SSize_t_MAX - data->pos_min
1199                                          ? SSize_t_MAX
1200                                          : data->pos_min + data->pos_delta));
1201             if (is_inf
1202                  || (STRLEN)data->offset_float_max > (STRLEN)SSize_t_MAX)
1203                 data->offset_float_max = SSize_t_MAX;
1204             if (data->flags & SF_BEFORE_EOL)
1205                 data->flags
1206                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
1207             else
1208                 data->flags &= ~SF_FL_BEFORE_EOL;
1209             data->minlen_float=minlenp;
1210             data->lookbehind_float=0;
1211         }
1212     }
1213     SvCUR_set(data->last_found, 0);
1214     {
1215         SV * const sv = data->last_found;
1216         if (SvUTF8(sv) && SvMAGICAL(sv)) {
1217             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
1218             if (mg)
1219                 mg->mg_len = 0;
1220         }
1221     }
1222     data->last_end = -1;
1223     data->flags &= ~SF_BEFORE_EOL;
1224     DEBUG_STUDYDATA("commit: ",data,0);
1225 }
1226
1227 /* An SSC is just a regnode_charclass_posix with an extra field: the inversion
1228  * list that describes which code points it matches */
1229
1230 STATIC void
1231 S_ssc_anything(pTHX_ regnode_ssc *ssc)
1232 {
1233     /* Set the SSC 'ssc' to match an empty string or any code point */
1234
1235     PERL_ARGS_ASSERT_SSC_ANYTHING;
1236
1237     assert(is_ANYOF_SYNTHETIC(ssc));
1238
1239     ssc->invlist = sv_2mortal(_new_invlist(2)); /* mortalize so won't leak */
1240     _append_range_to_invlist(ssc->invlist, 0, UV_MAX);
1241     ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING;  /* Plus matches empty */
1242 }
1243
1244 STATIC int
1245 S_ssc_is_anything(const regnode_ssc *ssc)
1246 {
1247     /* Returns TRUE if the SSC 'ssc' can match the empty string and any code
1248      * point; FALSE otherwise.  Thus, this is used to see if using 'ssc' buys
1249      * us anything: if the function returns TRUE, 'ssc' hasn't been restricted
1250      * in any way, so there's no point in using it */
1251
1252     UV start, end;
1253     bool ret;
1254
1255     PERL_ARGS_ASSERT_SSC_IS_ANYTHING;
1256
1257     assert(is_ANYOF_SYNTHETIC(ssc));
1258
1259     if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) {
1260         return FALSE;
1261     }
1262
1263     /* See if the list consists solely of the range 0 - Infinity */
1264     invlist_iterinit(ssc->invlist);
1265     ret = invlist_iternext(ssc->invlist, &start, &end)
1266           && start == 0
1267           && end == UV_MAX;
1268
1269     invlist_iterfinish(ssc->invlist);
1270
1271     if (ret) {
1272         return TRUE;
1273     }
1274
1275     /* If e.g., both \w and \W are set, matches everything */
1276     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1277         int i;
1278         for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) {
1279             if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) {
1280                 return TRUE;
1281             }
1282         }
1283     }
1284
1285     return FALSE;
1286 }
1287
1288 STATIC void
1289 S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc)
1290 {
1291     /* Initializes the SSC 'ssc'.  This includes setting it to match an empty
1292      * string, any code point, or any posix class under locale */
1293
1294     PERL_ARGS_ASSERT_SSC_INIT;
1295
1296     Zero(ssc, 1, regnode_ssc);
1297     set_ANYOF_SYNTHETIC(ssc);
1298     ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP);
1299     ssc_anything(ssc);
1300
1301     /* If any portion of the regex is to operate under locale rules that aren't
1302      * fully known at compile time, initialization includes it.  The reason
1303      * this isn't done for all regexes is that the optimizer was written under
1304      * the assumption that locale was all-or-nothing.  Given the complexity and
1305      * lack of documentation in the optimizer, and that there are inadequate
1306      * test cases for locale, many parts of it may not work properly, it is
1307      * safest to avoid locale unless necessary. */
1308     if (RExC_contains_locale) {
1309         ANYOF_POSIXL_SETALL(ssc);
1310     }
1311     else {
1312         ANYOF_POSIXL_ZERO(ssc);
1313     }
1314 }
1315
1316 STATIC int
1317 S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state,
1318                         const regnode_ssc *ssc)
1319 {
1320     /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only
1321      * to the list of code points matched, and locale posix classes; hence does
1322      * not check its flags) */
1323
1324     UV start, end;
1325     bool ret;
1326
1327     PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT;
1328
1329     assert(is_ANYOF_SYNTHETIC(ssc));
1330
1331     invlist_iterinit(ssc->invlist);
1332     ret = invlist_iternext(ssc->invlist, &start, &end)
1333           && start == 0
1334           && end == UV_MAX;
1335
1336     invlist_iterfinish(ssc->invlist);
1337
1338     if (! ret) {
1339         return FALSE;
1340     }
1341
1342     if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) {
1343         return FALSE;
1344     }
1345
1346     return TRUE;
1347 }
1348
1349 STATIC SV*
1350 S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state,
1351                                const regnode_charclass* const node)
1352 {
1353     /* Returns a mortal inversion list defining which code points are matched
1354      * by 'node', which is of type ANYOF.  Handles complementing the result if
1355      * appropriate.  If some code points aren't knowable at this time, the
1356      * returned list must, and will, contain every code point that is a
1357      * possibility. */
1358
1359     SV* invlist = sv_2mortal(_new_invlist(0));
1360     SV* only_utf8_locale_invlist = NULL;
1361     unsigned int i;
1362     const U32 n = ARG(node);
1363     bool new_node_has_latin1 = FALSE;
1364
1365     PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC;
1366
1367     /* Look at the data structure created by S_set_ANYOF_arg() */
1368     if (n != ANYOF_ONLY_HAS_BITMAP) {
1369         SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]);
1370         AV * const av = MUTABLE_AV(SvRV(rv));
1371         SV **const ary = AvARRAY(av);
1372         assert(RExC_rxi->data->what[n] == 's');
1373
1374         if (ary[1] && ary[1] != &PL_sv_undef) { /* Has compile-time swash */
1375             invlist = sv_2mortal(invlist_clone(_get_swash_invlist(ary[1])));
1376         }
1377         else if (ary[0] && ary[0] != &PL_sv_undef) {
1378
1379             /* Here, no compile-time swash, and there are things that won't be
1380              * known until runtime -- we have to assume it could be anything */
1381             return _add_range_to_invlist(invlist, 0, UV_MAX);
1382         }
1383         else if (ary[3] && ary[3] != &PL_sv_undef) {
1384
1385             /* Here no compile-time swash, and no run-time only data.  Use the
1386              * node's inversion list */
1387             invlist = sv_2mortal(invlist_clone(ary[3]));
1388         }
1389
1390         /* Get the code points valid only under UTF-8 locales */
1391         if ((ANYOF_FLAGS(node) & ANYOFL_FOLD)
1392             && ary[2] && ary[2] != &PL_sv_undef)
1393         {
1394             only_utf8_locale_invlist = ary[2];
1395         }
1396     }
1397
1398     /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS
1399      * code points, and an inversion list for the others, but if there are code
1400      * points that should match only conditionally on the target string being
1401      * UTF-8, those are placed in the inversion list, and not the bitmap.
1402      * Since there are circumstances under which they could match, they are
1403      * included in the SSC.  But if the ANYOF node is to be inverted, we have
1404      * to exclude them here, so that when we invert below, the end result
1405      * actually does include them.  (Think about "\xe0" =~ /[^\xc0]/di;).  We
1406      * have to do this here before we add the unconditionally matched code
1407      * points */
1408     if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1409         _invlist_intersection_complement_2nd(invlist,
1410                                              PL_UpperLatin1,
1411                                              &invlist);
1412     }
1413
1414     /* Add in the points from the bit map */
1415     for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
1416         if (ANYOF_BITMAP_TEST(node, i)) {
1417             invlist = add_cp_to_invlist(invlist, i);
1418             new_node_has_latin1 = TRUE;
1419         }
1420     }
1421
1422     /* If this can match all upper Latin1 code points, have to add them
1423      * as well */
1424     if (OP(node) == ANYOFD
1425         && (ANYOF_FLAGS(node) & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
1426     {
1427         _invlist_union(invlist, PL_UpperLatin1, &invlist);
1428     }
1429
1430     /* Similarly for these */
1431     if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
1432         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
1433     }
1434
1435     if (ANYOF_FLAGS(node) & ANYOF_INVERT) {
1436         _invlist_invert(invlist);
1437     }
1438     else if (new_node_has_latin1 && ANYOF_FLAGS(node) & ANYOFL_FOLD) {
1439
1440         /* Under /li, any 0-255 could fold to any other 0-255, depending on the
1441          * locale.  We can skip this if there are no 0-255 at all. */
1442         _invlist_union(invlist, PL_Latin1, &invlist);
1443     }
1444
1445     /* Similarly add the UTF-8 locale possible matches.  These have to be
1446      * deferred until after the non-UTF-8 locale ones are taken care of just
1447      * above, or it leads to wrong results under ANYOF_INVERT */
1448     if (only_utf8_locale_invlist) {
1449         _invlist_union_maybe_complement_2nd(invlist,
1450                                             only_utf8_locale_invlist,
1451                                             ANYOF_FLAGS(node) & ANYOF_INVERT,
1452                                             &invlist);
1453     }
1454
1455     return invlist;
1456 }
1457
1458 /* These two functions currently do the exact same thing */
1459 #define ssc_init_zero           ssc_init
1460
1461 #define ssc_add_cp(ssc, cp)   ssc_add_range((ssc), (cp), (cp))
1462 #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX)
1463
1464 /* 'AND' a given class with another one.  Can create false positives.  'ssc'
1465  * should not be inverted.  'and_with->flags & ANYOF_MATCHES_POSIXL' should be
1466  * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */
1467
1468 STATIC void
1469 S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1470                 const regnode_charclass *and_with)
1471 {
1472     /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either
1473      * another SSC or a regular ANYOF class.  Can create false positives. */
1474
1475     SV* anded_cp_list;
1476     U8  anded_flags;
1477
1478     PERL_ARGS_ASSERT_SSC_AND;
1479
1480     assert(is_ANYOF_SYNTHETIC(ssc));
1481
1482     /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract
1483      * the code point inversion list and just the relevant flags */
1484     if (is_ANYOF_SYNTHETIC(and_with)) {
1485         anded_cp_list = ((regnode_ssc *)and_with)->invlist;
1486         anded_flags = ANYOF_FLAGS(and_with);
1487
1488         /* XXX This is a kludge around what appears to be deficiencies in the
1489          * optimizer.  If we make S_ssc_anything() add in the WARN_SUPER flag,
1490          * there are paths through the optimizer where it doesn't get weeded
1491          * out when it should.  And if we don't make some extra provision for
1492          * it like the code just below, it doesn't get added when it should.
1493          * This solution is to add it only when AND'ing, which is here, and
1494          * only when what is being AND'ed is the pristine, original node
1495          * matching anything.  Thus it is like adding it to ssc_anything() but
1496          * only when the result is to be AND'ed.  Probably the same solution
1497          * could be adopted for the same problem we have with /l matching,
1498          * which is solved differently in S_ssc_init(), and that would lead to
1499          * fewer false positives than that solution has.  But if this solution
1500          * creates bugs, the consequences are only that a warning isn't raised
1501          * that should be; while the consequences for having /l bugs is
1502          * incorrect matches */
1503         if (ssc_is_anything((regnode_ssc *)and_with)) {
1504             anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
1505         }
1506     }
1507     else {
1508         anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with);
1509         if (OP(and_with) == ANYOFD) {
1510             anded_flags = ANYOF_FLAGS(and_with) & ANYOF_COMMON_FLAGS;
1511         }
1512         else {
1513             anded_flags = ANYOF_FLAGS(and_with)
1514             &( ANYOF_COMMON_FLAGS
1515               |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1516               |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1517             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(and_with))) {
1518                 anded_flags &=
1519                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1520             }
1521         }
1522     }
1523
1524     ANYOF_FLAGS(ssc) &= anded_flags;
1525
1526     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1527      * C2 is the list of code points in 'and-with'; P2, its posix classes.
1528      * 'and_with' may be inverted.  When not inverted, we have the situation of
1529      * computing:
1530      *  (C1 | P1) & (C2 | P2)
1531      *                     =  (C1 & (C2 | P2)) | (P1 & (C2 | P2))
1532      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1533      *                    <=  ((C1 & C2) |       P2)) | ( P1       | (P1 & P2))
1534      *                    <=  ((C1 & C2) | P1 | P2)
1535      * Alternatively, the last few steps could be:
1536      *                     =  ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2))
1537      *                    <=  ((C1 & C2) |  C1      ) | (      C2  | (P1 & P2))
1538      *                    <=  (C1 | C2 | (P1 & P2))
1539      * We favor the second approach if either P1 or P2 is non-empty.  This is
1540      * because these components are a barrier to doing optimizations, as what
1541      * they match cannot be known until the moment of matching as they are
1542      * dependent on the current locale, 'AND"ing them likely will reduce or
1543      * eliminate them.
1544      * But we can do better if we know that C1,P1 are in their initial state (a
1545      * frequent occurrence), each matching everything:
1546      *  (<everything>) & (C2 | P2) =  C2 | P2
1547      * Similarly, if C2,P2 are in their initial state (again a frequent
1548      * occurrence), the result is a no-op
1549      *  (C1 | P1) & (<everything>) =  C1 | P1
1550      *
1551      * Inverted, we have
1552      *  (C1 | P1) & ~(C2 | P2)  =  (C1 | P1) & (~C2 & ~P2)
1553      *                          =  (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2))
1554      *                         <=  (C1 & ~C2) | (P1 & ~P2)
1555      * */
1556
1557     if ((ANYOF_FLAGS(and_with) & ANYOF_INVERT)
1558         && ! is_ANYOF_SYNTHETIC(and_with))
1559     {
1560         unsigned int i;
1561
1562         ssc_intersection(ssc,
1563                          anded_cp_list,
1564                          FALSE /* Has already been inverted */
1565                          );
1566
1567         /* If either P1 or P2 is empty, the intersection will be also; can skip
1568          * the loop */
1569         if (! (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL)) {
1570             ANYOF_POSIXL_ZERO(ssc);
1571         }
1572         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1573
1574             /* Note that the Posix class component P from 'and_with' actually
1575              * looks like:
1576              *      P = Pa | Pb | ... | Pn
1577              * where each component is one posix class, such as in [\w\s].
1578              * Thus
1579              *      ~P = ~(Pa | Pb | ... | Pn)
1580              *         = ~Pa & ~Pb & ... & ~Pn
1581              *        <= ~Pa | ~Pb | ... | ~Pn
1582              * The last is something we can easily calculate, but unfortunately
1583              * is likely to have many false positives.  We could do better
1584              * in some (but certainly not all) instances if two classes in
1585              * P have known relationships.  For example
1586              *      :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print:
1587              * So
1588              *      :lower: & :print: = :lower:
1589              * And similarly for classes that must be disjoint.  For example,
1590              * since \s and \w can have no elements in common based on rules in
1591              * the POSIX standard,
1592              *      \w & ^\S = nothing
1593              * Unfortunately, some vendor locales do not meet the Posix
1594              * standard, in particular almost everything by Microsoft.
1595              * The loop below just changes e.g., \w into \W and vice versa */
1596
1597             regnode_charclass_posixl temp;
1598             int add = 1;    /* To calculate the index of the complement */
1599
1600             ANYOF_POSIXL_ZERO(&temp);
1601             for (i = 0; i < ANYOF_MAX; i++) {
1602                 assert(i % 2 != 0
1603                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)
1604                        || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1));
1605
1606                 if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) {
1607                     ANYOF_POSIXL_SET(&temp, i + add);
1608                 }
1609                 add = 0 - add; /* 1 goes to -1; -1 goes to 1 */
1610             }
1611             ANYOF_POSIXL_AND(&temp, ssc);
1612
1613         } /* else ssc already has no posixes */
1614     } /* else: Not inverted.  This routine is a no-op if 'and_with' is an SSC
1615          in its initial state */
1616     else if (! is_ANYOF_SYNTHETIC(and_with)
1617              || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with))
1618     {
1619         /* But if 'ssc' is in its initial state, the result is just 'and_with';
1620          * copy it over 'ssc' */
1621         if (ssc_is_cp_posixl_init(pRExC_state, ssc)) {
1622             if (is_ANYOF_SYNTHETIC(and_with)) {
1623                 StructCopy(and_with, ssc, regnode_ssc);
1624             }
1625             else {
1626                 ssc->invlist = anded_cp_list;
1627                 ANYOF_POSIXL_ZERO(ssc);
1628                 if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1629                     ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc);
1630                 }
1631             }
1632         }
1633         else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)
1634                  || (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL))
1635         {
1636             /* One or the other of P1, P2 is non-empty. */
1637             if (ANYOF_FLAGS(and_with) & ANYOF_MATCHES_POSIXL) {
1638                 ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc);
1639             }
1640             ssc_union(ssc, anded_cp_list, FALSE);
1641         }
1642         else { /* P1 = P2 = empty */
1643             ssc_intersection(ssc, anded_cp_list, FALSE);
1644         }
1645     }
1646 }
1647
1648 STATIC void
1649 S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc,
1650                const regnode_charclass *or_with)
1651 {
1652     /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either
1653      * another SSC or a regular ANYOF class.  Can create false positives if
1654      * 'or_with' is to be inverted. */
1655
1656     SV* ored_cp_list;
1657     U8 ored_flags;
1658
1659     PERL_ARGS_ASSERT_SSC_OR;
1660
1661     assert(is_ANYOF_SYNTHETIC(ssc));
1662
1663     /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract
1664      * the code point inversion list and just the relevant flags */
1665     if (is_ANYOF_SYNTHETIC(or_with)) {
1666         ored_cp_list = ((regnode_ssc*) or_with)->invlist;
1667         ored_flags = ANYOF_FLAGS(or_with);
1668     }
1669     else {
1670         ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with);
1671         ored_flags = ANYOF_FLAGS(or_with) & ANYOF_COMMON_FLAGS;
1672         if (OP(or_with) != ANYOFD) {
1673             ored_flags
1674             |= ANYOF_FLAGS(or_with)
1675              & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1676                 |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP);
1677             if (ANYOFL_UTF8_LOCALE_REQD(ANYOF_FLAGS(or_with))) {
1678                 ored_flags |=
1679                     ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
1680             }
1681         }
1682     }
1683
1684     ANYOF_FLAGS(ssc) |= ored_flags;
1685
1686     /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes.
1687      * C2 is the list of code points in 'or-with'; P2, its posix classes.
1688      * 'or_with' may be inverted.  When not inverted, we have the simple
1689      * situation of computing:
1690      *  (C1 | P1) | (C2 | P2)  =  (C1 | C2) | (P1 | P2)
1691      * If P1|P2 yields a situation with both a class and its complement are
1692      * set, like having both \w and \W, this matches all code points, and we
1693      * can delete these from the P component of the ssc going forward.  XXX We
1694      * might be able to delete all the P components, but I (khw) am not certain
1695      * about this, and it is better to be safe.
1696      *
1697      * Inverted, we have
1698      *  (C1 | P1) | ~(C2 | P2)  =  (C1 | P1) | (~C2 & ~P2)
1699      *                         <=  (C1 | P1) | ~C2
1700      *                         <=  (C1 | ~C2) | P1
1701      * (which results in actually simpler code than the non-inverted case)
1702      * */
1703
1704     if ((ANYOF_FLAGS(or_with) & ANYOF_INVERT)
1705         && ! is_ANYOF_SYNTHETIC(or_with))
1706     {
1707         /* We ignore P2, leaving P1 going forward */
1708     }   /* else  Not inverted */
1709     else if (ANYOF_FLAGS(or_with) & ANYOF_MATCHES_POSIXL) {
1710         ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc);
1711         if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1712             unsigned int i;
1713             for (i = 0; i < ANYOF_MAX; i += 2) {
1714                 if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1))
1715                 {
1716                     ssc_match_all_cp(ssc);
1717                     ANYOF_POSIXL_CLEAR(ssc, i);
1718                     ANYOF_POSIXL_CLEAR(ssc, i+1);
1719                 }
1720             }
1721         }
1722     }
1723
1724     ssc_union(ssc,
1725               ored_cp_list,
1726               FALSE /* Already has been inverted */
1727               );
1728 }
1729
1730 PERL_STATIC_INLINE void
1731 S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd)
1732 {
1733     PERL_ARGS_ASSERT_SSC_UNION;
1734
1735     assert(is_ANYOF_SYNTHETIC(ssc));
1736
1737     _invlist_union_maybe_complement_2nd(ssc->invlist,
1738                                         invlist,
1739                                         invert2nd,
1740                                         &ssc->invlist);
1741 }
1742
1743 PERL_STATIC_INLINE void
1744 S_ssc_intersection(pTHX_ regnode_ssc *ssc,
1745                          SV* const invlist,
1746                          const bool invert2nd)
1747 {
1748     PERL_ARGS_ASSERT_SSC_INTERSECTION;
1749
1750     assert(is_ANYOF_SYNTHETIC(ssc));
1751
1752     _invlist_intersection_maybe_complement_2nd(ssc->invlist,
1753                                                invlist,
1754                                                invert2nd,
1755                                                &ssc->invlist);
1756 }
1757
1758 PERL_STATIC_INLINE void
1759 S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end)
1760 {
1761     PERL_ARGS_ASSERT_SSC_ADD_RANGE;
1762
1763     assert(is_ANYOF_SYNTHETIC(ssc));
1764
1765     ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end);
1766 }
1767
1768 PERL_STATIC_INLINE void
1769 S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp)
1770 {
1771     /* AND just the single code point 'cp' into the SSC 'ssc' */
1772
1773     SV* cp_list = _new_invlist(2);
1774
1775     PERL_ARGS_ASSERT_SSC_CP_AND;
1776
1777     assert(is_ANYOF_SYNTHETIC(ssc));
1778
1779     cp_list = add_cp_to_invlist(cp_list, cp);
1780     ssc_intersection(ssc, cp_list,
1781                      FALSE /* Not inverted */
1782                      );
1783     SvREFCNT_dec_NN(cp_list);
1784 }
1785
1786 PERL_STATIC_INLINE void
1787 S_ssc_clear_locale(regnode_ssc *ssc)
1788 {
1789     /* Set the SSC 'ssc' to not match any locale things */
1790     PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE;
1791
1792     assert(is_ANYOF_SYNTHETIC(ssc));
1793
1794     ANYOF_POSIXL_ZERO(ssc);
1795     ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS;
1796 }
1797
1798 #define NON_OTHER_COUNT   NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C
1799
1800 STATIC bool
1801 S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc)
1802 {
1803     /* The synthetic start class is used to hopefully quickly winnow down
1804      * places where a pattern could start a match in the target string.  If it
1805      * doesn't really narrow things down that much, there isn't much point to
1806      * having the overhead of using it.  This function uses some very crude
1807      * heuristics to decide if to use the ssc or not.
1808      *
1809      * It returns TRUE if 'ssc' rules out more than half what it considers to
1810      * be the "likely" possible matches, but of course it doesn't know what the
1811      * actual things being matched are going to be; these are only guesses
1812      *
1813      * For /l matches, it assumes that the only likely matches are going to be
1814      *      in the 0-255 range, uniformly distributed, so half of that is 127
1815      * For /a and /d matches, it assumes that the likely matches will be just
1816      *      the ASCII range, so half of that is 63
1817      * For /u and there isn't anything matching above the Latin1 range, it
1818      *      assumes that that is the only range likely to be matched, and uses
1819      *      half that as the cut-off: 127.  If anything matches above Latin1,
1820      *      it assumes that all of Unicode could match (uniformly), except for
1821      *      non-Unicode code points and things in the General Category "Other"
1822      *      (unassigned, private use, surrogates, controls and formats).  This
1823      *      is a much large number. */
1824
1825     const U32 max_match = (LOC)
1826                           ? 127
1827                           : (! UNI_SEMANTICS)
1828                             ? 63
1829                             : (invlist_highest(ssc->invlist) < 256)
1830                               ? 127
1831                               : ((NON_OTHER_COUNT + 1) / 2) - 1;
1832     U32 count = 0;      /* Running total of number of code points matched by
1833                            'ssc' */
1834     UV start, end;      /* Start and end points of current range in inversion
1835                            list */
1836
1837     PERL_ARGS_ASSERT_IS_SSC_WORTH_IT;
1838
1839     invlist_iterinit(ssc->invlist);
1840     while (invlist_iternext(ssc->invlist, &start, &end)) {
1841
1842         /* /u is the only thing that we expect to match above 255; so if not /u
1843          * and even if there are matches above 255, ignore them.  This catches
1844          * things like \d under /d which does match the digits above 255, but
1845          * since the pattern is /d, it is not likely to be expecting them */
1846         if (! UNI_SEMANTICS) {
1847             if (start > 255) {
1848                 break;
1849             }
1850             end = MIN(end, 255);
1851         }
1852         count += end - start + 1;
1853         if (count > max_match) {
1854             invlist_iterfinish(ssc->invlist);
1855             return FALSE;
1856         }
1857     }
1858
1859     return TRUE;
1860 }
1861
1862
1863 STATIC void
1864 S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc)
1865 {
1866     /* The inversion list in the SSC is marked mortal; now we need a more
1867      * permanent copy, which is stored the same way that is done in a regular
1868      * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit
1869      * map */
1870
1871     SV* invlist = invlist_clone(ssc->invlist);
1872
1873     PERL_ARGS_ASSERT_SSC_FINALIZE;
1874
1875     assert(is_ANYOF_SYNTHETIC(ssc));
1876
1877     /* The code in this file assumes that all but these flags aren't relevant
1878      * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared
1879      * by the time we reach here */
1880     assert(! (ANYOF_FLAGS(ssc)
1881         & ~( ANYOF_COMMON_FLAGS
1882             |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER
1883             |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)));
1884
1885     populate_ANYOF_from_invlist( (regnode *) ssc, &invlist);
1886
1887     set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist,
1888                                 NULL, NULL, NULL, FALSE);
1889
1890     /* Make sure is clone-safe */
1891     ssc->invlist = NULL;
1892
1893     if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) {
1894         ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL;
1895     }
1896
1897     if (RExC_contains_locale) {
1898         OP(ssc) = ANYOFL;
1899     }
1900
1901     assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale);
1902 }
1903
1904 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1905 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
1906 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1907 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list         \
1908                                ? (TRIE_LIST_CUR( idx ) - 1)           \
1909                                : 0 )
1910
1911
1912 #ifdef DEBUGGING
1913 /*
1914    dump_trie(trie,widecharmap,revcharmap)
1915    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1916    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1917
1918    These routines dump out a trie in a somewhat readable format.
1919    The _interim_ variants are used for debugging the interim
1920    tables that are used to generate the final compressed
1921    representation which is what dump_trie expects.
1922
1923    Part of the reason for their existence is to provide a form
1924    of documentation as to how the different representations function.
1925
1926 */
1927
1928 /*
1929   Dumps the final compressed table form of the trie to Perl_debug_log.
1930   Used for debugging make_trie().
1931 */
1932
1933 STATIC void
1934 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1935             AV *revcharmap, U32 depth)
1936 {
1937     U32 state;
1938     SV *sv=sv_newmortal();
1939     int colwidth= widecharmap ? 6 : 4;
1940     U16 word;
1941     GET_RE_DEBUG_FLAGS_DECL;
1942
1943     PERL_ARGS_ASSERT_DUMP_TRIE;
1944
1945     PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1946         (int)depth * 2 + 2,"",
1947         "Match","Base","Ofs" );
1948
1949     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1950         SV ** const tmp = av_fetch( revcharmap, state, 0);
1951         if ( tmp ) {
1952             PerlIO_printf( Perl_debug_log, "%*s",
1953                 colwidth,
1954                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
1955                             PL_colors[0], PL_colors[1],
1956                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1957                             PERL_PV_ESCAPE_FIRSTCHAR
1958                 )
1959             );
1960         }
1961     }
1962     PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1963         (int)depth * 2 + 2,"");
1964
1965     for( state = 0 ; state < trie->uniquecharcount ; state++ )
1966         PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1967     PerlIO_printf( Perl_debug_log, "\n");
1968
1969     for( state = 1 ; state < trie->statecount ; state++ ) {
1970         const U32 base = trie->states[ state ].trans.base;
1971
1972         PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|",
1973                                        (int)depth * 2 + 2,"", (UV)state);
1974
1975         if ( trie->states[ state ].wordnum ) {
1976             PerlIO_printf( Perl_debug_log, " W%4X",
1977                                            trie->states[ state ].wordnum );
1978         } else {
1979             PerlIO_printf( Perl_debug_log, "%6s", "" );
1980         }
1981
1982         PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1983
1984         if ( base ) {
1985             U32 ofs = 0;
1986
1987             while( ( base + ofs  < trie->uniquecharcount ) ||
1988                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
1989                      && trie->trans[ base + ofs - trie->uniquecharcount ].check
1990                                                                     != state))
1991                     ofs++;
1992
1993             PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1994
1995             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1996                 if ( ( base + ofs >= trie->uniquecharcount )
1997                         && ( base + ofs - trie->uniquecharcount
1998                                                         < trie->lasttrans )
1999                         && trie->trans[ base + ofs
2000                                     - trie->uniquecharcount ].check == state )
2001                 {
2002                    PerlIO_printf( Perl_debug_log, "%*"UVXf,
2003                     colwidth,
2004                     (UV)trie->trans[ base + ofs
2005                                              - trie->uniquecharcount ].next );
2006                 } else {
2007                     PerlIO_printf( Perl_debug_log, "%*s",colwidth,"   ." );
2008                 }
2009             }
2010
2011             PerlIO_printf( Perl_debug_log, "]");
2012
2013         }
2014         PerlIO_printf( Perl_debug_log, "\n" );
2015     }
2016     PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=",
2017                                 (int)depth*2, "");
2018     for (word=1; word <= trie->wordcount; word++) {
2019         PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
2020             (int)word, (int)(trie->wordinfo[word].prev),
2021             (int)(trie->wordinfo[word].len));
2022     }
2023     PerlIO_printf(Perl_debug_log, "\n" );
2024 }
2025 /*
2026   Dumps a fully constructed but uncompressed trie in list form.
2027   List tries normally only are used for construction when the number of
2028   possible chars (trie->uniquecharcount) is very high.
2029   Used for debugging make_trie().
2030 */
2031 STATIC void
2032 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
2033                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
2034                          U32 depth)
2035 {
2036     U32 state;
2037     SV *sv=sv_newmortal();
2038     int colwidth= widecharmap ? 6 : 4;
2039     GET_RE_DEBUG_FLAGS_DECL;
2040
2041     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
2042
2043     /* print out the table precompression.  */
2044     PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
2045         (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
2046         "------:-----+-----------------\n" );
2047
2048     for( state=1 ; state < next_alloc ; state ++ ) {
2049         U16 charid;
2050
2051         PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
2052             (int)depth * 2 + 2,"", (UV)state  );
2053         if ( ! trie->states[ state ].wordnum ) {
2054             PerlIO_printf( Perl_debug_log, "%5s| ","");
2055         } else {
2056             PerlIO_printf( Perl_debug_log, "W%4x| ",
2057                 trie->states[ state ].wordnum
2058             );
2059         }
2060         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
2061             SV ** const tmp = av_fetch( revcharmap,
2062                                         TRIE_LIST_ITEM(state,charid).forid, 0);
2063             if ( tmp ) {
2064                 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
2065                     colwidth,
2066                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp),
2067                               colwidth,
2068                               PL_colors[0], PL_colors[1],
2069                               (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
2070                               | PERL_PV_ESCAPE_FIRSTCHAR
2071                     ) ,
2072                     TRIE_LIST_ITEM(state,charid).forid,
2073                     (UV)TRIE_LIST_ITEM(state,charid).newstate
2074                 );
2075                 if (!(charid % 10))
2076                     PerlIO_printf(Perl_debug_log, "\n%*s| ",
2077                         (int)((depth * 2) + 14), "");
2078             }
2079         }
2080         PerlIO_printf( Perl_debug_log, "\n");
2081     }
2082 }
2083
2084 /*
2085   Dumps a fully constructed but uncompressed trie in table form.
2086   This is the normal DFA style state transition table, with a few
2087   twists to facilitate compression later.
2088   Used for debugging make_trie().
2089 */
2090 STATIC void
2091 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
2092                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
2093                           U32 depth)
2094 {
2095     U32 state;
2096     U16 charid;
2097     SV *sv=sv_newmortal();
2098     int colwidth= widecharmap ? 6 : 4;
2099     GET_RE_DEBUG_FLAGS_DECL;
2100
2101     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
2102
2103     /*
2104        print out the table precompression so that we can do a visual check
2105        that they are identical.
2106      */
2107
2108     PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
2109
2110     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2111         SV ** const tmp = av_fetch( revcharmap, charid, 0);
2112         if ( tmp ) {
2113             PerlIO_printf( Perl_debug_log, "%*s",
2114                 colwidth,
2115                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
2116                             PL_colors[0], PL_colors[1],
2117                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2118                             PERL_PV_ESCAPE_FIRSTCHAR
2119                 )
2120             );
2121         }
2122     }
2123
2124     PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
2125
2126     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
2127         PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
2128     }
2129
2130     PerlIO_printf( Perl_debug_log, "\n" );
2131
2132     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
2133
2134         PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
2135             (int)depth * 2 + 2,"",
2136             (UV)TRIE_NODENUM( state ) );
2137
2138         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
2139             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
2140             if (v)
2141                 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
2142             else
2143                 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
2144         }
2145         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
2146             PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n",
2147                                             (UV)trie->trans[ state ].check );
2148         } else {
2149             PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n",
2150                                             (UV)trie->trans[ state ].check,
2151             trie->states[ TRIE_NODENUM( state ) ].wordnum );
2152         }
2153     }
2154 }
2155
2156 #endif
2157
2158
2159 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
2160   startbranch: the first branch in the whole branch sequence
2161   first      : start branch of sequence of branch-exact nodes.
2162                May be the same as startbranch
2163   last       : Thing following the last branch.
2164                May be the same as tail.
2165   tail       : item following the branch sequence
2166   count      : words in the sequence
2167   flags      : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/
2168   depth      : indent depth
2169
2170 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
2171
2172 A trie is an N'ary tree where the branches are determined by digital
2173 decomposition of the key. IE, at the root node you look up the 1st character and
2174 follow that branch repeat until you find the end of the branches. Nodes can be
2175 marked as "accepting" meaning they represent a complete word. Eg:
2176
2177   /he|she|his|hers/
2178
2179 would convert into the following structure. Numbers represent states, letters
2180 following numbers represent valid transitions on the letter from that state, if
2181 the number is in square brackets it represents an accepting state, otherwise it
2182 will be in parenthesis.
2183
2184       +-h->+-e->[3]-+-r->(8)-+-s->[9]
2185       |    |
2186       |   (2)
2187       |    |
2188      (1)   +-i->(6)-+-s->[7]
2189       |
2190       +-s->(3)-+-h->(4)-+-e->[5]
2191
2192       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
2193
2194 This shows that when matching against the string 'hers' we will begin at state 1
2195 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
2196 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
2197 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
2198 single traverse. We store a mapping from accepting to state to which word was
2199 matched, and then when we have multiple possibilities we try to complete the
2200 rest of the regex in the order in which they occurred in the alternation.
2201
2202 The only prior NFA like behaviour that would be changed by the TRIE support is
2203 the silent ignoring of duplicate alternations which are of the form:
2204
2205  / (DUPE|DUPE) X? (?{ ... }) Y /x
2206
2207 Thus EVAL blocks following a trie may be called a different number of times with
2208 and without the optimisation. With the optimisations dupes will be silently
2209 ignored. This inconsistent behaviour of EVAL type nodes is well established as
2210 the following demonstrates:
2211
2212  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
2213
2214 which prints out 'word' three times, but
2215
2216  'words'=~/(word|word|word)(?{ print $1 })S/
2217
2218 which doesnt print it out at all. This is due to other optimisations kicking in.
2219
2220 Example of what happens on a structural level:
2221
2222 The regexp /(ac|ad|ab)+/ will produce the following debug output:
2223
2224    1: CURLYM[1] {1,32767}(18)
2225    5:   BRANCH(8)
2226    6:     EXACT <ac>(16)
2227    8:   BRANCH(11)
2228    9:     EXACT <ad>(16)
2229   11:   BRANCH(14)
2230   12:     EXACT <ab>(16)
2231   16:   SUCCEED(0)
2232   17:   NOTHING(18)
2233   18: END(0)
2234
2235 This would be optimizable with startbranch=5, first=5, last=16, tail=16
2236 and should turn into:
2237
2238    1: CURLYM[1] {1,32767}(18)
2239    5:   TRIE(16)
2240         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
2241           <ac>
2242           <ad>
2243           <ab>
2244   16:   SUCCEED(0)
2245   17:   NOTHING(18)
2246   18: END(0)
2247
2248 Cases where tail != last would be like /(?foo|bar)baz/:
2249
2250    1: BRANCH(4)
2251    2:   EXACT <foo>(8)
2252    4: BRANCH(7)
2253    5:   EXACT <bar>(8)
2254    7: TAIL(8)
2255    8: EXACT <baz>(10)
2256   10: END(0)
2257
2258 which would be optimizable with startbranch=1, first=1, last=7, tail=8
2259 and would end up looking like:
2260
2261     1: TRIE(8)
2262       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
2263         <foo>
2264         <bar>
2265    7: TAIL(8)
2266    8: EXACT <baz>(10)
2267   10: END(0)
2268
2269     d = uvchr_to_utf8_flags(d, uv, 0);
2270
2271 is the recommended Unicode-aware way of saying
2272
2273     *(d++) = uv;
2274 */
2275
2276 #define TRIE_STORE_REVCHAR(val)                                            \
2277     STMT_START {                                                           \
2278         if (UTF) {                                                         \
2279             SV *zlopp = newSV(UTF8_MAXBYTES);                              \
2280             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
2281             unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \
2282             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
2283             SvPOK_on(zlopp);                                               \
2284             SvUTF8_on(zlopp);                                              \
2285             av_push(revcharmap, zlopp);                                    \
2286         } else {                                                           \
2287             char ooooff = (char)val;                                           \
2288             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
2289         }                                                                  \
2290         } STMT_END
2291
2292 /* This gets the next character from the input, folding it if not already
2293  * folded. */
2294 #define TRIE_READ_CHAR STMT_START {                                           \
2295     wordlen++;                                                                \
2296     if ( UTF ) {                                                              \
2297         /* if it is UTF then it is either already folded, or does not need    \
2298          * folding */                                                         \
2299         uvc = valid_utf8_to_uvchr( (const U8*) uc, &len);                     \
2300     }                                                                         \
2301     else if (folder == PL_fold_latin1) {                                      \
2302         /* This folder implies Unicode rules, which in the range expressible  \
2303          *  by not UTF is the lower case, with the two exceptions, one of     \
2304          *  which should have been taken care of before calling this */       \
2305         assert(*uc != LATIN_SMALL_LETTER_SHARP_S);                            \
2306         uvc = toLOWER_L1(*uc);                                                \
2307         if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU;         \
2308         len = 1;                                                              \
2309     } else {                                                                  \
2310         /* raw data, will be folded later if needed */                        \
2311         uvc = (U32)*uc;                                                       \
2312         len = 1;                                                              \
2313     }                                                                         \
2314 } STMT_END
2315
2316
2317
2318 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
2319     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
2320         U32 ging = TRIE_LIST_LEN( state ) *= 2;                 \
2321         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
2322     }                                                           \
2323     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
2324     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
2325     TRIE_LIST_CUR( state )++;                                   \
2326 } STMT_END
2327
2328 #define TRIE_LIST_NEW(state) STMT_START {                       \
2329     Newxz( trie->states[ state ].trans.list,               \
2330         4, reg_trie_trans_le );                                 \
2331      TRIE_LIST_CUR( state ) = 1;                                \
2332      TRIE_LIST_LEN( state ) = 4;                                \
2333 } STMT_END
2334
2335 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
2336     U16 dupe= trie->states[ state ].wordnum;                    \
2337     regnode * const noper_next = regnext( noper );              \
2338                                                                 \
2339     DEBUG_r({                                                   \
2340         /* store the word for dumping */                        \
2341         SV* tmp;                                                \
2342         if (OP(noper) != NOTHING)                               \
2343             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
2344         else                                                    \
2345             tmp = newSVpvn_utf8( "", 0, UTF );                  \
2346         av_push( trie_words, tmp );                             \
2347     });                                                         \
2348                                                                 \
2349     curword++;                                                  \
2350     trie->wordinfo[curword].prev   = 0;                         \
2351     trie->wordinfo[curword].len    = wordlen;                   \
2352     trie->wordinfo[curword].accept = state;                     \
2353                                                                 \
2354     if ( noper_next < tail ) {                                  \
2355         if (!trie->jump)                                        \
2356             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \
2357                                                  sizeof(U16) ); \
2358         trie->jump[curword] = (U16)(noper_next - convert);      \
2359         if (!jumper)                                            \
2360             jumper = noper_next;                                \
2361         if (!nextbranch)                                        \
2362             nextbranch= regnext(cur);                           \
2363     }                                                           \
2364                                                                 \
2365     if ( dupe ) {                                               \
2366         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
2367         /* chain, so that when the bits of chain are later    */\
2368         /* linked together, the dups appear in the chain      */\
2369         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
2370         trie->wordinfo[dupe].prev = curword;                    \
2371     } else {                                                    \
2372         /* we haven't inserted this word yet.                */ \
2373         trie->states[ state ].wordnum = curword;                \
2374     }                                                           \
2375 } STMT_END
2376
2377
2378 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
2379      ( ( base + charid >=  ucharcount                                   \
2380          && base + charid < ubound                                      \
2381          && state == trie->trans[ base - ucharcount + charid ].check    \
2382          && trie->trans[ base - ucharcount + charid ].next )            \
2383            ? trie->trans[ base - ucharcount + charid ].next             \
2384            : ( state==1 ? special : 0 )                                 \
2385       )
2386
2387 #define MADE_TRIE       1
2388 #define MADE_JUMP_TRIE  2
2389 #define MADE_EXACT_TRIE 4
2390
2391 STATIC I32
2392 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch,
2393                   regnode *first, regnode *last, regnode *tail,
2394                   U32 word_count, U32 flags, U32 depth)
2395 {
2396     /* first pass, loop through and scan words */
2397     reg_trie_data *trie;
2398     HV *widecharmap = NULL;
2399     AV *revcharmap = newAV();
2400     regnode *cur;
2401     STRLEN len = 0;
2402     UV uvc = 0;
2403     U16 curword = 0;
2404     U32 next_alloc = 0;
2405     regnode *jumper = NULL;
2406     regnode *nextbranch = NULL;
2407     regnode *convert = NULL;
2408     U32 *prev_states; /* temp array mapping each state to previous one */
2409     /* we just use folder as a flag in utf8 */
2410     const U8 * folder = NULL;
2411
2412 #ifdef DEBUGGING
2413     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuuu"));
2414     AV *trie_words = NULL;
2415     /* along with revcharmap, this only used during construction but both are
2416      * useful during debugging so we store them in the struct when debugging.
2417      */
2418 #else
2419     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu"));
2420     STRLEN trie_charcount=0;
2421 #endif
2422     SV *re_trie_maxbuff;
2423     GET_RE_DEBUG_FLAGS_DECL;
2424
2425     PERL_ARGS_ASSERT_MAKE_TRIE;
2426 #ifndef DEBUGGING
2427     PERL_UNUSED_ARG(depth);
2428 #endif
2429
2430     switch (flags) {
2431         case EXACT: case EXACTL: break;
2432         case EXACTFA:
2433         case EXACTFU_SS:
2434         case EXACTFU:
2435         case EXACTFLU8: folder = PL_fold_latin1; break;
2436         case EXACTF:  folder = PL_fold; break;
2437         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
2438     }
2439
2440     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
2441     trie->refcount = 1;
2442     trie->startstate = 1;
2443     trie->wordcount = word_count;
2444     RExC_rxi->data->data[ data_slot ] = (void*)trie;
2445     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
2446     if (flags == EXACT || flags == EXACTL)
2447         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
2448     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
2449                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
2450
2451     DEBUG_r({
2452         trie_words = newAV();
2453     });
2454
2455     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2456     assert(re_trie_maxbuff);
2457     if (!SvIOK(re_trie_maxbuff)) {
2458         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2459     }
2460     DEBUG_TRIE_COMPILE_r({
2461         PerlIO_printf( Perl_debug_log,
2462           "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
2463           (int)depth * 2 + 2, "",
2464           REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
2465           REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth);
2466     });
2467
2468    /* Find the node we are going to overwrite */
2469     if ( first == startbranch && OP( last ) != BRANCH ) {
2470         /* whole branch chain */
2471         convert = first;
2472     } else {
2473         /* branch sub-chain */
2474         convert = NEXTOPER( first );
2475     }
2476
2477     /*  -- First loop and Setup --
2478
2479        We first traverse the branches and scan each word to determine if it
2480        contains widechars, and how many unique chars there are, this is
2481        important as we have to build a table with at least as many columns as we
2482        have unique chars.
2483
2484        We use an array of integers to represent the character codes 0..255
2485        (trie->charmap) and we use a an HV* to store Unicode characters. We use
2486        the native representation of the character value as the key and IV's for
2487        the coded index.
2488
2489        *TODO* If we keep track of how many times each character is used we can
2490        remap the columns so that the table compression later on is more
2491        efficient in terms of memory by ensuring the most common value is in the
2492        middle and the least common are on the outside.  IMO this would be better
2493        than a most to least common mapping as theres a decent chance the most
2494        common letter will share a node with the least common, meaning the node
2495        will not be compressible. With a middle is most common approach the worst
2496        case is when we have the least common nodes twice.
2497
2498      */
2499
2500     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2501         regnode *noper = NEXTOPER( cur );
2502         const U8 *uc = (U8*)STRING( noper );
2503         const U8 *e  = uc + STR_LEN( noper );
2504         int foldlen = 0;
2505         U32 wordlen      = 0;         /* required init */
2506         STRLEN minchars = 0;
2507         STRLEN maxchars = 0;
2508         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the
2509                                                bitmap?*/
2510
2511         if (OP(noper) == NOTHING) {
2512             regnode *noper_next= regnext(noper);
2513             if (noper_next != tail && OP(noper_next) == flags) {
2514                 noper = noper_next;
2515                 uc= (U8*)STRING(noper);
2516                 e= uc + STR_LEN(noper);
2517                 trie->minlen= STR_LEN(noper);
2518             } else {
2519                 trie->minlen= 0;
2520                 continue;
2521             }
2522         }
2523
2524         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
2525             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
2526                                           regardless of encoding */
2527             if (OP( noper ) == EXACTFU_SS) {
2528                 /* false positives are ok, so just set this */
2529                 TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S);
2530             }
2531         }
2532         for ( ; uc < e ; uc += len ) {  /* Look at each char in the current
2533                                            branch */
2534             TRIE_CHARCOUNT(trie)++;
2535             TRIE_READ_CHAR;
2536
2537             /* TRIE_READ_CHAR returns the current character, or its fold if /i
2538              * is in effect.  Under /i, this character can match itself, or
2539              * anything that folds to it.  If not under /i, it can match just
2540              * itself.  Most folds are 1-1, for example k, K, and KELVIN SIGN
2541              * all fold to k, and all are single characters.   But some folds
2542              * expand to more than one character, so for example LATIN SMALL
2543              * LIGATURE FFI folds to the three character sequence 'ffi'.  If
2544              * the string beginning at 'uc' is 'ffi', it could be matched by
2545              * three characters, or just by the one ligature character. (It
2546              * could also be matched by two characters: LATIN SMALL LIGATURE FF
2547              * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI).
2548              * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also
2549              * match.)  The trie needs to know the minimum and maximum number
2550              * of characters that could match so that it can use size alone to
2551              * quickly reject many match attempts.  The max is simple: it is
2552              * the number of folded characters in this branch (since a fold is
2553              * never shorter than what folds to it. */
2554
2555             maxchars++;
2556
2557             /* And the min is equal to the max if not under /i (indicated by
2558              * 'folder' being NULL), or there are no multi-character folds.  If
2559              * there is a multi-character fold, the min is incremented just
2560              * once, for the character that folds to the sequence.  Each
2561              * character in the sequence needs to be added to the list below of
2562              * characters in the trie, but we count only the first towards the
2563              * min number of characters needed.  This is done through the
2564              * variable 'foldlen', which is returned by the macros that look
2565              * for these sequences as the number of bytes the sequence
2566              * occupies.  Each time through the loop, we decrement 'foldlen' by
2567              * how many bytes the current char occupies.  Only when it reaches
2568              * 0 do we increment 'minchars' or look for another multi-character
2569              * sequence. */
2570             if (folder == NULL) {
2571                 minchars++;
2572             }
2573             else if (foldlen > 0) {
2574                 foldlen -= (UTF) ? UTF8SKIP(uc) : 1;
2575             }
2576             else {
2577                 minchars++;
2578
2579                 /* See if *uc is the beginning of a multi-character fold.  If
2580                  * so, we decrement the length remaining to look at, to account
2581                  * for the current character this iteration.  (We can use 'uc'
2582                  * instead of the fold returned by TRIE_READ_CHAR because for
2583                  * non-UTF, the latin1_safe macro is smart enough to account
2584                  * for all the unfolded characters, and because for UTF, the
2585                  * string will already have been folded earlier in the
2586                  * compilation process */
2587                 if (UTF) {
2588                     if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) {
2589                         foldlen -= UTF8SKIP(uc);
2590                     }
2591                 }
2592                 else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) {
2593                     foldlen--;
2594                 }
2595             }
2596
2597             /* The current character (and any potential folds) should be added
2598              * to the possible matching characters for this position in this
2599              * branch */
2600             if ( uvc < 256 ) {
2601                 if ( folder ) {
2602                     U8 folded= folder[ (U8) uvc ];
2603                     if ( !trie->charmap[ folded ] ) {
2604                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
2605                         TRIE_STORE_REVCHAR( folded );
2606                     }
2607                 }
2608                 if ( !trie->charmap[ uvc ] ) {
2609                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
2610                     TRIE_STORE_REVCHAR( uvc );
2611                 }
2612                 if ( set_bit ) {
2613                     /* store the codepoint in the bitmap, and its folded
2614                      * equivalent. */
2615                     TRIE_BITMAP_SET(trie, uvc);
2616
2617                     /* store the folded codepoint */
2618                     if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
2619
2620                     if ( !UTF ) {
2621                         /* store first byte of utf8 representation of
2622                            variant codepoints */
2623                         if (! UVCHR_IS_INVARIANT(uvc)) {
2624                             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
2625                         }
2626                     }
2627                     set_bit = 0; /* We've done our bit :-) */
2628                 }
2629             } else {
2630
2631                 /* XXX We could come up with the list of code points that fold
2632                  * to this using PL_utf8_foldclosures, except not for
2633                  * multi-char folds, as there may be multiple combinations
2634                  * there that could work, which needs to wait until runtime to
2635                  * resolve (The comment about LIGATURE FFI above is such an
2636                  * example */
2637
2638                 SV** svpp;
2639                 if ( !widecharmap )
2640                     widecharmap = newHV();
2641
2642                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
2643
2644                 if ( !svpp )
2645                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
2646
2647                 if ( !SvTRUE( *svpp ) ) {
2648                     sv_setiv( *svpp, ++trie->uniquecharcount );
2649                     TRIE_STORE_REVCHAR(uvc);
2650                 }
2651             }
2652         } /* end loop through characters in this branch of the trie */
2653
2654         /* We take the min and max for this branch and combine to find the min
2655          * and max for all branches processed so far */
2656         if( cur == first ) {
2657             trie->minlen = minchars;
2658             trie->maxlen = maxchars;
2659         } else if (minchars < trie->minlen) {
2660             trie->minlen = minchars;
2661         } else if (maxchars > trie->maxlen) {
2662             trie->maxlen = maxchars;
2663         }
2664     } /* end first pass */
2665     DEBUG_TRIE_COMPILE_r(
2666         PerlIO_printf( Perl_debug_log,
2667                 "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
2668                 (int)depth * 2 + 2,"",
2669                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
2670                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
2671                 (int)trie->minlen, (int)trie->maxlen )
2672     );
2673
2674     /*
2675         We now know what we are dealing with in terms of unique chars and
2676         string sizes so we can calculate how much memory a naive
2677         representation using a flat table  will take. If it's over a reasonable
2678         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
2679         conservative but potentially much slower representation using an array
2680         of lists.
2681
2682         At the end we convert both representations into the same compressed
2683         form that will be used in regexec.c for matching with. The latter
2684         is a form that cannot be used to construct with but has memory
2685         properties similar to the list form and access properties similar
2686         to the table form making it both suitable for fast searches and
2687         small enough that its feasable to store for the duration of a program.
2688
2689         See the comment in the code where the compressed table is produced
2690         inplace from the flat tabe representation for an explanation of how
2691         the compression works.
2692
2693     */
2694
2695
2696     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
2697     prev_states[1] = 0;
2698
2699     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1)
2700                                                     > SvIV(re_trie_maxbuff) )
2701     {
2702         /*
2703             Second Pass -- Array Of Lists Representation
2704
2705             Each state will be represented by a list of charid:state records
2706             (reg_trie_trans_le) the first such element holds the CUR and LEN
2707             points of the allocated array. (See defines above).
2708
2709             We build the initial structure using the lists, and then convert
2710             it into the compressed table form which allows faster lookups
2711             (but cant be modified once converted).
2712         */
2713
2714         STRLEN transcount = 1;
2715
2716         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2717             "%*sCompiling trie using list compiler\n",
2718             (int)depth * 2 + 2, ""));
2719
2720         trie->states = (reg_trie_state *)
2721             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2722                                   sizeof(reg_trie_state) );
2723         TRIE_LIST_NEW(1);
2724         next_alloc = 2;
2725
2726         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2727
2728             regnode *noper   = NEXTOPER( cur );
2729             U8 *uc           = (U8*)STRING( noper );
2730             const U8 *e      = uc + STR_LEN( noper );
2731             U32 state        = 1;         /* required init */
2732             U16 charid       = 0;         /* sanity init */
2733             U32 wordlen      = 0;         /* required init */
2734
2735             if (OP(noper) == NOTHING) {
2736                 regnode *noper_next= regnext(noper);
2737                 if (noper_next != tail && OP(noper_next) == flags) {
2738                     noper = noper_next;
2739                     uc= (U8*)STRING(noper);
2740                     e= uc + STR_LEN(noper);
2741                 }
2742             }
2743
2744             if (OP(noper) != NOTHING) {
2745                 for ( ; uc < e ; uc += len ) {
2746
2747                     TRIE_READ_CHAR;
2748
2749                     if ( uvc < 256 ) {
2750                         charid = trie->charmap[ uvc ];
2751                     } else {
2752                         SV** const svpp = hv_fetch( widecharmap,
2753                                                     (char*)&uvc,
2754                                                     sizeof( UV ),
2755                                                     0);
2756                         if ( !svpp ) {
2757                             charid = 0;
2758                         } else {
2759                             charid=(U16)SvIV( *svpp );
2760                         }
2761                     }
2762                     /* charid is now 0 if we dont know the char read, or
2763                      * nonzero if we do */
2764                     if ( charid ) {
2765
2766                         U16 check;
2767                         U32 newstate = 0;
2768
2769                         charid--;
2770                         if ( !trie->states[ state ].trans.list ) {
2771                             TRIE_LIST_NEW( state );
2772                         }
2773                         for ( check = 1;
2774                               check <= TRIE_LIST_USED( state );
2775                               check++ )
2776                         {
2777                             if ( TRIE_LIST_ITEM( state, check ).forid
2778                                                                     == charid )
2779                             {
2780                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
2781                                 break;
2782                             }
2783                         }
2784                         if ( ! newstate ) {
2785                             newstate = next_alloc++;
2786                             prev_states[newstate] = state;
2787                             TRIE_LIST_PUSH( state, charid, newstate );
2788                             transcount++;
2789                         }
2790                         state = newstate;
2791                     } else {
2792                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2793                     }
2794                 }
2795             }
2796             TRIE_HANDLE_WORD(state);
2797
2798         } /* end second pass */
2799
2800         /* next alloc is the NEXT state to be allocated */
2801         trie->statecount = next_alloc;
2802         trie->states = (reg_trie_state *)
2803             PerlMemShared_realloc( trie->states,
2804                                    next_alloc
2805                                    * sizeof(reg_trie_state) );
2806
2807         /* and now dump it out before we compress it */
2808         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
2809                                                          revcharmap, next_alloc,
2810                                                          depth+1)
2811         );
2812
2813         trie->trans = (reg_trie_trans *)
2814             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
2815         {
2816             U32 state;
2817             U32 tp = 0;
2818             U32 zp = 0;
2819
2820
2821             for( state=1 ; state < next_alloc ; state ++ ) {
2822                 U32 base=0;
2823
2824                 /*
2825                 DEBUG_TRIE_COMPILE_MORE_r(
2826                     PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
2827                 );
2828                 */
2829
2830                 if (trie->states[state].trans.list) {
2831                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
2832                     U16 maxid=minid;
2833                     U16 idx;
2834
2835                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2836                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
2837                         if ( forid < minid ) {
2838                             minid=forid;
2839                         } else if ( forid > maxid ) {
2840                             maxid=forid;
2841                         }
2842                     }
2843                     if ( transcount < tp + maxid - minid + 1) {
2844                         transcount *= 2;
2845                         trie->trans = (reg_trie_trans *)
2846                             PerlMemShared_realloc( trie->trans,
2847                                                      transcount
2848                                                      * sizeof(reg_trie_trans) );
2849                         Zero( trie->trans + (transcount / 2),
2850                               transcount / 2,
2851                               reg_trie_trans );
2852                     }
2853                     base = trie->uniquecharcount + tp - minid;
2854                     if ( maxid == minid ) {
2855                         U32 set = 0;
2856                         for ( ; zp < tp ; zp++ ) {
2857                             if ( ! trie->trans[ zp ].next ) {
2858                                 base = trie->uniquecharcount + zp - minid;
2859                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state,
2860                                                                    1).newstate;
2861                                 trie->trans[ zp ].check = state;
2862                                 set = 1;
2863                                 break;
2864                             }
2865                         }
2866                         if ( !set ) {
2867                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state,
2868                                                                    1).newstate;
2869                             trie->trans[ tp ].check = state;
2870                             tp++;
2871                             zp = tp;
2872                         }
2873                     } else {
2874                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
2875                             const U32 tid = base
2876                                            - trie->uniquecharcount
2877                                            + TRIE_LIST_ITEM( state, idx ).forid;
2878                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state,
2879                                                                 idx ).newstate;
2880                             trie->trans[ tid ].check = state;
2881                         }
2882                         tp += ( maxid - minid + 1 );
2883                     }
2884                     Safefree(trie->states[ state ].trans.list);
2885                 }
2886                 /*
2887                 DEBUG_TRIE_COMPILE_MORE_r(
2888                     PerlIO_printf( Perl_debug_log, " base: %d\n",base);
2889                 );
2890                 */
2891                 trie->states[ state ].trans.base=base;
2892             }
2893             trie->lasttrans = tp + 1;
2894         }
2895     } else {
2896         /*
2897            Second Pass -- Flat Table Representation.
2898
2899            we dont use the 0 slot of either trans[] or states[] so we add 1 to
2900            each.  We know that we will need Charcount+1 trans at most to store
2901            the data (one row per char at worst case) So we preallocate both
2902            structures assuming worst case.
2903
2904            We then construct the trie using only the .next slots of the entry
2905            structs.
2906
2907            We use the .check field of the first entry of the node temporarily
2908            to make compression both faster and easier by keeping track of how
2909            many non zero fields are in the node.
2910
2911            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
2912            transition.
2913
2914            There are two terms at use here: state as a TRIE_NODEIDX() which is
2915            a number representing the first entry of the node, and state as a
2916            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1)
2917            and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3)
2918            if there are 2 entrys per node. eg:
2919
2920              A B       A B
2921           1. 2 4    1. 3 7
2922           2. 0 3    3. 0 5
2923           3. 0 0    5. 0 0
2924           4. 0 0    7. 0 0
2925
2926            The table is internally in the right hand, idx form. However as we
2927            also have to deal with the states array which is indexed by nodenum
2928            we have to use TRIE_NODENUM() to convert.
2929
2930         */
2931         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
2932             "%*sCompiling trie using table compiler\n",
2933             (int)depth * 2 + 2, ""));
2934
2935         trie->trans = (reg_trie_trans *)
2936             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2937                                   * trie->uniquecharcount + 1,
2938                                   sizeof(reg_trie_trans) );
2939         trie->states = (reg_trie_state *)
2940             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2941                                   sizeof(reg_trie_state) );
2942         next_alloc = trie->uniquecharcount + 1;
2943
2944
2945         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2946
2947             regnode *noper   = NEXTOPER( cur );
2948             const U8 *uc     = (U8*)STRING( noper );
2949             const U8 *e      = uc + STR_LEN( noper );
2950
2951             U32 state        = 1;         /* required init */
2952
2953             U16 charid       = 0;         /* sanity init */
2954             U32 accept_state = 0;         /* sanity init */
2955
2956             U32 wordlen      = 0;         /* required init */
2957
2958             if (OP(noper) == NOTHING) {
2959                 regnode *noper_next= regnext(noper);
2960                 if (noper_next != tail && OP(noper_next) == flags) {
2961                     noper = noper_next;
2962                     uc= (U8*)STRING(noper);
2963                     e= uc + STR_LEN(noper);
2964                 }
2965             }
2966
2967             if ( OP(noper) != NOTHING ) {
2968                 for ( ; uc < e ; uc += len ) {
2969
2970                     TRIE_READ_CHAR;
2971
2972                     if ( uvc < 256 ) {
2973                         charid = trie->charmap[ uvc ];
2974                     } else {
2975                         SV* const * const svpp = hv_fetch( widecharmap,
2976                                                            (char*)&uvc,
2977                                                            sizeof( UV ),
2978                                                            0);
2979                         charid = svpp ? (U16)SvIV(*svpp) : 0;
2980                     }
2981                     if ( charid ) {
2982                         charid--;
2983                         if ( !trie->trans[ state + charid ].next ) {
2984                             trie->trans[ state + charid ].next = next_alloc;
2985                             trie->trans[ state ].check++;
2986                             prev_states[TRIE_NODENUM(next_alloc)]
2987                                     = TRIE_NODENUM(state);
2988                             next_alloc += trie->uniquecharcount;
2989                         }
2990                         state = trie->trans[ state + charid ].next;
2991                     } else {
2992                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2993                     }
2994                     /* charid is now 0 if we dont know the char read, or
2995                      * nonzero if we do */
2996                 }
2997             }
2998             accept_state = TRIE_NODENUM( state );
2999             TRIE_HANDLE_WORD(accept_state);
3000
3001         } /* end second pass */
3002
3003         /* and now dump it out before we compress it */
3004         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
3005                                                           revcharmap,
3006                                                           next_alloc, depth+1));
3007
3008         {
3009         /*
3010            * Inplace compress the table.*
3011
3012            For sparse data sets the table constructed by the trie algorithm will
3013            be mostly 0/FAIL transitions or to put it another way mostly empty.
3014            (Note that leaf nodes will not contain any transitions.)
3015
3016            This algorithm compresses the tables by eliminating most such
3017            transitions, at the cost of a modest bit of extra work during lookup:
3018
3019            - Each states[] entry contains a .base field which indicates the
3020            index in the state[] array wheres its transition data is stored.
3021
3022            - If .base is 0 there are no valid transitions from that node.
3023
3024            - If .base is nonzero then charid is added to it to find an entry in
3025            the trans array.
3026
3027            -If trans[states[state].base+charid].check!=state then the
3028            transition is taken to be a 0/Fail transition. Thus if there are fail
3029            transitions at the front of the node then the .base offset will point
3030            somewhere inside the previous nodes data (or maybe even into a node
3031            even earlier), but the .check field determines if the transition is
3032            valid.
3033
3034            XXX - wrong maybe?
3035            The following process inplace converts the table to the compressed
3036            table: We first do not compress the root node 1,and mark all its
3037            .check pointers as 1 and set its .base pointer as 1 as well. This
3038            allows us to do a DFA construction from the compressed table later,
3039            and ensures that any .base pointers we calculate later are greater
3040            than 0.
3041
3042            - We set 'pos' to indicate the first entry of the second node.
3043
3044            - We then iterate over the columns of the node, finding the first and
3045            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
3046            and set the .check pointers accordingly, and advance pos
3047            appropriately and repreat for the next node. Note that when we copy
3048            the next pointers we have to convert them from the original
3049            NODEIDX form to NODENUM form as the former is not valid post
3050            compression.
3051
3052            - If a node has no transitions used we mark its base as 0 and do not
3053            advance the pos pointer.
3054
3055            - If a node only has one transition we use a second pointer into the
3056            structure to fill in allocated fail transitions from other states.
3057            This pointer is independent of the main pointer and scans forward
3058            looking for null transitions that are allocated to a state. When it
3059            finds one it writes the single transition into the "hole".  If the
3060            pointer doesnt find one the single transition is appended as normal.
3061
3062            - Once compressed we can Renew/realloc the structures to release the
3063            excess space.
3064
3065            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
3066            specifically Fig 3.47 and the associated pseudocode.
3067
3068            demq
3069         */
3070         const U32 laststate = TRIE_NODENUM( next_alloc );
3071         U32 state, charid;
3072         U32 pos = 0, zp=0;
3073         trie->statecount = laststate;
3074
3075         for ( state = 1 ; state < laststate ; state++ ) {
3076             U8 flag = 0;
3077             const U32 stateidx = TRIE_NODEIDX( state );
3078             const U32 o_used = trie->trans[ stateidx ].check;
3079             U32 used = trie->trans[ stateidx ].check;
3080             trie->trans[ stateidx ].check = 0;
3081
3082             for ( charid = 0;
3083                   used && charid < trie->uniquecharcount;
3084                   charid++ )
3085             {
3086                 if ( flag || trie->trans[ stateidx + charid ].next ) {
3087                     if ( trie->trans[ stateidx + charid ].next ) {
3088                         if (o_used == 1) {
3089                             for ( ; zp < pos ; zp++ ) {
3090                                 if ( ! trie->trans[ zp ].next ) {
3091                                     break;
3092                                 }
3093                             }
3094                             trie->states[ state ].trans.base
3095                                                     = zp
3096                                                       + trie->uniquecharcount
3097                                                       - charid ;
3098                             trie->trans[ zp ].next
3099                                 = SAFE_TRIE_NODENUM( trie->trans[ stateidx
3100                                                              + charid ].next );
3101                             trie->trans[ zp ].check = state;
3102                             if ( ++zp > pos ) pos = zp;
3103                             break;
3104                         }
3105                         used--;
3106                     }
3107                     if ( !flag ) {
3108                         flag = 1;
3109                         trie->states[ state ].trans.base
3110                                        = pos + trie->uniquecharcount - charid ;
3111                     }
3112                     trie->trans[ pos ].next
3113                         = SAFE_TRIE_NODENUM(
3114                                        trie->trans[ stateidx + charid ].next );
3115                     trie->trans[ pos ].check = state;
3116                     pos++;
3117                 }
3118             }
3119         }
3120         trie->lasttrans = pos + 1;
3121         trie->states = (reg_trie_state *)
3122             PerlMemShared_realloc( trie->states, laststate
3123                                    * sizeof(reg_trie_state) );
3124         DEBUG_TRIE_COMPILE_MORE_r(
3125             PerlIO_printf( Perl_debug_log,
3126                 "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
3127                 (int)depth * 2 + 2,"",
3128                 (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount
3129                        + 1 ),
3130                 (IV)next_alloc,
3131                 (IV)pos,
3132                 ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
3133             );
3134
3135         } /* end table compress */
3136     }
3137     DEBUG_TRIE_COMPILE_MORE_r(
3138             PerlIO_printf(Perl_debug_log,
3139                 "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
3140                 (int)depth * 2 + 2, "",
3141                 (UV)trie->statecount,
3142                 (UV)trie->lasttrans)
3143     );
3144     /* resize the trans array to remove unused space */
3145     trie->trans = (reg_trie_trans *)
3146         PerlMemShared_realloc( trie->trans, trie->lasttrans
3147                                * sizeof(reg_trie_trans) );
3148
3149     {   /* Modify the program and insert the new TRIE node */
3150         U8 nodetype =(U8)(flags & 0xFF);
3151         char *str=NULL;
3152
3153 #ifdef DEBUGGING
3154         regnode *optimize = NULL;
3155 #ifdef RE_TRACK_PATTERN_OFFSETS
3156
3157         U32 mjd_offset = 0;
3158         U32 mjd_nodelen = 0;
3159 #endif /* RE_TRACK_PATTERN_OFFSETS */
3160 #endif /* DEBUGGING */
3161         /*
3162            This means we convert either the first branch or the first Exact,
3163            depending on whether the thing following (in 'last') is a branch
3164            or not and whther first is the startbranch (ie is it a sub part of
3165            the alternation or is it the whole thing.)
3166            Assuming its a sub part we convert the EXACT otherwise we convert
3167            the whole branch sequence, including the first.
3168          */
3169         /* Find the node we are going to overwrite */
3170         if ( first != startbranch || OP( last ) == BRANCH ) {
3171             /* branch sub-chain */
3172             NEXT_OFF( first ) = (U16)(last - first);
3173 #ifdef RE_TRACK_PATTERN_OFFSETS
3174             DEBUG_r({
3175                 mjd_offset= Node_Offset((convert));
3176                 mjd_nodelen= Node_Length((convert));
3177             });
3178 #endif
3179             /* whole branch chain */
3180         }
3181 #ifdef RE_TRACK_PATTERN_OFFSETS
3182         else {
3183             DEBUG_r({
3184                 const  regnode *nop = NEXTOPER( convert );
3185                 mjd_offset= Node_Offset((nop));
3186                 mjd_nodelen= Node_Length((nop));
3187             });
3188         }
3189         DEBUG_OPTIMISE_r(
3190             PerlIO_printf(Perl_debug_log,
3191                 "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
3192                 (int)depth * 2 + 2, "",
3193                 (UV)mjd_offset, (UV)mjd_nodelen)
3194         );
3195 #endif
3196         /* But first we check to see if there is a common prefix we can
3197            split out as an EXACT and put in front of the TRIE node.  */
3198         trie->startstate= 1;
3199         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
3200             U32 state;
3201             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
3202                 U32 ofs = 0;
3203                 I32 idx = -1;
3204                 U32 count = 0;
3205                 const U32 base = trie->states[ state ].trans.base;
3206
3207                 if ( trie->states[state].wordnum )
3208                         count = 1;
3209
3210                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
3211                     if ( ( base + ofs >= trie->uniquecharcount ) &&
3212                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
3213                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
3214                     {
3215                         if ( ++count > 1 ) {
3216                             SV **tmp = av_fetch( revcharmap, ofs, 0);
3217                             const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
3218                             if ( state == 1 ) break;
3219                             if ( count == 2 ) {
3220                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
3221                                 DEBUG_OPTIMISE_r(
3222                                     PerlIO_printf(Perl_debug_log,
3223                                         "%*sNew Start State=%"UVuf" Class: [",
3224                                         (int)depth * 2 + 2, "",
3225                                         (UV)state));
3226                                 if (idx >= 0) {
3227                                     SV ** const tmp = av_fetch( revcharmap, idx, 0);
3228                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
3229
3230                                     TRIE_BITMAP_SET(trie,*ch);
3231                                     if ( folder )
3232                                         TRIE_BITMAP_SET(trie, folder[ *ch ]);
3233                                     DEBUG_OPTIMISE_r(
3234                                         PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
3235                                     );
3236                                 }
3237                             }
3238                             TRIE_BITMAP_SET(trie,*ch);
3239                             if ( folder )
3240                                 TRIE_BITMAP_SET(trie,folder[ *ch ]);
3241                             DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
3242                         }
3243                         idx = ofs;
3244                     }
3245                 }
3246                 if ( count == 1 ) {
3247                     SV **tmp = av_fetch( revcharmap, idx, 0);
3248                     STRLEN len;
3249                     char *ch = SvPV( *tmp, len );
3250                     DEBUG_OPTIMISE_r({
3251                         SV *sv=sv_newmortal();
3252                         PerlIO_printf( Perl_debug_log,
3253                             "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
3254                             (int)depth * 2 + 2, "",
3255                             (UV)state, (UV)idx,
3256                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
3257                                 PL_colors[0], PL_colors[1],
3258                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
3259                                 PERL_PV_ESCAPE_FIRSTCHAR
3260                             )
3261                         );
3262                     });
3263                     if ( state==1 ) {
3264                         OP( convert ) = nodetype;
3265                         str=STRING(convert);
3266                         STR_LEN(convert)=0;
3267                     }
3268                     STR_LEN(convert) += len;
3269                     while (len--)
3270                         *str++ = *ch++;
3271                 } else {
3272 #ifdef DEBUGGING
3273                     if (state>1)
3274                         DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
3275 #endif
3276                     break;
3277                 }
3278             }
3279             trie->prefixlen = (state-1);
3280             if (str) {
3281                 regnode *n = convert+NODE_SZ_STR(convert);
3282                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
3283                 trie->startstate = state;
3284                 trie->minlen -= (state - 1);
3285                 trie->maxlen -= (state - 1);
3286 #ifdef DEBUGGING
3287                /* At least the UNICOS C compiler choked on this
3288                 * being argument to DEBUG_r(), so let's just have
3289                 * it right here. */
3290                if (
3291 #ifdef PERL_EXT_RE_BUILD
3292                    1
3293 #else
3294                    DEBUG_r_TEST
3295 #endif
3296                    ) {
3297                    regnode *fix = convert;
3298                    U32 word = trie->wordcount;
3299                    mjd_nodelen++;
3300                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
3301                    while( ++fix < n ) {
3302                        Set_Node_Offset_Length(fix, 0, 0);
3303                    }
3304                    while (word--) {
3305                        SV ** const tmp = av_fetch( trie_words, word, 0 );
3306                        if (tmp) {
3307                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
3308                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
3309                            else
3310                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
3311                        }
3312                    }
3313                }
3314 #endif
3315                 if (trie->maxlen) {
3316                     convert = n;
3317                 } else {
3318                     NEXT_OFF(convert) = (U16)(tail - convert);
3319                     DEBUG_r(optimize= n);
3320                 }
3321             }
3322         }
3323         if (!jumper)
3324             jumper = last;
3325         if ( trie->maxlen ) {
3326             NEXT_OFF( convert ) = (U16)(tail - convert);
3327             ARG_SET( convert, data_slot );
3328             /* Store the offset to the first unabsorbed branch in
3329                jump[0], which is otherwise unused by the jump logic.
3330                We use this when dumping a trie and during optimisation. */
3331             if (trie->jump)
3332                 trie->jump[0] = (U16)(nextbranch - convert);
3333
3334             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
3335              *   and there is a bitmap
3336              *   and the first "jump target" node we found leaves enough room
3337              * then convert the TRIE node into a TRIEC node, with the bitmap
3338              * embedded inline in the opcode - this is hypothetically faster.
3339              */
3340             if ( !trie->states[trie->startstate].wordnum
3341                  && trie->bitmap
3342                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
3343             {
3344                 OP( convert ) = TRIEC;
3345                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
3346                 PerlMemShared_free(trie->bitmap);
3347                 trie->bitmap= NULL;
3348             } else
3349                 OP( convert ) = TRIE;
3350
3351             /* store the type in the flags */
3352             convert->flags = nodetype;
3353             DEBUG_r({
3354             optimize = convert
3355                       + NODE_STEP_REGNODE
3356                       + regarglen[ OP( convert ) ];
3357             });
3358             /* XXX We really should free up the resource in trie now,
3359                    as we won't use them - (which resources?) dmq */
3360         }
3361         /* needed for dumping*/
3362         DEBUG_r(if (optimize) {
3363             regnode *opt = convert;
3364
3365             while ( ++opt < optimize) {
3366                 Set_Node_Offset_Length(opt,0,0);
3367             }
3368             /*
3369                 Try to clean up some of the debris left after the
3370                 optimisation.
3371              */
3372             while( optimize < jumper ) {
3373                 mjd_nodelen += Node_Length((optimize));
3374                 OP( optimize ) = OPTIMIZED;
3375                 Set_Node_Offset_Length(optimize,0,0);
3376                 optimize++;
3377             }
3378             Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
3379         });
3380     } /* end node insert */
3381
3382     /*  Finish populating the prev field of the wordinfo array.  Walk back
3383      *  from each accept state until we find another accept state, and if
3384      *  so, point the first word's .prev field at the second word. If the
3385      *  second already has a .prev field set, stop now. This will be the
3386      *  case either if we've already processed that word's accept state,
3387      *  or that state had multiple words, and the overspill words were
3388      *  already linked up earlier.
3389      */
3390     {
3391         U16 word;
3392         U32 state;
3393         U16 prev;
3394
3395         for (word=1; word <= trie->wordcount; word++) {
3396             prev = 0;
3397             if (trie->wordinfo[word].prev)
3398                 continue;
3399             state = trie->wordinfo[word].accept;
3400             while (state) {
3401                 state = prev_states[state];
3402                 if (!state)
3403                     break;
3404                 prev = trie->states[state].wordnum;
3405                 if (prev)
3406                     break;
3407             }
3408             trie->wordinfo[word].prev = prev;
3409         }
3410         Safefree(prev_states);
3411     }
3412
3413
3414     /* and now dump out the compressed format */
3415     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
3416
3417     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
3418 #ifdef DEBUGGING
3419     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
3420     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
3421 #else
3422     SvREFCNT_dec_NN(revcharmap);
3423 #endif
3424     return trie->jump
3425            ? MADE_JUMP_TRIE
3426            : trie->startstate>1
3427              ? MADE_EXACT_TRIE
3428              : MADE_TRIE;
3429 }
3430
3431 STATIC regnode *
3432 S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth)
3433 {
3434 /* The Trie is constructed and compressed now so we can build a fail array if
3435  * it's needed
3436
3437    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and
3438    3.32 in the
3439    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi,
3440    Ullman 1985/88
3441    ISBN 0-201-10088-6
3442
3443    We find the fail state for each state in the trie, this state is the longest
3444    proper suffix of the current state's 'word' that is also a proper prefix of
3445    another word in our trie. State 1 represents the word '' and is thus the
3446    default fail state. This allows the DFA not to have to restart after its
3447    tried and failed a word at a given point, it simply continues as though it
3448    had been matching the other word in the first place.
3449    Consider
3450       'abcdgu'=~/abcdefg|cdgu/
3451    When we get to 'd' we are still matching the first word, we would encounter
3452    'g' which would fail, which would bring us to the state representing 'd' in
3453    the second word where we would try 'g' and succeed, proceeding to match
3454    'cdgu'.
3455  */
3456  /* add a fail transition */
3457     const U32 trie_offset = ARG(source);
3458     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
3459     U32 *q;
3460     const U32 ucharcount = trie->uniquecharcount;
3461     const U32 numstates = trie->statecount;
3462     const U32 ubound = trie->lasttrans + ucharcount;
3463     U32 q_read = 0;
3464     U32 q_write = 0;
3465     U32 charid;
3466     U32 base = trie->states[ 1 ].trans.base;
3467     U32 *fail;
3468     reg_ac_data *aho;
3469     const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T"));
3470     regnode *stclass;
3471     GET_RE_DEBUG_FLAGS_DECL;
3472
3473     PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE;
3474     PERL_UNUSED_CONTEXT;
3475 #ifndef DEBUGGING
3476     PERL_UNUSED_ARG(depth);
3477 #endif
3478
3479     if ( OP(source) == TRIE ) {
3480         struct regnode_1 *op = (struct regnode_1 *)
3481             PerlMemShared_calloc(1, sizeof(struct regnode_1));
3482         StructCopy(source,op,struct regnode_1);
3483         stclass = (regnode *)op;
3484     } else {
3485         struct regnode_charclass *op = (struct regnode_charclass *)
3486             PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
3487         StructCopy(source,op,struct regnode_charclass);
3488         stclass = (regnode *)op;
3489     }
3490     OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */
3491
3492     ARG_SET( stclass, data_slot );
3493     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
3494     RExC_rxi->data->data[ data_slot ] = (void*)aho;
3495     aho->trie=trie_offset;
3496     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
3497     Copy( trie->states, aho->states, numstates, reg_trie_state );
3498     Newxz( q, numstates, U32);
3499     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
3500     aho->refcount = 1;
3501     fail = aho->fail;
3502     /* initialize fail[0..1] to be 1 so that we always have
3503        a valid final fail state */
3504     fail[ 0 ] = fail[ 1 ] = 1;
3505
3506     for ( charid = 0; charid < ucharcount ; charid++ ) {
3507         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
3508         if ( newstate ) {
3509             q[ q_write ] = newstate;
3510             /* set to point at the root */
3511             fail[ q[ q_write++ ] ]=1;
3512         }
3513     }
3514     while ( q_read < q_write) {
3515         const U32 cur = q[ q_read++ % numstates ];
3516         base = trie->states[ cur ].trans.base;
3517
3518         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
3519             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
3520             if (ch_state) {
3521                 U32 fail_state = cur;
3522                 U32 fail_base;
3523                 do {
3524                     fail_state = fail[ fail_state ];
3525                     fail_base = aho->states[ fail_state ].trans.base;
3526                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
3527
3528                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
3529                 fail[ ch_state ] = fail_state;
3530                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
3531                 {
3532                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
3533                 }
3534                 q[ q_write++ % numstates] = ch_state;
3535             }
3536         }
3537     }
3538     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
3539        when we fail in state 1, this allows us to use the
3540        charclass scan to find a valid start char. This is based on the principle
3541        that theres a good chance the string being searched contains lots of stuff
3542        that cant be a start char.
3543      */
3544     fail[ 0 ] = fail[ 1 ] = 0;
3545     DEBUG_TRIE_COMPILE_r({
3546         PerlIO_printf(Perl_debug_log,
3547                       "%*sStclass Failtable (%"UVuf" states): 0",
3548                       (int)(depth * 2), "", (UV)numstates
3549         );
3550         for( q_read=1; q_read<numstates; q_read++ ) {
3551             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
3552         }
3553         PerlIO_printf(Perl_debug_log, "\n");
3554     });
3555     Safefree(q);
3556     /*RExC_seen |= REG_TRIEDFA_SEEN;*/
3557     return stclass;
3558 }
3559
3560
3561 #define DEBUG_PEEP(str,scan,depth) \
3562     DEBUG_OPTIMISE_r({if (scan){ \
3563        regnode *Next = regnext(scan); \
3564        regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state); \
3565        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)", \
3566            (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv),\
3567            Next ? (REG_NODE_NUM(Next)) : 0 ); \
3568        DEBUG_SHOW_STUDY_FLAGS(flags," [ ","]");\
3569        PerlIO_printf(Perl_debug_log, "\n"); \
3570    }});
3571
3572 /* The below joins as many adjacent EXACTish nodes as possible into a single
3573  * one.  The regop may be changed if the node(s) contain certain sequences that
3574  * require special handling.  The joining is only done if:
3575  * 1) there is room in the current conglomerated node to entirely contain the
3576  *    next one.
3577  * 2) they are the exact same node type
3578  *
3579  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
3580  * these get optimized out
3581  *
3582  * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full
3583  * as possible, even if that means splitting an existing node so that its first
3584  * part is moved to the preceeding node.  This would maximise the efficiency of
3585  * memEQ during matching.  Elsewhere in this file, khw proposes splitting
3586  * EXACTFish nodes into portions that don't change under folding vs those that
3587  * do.  Those portions that don't change may be the only things in the pattern that
3588  * could be used to find fixed and floating strings.
3589  *
3590  * If a node is to match under /i (folded), the number of characters it matches
3591  * can be different than its character length if it contains a multi-character
3592  * fold.  *min_subtract is set to the total delta number of characters of the
3593  * input nodes.
3594  *
3595  * And *unfolded_multi_char is set to indicate whether or not the node contains
3596  * an unfolded multi-char fold.  This happens when whether the fold is valid or
3597  * not won't be known until runtime; namely for EXACTF nodes that contain LATIN
3598  * SMALL LETTER SHARP S, as only if the target string being matched against
3599  * turns out to be UTF-8 is that fold valid; and also for EXACTFL nodes whose
3600  * folding rules depend on the locale in force at runtime.  (Multi-char folds
3601  * whose components are all above the Latin1 range are not run-time locale
3602  * dependent, and have already been folded by the time this function is
3603  * called.)
3604  *
3605  * This is as good a place as any to discuss the design of handling these
3606  * multi-character fold sequences.  It's been wrong in Perl for a very long
3607  * time.  There are three code points in Unicode whose multi-character folds
3608  * were long ago discovered to mess things up.  The previous designs for
3609  * dealing with these involved assigning a special node for them.  This
3610  * approach doesn't always work, as evidenced by this example:
3611  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
3612  * Both sides fold to "sss", but if the pattern is parsed to create a node that
3613  * would match just the \xDF, it won't be able to handle the case where a
3614  * successful match would have to cross the node's boundary.  The new approach
3615  * that hopefully generally solves the problem generates an EXACTFU_SS node
3616  * that is "sss" in this case.
3617  *
3618  * It turns out that there are problems with all multi-character folds, and not
3619  * just these three.  Now the code is general, for all such cases.  The
3620  * approach taken is:
3621  * 1)   This routine examines each EXACTFish node that could contain multi-
3622  *      character folded sequences.  Since a single character can fold into
3623  *      such a sequence, the minimum match length for this node is less than
3624  *      the number of characters in the node.  This routine returns in
3625  *      *min_subtract how many characters to subtract from the the actual
3626  *      length of the string to get a real minimum match length; it is 0 if
3627  *      there are no multi-char foldeds.  This delta is used by the caller to
3628  *      adjust the min length of the match, and the delta between min and max,
3629  *      so that the optimizer doesn't reject these possibilities based on size
3630  *      constraints.
3631  * 2)   For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
3632  *      is used for an EXACTFU node that contains at least one "ss" sequence in
3633  *      it.  For non-UTF-8 patterns and strings, this is the only case where
3634  *      there is a possible fold length change.  That means that a regular
3635  *      EXACTFU node without UTF-8 involvement doesn't have to concern itself
3636  *      with length changes, and so can be processed faster.  regexec.c takes
3637  *      advantage of this.  Generally, an EXACTFish node that is in UTF-8 is
3638  *      pre-folded by regcomp.c (except EXACTFL, some of whose folds aren't
3639  *      known until runtime).  This saves effort in regex matching.  However,
3640  *      the pre-folding isn't done for non-UTF8 patterns because the fold of
3641  *      the MICRO SIGN requires UTF-8, and we don't want to slow things down by
3642  *      forcing the pattern into UTF8 unless necessary.  Also what EXACTF (and,
3643  *      again, EXACTFL) nodes fold to isn't known until runtime.  The fold
3644  *      possibilities for the non-UTF8 patterns are quite simple, except for
3645  *      the sharp s.  All the ones that don't involve a UTF-8 target string are
3646  *      members of a fold-pair, and arrays are set up for all of them so that
3647  *      the other member of the pair can be found quickly.  Code elsewhere in
3648  *      this file makes sure that in EXACTFU nodes, the sharp s gets folded to
3649  *      'ss', even if the pattern isn't UTF-8.  This avoids the issues
3650  *      described in the next item.
3651  * 3)   A problem remains for unfolded multi-char folds. (These occur when the
3652  *      validity of the fold won't be known until runtime, and so must remain
3653  *      unfolded for now.  This happens for the sharp s in EXACTF and EXACTFA
3654  *      nodes when the pattern isn't in UTF-8.  (Note, BTW, that there cannot
3655  *      be an EXACTF node with a UTF-8 pattern.)  They also occur for various
3656  *      folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.)
3657  *      The reason this is a problem is that the optimizer part of regexec.c
3658  *      (probably unwittingly, in Perl_regexec_flags()) makes an assumption
3659  *      that a character in the pattern corresponds to at most a single
3660  *      character in the target string.  (And I do mean character, and not byte
3661  *      here, unlike other parts of the documentation that have never been
3662  *      updated to account for multibyte Unicode.)  sharp s in EXACTF and
3663  *      EXACTFL nodes can match the two character string 'ss'; in EXACTFA nodes
3664  *      it can match "\x{17F}\x{17F}".  These, along with other ones in EXACTFL
3665  *      nodes, violate the assumption, and they are the only instances where it
3666  *      is violated.  I'm reluctant to try to change the assumption, as the
3667  *      code involved is impenetrable to me (khw), so instead the code here
3668  *      punts.  This routine examines EXACTFL nodes, and (when the pattern
3669  *      isn't UTF-8) EXACTF and EXACTFA for such unfolded folds, and returns a
3670  *      boolean indicating whether or not the node contains such a fold.  When
3671  *      it is true, the caller sets a flag that later causes the optimizer in
3672  *      this file to not set values for the floating and fixed string lengths,
3673  *      and thus avoids the optimizer code in regexec.c that makes the invalid
3674  *      assumption.  Thus, there is no optimization based on string lengths for
3675  *      EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern
3676  *      EXACTF and EXACTFA nodes that contain the sharp s.  (The reason the
3677  *      assumption is wrong only in these cases is that all other non-UTF-8
3678  *      folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to
3679  *      their expanded versions.  (Again, we can't prefold sharp s to 'ss' in
3680  *      EXACTF nodes because we don't know at compile time if it actually
3681  *      matches 'ss' or not.  For EXACTF nodes it will match iff the target
3682  *      string is in UTF-8.  This is in contrast to EXACTFU nodes, where it
3683  *      always matches; and EXACTFA where it never does.  In an EXACTFA node in
3684  *      a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the
3685  *      problem; but in a non-UTF8 pattern, folding it to that above-Latin1
3686  *      string would require the pattern to be forced into UTF-8, the overhead
3687  *      of which we want to avoid.  Similarly the unfolded multi-char folds in
3688  *      EXACTFL nodes will match iff the locale at the time of match is a UTF-8
3689  *      locale.)
3690  *
3691  *      Similarly, the code that generates tries doesn't currently handle
3692  *      not-already-folded multi-char folds, and it looks like a pain to change
3693  *      that.  Therefore, trie generation of EXACTFA nodes with the sharp s
3694  *      doesn't work.  Instead, such an EXACTFA is turned into a new regnode,
3695  *      EXACTFA_NO_TRIE, which the trie code knows not to handle.  Most people
3696  *      using /iaa matching will be doing so almost entirely with ASCII
3697  *      strings, so this should rarely be encountered in practice */
3698
3699 #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \
3700     if (PL_regkind[OP(scan)] == EXACT) \
3701         join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags),NULL,depth+1)
3702
3703 STATIC U32
3704 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan,
3705                    UV *min_subtract, bool *unfolded_multi_char,
3706                    U32 flags,regnode *val, U32 depth)
3707 {
3708     /* Merge several consecutive EXACTish nodes into one. */
3709     regnode *n = regnext(scan);
3710     U32 stringok = 1;
3711     regnode *next = scan + NODE_SZ_STR(scan);
3712     U32 merged = 0;
3713     U32 stopnow = 0;
3714 #ifdef DEBUGGING
3715     regnode *stop = scan;
3716     GET_RE_DEBUG_FLAGS_DECL;
3717 #else
3718     PERL_UNUSED_ARG(depth);
3719 #endif
3720
3721     PERL_ARGS_ASSERT_JOIN_EXACT;
3722 #ifndef EXPERIMENTAL_INPLACESCAN
3723     PERL_UNUSED_ARG(flags);
3724     PERL_UNUSED_ARG(val);
3725 #endif
3726     DEBUG_PEEP("join",scan,depth);
3727
3728     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
3729      * EXACT ones that are mergeable to the current one. */
3730     while (n
3731            && (PL_regkind[OP(n)] == NOTHING
3732                || (stringok && OP(n) == OP(scan)))
3733            && NEXT_OFF(n)
3734            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
3735     {
3736
3737         if (OP(n) == TAIL || n > next)
3738             stringok = 0;
3739         if (PL_regkind[OP(n)] == NOTHING) {
3740             DEBUG_PEEP("skip:",n,depth);
3741             NEXT_OFF(scan) += NEXT_OFF(n);
3742             next = n + NODE_STEP_REGNODE;
3743 #ifdef DEBUGGING
3744             if (stringok)
3745                 stop = n;
3746 #endif
3747             n = regnext(n);
3748         }
3749         else if (stringok) {
3750             const unsigned int oldl = STR_LEN(scan);
3751             regnode * const nnext = regnext(n);
3752
3753             /* XXX I (khw) kind of doubt that this works on platforms (should
3754              * Perl ever run on one) where U8_MAX is above 255 because of lots
3755              * of other assumptions */
3756             /* Don't join if the sum can't fit into a single node */
3757             if (oldl + STR_LEN(n) > U8_MAX)
3758                 break;
3759
3760             DEBUG_PEEP("merg",n,depth);
3761             merged++;
3762
3763             NEXT_OFF(scan) += NEXT_OFF(n);
3764             STR_LEN(scan) += STR_LEN(n);
3765             next = n + NODE_SZ_STR(n);
3766             /* Now we can overwrite *n : */
3767             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
3768 #ifdef DEBUGGING
3769             stop = next - 1;
3770 #endif
3771             n = nnext;
3772             if (stopnow) break;
3773         }
3774
3775 #ifdef EXPERIMENTAL_INPLACESCAN
3776         if (flags && !NEXT_OFF(n)) {
3777             DEBUG_PEEP("atch", val, depth);
3778             if (reg_off_by_arg[OP(n)]) {
3779                 ARG_SET(n, val - n);
3780             }
3781             else {
3782                 NEXT_OFF(n) = val - n;
3783             }
3784             stopnow = 1;
3785         }
3786 #endif
3787     }
3788
3789     *min_subtract = 0;
3790     *unfolded_multi_char = FALSE;
3791
3792     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
3793      * can now analyze for sequences of problematic code points.  (Prior to
3794      * this final joining, sequences could have been split over boundaries, and
3795      * hence missed).  The sequences only happen in folding, hence for any
3796      * non-EXACT EXACTish node */
3797     if (OP(scan) != EXACT && OP(scan) != EXACTL) {
3798         U8* s0 = (U8*) STRING(scan);
3799         U8* s = s0;
3800         U8* s_end = s0 + STR_LEN(scan);
3801
3802         int total_count_delta = 0;  /* Total delta number of characters that
3803                                        multi-char folds expand to */
3804
3805         /* One pass is made over the node's string looking for all the
3806          * possibilities.  To avoid some tests in the loop, there are two main
3807          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
3808          * non-UTF-8 */
3809         if (UTF) {
3810             U8* folded = NULL;
3811
3812             if (OP(scan) == EXACTFL) {
3813                 U8 *d;
3814
3815                 /* An EXACTFL node would already have been changed to another
3816                  * node type unless there is at least one character in it that
3817                  * is problematic; likely a character whose fold definition
3818                  * won't be known until runtime, and so has yet to be folded.
3819                  * For all but the UTF-8 locale, folds are 1-1 in length, but
3820                  * to handle the UTF-8 case, we need to create a temporary
3821                  * folded copy using UTF-8 locale rules in order to analyze it.
3822                  * This is because our macros that look to see if a sequence is
3823                  * a multi-char fold assume everything is folded (otherwise the
3824                  * tests in those macros would be too complicated and slow).
3825                  * Note that here, the non-problematic folds will have already
3826                  * been done, so we can just copy such characters.  We actually
3827                  * don't completely fold the EXACTFL string.  We skip the
3828                  * unfolded multi-char folds, as that would just create work
3829                  * below to figure out the size they already are */
3830
3831                 Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8);
3832                 d = folded;
3833                 while (s < s_end) {
3834                     STRLEN s_len = UTF8SKIP(s);
3835                     if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) {
3836                         Copy(s, d, s_len, U8);
3837                         d += s_len;
3838                     }
3839                     else if (is_FOLDS_TO_MULTI_utf8(s)) {
3840                         *unfolded_multi_char = TRUE;
3841                         Copy(s, d, s_len, U8);
3842                         d += s_len;
3843                     }
3844                     else if (isASCII(*s)) {
3845                         *(d++) = toFOLD(*s);
3846                     }
3847                     else {
3848                         STRLEN len;
3849                         _to_utf8_fold_flags(s, d, &len, FOLD_FLAGS_FULL);
3850                         d += len;
3851                     }
3852                     s += s_len;
3853                 }
3854
3855                 /* Point the remainder of the routine to look at our temporary
3856                  * folded copy */
3857                 s = folded;
3858                 s_end = d;
3859             } /* End of creating folded copy of EXACTFL string */
3860
3861             /* Examine the string for a multi-character fold sequence.  UTF-8
3862              * patterns have all characters pre-folded by the time this code is
3863              * executed */
3864             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
3865                                      length sequence we are looking for is 2 */
3866             {
3867                 int count = 0;  /* How many characters in a multi-char fold */
3868                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
3869                 if (! len) {    /* Not a multi-char fold: get next char */
3870                     s += UTF8SKIP(s);
3871                     continue;
3872                 }
3873
3874                 /* Nodes with 'ss' require special handling, except for
3875                  * EXACTFA-ish for which there is no multi-char fold to this */
3876                 if (len == 2 && *s == 's' && *(s+1) == 's'
3877                     && OP(scan) != EXACTFA
3878                     && OP(scan) != EXACTFA_NO_TRIE)
3879                 {
3880                     count = 2;
3881                     if (OP(scan) != EXACTFL) {
3882                         OP(scan) = EXACTFU_SS;
3883                     }
3884                     s += 2;
3885                 }
3886                 else { /* Here is a generic multi-char fold. */
3887                     U8* multi_end  = s + len;
3888
3889                     /* Count how many characters are in it.  In the case of
3890                      * /aa, no folds which contain ASCII code points are
3891                      * allowed, so check for those, and skip if found. */
3892                     if (OP(scan) != EXACTFA && OP(scan) != EXACTFA_NO_TRIE) {
3893                         count = utf8_length(s, multi_end);
3894                         s = multi_end;
3895                     }
3896                     else {
3897                         while (s < multi_end) {
3898                             if (isASCII(*s)) {
3899                                 s++;
3900                                 goto next_iteration;
3901                             }
3902                             else {
3903                                 s += UTF8SKIP(s);
3904                             }
3905                             count++;
3906                         }
3907                     }
3908                 }
3909
3910                 /* The delta is how long the sequence is minus 1 (1 is how long
3911                  * the character that folds to the sequence is) */
3912                 total_count_delta += count - 1;
3913               next_iteration: ;
3914             }
3915
3916             /* We created a temporary folded copy of the string in EXACTFL
3917              * nodes.  Therefore we need to be sure it doesn't go below zero,
3918              * as the real string could be shorter */
3919             if (OP(scan) == EXACTFL) {
3920                 int total_chars = utf8_length((U8*) STRING(scan),
3921                                            (U8*) STRING(scan) + STR_LEN(scan));
3922                 if (total_count_delta > total_chars) {
3923                     total_count_delta = total_chars;
3924                 }
3925             }
3926
3927             *min_subtract += total_count_delta;
3928             Safefree(folded);
3929         }
3930         else if (OP(scan) == EXACTFA) {
3931
3932             /* Non-UTF-8 pattern, EXACTFA node.  There can't be a multi-char
3933              * fold to the ASCII range (and there are no existing ones in the
3934              * upper latin1 range).  But, as outlined in the comments preceding
3935              * this function, we need to flag any occurrences of the sharp s.
3936              * This character forbids trie formation (because of added
3937              * complexity) */
3938 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
3939    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
3940                                       || UNICODE_DOT_DOT_VERSION > 0)
3941             while (s < s_end) {
3942                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
3943                     OP(scan) = EXACTFA_NO_TRIE;
3944                     *unfolded_multi_char = TRUE;
3945                     break;
3946                 }
3947                 s++;
3948             }
3949         }
3950         else {
3951
3952             /* Non-UTF-8 pattern, not EXACTFA node.  Look for the multi-char
3953              * folds that are all Latin1.  As explained in the comments
3954              * preceding this function, we look also for the sharp s in EXACTF
3955              * and EXACTFL nodes; it can be in the final position.  Otherwise
3956              * we can stop looking 1 byte earlier because have to find at least
3957              * two characters for a multi-fold */
3958             const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL)
3959                               ? s_end
3960                               : s_end -1;
3961
3962             while (s < upper) {
3963                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
3964                 if (! len) {    /* Not a multi-char fold. */
3965                     if (*s == LATIN_SMALL_LETTER_SHARP_S
3966                         && (OP(scan) == EXACTF || OP(scan) == EXACTFL))
3967                     {
3968                         *unfolded_multi_char = TRUE;
3969                     }
3970                     s++;
3971                     continue;
3972                 }
3973
3974                 if (len == 2
3975                     && isALPHA_FOLD_EQ(*s, 's')
3976                     && isALPHA_FOLD_EQ(*(s+1), 's'))
3977                 {
3978
3979                     /* EXACTF nodes need to know that the minimum length
3980                      * changed so that a sharp s in the string can match this
3981                      * ss in the pattern, but they remain EXACTF nodes, as they
3982                      * won't match this unless the target string is is UTF-8,
3983                      * which we don't know until runtime.  EXACTFL nodes can't
3984                      * transform into EXACTFU nodes */
3985                     if (OP(scan) != EXACTF && OP(scan) != EXACTFL) {
3986                         OP(scan) = EXACTFU_SS;
3987                     }
3988                 }
3989
3990                 *min_subtract += len - 1;
3991                 s += len;
3992             }
3993 #endif
3994         }
3995     }
3996
3997 #ifdef DEBUGGING
3998     /* Allow dumping but overwriting the collection of skipped
3999      * ops and/or strings with fake optimized ops */
4000     n = scan + NODE_SZ_STR(scan);
4001     while (n <= stop) {
4002         OP(n) = OPTIMIZED;
4003         FLAGS(n) = 0;
4004         NEXT_OFF(n) = 0;
4005         n++;
4006     }
4007 #endif
4008     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
4009     return stopnow;
4010 }
4011
4012 /* REx optimizer.  Converts nodes into quicker variants "in place".
4013    Finds fixed substrings.  */
4014
4015 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
4016    to the position after last scanned or to NULL. */
4017
4018 #define INIT_AND_WITHP \
4019     assert(!and_withp); \
4020     Newx(and_withp,1, regnode_ssc); \
4021     SAVEFREEPV(and_withp)
4022
4023
4024 static void
4025 S_unwind_scan_frames(pTHX_ const void *p)
4026 {
4027     scan_frame *f= (scan_frame *)p;
4028     do {
4029         scan_frame *n= f->next_frame;
4030         Safefree(f);
4031         f= n;
4032     } while (f);
4033 }
4034
4035
4036 STATIC SSize_t
4037 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
4038                         SSize_t *minlenp, SSize_t *deltap,
4039                         regnode *last,
4040                         scan_data_t *data,
4041                         I32 stopparen,
4042                         U32 recursed_depth,
4043                         regnode_ssc *and_withp,
4044                         U32 flags, U32 depth)
4045                         /* scanp: Start here (read-write). */
4046                         /* deltap: Write maxlen-minlen here. */
4047                         /* last: Stop before this one. */
4048                         /* data: string data about the pattern */
4049                         /* stopparen: treat close N as END */
4050                         /* recursed: which subroutines have we recursed into */
4051                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
4052 {
4053     /* There must be at least this number of characters to match */
4054     SSize_t min = 0;
4055     I32 pars = 0, code;
4056     regnode *scan = *scanp, *next;
4057     SSize_t delta = 0;
4058     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
4059     int is_inf_internal = 0;            /* The studied chunk is infinite */
4060     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
4061     scan_data_t data_fake;
4062     SV *re_trie_maxbuff = NULL;
4063     regnode *first_non_open = scan;
4064     SSize_t stopmin = SSize_t_MAX;
4065     scan_frame *frame = NULL;
4066     GET_RE_DEBUG_FLAGS_DECL;
4067
4068     PERL_ARGS_ASSERT_STUDY_CHUNK;
4069
4070
4071     if ( depth == 0 ) {
4072         while (first_non_open && OP(first_non_open) == OPEN)
4073             first_non_open=regnext(first_non_open);
4074     }
4075
4076
4077   fake_study_recurse:
4078     DEBUG_r(
4079         RExC_study_chunk_recursed_count++;
4080     );
4081     DEBUG_OPTIMISE_MORE_r(
4082     {
4083         PerlIO_printf(Perl_debug_log,
4084             "%*sstudy_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p",
4085             (int)(depth*2), "", (long)stopparen,
4086             (unsigned long)RExC_study_chunk_recursed_count,
4087             (unsigned long)depth, (unsigned long)recursed_depth,
4088             scan,
4089             last);
4090         if (recursed_depth) {
4091             U32 i;
4092             U32 j;
4093             for ( j = 0 ; j < recursed_depth ; j++ ) {
4094                 for ( i = 0 ; i < (U32)RExC_npar ; i++ ) {
4095                     if (
4096                         PAREN_TEST(RExC_study_chunk_recursed +
4097                                    ( j * RExC_study_chunk_recursed_bytes), i )
4098                         && (
4099                             !j ||
4100                             !PAREN_TEST(RExC_study_chunk_recursed +
4101                                    (( j - 1 ) * RExC_study_chunk_recursed_bytes), i)
4102                         )
4103                     ) {
4104                         PerlIO_printf(Perl_debug_log," %d",(int)i);
4105                         break;
4106                     }
4107                 }
4108                 if ( j + 1 < recursed_depth ) {
4109                     PerlIO_printf(Perl_debug_log, ",");
4110                 }
4111             }
4112         }
4113         PerlIO_printf(Perl_debug_log,"\n");
4114     }
4115     );
4116     while ( scan && OP(scan) != END && scan < last ){
4117         UV min_subtract = 0;    /* How mmany chars to subtract from the minimum
4118                                    node length to get a real minimum (because
4119                                    the folded version may be shorter) */
4120         bool unfolded_multi_char = FALSE;
4121         /* Peephole optimizer: */
4122         DEBUG_STUDYDATA("Peep:", data, depth);
4123         DEBUG_PEEP("Peep", scan, depth);
4124
4125
4126         /* The reason we do this here we need to deal with things like /(?:f)(?:o)(?:o)/
4127          * which cant be dealt with by the normal EXACT parsing code, as each (?:..) is handled
4128          * by a different invocation of reg() -- Yves
4129          */
4130         JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
4131
4132         /* Follow the next-chain of the current node and optimize
4133            away all the NOTHINGs from it.  */
4134         if (OP(scan) != CURLYX) {
4135             const int max = (reg_off_by_arg[OP(scan)]
4136                        ? I32_MAX
4137                        /* I32 may be smaller than U16 on CRAYs! */
4138                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
4139             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
4140             int noff;
4141             regnode *n = scan;
4142
4143             /* Skip NOTHING and LONGJMP. */
4144             while ((n = regnext(n))
4145                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
4146                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
4147                    && off + noff < max)
4148                 off += noff;
4149             if (reg_off_by_arg[OP(scan)])
4150                 ARG(scan) = off;
4151             else
4152                 NEXT_OFF(scan) = off;
4153         }
4154
4155         /* The principal pseudo-switch.  Cannot be a switch, since we
4156            look into several different things.  */
4157         if ( OP(scan) == DEFINEP ) {
4158             SSize_t minlen = 0;
4159             SSize_t deltanext = 0;
4160             SSize_t fake_last_close = 0;
4161             I32 f = SCF_IN_DEFINE;
4162
4163             StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4164             scan = regnext(scan);
4165             assert( OP(scan) == IFTHEN );
4166             DEBUG_PEEP("expect IFTHEN", scan, depth);
4167
4168             data_fake.last_closep= &fake_last_close;
4169             minlen = *minlenp;
4170             next = regnext(scan);
4171             scan = NEXTOPER(NEXTOPER(scan));
4172             DEBUG_PEEP("scan", scan, depth);
4173             DEBUG_PEEP("next", next, depth);
4174
4175             /* we suppose the run is continuous, last=next...
4176              * NOTE we dont use the return here! */
4177             (void)study_chunk(pRExC_state, &scan, &minlen,
4178                               &deltanext, next, &data_fake, stopparen,
4179                               recursed_depth, NULL, f, depth+1);
4180
4181             scan = next;
4182         } else
4183         if (
4184             OP(scan) == BRANCH  ||
4185             OP(scan) == BRANCHJ ||
4186             OP(scan) == IFTHEN
4187         ) {
4188             next = regnext(scan);
4189             code = OP(scan);
4190
4191             /* The op(next)==code check below is to see if we
4192              * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN"
4193              * IFTHEN is special as it might not appear in pairs.
4194              * Not sure whether BRANCH-BRANCHJ is possible, regardless
4195              * we dont handle it cleanly. */
4196             if (OP(next) == code || code == IFTHEN) {
4197                 /* NOTE - There is similar code to this block below for
4198                  * handling TRIE nodes on a re-study.  If you change stuff here
4199                  * check there too. */
4200                 SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0;
4201                 regnode_ssc accum;
4202                 regnode * const startbranch=scan;
4203
4204                 if (flags & SCF_DO_SUBSTR) {
4205                     /* Cannot merge strings after this. */
4206                     scan_commit(pRExC_state, data, minlenp, is_inf);
4207                 }
4208
4209                 if (flags & SCF_DO_STCLASS)
4210                     ssc_init_zero(pRExC_state, &accum);
4211
4212                 while (OP(scan) == code) {
4213                     SSize_t deltanext, minnext, fake;
4214                     I32 f = 0;
4215                     regnode_ssc this_class;
4216
4217                     DEBUG_PEEP("Branch", scan, depth);
4218
4219                     num++;
4220                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
4221                     if (data) {
4222                         data_fake.whilem_c = data->whilem_c;
4223                         data_fake.last_closep = data->last_closep;
4224                     }
4225                     else
4226                         data_fake.last_closep = &fake;
4227
4228                     data_fake.pos_delta = delta;
4229                     next = regnext(scan);
4230
4231                     scan = NEXTOPER(scan); /* everything */
4232                     if (code != BRANCH)    /* everything but BRANCH */
4233                         scan = NEXTOPER(scan);
4234
4235                     if (flags & SCF_DO_STCLASS) {
4236                         ssc_init(pRExC_state, &this_class);
4237                         data_fake.start_class = &this_class;
4238                         f = SCF_DO_STCLASS_AND;
4239                     }
4240                     if (flags & SCF_WHILEM_VISITED_POS)
4241                         f |= SCF_WHILEM_VISITED_POS;
4242
4243                     /* we suppose the run is continuous, last=next...*/
4244                     minnext = study_chunk(pRExC_state, &scan, minlenp,
4245                                       &deltanext, next, &data_fake, stopparen,
4246                                       recursed_depth, NULL, f,depth+1);
4247
4248                     if (min1 > minnext)
4249                         min1 = minnext;
4250                     if (deltanext == SSize_t_MAX) {
4251                         is_inf = is_inf_internal = 1;
4252                         max1 = SSize_t_MAX;
4253                     } else if (max1 < minnext + deltanext)
4254                         max1 = minnext + deltanext;
4255                     scan = next;
4256                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4257                         pars++;
4258                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4259                         if ( stopmin > minnext)
4260                             stopmin = min + min1;
4261                         flags &= ~SCF_DO_SUBSTR;
4262                         if (data)
4263                             data->flags |= SCF_SEEN_ACCEPT;
4264                     }
4265                     if (data) {
4266                         if (data_fake.flags & SF_HAS_EVAL)
4267                             data->flags |= SF_HAS_EVAL;
4268                         data->whilem_c = data_fake.whilem_c;
4269                     }
4270                     if (flags & SCF_DO_STCLASS)
4271                         ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class);
4272                 }
4273                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
4274                     min1 = 0;
4275                 if (flags & SCF_DO_SUBSTR) {
4276                     data->pos_min += min1;
4277                     if (data->pos_delta >= SSize_t_MAX - (max1 - min1))
4278                         data->pos_delta = SSize_t_MAX;
4279                     else
4280                         data->pos_delta += max1 - min1;
4281                     if (max1 != min1 || is_inf)
4282                         data->longest = &(data->longest_float);
4283                 }
4284                 min += min1;
4285                 if (delta == SSize_t_MAX
4286                  || SSize_t_MAX - delta - (max1 - min1) < 0)
4287                     delta = SSize_t_MAX;
4288                 else
4289                     delta += max1 - min1;
4290                 if (flags & SCF_DO_STCLASS_OR) {
4291                     ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum);
4292                     if (min1) {
4293                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4294                         flags &= ~SCF_DO_STCLASS;
4295                     }
4296                 }
4297                 else if (flags & SCF_DO_STCLASS_AND) {
4298                     if (min1) {
4299                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
4300                         flags &= ~SCF_DO_STCLASS;
4301                     }
4302                     else {
4303                         /* Switch to OR mode: cache the old value of
4304                          * data->start_class */
4305                         INIT_AND_WITHP;
4306                         StructCopy(data->start_class, and_withp, regnode_ssc);
4307                         flags &= ~SCF_DO_STCLASS_AND;
4308                         StructCopy(&accum, data->start_class, regnode_ssc);
4309                         flags |= SCF_DO_STCLASS_OR;
4310                     }
4311                 }
4312
4313                 if (PERL_ENABLE_TRIE_OPTIMISATION &&
4314                         OP( startbranch ) == BRANCH )
4315                 {
4316                 /* demq.
4317
4318                    Assuming this was/is a branch we are dealing with: 'scan'
4319                    now points at the item that follows the branch sequence,
4320                    whatever it is. We now start at the beginning of the
4321                    sequence and look for subsequences of
4322
4323                    BRANCH->EXACT=>x1
4324                    BRANCH->EXACT=>x2
4325                    tail
4326
4327                    which would be constructed from a pattern like
4328                    /A|LIST|OF|WORDS/
4329
4330                    If we can find such a subsequence we need to turn the first
4331                    element into a trie and then add the subsequent branch exact
4332                    strings to the trie.
4333
4334                    We have two cases
4335
4336                      1. patterns where the whole set of branches can be
4337                         converted.
4338
4339                      2. patterns where only a subset can be converted.
4340
4341                    In case 1 we can replace the whole set with a single regop
4342                    for the trie. In case 2 we need to keep the start and end
4343                    branches so
4344
4345                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
4346                      becomes BRANCH TRIE; BRANCH X;
4347
4348                   There is an additional case, that being where there is a
4349                   common prefix, which gets split out into an EXACT like node
4350                   preceding the TRIE node.
4351
4352                   If x(1..n)==tail then we can do a simple trie, if not we make
4353                   a "jump" trie, such that when we match the appropriate word
4354                   we "jump" to the appropriate tail node. Essentially we turn
4355                   a nested if into a case structure of sorts.
4356
4357                 */
4358
4359                     int made=0;
4360                     if (!re_trie_maxbuff) {
4361                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
4362                         if (!SvIOK(re_trie_maxbuff))
4363                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
4364                     }
4365                     if ( SvIV(re_trie_maxbuff)>=0  ) {
4366                         regnode *cur;
4367                         regnode *first = (regnode *)NULL;
4368                         regnode *last = (regnode *)NULL;
4369                         regnode *tail = scan;
4370                         U8 trietype = 0;
4371                         U32 count=0;
4372
4373                         /* var tail is used because there may be a TAIL
4374                            regop in the way. Ie, the exacts will point to the
4375                            thing following the TAIL, but the last branch will
4376                            point at the TAIL. So we advance tail. If we
4377                            have nested (?:) we may have to move through several
4378                            tails.
4379                          */
4380
4381                         while ( OP( tail ) == TAIL ) {
4382                             /* this is the TAIL generated by (?:) */
4383                             tail = regnext( tail );
4384                         }
4385
4386
4387                         DEBUG_TRIE_COMPILE_r({
4388                             regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state);
4389                             PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
4390                               (int)depth * 2 + 2, "",
4391                               "Looking for TRIE'able sequences. Tail node is: ",
4392                               SvPV_nolen_const( RExC_mysv )
4393                             );
4394                         });
4395
4396                         /*
4397
4398                             Step through the branches
4399                                 cur represents each branch,
4400                                 noper is the first thing to be matched as part
4401                                       of that branch
4402                                 noper_next is the regnext() of that node.
4403
4404                             We normally handle a case like this
4405                             /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also
4406                             support building with NOJUMPTRIE, which restricts
4407                             the trie logic to structures like /FOO|BAR/.
4408
4409                             If noper is a trieable nodetype then the branch is
4410                             a possible optimization target. If we are building
4411                             under NOJUMPTRIE then we require that noper_next is
4412                             the same as scan (our current position in the regex
4413                             program).
4414
4415                             Once we have two or more consecutive such branches
4416                             we can create a trie of the EXACT's contents and
4417                             stitch it in place into the program.
4418
4419                             If the sequence represents all of the branches in
4420                             the alternation we replace the entire thing with a
4421                             single TRIE node.
4422
4423                             Otherwise when it is a subsequence we need to
4424                             stitch it in place and replace only the relevant
4425                             branches. This means the first branch has to remain
4426                             as it is used by the alternation logic, and its
4427                             next pointer, and needs to be repointed at the item
4428                             on the branch chain following the last branch we
4429                             have optimized away.
4430
4431                             This could be either a BRANCH, in which case the
4432                             subsequence is internal, or it could be the item
4433                             following the branch sequence in which case the
4434                             subsequence is at the end (which does not
4435                             necessarily mean the first node is the start of the
4436                             alternation).
4437
4438                             TRIE_TYPE(X) is a define which maps the optype to a
4439                             trietype.
4440
4441                                 optype          |  trietype
4442                                 ----------------+-----------
4443                                 NOTHING         | NOTHING
4444                                 EXACT           | EXACT
4445                                 EXACTFU         | EXACTFU
4446                                 EXACTFU_SS      | EXACTFU
4447                                 EXACTFA         | EXACTFA
4448                                 EXACTL          | EXACTL
4449                                 EXACTFLU8       | EXACTFLU8
4450
4451
4452                         */
4453 #define TRIE_TYPE(X) ( ( NOTHING == (X) )                                   \
4454                        ? NOTHING                                            \
4455                        : ( EXACT == (X) )                                   \
4456                          ? EXACT                                            \
4457                          : ( EXACTFU == (X) || EXACTFU_SS == (X) )          \
4458                            ? EXACTFU                                        \
4459                            : ( EXACTFA == (X) )                             \
4460                              ? EXACTFA                                      \
4461                              : ( EXACTL == (X) )                            \
4462                                ? EXACTL                                     \
4463                                : ( EXACTFLU8 == (X) )                        \
4464                                  ? EXACTFLU8                                 \
4465                                  : 0 )
4466
4467                         /* dont use tail as the end marker for this traverse */
4468                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
4469                             regnode * const noper = NEXTOPER( cur );
4470                             U8 noper_type = OP( noper );
4471                             U8 noper_trietype = TRIE_TYPE( noper_type );
4472 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
4473                             regnode * const noper_next = regnext( noper );
4474                             U8 noper_next_type = (noper_next && noper_next != tail) ? OP(noper_next) : 0;
4475                             U8 noper_next_trietype = (noper_next && noper_next != tail) ? TRIE_TYPE( noper_next_type ) :0;
4476 #endif
4477
4478                             DEBUG_TRIE_COMPILE_r({
4479                                 regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4480                                 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
4481                                    (int)depth * 2 + 2,"", SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) );
4482
4483                                 regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state);
4484                                 PerlIO_printf( Perl_debug_log, " -> %s",
4485                                     SvPV_nolen_const(RExC_mysv));
4486
4487                                 if ( noper_next ) {
4488                                   regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state);
4489                                   PerlIO_printf( Perl_debug_log,"\t=> %s\t",
4490                                     SvPV_nolen_const(RExC_mysv));
4491                                 }
4492                                 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d,tt==%s,nt==%s,nnt==%s)\n",
4493                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
4494                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype]
4495                                 );
4496                             });
4497
4498                             /* Is noper a trieable nodetype that can be merged
4499                              * with the current trie (if there is one)? */
4500                             if ( noper_trietype
4501                                   &&
4502                                   (
4503                                         ( noper_trietype == NOTHING)
4504                                         || ( trietype == NOTHING )
4505                                         || ( trietype == noper_trietype )
4506                                   )
4507 #ifdef NOJUMPTRIE
4508                                   && noper_next == tail
4509 #endif
4510                                   && count < U16_MAX)
4511                             {
4512                                 /* Handle mergable triable node Either we are
4513                                  * the first node in a new trieable sequence,
4514                                  * in which case we do some bookkeeping,
4515                                  * otherwise we update the end pointer. */
4516                                 if ( !first ) {
4517                                     first = cur;
4518                                     if ( noper_trietype == NOTHING ) {
4519 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
4520                                         regnode * const noper_next = regnext( noper );
4521                                         U8 noper_next_type = (noper_next && noper_next!=tail) ? OP(noper_next) : 0;
4522                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
4523 #endif
4524
4525                                         if ( noper_next_trietype ) {
4526                                             trietype = noper_next_trietype;
4527                                         } else if (noper_next_type)  {
4528                                             /* a NOTHING regop is 1 regop wide.
4529                                              * We need at least two for a trie
4530                                              * so we can't merge this in */
4531                                             first = NULL;
4532                                         }
4533                                     } else {
4534                                         trietype = noper_trietype;
4535                                     }
4536                                 } else {
4537                                     if ( trietype == NOTHING )
4538                                         trietype = noper_trietype;
4539                                     last = cur;
4540                                 }
4541                                 if (first)
4542                                     count++;
4543                             } /* end handle mergable triable node */
4544                             else {
4545                                 /* handle unmergable node -
4546                                  * noper may either be a triable node which can
4547                                  * not be tried together with the current trie,
4548                                  * or a non triable node */
4549                                 if ( last ) {
4550                                     /* If last is set and trietype is not
4551                                      * NOTHING then we have found at least two
4552                                      * triable branch sequences in a row of a
4553                                      * similar trietype so we can turn them
4554                                      * into a trie. If/when we allow NOTHING to
4555                                      * start a trie sequence this condition
4556                                      * will be required, and it isn't expensive
4557                                      * so we leave it in for now. */
4558                                     if ( trietype && trietype != NOTHING )
4559                                         make_trie( pRExC_state,
4560                                                 startbranch, first, cur, tail,
4561                                                 count, trietype, depth+1 );
4562                                     last = NULL; /* note: we clear/update
4563                                                     first, trietype etc below,
4564                                                     so we dont do it here */
4565                                 }
4566                                 if ( noper_trietype
4567 #ifdef NOJUMPTRIE
4568                                      && noper_next == tail
4569 #endif
4570                                 ){
4571                                     /* noper is triable, so we can start a new
4572                                      * trie sequence */
4573                                     count = 1;
4574                                     first = cur;
4575                                     trietype = noper_trietype;
4576                                 } else if (first) {
4577                                     /* if we already saw a first but the
4578                                      * current node is not triable then we have
4579                                      * to reset the first information. */
4580                                     count = 0;
4581                                     first = NULL;
4582                                     trietype = 0;
4583                                 }
4584                             } /* end handle unmergable node */
4585                         } /* loop over branches */
4586                         DEBUG_TRIE_COMPILE_r({
4587                             regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4588                             PerlIO_printf( Perl_debug_log,
4589                               "%*s- %s (%d) <SCAN FINISHED>\n",
4590                               (int)depth * 2 + 2,
4591                               "", SvPV_nolen_const( RExC_mysv ),REG_NODE_NUM(cur));
4592
4593                         });
4594                         if ( last && trietype ) {
4595                             if ( trietype != NOTHING ) {
4596                                 /* the last branch of the sequence was part of
4597                                  * a trie, so we have to construct it here
4598                                  * outside of the loop */
4599                                 made= make_trie( pRExC_state, startbranch,
4600                                                  first, scan, tail, count,
4601                                                  trietype, depth+1 );
4602 #ifdef TRIE_STUDY_OPT
4603                                 if ( ((made == MADE_EXACT_TRIE &&
4604                                      startbranch == first)
4605                                      || ( first_non_open == first )) &&
4606                                      depth==0 ) {
4607                                     flags |= SCF_TRIE_RESTUDY;
4608                                     if ( startbranch == first
4609                                          && scan == tail )
4610                                     {
4611                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN;
4612                                     }
4613                                 }
4614 #endif
4615                             } else {
4616                                 /* at this point we know whatever we have is a
4617                                  * NOTHING sequence/branch AND if 'startbranch'
4618                                  * is 'first' then we can turn the whole thing
4619                                  * into a NOTHING
4620                                  */
4621                                 if ( startbranch == first ) {
4622                                     regnode *opt;
4623                                     /* the entire thing is a NOTHING sequence,
4624                                      * something like this: (?:|) So we can
4625                                      * turn it into a plain NOTHING op. */
4626                                     DEBUG_TRIE_COMPILE_r({
4627                                         regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state);
4628                                         PerlIO_printf( Perl_debug_log,
4629                                           "%*s- %s (%d) <NOTHING BRANCH SEQUENCE>\n", (int)depth * 2 + 2,
4630                                           "", SvPV_nolen_const( RExC_mysv ),REG_NODE_NUM(cur));
4631
4632                                     });
4633                                     OP(startbranch)= NOTHING;
4634                                     NEXT_OFF(startbranch)= tail - startbranch;
4635                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
4636                                         OP(opt)= OPTIMIZED;
4637                                 }
4638                             }
4639                         } /* end if ( last) */
4640                     } /* TRIE_MAXBUF is non zero */
4641
4642                 } /* do trie */
4643
4644             }
4645             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
4646                 scan = NEXTOPER(NEXTOPER(scan));
4647             } else                      /* single branch is optimized. */
4648                 scan = NEXTOPER(scan);
4649             continue;
4650         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
4651             I32 paren = 0;
4652             regnode *start = NULL;
4653             regnode *end = NULL;
4654             U32 my_recursed_depth= recursed_depth;
4655
4656
4657             if (OP(scan) != SUSPEND) { /* GOSUB/GOSTART */
4658                 /* Do setup, note this code has side effects beyond
4659                  * the rest of this block. Specifically setting
4660                  * RExC_recurse[] must happen at least once during
4661                  * study_chunk(). */
4662                 if (OP(scan) == GOSUB) {
4663                     paren = ARG(scan);
4664                     RExC_recurse[ARG2L(scan)] = scan;
4665                     start = RExC_open_parens[paren-1];
4666                     end   = RExC_close_parens[paren-1];
4667                 } else {
4668                     start = RExC_rxi->program + 1;
4669                     end   = RExC_opend;
4670                 }
4671                 /* NOTE we MUST always execute the above code, even
4672                  * if we do nothing with a GOSUB/GOSTART */
4673                 if (
4674                     ( flags & SCF_IN_DEFINE )
4675                     ||
4676                     (
4677                         (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF))
4678                         &&
4679                         ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 )
4680                     )
4681                 ) {
4682                     /* no need to do anything here if we are in a define. */
4683                     /* or we are after some kind of infinite construct
4684                      * so we can skip recursing into this item.
4685                      * Since it is infinite we will not change the maxlen
4686                      * or delta, and if we miss something that might raise
4687                      * the minlen it will merely pessimise a little.
4688                      *
4689                      * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/
4690                      * might result in a minlen of 1 and not of 4,
4691                      * but this doesn't make us mismatch, just try a bit
4692                      * harder than we should.
4693                      * */
4694                     scan= regnext(scan);
4695                     continue;
4696                 }
4697
4698                 if (
4699                     !recursed_depth
4700                     ||
4701                     !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren)
4702                 ) {
4703                     /* it is quite possible that there are more efficient ways
4704                      * to do this. We maintain a bitmap per level of recursion
4705                      * of which patterns we have entered so we can detect if a
4706                      * pattern creates a possible infinite loop. When we
4707                      * recurse down a level we copy the previous levels bitmap
4708                      * down. When we are at recursion level 0 we zero the top
4709                      * level bitmap. It would be nice to implement a different
4710                      * more efficient way of doing this. In particular the top
4711                      * level bitmap may be unnecessary.
4712                      */
4713                     if (!recursed_depth) {
4714                         Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8);
4715                     } else {
4716                         Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes),
4717                              RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes),
4718                              RExC_study_chunk_recursed_bytes, U8);
4719                     }
4720                     /* we havent recursed into this paren yet, so recurse into it */
4721                     DEBUG_STUDYDATA("set:", data,depth);
4722                     PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren);
4723                     my_recursed_depth= recursed_depth + 1;
4724                 } else {
4725                     DEBUG_STUDYDATA("inf:", data,depth);
4726                     /* some form of infinite recursion, assume infinite length
4727                      * */
4728                     if (flags & SCF_DO_SUBSTR) {
4729                         scan_commit(pRExC_state, data, minlenp, is_inf);
4730                         data->longest = &(data->longest_float);
4731                     }
4732                     is_inf = is_inf_internal = 1;
4733                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4734                         ssc_anything(data->start_class);
4735                     flags &= ~SCF_DO_STCLASS;
4736
4737                     start= NULL; /* reset start so we dont recurse later on. */
4738                 }
4739             } else {
4740                 paren = stopparen;
4741                 start = scan + 2;
4742                 end = regnext(scan);
4743             }
4744             if (start) {
4745                 scan_frame *newframe;
4746                 assert(end);
4747                 if (!RExC_frame_last) {
4748                     Newxz(newframe, 1, scan_frame);
4749                     SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe);
4750                     RExC_frame_head= newframe;
4751                     RExC_frame_count++;
4752                 } else if (!RExC_frame_last->next_frame) {
4753                     Newxz(newframe,1,scan_frame);
4754                     RExC_frame_last->next_frame= newframe;
4755                     newframe->prev_frame= RExC_frame_last;
4756                     RExC_frame_count++;
4757                 } else {
4758                     newframe= RExC_frame_last->next_frame;
4759                 }
4760                 RExC_frame_last= newframe;
4761
4762                 newframe->next_regnode = regnext(scan);
4763                 newframe->last_regnode = last;
4764                 newframe->stopparen = stopparen;
4765                 newframe->prev_recursed_depth = recursed_depth;
4766                 newframe->this_prev_frame= frame;
4767
4768                 DEBUG_STUDYDATA("frame-new:",data,depth);
4769                 DEBUG_PEEP("fnew", scan, depth);
4770
4771                 frame = newframe;
4772                 scan =  start;
4773                 stopparen = paren;
4774                 last = end;
4775                 depth = depth + 1;
4776                 recursed_depth= my_recursed_depth;
4777
4778                 continue;
4779             }
4780         }
4781         else if (OP(scan) == EXACT || OP(scan) == EXACTL) {
4782             SSize_t l = STR_LEN(scan);
4783             UV uc;
4784             if (UTF) {
4785                 const U8 * const s = (U8*)STRING(scan);
4786                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
4787                 l = utf8_length(s, s + l);
4788             } else {
4789                 uc = *((U8*)STRING(scan));
4790             }
4791             min += l;
4792             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
4793                 /* The code below prefers earlier match for fixed
4794                    offset, later match for variable offset.  */
4795                 if (data->last_end == -1) { /* Update the start info. */
4796                     data->last_start_min = data->pos_min;
4797                     data->last_start_max = is_inf
4798                         ? SSize_t_MAX : data->pos_min + data->pos_delta;
4799                 }
4800                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
4801                 if (UTF)
4802                     SvUTF8_on(data->last_found);
4803                 {
4804                     SV * const sv = data->last_found;
4805                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
4806                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
4807                     if (mg && mg->mg_len >= 0)
4808                         mg->mg_len += utf8_length((U8*)STRING(scan),
4809                                               (U8*)STRING(scan)+STR_LEN(scan));
4810                 }
4811                 data->last_end = data->pos_min + l;
4812                 data->pos_min += l; /* As in the first entry. */
4813                 data->flags &= ~SF_BEFORE_EOL;
4814             }
4815
4816             /* ANDing the code point leaves at most it, and not in locale, and
4817              * can't match null string */
4818             if (flags & SCF_DO_STCLASS_AND) {
4819                 ssc_cp_and(data->start_class, uc);
4820                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
4821                 ssc_clear_locale(data->start_class);
4822             }
4823             else if (flags & SCF_DO_STCLASS_OR) {
4824                 ssc_add_cp(data->start_class, uc);
4825                 ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4826
4827                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
4828                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
4829             }
4830             flags &= ~SCF_DO_STCLASS;
4831         }
4832         else if (PL_regkind[OP(scan)] == EXACT) {
4833             /* But OP != EXACT!, so is EXACTFish */
4834             SSize_t l = STR_LEN(scan);
4835             const U8 * s = (U8*)STRING(scan);
4836
4837             /* Search for fixed substrings supports EXACT only. */
4838             if (flags & SCF_DO_SUBSTR) {
4839                 assert(data);
4840                 scan_commit(pRExC_state, data, minlenp, is_inf);
4841             }
4842             if (UTF) {
4843                 l = utf8_length(s, s + l);
4844             }
4845             if (unfolded_multi_char) {
4846                 RExC_seen |= REG_UNFOLDED_MULTI_SEEN;
4847             }
4848             min += l - min_subtract;
4849             assert (min >= 0);
4850             delta += min_subtract;
4851             if (flags & SCF_DO_SUBSTR) {
4852                 data->pos_min += l - min_subtract;
4853                 if (data->pos_min < 0) {
4854                     data->pos_min = 0;
4855                 }
4856                 data->pos_delta += min_subtract;
4857                 if (min_subtract) {
4858                     data->longest = &(data->longest_float);
4859                 }
4860             }
4861
4862             if (flags & SCF_DO_STCLASS) {
4863                 SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan);
4864
4865                 assert(EXACTF_invlist);
4866                 if (flags & SCF_DO_STCLASS_AND) {
4867                     if (OP(scan) != EXACTFL)
4868                         ssc_clear_locale(data->start_class);
4869                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
4870                     ANYOF_POSIXL_ZERO(data->start_class);
4871                     ssc_intersection(data->start_class, EXACTF_invlist, FALSE);
4872                 }
4873                 else {  /* SCF_DO_STCLASS_OR */
4874                     ssc_union(data->start_class, EXACTF_invlist, FALSE);
4875                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
4876
4877                     /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
4878                     ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
4879                 }
4880                 flags &= ~SCF_DO_STCLASS;
4881                 SvREFCNT_dec(EXACTF_invlist);
4882             }
4883         }
4884         else if (REGNODE_VARIES(OP(scan))) {
4885             SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0;
4886             I32 fl = 0, f = flags;
4887             regnode * const oscan = scan;
4888             regnode_ssc this_class;
4889             regnode_ssc *oclass = NULL;
4890             I32 next_is_eval = 0;
4891
4892             switch (PL_regkind[OP(scan)]) {
4893             case WHILEM:                /* End of (?:...)* . */
4894                 scan = NEXTOPER(scan);
4895                 goto finish;
4896             case PLUS:
4897                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
4898                     next = NEXTOPER(scan);
4899                     if (OP(next) == EXACT
4900                         || OP(next) == EXACTL
4901                         || (flags & SCF_DO_STCLASS))
4902                     {
4903                         mincount = 1;
4904                         maxcount = REG_INFTY;
4905                         next = regnext(scan);
4906                         scan = NEXTOPER(scan);
4907                         goto do_curly;
4908                     }
4909                 }
4910                 if (flags & SCF_DO_SUBSTR)
4911                     data->pos_min++;
4912                 min++;
4913                 /* FALLTHROUGH */
4914             case STAR:
4915                 if (flags & SCF_DO_STCLASS) {
4916                     mincount = 0;
4917                     maxcount = REG_INFTY;
4918                     next = regnext(scan);
4919                     scan = NEXTOPER(scan);
4920                     goto do_curly;
4921                 }
4922                 if (flags & SCF_DO_SUBSTR) {
4923                     scan_commit(pRExC_state, data, minlenp, is_inf);
4924                     /* Cannot extend fixed substrings */
4925                     data->longest = &(data->longest_float);
4926                 }
4927                 is_inf = is_inf_internal = 1;
4928                 scan = regnext(scan);
4929                 goto optimize_curly_tail;
4930             case CURLY:
4931                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
4932                     && (scan->flags == stopparen))
4933                 {
4934                     mincount = 1;
4935                     maxcount = 1;
4936                 } else {
4937                     mincount = ARG1(scan);
4938                     maxcount = ARG2(scan);
4939                 }
4940                 next = regnext(scan);
4941                 if (OP(scan) == CURLYX) {
4942                     I32 lp = (data ? *(data->last_closep) : 0);
4943                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
4944                 }
4945                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
4946                 next_is_eval = (OP(scan) == EVAL);
4947               do_curly:
4948                 if (flags & SCF_DO_SUBSTR) {
4949                     if (mincount == 0)
4950                         scan_commit(pRExC_state, data, minlenp, is_inf);
4951                     /* Cannot extend fixed substrings */
4952                     pos_before = data->pos_min;
4953                 }
4954                 if (data) {
4955                     fl = data->flags;
4956                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
4957                     if (is_inf)
4958                         data->flags |= SF_IS_INF;
4959                 }
4960                 if (flags & SCF_DO_STCLASS) {
4961                     ssc_init(pRExC_state, &this_class);
4962                     oclass = data->start_class;
4963                     data->start_class = &this_class;
4964                     f |= SCF_DO_STCLASS_AND;
4965                     f &= ~SCF_DO_STCLASS_OR;
4966                 }
4967                 /* Exclude from super-linear cache processing any {n,m}
4968                    regops for which the combination of input pos and regex
4969                    pos is not enough information to determine if a match
4970                    will be possible.
4971
4972                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
4973                    regex pos at the \s*, the prospects for a match depend not
4974                    only on the input position but also on how many (bar\s*)
4975                    repeats into the {4,8} we are. */
4976                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
4977                     f &= ~SCF_WHILEM_VISITED_POS;
4978
4979                 /* This will finish on WHILEM, setting scan, or on NULL: */
4980                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
4981                                   last, data, stopparen, recursed_depth, NULL,
4982                                   (mincount == 0
4983                                    ? (f & ~SCF_DO_SUBSTR)
4984                                    : f)
4985                                   ,depth+1);
4986
4987                 if (flags & SCF_DO_STCLASS)
4988                     data->start_class = oclass;
4989                 if (mincount == 0 || minnext == 0) {
4990                     if (flags & SCF_DO_STCLASS_OR) {
4991                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
4992                     }
4993                     else if (flags & SCF_DO_STCLASS_AND) {
4994                         /* Switch to OR mode: cache the old value of
4995                          * data->start_class */
4996                         INIT_AND_WITHP;
4997                         StructCopy(data->start_class, and_withp, regnode_ssc);
4998                         flags &= ~SCF_DO_STCLASS_AND;
4999                         StructCopy(&this_class, data->start_class, regnode_ssc);
5000                         flags |= SCF_DO_STCLASS_OR;
5001                         ANYOF_FLAGS(data->start_class)
5002                                                 |= SSC_MATCHES_EMPTY_STRING;
5003                     }
5004                 } else {                /* Non-zero len */
5005                     if (flags & SCF_DO_STCLASS_OR) {
5006                         ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5007                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5008                     }
5009                     else if (flags & SCF_DO_STCLASS_AND)
5010                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class);
5011                     flags &= ~SCF_DO_STCLASS;
5012                 }
5013                 if (!scan)              /* It was not CURLYX, but CURLY. */
5014                     scan = next;
5015                 if (!(flags & SCF_TRIE_DOING_RESTUDY)
5016                     /* ? quantifier ok, except for (?{ ... }) */
5017                     && (next_is_eval || !(mincount == 0 && maxcount == 1))
5018                     && (minnext == 0) && (deltanext == 0)
5019                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
5020                     && maxcount <= REG_INFTY/3) /* Complement check for big
5021                                                    count */
5022                 {
5023                     /* Fatal warnings may leak the regexp without this: */
5024                     SAVEFREESV(RExC_rx_sv);
5025                     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
5026                         "Quantifier unexpected on zero-length expression "
5027                         "in regex m/%"UTF8f"/",
5028                          UTF8fARG(UTF, RExC_precomp_end - RExC_precomp,
5029                                   RExC_precomp));
5030                     (void)ReREFCNT_inc(RExC_rx_sv);
5031                 }
5032
5033                 min += minnext * mincount;
5034                 is_inf_internal |= deltanext == SSize_t_MAX
5035                          || (maxcount == REG_INFTY && minnext + deltanext > 0);
5036                 is_inf |= is_inf_internal;
5037                 if (is_inf) {
5038                     delta = SSize_t_MAX;
5039                 } else {
5040                     delta += (minnext + deltanext) * maxcount
5041                              - minnext * mincount;
5042                 }
5043                 /* Try powerful optimization CURLYX => CURLYN. */
5044                 if (  OP(oscan) == CURLYX && data
5045                       && data->flags & SF_IN_PAR
5046                       && !(data->flags & SF_HAS_EVAL)
5047                       && !deltanext && minnext == 1 ) {
5048                     /* Try to optimize to CURLYN.  */
5049                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
5050                     regnode * const nxt1 = nxt;
5051 #ifdef DEBUGGING
5052                     regnode *nxt2;
5053 #endif
5054
5055                     /* Skip open. */
5056                     nxt = regnext(nxt);
5057                     if (!REGNODE_SIMPLE(OP(nxt))
5058                         && !(PL_regkind[OP(nxt)] == EXACT
5059                              && STR_LEN(nxt) == 1))
5060                         goto nogo;
5061 #ifdef DEBUGGING
5062                     nxt2 = nxt;
5063 #endif
5064                     nxt = regnext(nxt);
5065                     if (OP(nxt) != CLOSE)
5066                         goto nogo;
5067                     if (RExC_open_parens) {
5068                         RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
5069                         RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
5070                     }
5071                     /* Now we know that nxt2 is the only contents: */
5072                     oscan->flags = (U8)ARG(nxt);
5073                     OP(oscan) = CURLYN;
5074                     OP(nxt1) = NOTHING; /* was OPEN. */
5075
5076 #ifdef DEBUGGING
5077                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5078                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
5079                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
5080                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
5081                     OP(nxt + 1) = OPTIMIZED; /* was count. */
5082                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
5083 #endif
5084                 }
5085               nogo:
5086
5087                 /* Try optimization CURLYX => CURLYM. */
5088                 if (  OP(oscan) == CURLYX && data
5089                       && !(data->flags & SF_HAS_PAR)
5090                       && !(data->flags & SF_HAS_EVAL)
5091                       && !deltanext     /* atom is fixed width */
5092                       && minnext != 0   /* CURLYM can't handle zero width */
5093
5094                          /* Nor characters whose fold at run-time may be
5095                           * multi-character */
5096                       && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
5097                 ) {
5098                     /* XXXX How to optimize if data == 0? */
5099                     /* Optimize to a simpler form.  */
5100                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
5101                     regnode *nxt2;
5102
5103                     OP(oscan) = CURLYM;
5104                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
5105                             && (OP(nxt2) != WHILEM))
5106                         nxt = nxt2;
5107                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
5108                     /* Need to optimize away parenths. */
5109                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
5110                         /* Set the parenth number.  */
5111                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
5112
5113                         oscan->flags = (U8)ARG(nxt);
5114                         if (RExC_open_parens) {
5115                             RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
5116                             RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
5117                         }
5118                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
5119                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
5120
5121 #ifdef DEBUGGING
5122                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
5123                         OP(nxt + 1) = OPTIMIZED; /* was count. */
5124                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
5125                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
5126 #endif
5127 #if 0
5128                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
5129                             regnode *nnxt = regnext(nxt1);
5130                             if (nnxt == nxt) {
5131                                 if (reg_off_by_arg[OP(nxt1)])
5132                                     ARG_SET(nxt1, nxt2 - nxt1);
5133                                 else if (nxt2 - nxt1 < U16_MAX)
5134                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
5135                                 else
5136                                     OP(nxt) = NOTHING;  /* Cannot beautify */
5137                             }
5138                             nxt1 = nnxt;
5139                         }
5140 #endif
5141                         /* Optimize again: */
5142                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
5143                                     NULL, stopparen, recursed_depth, NULL, 0,depth+1);
5144                     }
5145                     else
5146                         oscan->flags = 0;
5147                 }
5148                 else if ((OP(oscan) == CURLYX)
5149                          && (flags & SCF_WHILEM_VISITED_POS)
5150                          /* See the comment on a similar expression above.
5151                             However, this time it's not a subexpression
5152                             we care about, but the expression itself. */
5153                          && (maxcount == REG_INFTY)
5154                          && data && ++data->whilem_c < 16) {
5155                     /* This stays as CURLYX, we can put the count/of pair. */
5156                     /* Find WHILEM (as in regexec.c) */
5157                     regnode *nxt = oscan + NEXT_OFF(oscan);
5158
5159                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
5160                         nxt += ARG(nxt);
5161                     PREVOPER(nxt)->flags = (U8)(data->whilem_c
5162                         | (RExC_whilem_seen << 4)); /* On WHILEM */
5163                 }
5164                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
5165                     pars++;
5166                 if (flags & SCF_DO_SUBSTR) {
5167                     SV *last_str = NULL;
5168                     STRLEN last_chrs = 0;
5169                     int counted = mincount != 0;
5170
5171                     if (data->last_end > 0 && mincount != 0) { /* Ends with a
5172                                                                   string. */
5173                         SSize_t b = pos_before >= data->last_start_min
5174                             ? pos_before : data->last_start_min;
5175                         STRLEN l;
5176                         const char * const s = SvPV_const(data->last_found, l);
5177                         SSize_t old = b - data->last_start_min;
5178
5179                         if (UTF)
5180                             old = utf8_hop((U8*)s, old) - (U8*)s;
5181                         l -= old;
5182                         /* Get the added string: */
5183                         last_str = newSVpvn_utf8(s  + old, l, UTF);
5184                         last_chrs = UTF ? utf8_length((U8*)(s + old),
5185                                             (U8*)(s + old + l)) : l;
5186                         if (deltanext == 0 && pos_before == b) {
5187                             /* What was added is a constant string */
5188                             if (mincount > 1) {
5189
5190                                 SvGROW(last_str, (mincount * l) + 1);
5191                                 repeatcpy(SvPVX(last_str) + l,
5192                                           SvPVX_const(last_str), l,
5193                                           mincount - 1);
5194                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
5195                                 /* Add additional parts. */
5196                                 SvCUR_set(data->last_found,
5197                                           SvCUR(data->last_found) - l);
5198                                 sv_catsv(data->last_found, last_str);
5199                                 {
5200                                     SV * sv = data->last_found;
5201                                     MAGIC *mg =
5202                                         SvUTF8(sv) && SvMAGICAL(sv) ?
5203                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
5204                                     if (mg && mg->mg_len >= 0)
5205                                         mg->mg_len += last_chrs * (mincount-1);
5206                                 }
5207                                 last_chrs *= mincount;
5208                                 data->last_end += l * (mincount - 1);
5209                             }
5210                         } else {
5211                             /* start offset must point into the last copy */
5212                             data->last_start_min += minnext * (mincount - 1);
5213                             data->last_start_max =
5214                               is_inf
5215                                ? SSize_t_MAX
5216                                : data->last_start_max +
5217                                  (maxcount - 1) * (minnext + data->pos_delta);
5218                         }
5219                     }
5220                     /* It is counted once already... */
5221                     data->pos_min += minnext * (mincount - counted);
5222 #if 0
5223 PerlIO_printf(Perl_debug_log, "counted=%"UVuf" deltanext=%"UVuf
5224                               " SSize_t_MAX=%"UVuf" minnext=%"UVuf
5225                               " maxcount=%"UVuf" mincount=%"UVuf"\n",
5226     (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount,
5227     (UV)mincount);
5228 if (deltanext != SSize_t_MAX)
5229 PerlIO_printf(Perl_debug_log, "LHS=%"UVuf" RHS=%"UVuf"\n",
5230     (UV)(-counted * deltanext + (minnext + deltanext) * maxcount
5231           - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta));
5232 #endif
5233                     if (deltanext == SSize_t_MAX
5234                         || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta)
5235                         data->pos_delta = SSize_t_MAX;
5236                     else
5237                         data->pos_delta += - counted * deltanext +
5238                         (minnext + deltanext) * maxcount - minnext * mincount;
5239                     if (mincount != maxcount) {
5240                          /* Cannot extend fixed substrings found inside
5241                             the group.  */
5242                         scan_commit(pRExC_state, data, minlenp, is_inf);
5243                         if (mincount && last_str) {
5244                             SV * const sv = data->last_found;
5245                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
5246                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
5247
5248                             if (mg)
5249                                 mg->mg_len = -1;
5250                             sv_setsv(sv, last_str);
5251                             data->last_end = data->pos_min;
5252                             data->last_start_min = data->pos_min - last_chrs;
5253                             data->last_start_max = is_inf
5254                                 ? SSize_t_MAX
5255                                 : data->pos_min + data->pos_delta - last_chrs;
5256                         }
5257                         data->longest = &(data->longest_float);
5258                     }
5259                     SvREFCNT_dec(last_str);
5260                 }
5261                 if (data && (fl & SF_HAS_EVAL))
5262                     data->flags |= SF_HAS_EVAL;
5263               optimize_curly_tail:
5264                 if (OP(oscan) != CURLYX) {
5265                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
5266                            && NEXT_OFF(next))
5267                         NEXT_OFF(oscan) += NEXT_OFF(next);
5268                 }
5269                 continue;
5270
5271             default:
5272 #ifdef DEBUGGING
5273                 Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d",
5274                                                                     OP(scan));
5275 #endif
5276             case REF:
5277             case CLUMP:
5278                 if (flags & SCF_DO_SUBSTR) {
5279                     /* Cannot expect anything... */
5280                     scan_commit(pRExC_state, data, minlenp, is_inf);
5281                     data->longest = &(data->longest_float);
5282                 }
5283                 is_inf = is_inf_internal = 1;
5284                 if (flags & SCF_DO_STCLASS_OR) {
5285                     if (OP(scan) == CLUMP) {
5286                         /* Actually is any start char, but very few code points
5287                          * aren't start characters */
5288                         ssc_match_all_cp(data->start_class);
5289                     }
5290                     else {
5291                         ssc_anything(data->start_class);
5292                     }
5293                 }
5294                 flags &= ~SCF_DO_STCLASS;
5295                 break;
5296             }
5297         }
5298         else if (OP(scan) == LNBREAK) {
5299             if (flags & SCF_DO_STCLASS) {
5300                 if (flags & SCF_DO_STCLASS_AND) {
5301                     ssc_intersection(data->start_class,
5302                                     PL_XPosix_ptrs[_CC_VERTSPACE], FALSE);
5303                     ssc_clear_locale(data->start_class);
5304                     ANYOF_FLAGS(data->start_class)
5305                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5306                 }
5307                 else if (flags & SCF_DO_STCLASS_OR) {
5308                     ssc_union(data->start_class,
5309                               PL_XPosix_ptrs[_CC_VERTSPACE],
5310                               FALSE);
5311                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5312
5313                     /* See commit msg for
5314                      * 749e076fceedeb708a624933726e7989f2302f6a */
5315                     ANYOF_FLAGS(data->start_class)
5316                                                 &= ~SSC_MATCHES_EMPTY_STRING;
5317                 }
5318                 flags &= ~SCF_DO_STCLASS;
5319             }
5320             min++;
5321             if (delta != SSize_t_MAX)
5322                 delta++;    /* Because of the 2 char string cr-lf */
5323             if (flags & SCF_DO_SUBSTR) {
5324                 /* Cannot expect anything... */
5325                 scan_commit(pRExC_state, data, minlenp, is_inf);
5326                 data->pos_min += 1;
5327                 data->pos_delta += 1;
5328                 data->longest = &(data->longest_float);
5329             }
5330         }
5331         else if (REGNODE_SIMPLE(OP(scan))) {
5332
5333             if (flags & SCF_DO_SUBSTR) {
5334                 scan_commit(pRExC_state, data, minlenp, is_inf);
5335                 data->pos_min++;
5336             }
5337             min++;
5338             if (flags & SCF_DO_STCLASS) {
5339                 bool invert = 0;
5340                 SV* my_invlist = NULL;
5341                 U8 namedclass;
5342
5343                 /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */
5344                 ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING;
5345
5346                 /* Some of the logic below assumes that switching
5347                    locale on will only add false positives. */
5348                 switch (OP(scan)) {
5349
5350                 default:
5351 #ifdef DEBUGGING
5352                    Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d",
5353                                                                      OP(scan));
5354 #endif
5355                 case SANY:
5356                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5357                         ssc_match_all_cp(data->start_class);
5358                     break;
5359
5360                 case REG_ANY:
5361                     {
5362                         SV* REG_ANY_invlist = _new_invlist(2);
5363                         REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist,
5364                                                             '\n');
5365                         if (flags & SCF_DO_STCLASS_OR) {
5366                             ssc_union(data->start_class,
5367                                       REG_ANY_invlist,
5368                                       TRUE /* TRUE => invert, hence all but \n
5369                                             */
5370                                       );
5371                         }
5372                         else if (flags & SCF_DO_STCLASS_AND) {
5373                             ssc_intersection(data->start_class,
5374                                              REG_ANY_invlist,
5375                                              TRUE  /* TRUE => invert */
5376                                              );
5377                             ssc_clear_locale(data->start_class);
5378                         }
5379                         SvREFCNT_dec_NN(REG_ANY_invlist);
5380                     }
5381                     break;
5382
5383                 case ANYOFD:
5384                 case ANYOFL:
5385                 case ANYOF:
5386                     if (flags & SCF_DO_STCLASS_AND)
5387                         ssc_and(pRExC_state, data->start_class,
5388                                 (regnode_charclass *) scan);
5389                     else
5390                         ssc_or(pRExC_state, data->start_class,
5391                                                           (regnode_charclass *) scan);
5392                     break;
5393
5394                 case NPOSIXL:
5395                     invert = 1;
5396                     /* FALLTHROUGH */
5397
5398                 case POSIXL:
5399                     namedclass = classnum_to_namedclass(FLAGS(scan)) + invert;
5400                     if (flags & SCF_DO_STCLASS_AND) {
5401                         bool was_there = cBOOL(
5402                                           ANYOF_POSIXL_TEST(data->start_class,
5403                                                                  namedclass));
5404                         ANYOF_POSIXL_ZERO(data->start_class);
5405                         if (was_there) {    /* Do an AND */
5406                             ANYOF_POSIXL_SET(data->start_class, namedclass);
5407                         }
5408                         /* No individual code points can now match */
5409                         data->start_class->invlist
5410                                                 = sv_2mortal(_new_invlist(0));
5411                     }
5412                     else {
5413                         int complement = namedclass + ((invert) ? -1 : 1);
5414
5415                         assert(flags & SCF_DO_STCLASS_OR);
5416
5417                         /* If the complement of this class was already there,
5418                          * the result is that they match all code points,
5419                          * (\d + \D == everything).  Remove the classes from
5420                          * future consideration.  Locale is not relevant in
5421                          * this case */
5422                         if (ANYOF_POSIXL_TEST(data->start_class, complement)) {
5423                             ssc_match_all_cp(data->start_class);
5424                             ANYOF_POSIXL_CLEAR(data->start_class, namedclass);
5425                             ANYOF_POSIXL_CLEAR(data->start_class, complement);
5426                         }
5427                         else {  /* The usual case; just add this class to the
5428                                    existing set */
5429                             ANYOF_POSIXL_SET(data->start_class, namedclass);
5430                         }
5431                     }
5432                     break;
5433
5434                 case NPOSIXA:   /* For these, we always know the exact set of
5435                                    what's matched */
5436                     invert = 1;
5437                     /* FALLTHROUGH */
5438                 case POSIXA:
5439                     if (FLAGS(scan) == _CC_ASCII) {
5440                         my_invlist = invlist_clone(PL_XPosix_ptrs[_CC_ASCII]);
5441                     }
5442                     else {
5443                         _invlist_intersection(PL_XPosix_ptrs[FLAGS(scan)],
5444                                               PL_XPosix_ptrs[_CC_ASCII],
5445                                               &my_invlist);
5446                     }
5447                     goto join_posix;
5448
5449                 case NPOSIXD:
5450                 case NPOSIXU:
5451                     invert = 1;
5452                     /* FALLTHROUGH */
5453                 case POSIXD:
5454                 case POSIXU:
5455                     my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)]);
5456
5457                     /* NPOSIXD matches all upper Latin1 code points unless the
5458                      * target string being matched is UTF-8, which is
5459                      * unknowable until match time.  Since we are going to
5460                      * invert, we want to get rid of all of them so that the
5461                      * inversion will match all */
5462                     if (OP(scan) == NPOSIXD) {
5463                         _invlist_subtract(my_invlist, PL_UpperLatin1,
5464                                           &my_invlist);
5465                     }
5466
5467                   join_posix:
5468
5469                     if (flags & SCF_DO_STCLASS_AND) {
5470                         ssc_intersection(data->start_class, my_invlist, invert);
5471                         ssc_clear_locale(data->start_class);
5472                     }
5473                     else {
5474                         assert(flags & SCF_DO_STCLASS_OR);
5475                         ssc_union(data->start_class, my_invlist, invert);
5476                     }
5477                     SvREFCNT_dec(my_invlist);
5478                 }
5479                 if (flags & SCF_DO_STCLASS_OR)
5480                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5481                 flags &= ~SCF_DO_STCLASS;
5482             }
5483         }
5484         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
5485             data->flags |= (OP(scan) == MEOL
5486                             ? SF_BEFORE_MEOL
5487                             : SF_BEFORE_SEOL);
5488             scan_commit(pRExC_state, data, minlenp, is_inf);
5489
5490         }
5491         else if (  PL_regkind[OP(scan)] == BRANCHJ
5492                  /* Lookbehind, or need to calculate parens/evals/stclass: */
5493                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
5494                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM))
5495         {
5496             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5497                 || OP(scan) == UNLESSM )
5498             {
5499                 /* Negative Lookahead/lookbehind
5500                    In this case we can't do fixed string optimisation.
5501                 */
5502
5503                 SSize_t deltanext, minnext, fake = 0;
5504                 regnode *nscan;
5505                 regnode_ssc intrnl;
5506                 int f = 0;
5507
5508                 StructCopy(&zero_scan_data, &data_fake, scan_data_t);
5509                 if (data) {
5510                     data_fake.whilem_c = data->whilem_c;
5511                     data_fake.last_closep = data->last_closep;
5512                 }
5513                 else
5514                     data_fake.last_closep = &fake;
5515                 data_fake.pos_delta = delta;
5516                 if ( flags & SCF_DO_STCLASS && !scan->flags
5517                      && OP(scan) == IFMATCH ) { /* Lookahead */
5518                     ssc_init(pRExC_state, &intrnl);
5519                     data_fake.start_class = &intrnl;
5520                     f |= SCF_DO_STCLASS_AND;
5521                 }
5522                 if (flags & SCF_WHILEM_VISITED_POS)
5523                     f |= SCF_WHILEM_VISITED_POS;
5524                 next = regnext(scan);
5525                 nscan = NEXTOPER(NEXTOPER(scan));
5526                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
5527                                       last, &data_fake, stopparen,
5528                                       recursed_depth, NULL, f, depth+1);
5529                 if (scan->flags) {
5530                     if (deltanext) {
5531                         FAIL("Variable length lookbehind not implemented");
5532                     }
5533                     else if (minnext > (I32)U8_MAX) {
5534                         FAIL2("Lookbehind longer than %"UVuf" not implemented",
5535                               (UV)U8_MAX);
5536                     }
5537                     scan->flags = (U8)minnext;
5538                 }
5539                 if (data) {
5540                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5541                         pars++;
5542                     if (data_fake.flags & SF_HAS_EVAL)
5543                         data->flags |= SF_HAS_EVAL;
5544                     data->whilem_c = data_fake.whilem_c;
5545                 }
5546                 if (f & SCF_DO_STCLASS_AND) {
5547                     if (flags & SCF_DO_STCLASS_OR) {
5548                         /* OR before, AND after: ideally we would recurse with
5549                          * data_fake to get the AND applied by study of the
5550                          * remainder of the pattern, and then derecurse;
5551                          * *** HACK *** for now just treat as "no information".
5552                          * See [perl #56690].
5553                          */
5554                         ssc_init(pRExC_state, data->start_class);
5555                     }  else {
5556                         /* AND before and after: combine and continue.  These
5557                          * assertions are zero-length, so can match an EMPTY
5558                          * string */
5559                         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
5560                         ANYOF_FLAGS(data->start_class)
5561                                                    |= SSC_MATCHES_EMPTY_STRING;
5562                     }
5563                 }
5564             }
5565 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
5566             else {
5567                 /* Positive Lookahead/lookbehind
5568                    In this case we can do fixed string optimisation,
5569                    but we must be careful about it. Note in the case of
5570                    lookbehind the positions will be offset by the minimum
5571                    length of the pattern, something we won't know about
5572                    until after the recurse.
5573                 */
5574                 SSize_t deltanext, fake = 0;
5575                 regnode *nscan;
5576                 regnode_ssc intrnl;
5577                 int f = 0;
5578                 /* We use SAVEFREEPV so that when the full compile
5579                     is finished perl will clean up the allocated
5580                     minlens when it's all done. This way we don't
5581                     have to worry about freeing them when we know
5582                     they wont be used, which would be a pain.
5583                  */
5584                 SSize_t *minnextp;
5585                 Newx( minnextp, 1, SSize_t );
5586                 SAVEFREEPV(minnextp);
5587
5588                 if (data) {
5589                     StructCopy(data, &data_fake, scan_data_t);
5590                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
5591                         f |= SCF_DO_SUBSTR;
5592                         if (scan->flags)
5593                             scan_commit(pRExC_state, &data_fake, minlenp, is_inf);
5594                         data_fake.last_found=newSVsv(data->last_found);
5595                     }
5596                 }
5597                 else
5598                     data_fake.last_closep = &fake;
5599                 data_fake.flags = 0;
5600                 data_fake.pos_delta = delta;
5601                 if (is_inf)
5602                     data_fake.flags |= SF_IS_INF;
5603                 if ( flags & SCF_DO_STCLASS && !scan->flags
5604                      && OP(scan) == IFMATCH ) { /* Lookahead */
5605                     ssc_init(pRExC_state, &intrnl);
5606                     data_fake.start_class = &intrnl;
5607                     f |= SCF_DO_STCLASS_AND;
5608                 }
5609                 if (flags & SCF_WHILEM_VISITED_POS)
5610                     f |= SCF_WHILEM_VISITED_POS;
5611                 next = regnext(scan);
5612                 nscan = NEXTOPER(NEXTOPER(scan));
5613
5614                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
5615                                         &deltanext, last, &data_fake,
5616                                         stopparen, recursed_depth, NULL,
5617                                         f,depth+1);
5618                 if (scan->flags) {
5619                     if (deltanext) {
5620                         FAIL("Variable length lookbehind not implemented");
5621                     }
5622                     else if (*minnextp > (I32)U8_MAX) {
5623                         FAIL2("Lookbehind longer than %"UVuf" not implemented",
5624                               (UV)U8_MAX);
5625                     }
5626                     scan->flags = (U8)*minnextp;
5627                 }
5628
5629                 *minnextp += min;
5630
5631                 if (f & SCF_DO_STCLASS_AND) {
5632                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl);
5633                     ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING;
5634                 }
5635                 if (data) {
5636                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5637                         pars++;
5638                     if (data_fake.flags & SF_HAS_EVAL)
5639                         data->flags |= SF_HAS_EVAL;
5640                     data->whilem_c = data_fake.whilem_c;
5641                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
5642                         if (RExC_rx->minlen<*minnextp)
5643                             RExC_rx->minlen=*minnextp;
5644                         scan_commit(pRExC_state, &data_fake, minnextp, is_inf);
5645                         SvREFCNT_dec_NN(data_fake.last_found);
5646
5647                         if ( data_fake.minlen_fixed != minlenp )
5648                         {
5649                             data->offset_fixed= data_fake.offset_fixed;
5650                             data->minlen_fixed= data_fake.minlen_fixed;
5651                             data->lookbehind_fixed+= scan->flags;
5652                         }
5653                         if ( data_fake.minlen_float != minlenp )
5654                         {
5655                             data->minlen_float= data_fake.minlen_float;
5656                             data->offset_float_min=data_fake.offset_float_min;
5657                             data->offset_float_max=data_fake.offset_float_max;
5658                             data->lookbehind_float+= scan->flags;
5659                         }
5660                     }
5661                 }
5662             }
5663 #endif
5664         }
5665         else if (OP(scan) == OPEN) {
5666             if (stopparen != (I32)ARG(scan))
5667                 pars++;
5668         }
5669         else if (OP(scan) == CLOSE) {
5670             if (stopparen == (I32)ARG(scan)) {
5671                 break;
5672             }
5673             if ((I32)ARG(scan) == is_par) {
5674                 next = regnext(scan);
5675
5676                 if ( next && (OP(next) != WHILEM) && next < last)
5677                     is_par = 0;         /* Disable optimization */
5678             }
5679             if (data)
5680                 *(data->last_closep) = ARG(scan);
5681         }
5682         else if (OP(scan) == EVAL) {
5683                 if (data)
5684                     data->flags |= SF_HAS_EVAL;
5685         }
5686         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
5687             if (flags & SCF_DO_SUBSTR) {
5688                 scan_commit(pRExC_state, data, minlenp, is_inf);
5689                 flags &= ~SCF_DO_SUBSTR;
5690             }
5691             if (data && OP(scan)==ACCEPT) {
5692                 data->flags |= SCF_SEEN_ACCEPT;
5693                 if (stopmin > min)
5694                     stopmin = min;
5695             }
5696         }
5697         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
5698         {
5699                 if (flags & SCF_DO_SUBSTR) {
5700                     scan_commit(pRExC_state, data, minlenp, is_inf);
5701                     data->longest = &(data->longest_float);
5702                 }
5703                 is_inf = is_inf_internal = 1;
5704                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
5705                     ssc_anything(data->start_class);
5706                 flags &= ~SCF_DO_STCLASS;
5707         }
5708         else if (OP(scan) == GPOS) {
5709             if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) &&
5710                 !(delta || is_inf || (data && data->pos_delta)))
5711             {
5712                 if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR))
5713                     RExC_rx->intflags |= PREGf_ANCH_GPOS;
5714                 if (RExC_rx->gofs < (STRLEN)min)
5715                     RExC_rx->gofs = min;
5716             } else {
5717                 RExC_rx->intflags |= PREGf_GPOS_FLOAT;
5718                 RExC_rx->gofs = 0;
5719             }
5720         }
5721 #ifdef TRIE_STUDY_OPT
5722 #ifdef FULL_TRIE_STUDY
5723         else if (PL_regkind[OP(scan)] == TRIE) {
5724             /* NOTE - There is similar code to this block above for handling
5725                BRANCH nodes on the initial study.  If you change stuff here
5726                check there too. */
5727             regnode *trie_node= scan;
5728             regnode *tail= regnext(scan);
5729             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
5730             SSize_t max1 = 0, min1 = SSize_t_MAX;
5731             regnode_ssc accum;
5732
5733             if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */
5734                 /* Cannot merge strings after this. */
5735                 scan_commit(pRExC_state, data, minlenp, is_inf);
5736             }
5737             if (flags & SCF_DO_STCLASS)
5738                 ssc_init_zero(pRExC_state, &accum);
5739
5740             if (!trie->jump) {
5741                 min1= trie->minlen;
5742                 max1= trie->maxlen;
5743             } else {
5744                 const regnode *nextbranch= NULL;
5745                 U32 word;
5746
5747                 for ( word=1 ; word <= trie->wordcount ; word++)
5748                 {
5749                     SSize_t deltanext=0, minnext=0, f = 0, fake;
5750                     regnode_ssc this_class;
5751
5752                     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
5753                     if (data) {
5754                         data_fake.whilem_c = data->whilem_c;
5755                         data_fake.last_closep = data->last_closep;
5756                     }
5757                     else
5758                         data_fake.last_closep = &fake;
5759                     data_fake.pos_delta = delta;
5760                     if (flags & SCF_DO_STCLASS) {
5761                         ssc_init(pRExC_state, &this_class);
5762                         data_fake.start_class = &this_class;
5763                         f = SCF_DO_STCLASS_AND;
5764                     }
5765                     if (flags & SCF_WHILEM_VISITED_POS)
5766                         f |= SCF_WHILEM_VISITED_POS;
5767
5768                     if (trie->jump[word]) {
5769                         if (!nextbranch)
5770                             nextbranch = trie_node + trie->jump[0];
5771                         scan= trie_node + trie->jump[word];
5772                         /* We go from the jump point to the branch that follows
5773                            it. Note this means we need the vestigal unused
5774                            branches even though they arent otherwise used. */
5775                         minnext = study_chunk(pRExC_state, &scan, minlenp,
5776                             &deltanext, (regnode *)nextbranch, &data_fake,
5777                             stopparen, recursed_depth, NULL, f,depth+1);
5778                     }
5779                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
5780                         nextbranch= regnext((regnode*)nextbranch);
5781
5782                     if (min1 > (SSize_t)(minnext + trie->minlen))
5783                         min1 = minnext + trie->minlen;
5784                     if (deltanext == SSize_t_MAX) {
5785                         is_inf = is_inf_internal = 1;
5786                         max1 = SSize_t_MAX;
5787                     } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen))
5788                         max1 = minnext + deltanext + trie->maxlen;
5789
5790                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
5791                         pars++;
5792                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
5793                         if ( stopmin > min + min1)
5794                             stopmin = min + min1;
5795                         flags &= ~SCF_DO_SUBSTR;
5796                         if (data)
5797                             data->flags |= SCF_SEEN_ACCEPT;
5798                     }
5799                     if (data) {
5800                         if (data_fake.flags & SF_HAS_EVAL)
5801                             data->flags |= SF_HAS_EVAL;
5802                         data->whilem_c = data_fake.whilem_c;
5803                     }
5804                     if (flags & SCF_DO_STCLASS)
5805                         ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class);
5806                 }
5807             }
5808             if (flags & SCF_DO_SUBSTR) {
5809                 data->pos_min += min1;
5810                 data->pos_delta += max1 - min1;
5811                 if (max1 != min1 || is_inf)
5812                     data->longest = &(data->longest_float);
5813             }
5814             min += min1;
5815             if (delta != SSize_t_MAX)
5816                 delta += max1 - min1;
5817             if (flags & SCF_DO_STCLASS_OR) {
5818                 ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum);
5819                 if (min1) {
5820                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5821                     flags &= ~SCF_DO_STCLASS;
5822                 }
5823             }
5824             else if (flags & SCF_DO_STCLASS_AND) {
5825                 if (min1) {
5826                     ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum);
5827                     flags &= ~SCF_DO_STCLASS;
5828                 }
5829                 else {
5830                     /* Switch to OR mode: cache the old value of
5831                      * data->start_class */
5832                     INIT_AND_WITHP;
5833                     StructCopy(data->start_class, and_withp, regnode_ssc);
5834                     flags &= ~SCF_DO_STCLASS_AND;
5835                     StructCopy(&accum, data->start_class, regnode_ssc);
5836                     flags |= SCF_DO_STCLASS_OR;
5837                 }
5838             }
5839             scan= tail;
5840             continue;
5841         }
5842 #else
5843         else if (PL_regkind[OP(scan)] == TRIE) {
5844             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
5845             U8*bang=NULL;
5846
5847             min += trie->minlen;
5848             delta += (trie->maxlen - trie->minlen);
5849             flags &= ~SCF_DO_STCLASS; /* xxx */
5850             if (flags & SCF_DO_SUBSTR) {
5851                 /* Cannot expect anything... */
5852                 scan_commit(pRExC_state, data, minlenp, is_inf);
5853                 data->pos_min += trie->minlen;
5854                 data->pos_delta += (trie->maxlen - trie->minlen);
5855                 if (trie->maxlen != trie->minlen)
5856                     data->longest = &(data->longest_float);
5857             }
5858             if (trie->jump) /* no more substrings -- for now /grr*/
5859                flags &= ~SCF_DO_SUBSTR;
5860         }
5861 #endif /* old or new */
5862 #endif /* TRIE_STUDY_OPT */
5863
5864         /* Else: zero-length, ignore. */
5865         scan = regnext(scan);
5866     }
5867     /* If we are exiting a recursion we can unset its recursed bit
5868      * and allow ourselves to enter it again - no danger of an
5869      * infinite loop there.
5870     if (stopparen > -1 && recursed) {
5871         DEBUG_STUDYDATA("unset:", data,depth);
5872         PAREN_UNSET( recursed, stopparen);
5873     }
5874     */
5875     if (frame) {
5876         depth = depth - 1;
5877
5878         DEBUG_STUDYDATA("frame-end:",data,depth);
5879         DEBUG_PEEP("fend", scan, depth);
5880
5881         /* restore previous context */
5882         last = frame->last_regnode;
5883         scan = frame->next_regnode;
5884         stopparen = frame->stopparen;
5885         recursed_depth = frame->prev_recursed_depth;
5886
5887         RExC_frame_last = frame->prev_frame;
5888         frame = frame->this_prev_frame;
5889         goto fake_study_recurse;
5890     }
5891
5892   finish:
5893     assert(!frame);
5894     DEBUG_STUDYDATA("pre-fin:",data,depth);
5895
5896     *scanp = scan;
5897     *deltap = is_inf_internal ? SSize_t_MAX : delta;
5898
5899     if (flags & SCF_DO_SUBSTR && is_inf)
5900         data->pos_delta = SSize_t_MAX - data->pos_min;
5901     if (is_par > (I32)U8_MAX)
5902         is_par = 0;
5903     if (is_par && pars==1 && data) {
5904         data->flags |= SF_IN_PAR;
5905         data->flags &= ~SF_HAS_PAR;
5906     }
5907     else if (pars && data) {
5908         data->flags |= SF_HAS_PAR;
5909         data->flags &= ~SF_IN_PAR;
5910     }
5911     if (flags & SCF_DO_STCLASS_OR)
5912         ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp);
5913     if (flags & SCF_TRIE_RESTUDY)
5914         data->flags |=  SCF_TRIE_RESTUDY;
5915
5916     DEBUG_STUDYDATA("post-fin:",data,depth);
5917
5918     {
5919         SSize_t final_minlen= min < stopmin ? min : stopmin;
5920
5921         if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) {
5922             if (final_minlen > SSize_t_MAX - delta)
5923                 RExC_maxlen = SSize_t_MAX;
5924             else if (RExC_maxlen < final_minlen + delta)
5925                 RExC_maxlen = final_minlen + delta;
5926         }
5927         return final_minlen;
5928     }
5929     NOT_REACHED; /* NOTREACHED */
5930 }
5931
5932 STATIC U32
5933 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n)
5934 {
5935     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
5936
5937     PERL_ARGS_ASSERT_ADD_DATA;
5938
5939     Renewc(RExC_rxi->data,
5940            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
5941            char, struct reg_data);
5942     if(count)
5943         Renew(RExC_rxi->data->what, count + n, U8);
5944     else
5945         Newx(RExC_rxi->data->what, n, U8);
5946     RExC_rxi->data->count = count + n;
5947     Copy(s, RExC_rxi->data->what + count, n, U8);
5948     return count;
5949 }
5950
5951 /*XXX: todo make this not included in a non debugging perl, but appears to be
5952  * used anyway there, in 'use re' */
5953 #ifndef PERL_IN_XSUB_RE
5954 void
5955 Perl_reginitcolors(pTHX)
5956 {
5957     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
5958     if (s) {
5959         char *t = savepv(s);
5960         int i = 0;
5961         PL_colors[0] = t;
5962         while (++i < 6) {
5963             t = strchr(t, '\t');
5964             if (t) {
5965                 *t = '\0';
5966                 PL_colors[i] = ++t;
5967             }
5968             else
5969                 PL_colors[i] = t = (char *)"";
5970         }
5971     } else {
5972         int i = 0;
5973         while (i < 6)
5974             PL_colors[i++] = (char *)"";
5975     }
5976     PL_colorset = 1;
5977 }
5978 #endif
5979
5980
5981 #ifdef TRIE_STUDY_OPT
5982 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething)            \
5983     STMT_START {                                            \
5984         if (                                                \
5985               (data.flags & SCF_TRIE_RESTUDY)               \
5986               && ! restudied++                              \
5987         ) {                                                 \
5988             dOsomething;                                    \
5989             goto reStudy;                                   \
5990         }                                                   \
5991     } STMT_END
5992 #else
5993 #define CHECK_RESTUDY_GOTO_butfirst
5994 #endif
5995
5996 /*
5997  * pregcomp - compile a regular expression into internal code
5998  *
5999  * Decides which engine's compiler to call based on the hint currently in
6000  * scope
6001  */
6002
6003 #ifndef PERL_IN_XSUB_RE
6004
6005 /* return the currently in-scope regex engine (or the default if none)  */
6006
6007 regexp_engine const *
6008 Perl_current_re_engine(pTHX)
6009 {
6010     if (IN_PERL_COMPILETIME) {
6011         HV * const table = GvHV(PL_hintgv);
6012         SV **ptr;
6013
6014         if (!table || !(PL_hints & HINT_LOCALIZE_HH))
6015             return &PL_core_reg_engine;
6016         ptr = hv_fetchs(table, "regcomp", FALSE);
6017         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
6018             return &PL_core_reg_engine;
6019         return INT2PTR(regexp_engine*,SvIV(*ptr));
6020     }
6021     else {
6022         SV *ptr;
6023         if (!PL_curcop->cop_hints_hash)
6024             return &PL_core_reg_engine;
6025         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
6026         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
6027             return &PL_core_reg_engine;
6028         return INT2PTR(regexp_engine*,SvIV(ptr));
6029     }
6030 }
6031
6032
6033 REGEXP *
6034 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
6035 {
6036     regexp_engine const *eng = current_re_engine();
6037     GET_RE_DEBUG_FLAGS_DECL;
6038
6039     PERL_ARGS_ASSERT_PREGCOMP;
6040
6041     /* Dispatch a request to compile a regexp to correct regexp engine. */
6042     DEBUG_COMPILE_r({
6043         PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
6044                         PTR2UV(eng));
6045     });
6046     return CALLREGCOMP_ENG(eng, pattern, flags);
6047 }
6048 #endif
6049
6050 /* public(ish) entry point for the perl core's own regex compiling code.
6051  * It's actually a wrapper for Perl_re_op_compile that only takes an SV
6052  * pattern rather than a list of OPs, and uses the internal engine rather
6053  * than the current one */
6054
6055 REGEXP *
6056 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
6057 {
6058     SV *pat = pattern; /* defeat constness! */
6059     PERL_ARGS_ASSERT_RE_COMPILE;
6060     return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
6061 #ifdef PERL_IN_XSUB_RE
6062                                 &my_reg_engine,
6063 #else
6064                                 &PL_core_reg_engine,
6065 #endif
6066                                 NULL, NULL, rx_flags, 0);
6067 }
6068
6069
6070 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
6071  * blocks, recalculate the indices. Update pat_p and plen_p in-place to
6072  * point to the realloced string and length.
6073  *
6074  * This is essentially a copy of Perl_bytes_to_utf8() with the code index
6075  * stuff added */
6076
6077 static void
6078 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
6079                     char **pat_p, STRLEN *plen_p, int num_code_blocks)
6080 {
6081     U8 *const src = (U8*)*pat_p;
6082     U8 *dst, *d;
6083     int n=0;
6084     STRLEN s = 0;
6085     bool do_end = 0;
6086     GET_RE_DEBUG_FLAGS_DECL;
6087
6088     DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
6089         "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
6090
6091     Newx(dst, *plen_p * 2 + 1, U8);
6092     d = dst;
6093
6094     while (s < *plen_p) {
6095         append_utf8_from_native_byte(src[s], &d);
6096         if (n < num_code_blocks) {
6097             if (!do_end && pRExC_state->code_blocks[n].start == s) {
6098                 pRExC_state->code_blocks[n].start = d - dst - 1;
6099                 assert(*(d - 1) == '(');
6100                 do_end = 1;
6101             }
6102             else if (do_end && pRExC_state->code_blocks[n].end == s) {
6103                 pRExC_state->code_blocks[n].end = d - dst - 1;
6104                 assert(*(d - 1) == ')');
6105                 do_end = 0;
6106                 n++;
6107             }
6108         }
6109         s++;
6110     }
6111     *d = '\0';
6112     *plen_p = d - dst;
6113     *pat_p = (char*) dst;
6114     SAVEFREEPV(*pat_p);
6115     RExC_orig_utf8 = RExC_utf8 = 1;
6116 }
6117
6118
6119
6120 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
6121  * while recording any code block indices, and handling overloading,
6122  * nested qr// objects etc.  If pat is null, it will allocate a new
6123  * string, or just return the first arg, if there's only one.
6124  *
6125  * Returns the malloced/updated pat.
6126  * patternp and pat_count is the array of SVs to be concatted;
6127  * oplist is the optional list of ops that generated the SVs;
6128  * recompile_p is a pointer to a boolean that will be set if
6129  *   the regex will need to be recompiled.
6130  * delim, if non-null is an SV that will be inserted between each element
6131  */
6132
6133 static SV*
6134 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
6135                 SV *pat, SV ** const patternp, int pat_count,
6136                 OP *oplist, bool *recompile_p, SV *delim)
6137 {
6138     SV **svp;
6139     int n = 0;
6140     bool use_delim = FALSE;
6141     bool alloced = FALSE;
6142
6143     /* if we know we have at least two args, create an empty string,
6144      * then concatenate args to that. For no args, return an empty string */
6145     if (!pat && pat_count != 1) {
6146         pat = newSVpvs("");
6147         SAVEFREESV(pat);
6148         alloced = TRUE;
6149     }
6150
6151     for (svp = patternp; svp < patternp + pat_count; svp++) {
6152         SV *sv;
6153         SV *rx  = NULL;
6154         STRLEN orig_patlen = 0;
6155         bool code = 0;
6156         SV *msv = use_delim ? delim : *svp;
6157         if (!msv) msv = &PL_sv_undef;
6158
6159         /* if we've got a delimiter, we go round the loop twice for each
6160          * svp slot (except the last), using the delimiter the second
6161          * time round */
6162         if (use_delim) {
6163             svp--;
6164             use_delim = FALSE;
6165         }
6166         else if (delim)
6167             use_delim = TRUE;
6168
6169         if (SvTYPE(msv) == SVt_PVAV) {
6170             /* we've encountered an interpolated array within
6171              * the pattern, e.g. /...@a..../. Expand the list of elements,
6172              * then recursively append elements.
6173              * The code in this block is based on S_pushav() */
6174
6175             AV *const av = (AV*)msv;
6176             const SSize_t maxarg = AvFILL(av) + 1;
6177             SV **array;
6178
6179             if (oplist) {
6180                 assert(oplist->op_type == OP_PADAV
6181                     || oplist->op_type == OP_RV2AV);
6182                 oplist = OpSIBLING(oplist);
6183             }
6184
6185             if (SvRMAGICAL(av)) {
6186                 SSize_t i;
6187
6188                 Newx(array, maxarg, SV*);
6189                 SAVEFREEPV(array);
6190                 for (i=0; i < maxarg; i++) {
6191                     SV ** const svp = av_fetch(av, i, FALSE);
6192                     array[i] = svp ? *svp : &PL_sv_undef;
6193                 }
6194             }
6195             else
6196                 array = AvARRAY(av);
6197
6198             pat = S_concat_pat(aTHX_ pRExC_state, pat,
6199                                 array, maxarg, NULL, recompile_p,
6200                                 /* $" */
6201                                 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
6202
6203             continue;
6204         }
6205
6206
6207         /* we make the assumption here that each op in the list of
6208          * op_siblings maps to one SV pushed onto the stack,
6209          * except for code blocks, with have both an OP_NULL and
6210          * and OP_CONST.
6211          * This allows us to match up the list of SVs against the
6212          * list of OPs to find the next code block.
6213          *
6214          * Note that       PUSHMARK PADSV PADSV ..
6215          * is optimised to
6216          *                 PADRANGE PADSV  PADSV  ..
6217          * so the alignment still works. */
6218
6219         if (oplist) {
6220             if (oplist->op_type == OP_NULL
6221                 && (oplist->op_flags & OPf_SPECIAL))
6222             {
6223                 assert(n < pRExC_state->num_code_blocks);
6224                 pRExC_state->code_blocks[n].start = pat ? SvCUR(pat) : 0;
6225                 pRExC_state->code_blocks[n].block = oplist;
6226                 pRExC_state->code_blocks[n].src_regex = NULL;
6227                 n++;
6228                 code = 1;
6229                 oplist = OpSIBLING(oplist); /* skip CONST */
6230                 assert(oplist);
6231             }
6232             oplist = OpSIBLING(oplist);;
6233         }
6234
6235         /* apply magic and QR overloading to arg */
6236
6237         SvGETMAGIC(msv);
6238         if (SvROK(msv) && SvAMAGIC(msv)) {
6239             SV *sv = AMG_CALLunary(msv, regexp_amg);
6240             if (sv) {
6241                 if (SvROK(sv))
6242                     sv = SvRV(sv);
6243                 if (SvTYPE(sv) != SVt_REGEXP)
6244                     Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
6245                 msv = sv;
6246             }
6247         }
6248
6249         /* try concatenation overload ... */
6250         if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
6251                 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
6252         {
6253             sv_setsv(pat, sv);
6254             /* overloading involved: all bets are off over literal
6255              * code. Pretend we haven't seen it */
6256             pRExC_state->num_code_blocks -= n;
6257             n = 0;
6258         }
6259         else  {
6260             /* ... or failing that, try "" overload */
6261             while (SvAMAGIC(msv)
6262                     && (sv = AMG_CALLunary(msv, string_amg))
6263                     && sv != msv
6264                     &&  !(   SvROK(msv)
6265                           && SvROK(sv)
6266                           && SvRV(msv) == SvRV(sv))
6267             ) {
6268                 msv = sv;
6269                 SvGETMAGIC(msv);
6270             }
6271             if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
6272                 msv = SvRV(msv);
6273
6274             if (pat) {
6275                 /* this is a partially unrolled
6276                  *     sv_catsv_nomg(pat, msv);
6277                  * that allows us to adjust code block indices if
6278                  * needed */
6279                 STRLEN dlen;
6280                 char *dst = SvPV_force_nomg(pat, dlen);
6281                 orig_patlen = dlen;
6282                 if (SvUTF8(msv) && !SvUTF8(pat)) {
6283                     S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
6284                     sv_setpvn(pat, dst, dlen);
6285                     SvUTF8_on(pat);
6286                 }
6287                 sv_catsv_nomg(pat, msv);
6288                 rx = msv;
6289             }
6290             else
6291                 pat = msv;
6292
6293             if (code)
6294                 pRExC_state->code_blocks[n-1].end = SvCUR(pat)-1;
6295         }
6296
6297         /* extract any code blocks within any embedded qr//'s */
6298         if (rx && SvTYPE(rx) == SVt_REGEXP
6299             && RX_ENGINE((REGEXP*)rx)->op_comp)
6300         {
6301
6302             RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
6303             if (ri->num_code_blocks) {
6304                 int i;
6305                 /* the presence of an embedded qr// with code means
6306                  * we should always recompile: the text of the
6307                  * qr// may not have changed, but it may be a
6308                  * different closure than last time */
6309                 *recompile_p = 1;
6310                 Renew(pRExC_state->code_blocks,
6311                     pRExC_state->num_code_blocks + ri->num_code_blocks,
6312                     struct reg_code_block);
6313                 pRExC_state->num_code_blocks += ri->num_code_blocks;
6314
6315                 for (i=0; i < ri->num_code_blocks; i++) {
6316                     struct reg_code_block *src, *dst;
6317                     STRLEN offset =  orig_patlen
6318                         + ReANY((REGEXP *)rx)->pre_prefix;
6319                     assert(n < pRExC_state->num_code_blocks);
6320                     src = &ri->code_blocks[i];
6321                     dst = &pRExC_state->code_blocks[n];
6322                     dst->start      = src->start + offset;
6323                     dst->end        = src->end   + offset;
6324                     dst->block      = src->block;
6325                     dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
6326                                             src->src_regex
6327                                                 ? src->src_regex
6328                                                 : (REGEXP*)rx);
6329                     n++;
6330                 }
6331             }
6332         }
6333     }
6334     /* avoid calling magic multiple times on a single element e.g. =~ $qr */
6335     if (alloced)
6336         SvSETMAGIC(pat);
6337
6338     return pat;
6339 }
6340
6341
6342
6343 /* see if there are any run-time code blocks in the pattern.
6344  * False positives are allowed */
6345
6346 static bool
6347 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6348                     char *pat, STRLEN plen)
6349 {
6350     int n = 0;
6351     STRLEN s;
6352     
6353     PERL_UNUSED_CONTEXT;
6354
6355     for (s = 0; s < plen; s++) {
6356         if (n < pRExC_state->num_code_blocks
6357             && s == pRExC_state->code_blocks[n].start)
6358         {
6359             s = pRExC_state->code_blocks[n].end;
6360             n++;
6361             continue;
6362         }
6363         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
6364          * positives here */
6365         if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
6366             (pat[s+2] == '{'
6367                 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
6368         )
6369             return 1;
6370     }
6371     return 0;
6372 }
6373
6374 /* Handle run-time code blocks. We will already have compiled any direct
6375  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
6376  * copy of it, but with any literal code blocks blanked out and
6377  * appropriate chars escaped; then feed it into
6378  *
6379  *    eval "qr'modified_pattern'"
6380  *
6381  * For example,
6382  *
6383  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
6384  *
6385  * becomes
6386  *
6387  *    qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
6388  *
6389  * After eval_sv()-ing that, grab any new code blocks from the returned qr
6390  * and merge them with any code blocks of the original regexp.
6391  *
6392  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
6393  * instead, just save the qr and return FALSE; this tells our caller that
6394  * the original pattern needs upgrading to utf8.
6395  */
6396
6397 static bool
6398 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
6399     char *pat, STRLEN plen)
6400 {
6401     SV *qr;
6402
6403     GET_RE_DEBUG_FLAGS_DECL;
6404
6405     if (pRExC_state->runtime_code_qr) {
6406         /* this is the second time we've been called; this should
6407          * only happen if the main pattern got upgraded to utf8
6408          * during compilation; re-use the qr we compiled first time
6409          * round (which should be utf8 too)
6410          */
6411         qr = pRExC_state->runtime_code_qr;
6412         pRExC_state->runtime_code_qr = NULL;
6413         assert(RExC_utf8 && SvUTF8(qr));
6414     }
6415     else {
6416         int n = 0;
6417         STRLEN s;
6418         char *p, *newpat;
6419         int newlen = plen + 6; /* allow for "qr''x\0" extra chars */
6420         SV *sv, *qr_ref;
6421         dSP;
6422
6423         /* determine how many extra chars we need for ' and \ escaping */
6424         for (s = 0; s < plen; s++) {
6425             if (pat[s] == '\'' || pat[s] == '\\')
6426                 newlen++;
6427         }
6428
6429         Newx(newpat, newlen, char);
6430         p = newpat;
6431         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
6432
6433         for (s = 0; s < plen; s++) {
6434             if (n < pRExC_state->num_code_blocks
6435                 && s == pRExC_state->code_blocks[n].start)
6436             {
6437                 /* blank out literal code block */
6438                 assert(pat[s] == '(');
6439                 while (s <= pRExC_state->code_blocks[n].end) {
6440                     *p++ = '_';
6441                     s++;
6442                 }
6443                 s--;
6444                 n++;
6445                 continue;
6446             }
6447             if (pat[s] == '\'' || pat[s] == '\\')
6448                 *p++ = '\\';
6449             *p++ = pat[s];
6450         }
6451         *p++ = '\'';
6452         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED)
6453             *p++ = 'x';
6454         *p++ = '\0';
6455         DEBUG_COMPILE_r({
6456             PerlIO_printf(Perl_debug_log,
6457                 "%sre-parsing pattern for runtime code:%s %s\n",
6458                 PL_colors[4],PL_colors[5],newpat);
6459         });
6460
6461         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
6462         Safefree(newpat);
6463
6464         ENTER;
6465         SAVETMPS;
6466         save_re_context();
6467         PUSHSTACKi(PERLSI_REQUIRE);
6468         /* G_RE_REPARSING causes the toker to collapse \\ into \ when
6469          * parsing qr''; normally only q'' does this. It also alters
6470          * hints handling */
6471         eval_sv(sv, G_SCALAR|G_RE_REPARSING);
6472         SvREFCNT_dec_NN(sv);
6473         SPAGAIN;
6474         qr_ref = POPs;
6475         PUTBACK;
6476         {
6477             SV * const errsv = ERRSV;
6478             if (SvTRUE_NN(errsv))
6479             {
6480                 Safefree(pRExC_state->code_blocks);
6481                 /* use croak_sv ? */
6482                 Perl_croak_nocontext("%"SVf, SVfARG(errsv));
6483             }
6484         }
6485         assert(SvROK(qr_ref));
6486         qr = SvRV(qr_ref);
6487         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
6488         /* the leaving below frees the tmp qr_ref.
6489          * Give qr a life of its own */
6490         SvREFCNT_inc(qr);
6491         POPSTACK;
6492         FREETMPS;
6493         LEAVE;
6494
6495     }
6496
6497     if (!RExC_utf8 && SvUTF8(qr)) {
6498         /* first time through; the pattern got upgraded; save the
6499          * qr for the next time through */
6500         assert(!pRExC_state->runtime_code_qr);
6501         pRExC_state->runtime_code_qr = qr;
6502         return 0;
6503     }
6504
6505
6506     /* extract any code blocks within the returned qr//  */
6507
6508
6509     /* merge the main (r1) and run-time (r2) code blocks into one */
6510     {
6511         RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
6512         struct reg_code_block *new_block, *dst;
6513         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
6514         int i1 = 0, i2 = 0;
6515
6516         if (!r2->num_code_blocks) /* we guessed wrong */
6517         {
6518             SvREFCNT_dec_NN(qr);
6519             return 1;
6520         }
6521
6522         Newx(new_block,
6523             r1->num_code_blocks + r2->num_code_blocks,
6524             struct reg_code_block);
6525         dst = new_block;
6526
6527         while (    i1 < r1->num_code_blocks
6528                 || i2 < r2->num_code_blocks)
6529         {
6530             struct reg_code_block *src;
6531             bool is_qr = 0;
6532
6533             if (i1 == r1->num_code_blocks) {
6534                 src = &r2->code_blocks[i2++];
6535                 is_qr = 1;
6536             }
6537             else if (i2 == r2->num_code_blocks)
6538                 src = &r1->code_blocks[i1++];
6539             else if (  r1->code_blocks[i1].start
6540                      < r2->code_blocks[i2].start)
6541             {
6542                 src = &r1->code_blocks[i1++];
6543                 assert(src->end < r2->code_blocks[i2].start);
6544             }
6545             else {
6546                 assert(  r1->code_blocks[i1].start
6547                        > r2->code_blocks[i2].start);
6548                 src = &r2->code_blocks[i2++];
6549                 is_qr = 1;
6550                 assert(src->end < r1->code_blocks[i1].start);
6551             }
6552
6553             assert(pat[src->start] == '(');
6554             assert(pat[src->end]   == ')');
6555             dst->start      = src->start;
6556             dst->end        = src->end;
6557             dst->block      = src->block;
6558             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
6559                                     : src->src_regex;
6560             dst++;
6561         }
6562         r1->num_code_blocks += r2->num_code_blocks;
6563         Safefree(r1->code_blocks);
6564         r1->code_blocks = new_block;
6565     }
6566
6567     SvREFCNT_dec_NN(qr);
6568     return 1;
6569 }
6570
6571
6572 STATIC bool
6573 S_setup_longest(pTHX_ RExC_state_t *pRExC_state, SV* sv_longest,
6574                       SV** rx_utf8, SV** rx_substr, SSize_t* rx_end_shift,
6575                       SSize_t lookbehind, SSize_t offset, SSize_t *minlen,
6576                       STRLEN longest_length, bool eol, bool meol)
6577 {
6578     /* This is the common code for setting up the floating and fixed length
6579      * string data extracted from Perl_re_op_compile() below.  Returns a boolean
6580      * as to whether succeeded or not */
6581
6582     I32 t;
6583     SSize_t ml;
6584
6585     if (! (longest_length
6586            || (eol /* Can't have SEOL and MULTI */
6587                && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
6588           )
6589             /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */
6590         || (RExC_seen & REG_UNFOLDED_MULTI_SEEN))
6591     {
6592         return FALSE;
6593     }
6594
6595     /* copy the information about the longest from the reg_scan_data
6596         over to the program. */
6597     if (SvUTF8(sv_longest)) {
6598         *rx_utf8 = sv_longest;
6599         *rx_substr = NULL;
6600     } else {
6601         *rx_substr = sv_longest;
6602         *rx_utf8 = NULL;
6603     }
6604     /* end_shift is how many chars that must be matched that
6605         follow this item. We calculate it ahead of time as once the
6606         lookbehind offset is added in we lose the ability to correctly
6607         calculate it.*/
6608     ml = minlen ? *(minlen) : (SSize_t)longest_length;
6609     *rx_end_shift = ml - offset
6610         - longest_length + (SvTAIL(sv_longest) != 0)
6611         + lookbehind;
6612
6613     t = (eol/* Can't have SEOL and MULTI */
6614          && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
6615     fbm_compile(sv_longest, t ? FBMcf_TAIL : 0);
6616
6617     return TRUE;
6618 }
6619
6620 /*
6621  * Perl_re_op_compile - the perl internal RE engine's function to compile a
6622  * regular expression into internal code.
6623  * The pattern may be passed either as:
6624  *    a list of SVs (patternp plus pat_count)
6625  *    a list of OPs (expr)
6626  * If both are passed, the SV list is used, but the OP list indicates
6627  * which SVs are actually pre-compiled code blocks
6628  *
6629  * The SVs in the list have magic and qr overloading applied to them (and
6630  * the list may be modified in-place with replacement SVs in the latter
6631  * case).
6632  *
6633  * If the pattern hasn't changed from old_re, then old_re will be
6634  * returned.
6635  *
6636  * eng is the current engine. If that engine has an op_comp method, then
6637  * handle directly (i.e. we assume that op_comp was us); otherwise, just
6638  * do the initial concatenation of arguments and pass on to the external
6639  * engine.
6640  *
6641  * If is_bare_re is not null, set it to a boolean indicating whether the
6642  * arg list reduced (after overloading) to a single bare regex which has
6643  * been returned (i.e. /$qr/).
6644  *
6645  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
6646  *
6647  * pm_flags contains the PMf_* flags, typically based on those from the
6648  * pm_flags field of the related PMOP. Currently we're only interested in
6649  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
6650  *
6651  * We can't allocate space until we know how big the compiled form will be,
6652  * but we can't compile it (and thus know how big it is) until we've got a
6653  * place to put the code.  So we cheat:  we compile it twice, once with code
6654  * generation turned off and size counting turned on, and once "for real".
6655  * This also means that we don't allocate space until we are sure that the
6656  * thing really will compile successfully, and we never have to move the
6657  * code and thus invalidate pointers into it.  (Note that it has to be in
6658  * one piece because free() must be able to free it all.) [NB: not true in perl]
6659  *
6660  * Beware that the optimization-preparation code in here knows about some
6661  * of the structure of the compiled regexp.  [I'll say.]
6662  */
6663
6664 REGEXP *
6665 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
6666                     OP *expr, const regexp_engine* eng, REGEXP *old_re,
6667                      bool *is_bare_re, U32 orig_rx_flags, U32 pm_flags)
6668 {
6669     REGEXP *rx;
6670     struct regexp *r;
6671     regexp_internal *ri;
6672     STRLEN plen;
6673     char *exp;
6674     regnode *scan;
6675     I32 flags;
6676     SSize_t minlen = 0;
6677     U32 rx_flags;
6678     SV *pat;
6679     SV *code_blocksv = NULL;
6680     SV** new_patternp = patternp;
6681
6682     /* these are all flags - maybe they should be turned
6683      * into a single int with different bit masks */
6684     I32 sawlookahead = 0;
6685     I32 sawplus = 0;
6686     I32 sawopen = 0;
6687     I32 sawminmod = 0;
6688
6689     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
6690     bool recompile = 0;
6691     bool runtime_code = 0;
6692     scan_data_t data;
6693     RExC_state_t RExC_state;
6694     RExC_state_t * const pRExC_state = &RExC_state;
6695 #ifdef TRIE_STUDY_OPT
6696     int restudied = 0;
6697     RExC_state_t copyRExC_state;
6698 #endif
6699     GET_RE_DEBUG_FLAGS_DECL;
6700
6701     PERL_ARGS_ASSERT_RE_OP_COMPILE;
6702
6703     DEBUG_r(if (!PL_colorset) reginitcolors());
6704
6705     /* Initialize these here instead of as-needed, as is quick and avoids
6706      * having to test them each time otherwise */
6707     if (! PL_AboveLatin1) {
6708         PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
6709         PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
6710         PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist);
6711         PL_utf8_foldable = _new_invlist_C_array(_Perl_Any_Folds_invlist);
6712         PL_HasMultiCharFold =
6713                        _new_invlist_C_array(_Perl_Folds_To_Multi_Char_invlist);
6714
6715         /* This is calculated here, because the Perl program that generates the
6716          * static global ones doesn't currently have access to
6717          * NUM_ANYOF_CODE_POINTS */
6718         PL_InBitmap = _new_invlist(2);
6719         PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0,
6720                                                     NUM_ANYOF_CODE_POINTS - 1);
6721     }
6722
6723     pRExC_state->code_blocks = NULL;
6724     pRExC_state->num_code_blocks = 0;
6725
6726     if (is_bare_re)
6727         *is_bare_re = FALSE;
6728
6729     if (expr && (expr->op_type == OP_LIST ||
6730                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
6731         /* allocate code_blocks if needed */
6732         OP *o;
6733         int ncode = 0;
6734
6735         for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o))
6736             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
6737                 ncode++; /* count of DO blocks */
6738         if (ncode) {
6739             pRExC_state->num_code_blocks = ncode;
6740             Newx(pRExC_state->code_blocks, ncode, struct reg_code_block);
6741         }
6742     }
6743
6744     if (!pat_count) {
6745         /* compile-time pattern with just OP_CONSTs and DO blocks */
6746
6747         int n;
6748         OP *o;
6749
6750         /* find how many CONSTs there are */
6751         assert(expr);
6752         n = 0;
6753         if (expr->op_type == OP_CONST)
6754             n = 1;
6755         else
6756             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
6757                 if (o->op_type == OP_CONST)
6758                     n++;
6759             }
6760
6761         /* fake up an SV array */
6762
6763         assert(!new_patternp);
6764         Newx(new_patternp, n, SV*);
6765         SAVEFREEPV(new_patternp);
6766         pat_count = n;
6767
6768         n = 0;
6769         if (expr->op_type == OP_CONST)
6770             new_patternp[n] = cSVOPx_sv(expr);
6771         else
6772             for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) {
6773                 if (o->op_type == OP_CONST)
6774                     new_patternp[n++] = cSVOPo_sv;
6775             }
6776
6777     }
6778
6779     DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
6780         "Assembling pattern from %d elements%s\n", pat_count,
6781             orig_rx_flags & RXf_SPLIT ? " for split" : ""));
6782
6783     /* set expr to the first arg op */
6784
6785     if (pRExC_state->num_code_blocks
6786          && expr->op_type != OP_CONST)
6787     {
6788             expr = cLISTOPx(expr)->op_first;
6789             assert(   expr->op_type == OP_PUSHMARK
6790                    || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
6791                    || expr->op_type == OP_PADRANGE);
6792             expr = OpSIBLING(expr);
6793     }
6794
6795     pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
6796                         expr, &recompile, NULL);
6797
6798     /* handle bare (possibly after overloading) regex: foo =~ $re */
6799     {
6800         SV *re = pat;
6801         if (SvROK(re))
6802             re = SvRV(re);
6803         if (SvTYPE(re) == SVt_REGEXP) {
6804             if (is_bare_re)
6805                 *is_bare_re = TRUE;
6806             SvREFCNT_inc(re);
6807             Safefree(pRExC_state->code_blocks);
6808             DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
6809                 "Precompiled pattern%s\n",
6810                     orig_rx_flags & RXf_SPLIT ? " for split" : ""));
6811
6812             return (REGEXP*)re;
6813         }
6814     }
6815
6816     exp = SvPV_nomg(pat, plen);
6817
6818     if (!eng->op_comp) {
6819         if ((SvUTF8(pat) && IN_BYTES)
6820                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
6821         {
6822             /* make a temporary copy; either to convert to bytes,
6823              * or to avoid repeating get-magic / overloaded stringify */
6824             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
6825                                         (IN_BYTES ? 0 : SvUTF8(pat)));
6826         }
6827         Safefree(pRExC_state->code_blocks);
6828         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
6829     }
6830
6831     /* ignore the utf8ness if the pattern is 0 length */
6832     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
6833
6834     RExC_uni_semantics = 0;
6835     RExC_seen_unfolded_sharp_s = 0;
6836     RExC_contains_locale = 0;
6837     RExC_contains_i = 0;
6838     RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT);
6839     pRExC_state->runtime_code_qr = NULL;
6840     RExC_frame_head= NULL;
6841     RExC_frame_last= NULL;
6842     RExC_frame_count= 0;
6843
6844     DEBUG_r({
6845         RExC_mysv1= sv_newmortal();
6846         RExC_mysv2= sv_newmortal();
6847     });
6848     DEBUG_COMPILE_r({
6849             SV *dsv= sv_newmortal();
6850             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, 60);
6851             PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
6852                           PL_colors[4],PL_colors[5],s);
6853         });
6854
6855   redo_first_pass:
6856     /* we jump here if we have to recompile, e.g., from upgrading the pattern
6857      * to utf8 */
6858
6859     if ((pm_flags & PMf_USE_RE_EVAL)
6860                 /* this second condition covers the non-regex literal case,
6861                  * i.e.  $foo =~ '(?{})'. */
6862                 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
6863     )
6864         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
6865
6866     /* return old regex if pattern hasn't changed */
6867     /* XXX: note in the below we have to check the flags as well as the
6868      * pattern.
6869      *
6870      * Things get a touch tricky as we have to compare the utf8 flag
6871      * independently from the compile flags.  */
6872
6873     if (   old_re
6874         && !recompile
6875         && !!RX_UTF8(old_re) == !!RExC_utf8
6876         && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
6877         && RX_PRECOMP(old_re)
6878         && RX_PRELEN(old_re) == plen
6879         && memEQ(RX_PRECOMP(old_re), exp, plen)
6880         && !runtime_code /* with runtime code, always recompile */ )
6881     {
6882         Safefree(pRExC_state->code_blocks);
6883         return old_re;
6884     }
6885
6886     rx_flags = orig_rx_flags;
6887
6888     if (rx_flags & PMf_FOLD) {
6889         RExC_contains_i = 1;
6890     }
6891     if (   initial_charset == REGEX_DEPENDS_CHARSET
6892         && (RExC_utf8 ||RExC_uni_semantics))
6893     {
6894
6895         /* Set to use unicode semantics if the pattern is in utf8 and has the
6896          * 'depends' charset specified, as it means unicode when utf8  */
6897         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
6898     }
6899
6900     RExC_precomp = exp;
6901     RExC_precomp_adj = 0;
6902     RExC_flags = rx_flags;
6903     RExC_pm_flags = pm_flags;
6904
6905     if (runtime_code) {
6906         assert(TAINTING_get || !TAINT_get);
6907         if (TAINT_get)
6908             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
6909
6910         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
6911             /* whoops, we have a non-utf8 pattern, whilst run-time code
6912              * got compiled as utf8. Try again with a utf8 pattern */
6913             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
6914                                     pRExC_state->num_code_blocks);
6915             goto redo_first_pass;
6916         }
6917     }
6918     assert(!pRExC_state->runtime_code_qr);
6919
6920     RExC_sawback = 0;
6921
6922     RExC_seen = 0;
6923     RExC_maxlen = 0;
6924     RExC_in_lookbehind = 0;
6925     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
6926     RExC_extralen = 0;
6927     RExC_override_recoding = 0;
6928 #ifdef EBCDIC
6929     RExC_recode_x_to_native = 0;
6930 #endif
6931     RExC_in_multi_char_class = 0;
6932
6933     /* First pass: determine size, legality. */
6934     RExC_parse = exp;
6935     RExC_start = RExC_adjusted_start = exp;
6936     RExC_end = exp + plen;
6937     RExC_precomp_end = RExC_end;
6938     RExC_naughty = 0;
6939     RExC_npar = 1;
6940     RExC_nestroot = 0;
6941     RExC_size = 0L;
6942     RExC_emit = (regnode *) &RExC_emit_dummy;
6943     RExC_whilem_seen = 0;
6944     RExC_open_parens = NULL;
6945     RExC_close_parens = NULL;
6946     RExC_opend = NULL;
6947     RExC_paren_names = NULL;
6948 #ifdef DEBUGGING
6949     RExC_paren_name_list = NULL;
6950 #endif
6951     RExC_recurse = NULL;
6952     RExC_study_chunk_recursed = NULL;
6953     RExC_study_chunk_recursed_bytes= 0;
6954     RExC_recurse_count = 0;
6955     pRExC_state->code_index = 0;
6956
6957     /* This NUL is guaranteed because the pattern comes from an SV*, and the sv
6958      * code makes sure the final byte is an uncounted NUL.  But should this
6959      * ever not be the case, lots of things could read beyond the end of the
6960      * buffer: loops like
6961      *      while(isFOO(*RExC_parse)) RExC_parse++;
6962      *      strchr(RExC_parse, "foo");
6963      * etc.  So it is worth noting. */
6964     assert(*RExC_end == '\0');
6965
6966     DEBUG_PARSE_r(
6967         PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n");
6968         RExC_lastnum=0;
6969         RExC_lastparse=NULL;
6970     );
6971     /* reg may croak on us, not giving us a chance to free
6972        pRExC_state->code_blocks.  We cannot SAVEFREEPV it now, as we may
6973        need it to survive as long as the regexp (qr/(?{})/).
6974        We must check that code_blocksv is not already set, because we may
6975        have jumped back to restart the sizing pass. */
6976     if (pRExC_state->code_blocks && !code_blocksv) {
6977         code_blocksv = newSV_type(SVt_PV);
6978         SAVEFREESV(code_blocksv);
6979         SvPV_set(code_blocksv, (char *)pRExC_state->code_blocks);
6980         SvLEN_set(code_blocksv, 1); /*sufficient to make sv_clear free it*/
6981     }
6982     if (reg(pRExC_state, 0, &flags,1) == NULL) {
6983         /* It's possible to write a regexp in ascii that represents Unicode
6984         codepoints outside of the byte range, such as via \x{100}. If we
6985         detect such a sequence we have to convert the entire pattern to utf8
6986         and then recompile, as our sizing calculation will have been based
6987         on 1 byte == 1 character, but we will need to use utf8 to encode
6988         at least some part of the pattern, and therefore must convert the whole
6989         thing.
6990         -- dmq */
6991         if (flags & RESTART_PASS1) {
6992             if (flags & NEED_UTF8) {
6993                 S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
6994                                     pRExC_state->num_code_blocks);
6995             }
6996             else {
6997                 DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
6998                 "Need to redo pass 1\n"));
6999             }
7000
7001             goto redo_first_pass;
7002         }
7003         Perl_croak(aTHX_ "panic: reg returned NULL to re_op_compile for sizing pass, flags=%#"UVxf"", (UV) flags);
7004     }
7005     if (code_blocksv)
7006         SvLEN_set(code_blocksv,0); /* no you can't have it, sv_clear */
7007
7008     DEBUG_PARSE_r({
7009         PerlIO_printf(Perl_debug_log,
7010             "Required size %"IVdf" nodes\n"
7011             "Starting second pass (creation)\n",
7012             (IV)RExC_size);
7013         RExC_lastnum=0;
7014         RExC_lastparse=NULL;
7015     });
7016
7017     /* The first pass could have found things that force Unicode semantics */
7018     if ((RExC_utf8 || RExC_uni_semantics)
7019          && get_regex_charset(rx_flags) == REGEX_DEPENDS_CHARSET)
7020     {
7021         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
7022     }
7023
7024     /* Small enough for pointer-storage convention?
7025        If extralen==0, this means that we will not need long jumps. */
7026     if (RExC_size >= 0x10000L && RExC_extralen)
7027         RExC_size += RExC_extralen;
7028     else
7029         RExC_extralen = 0;
7030     if (RExC_whilem_seen > 15)
7031         RExC_whilem_seen = 15;
7032
7033     /* Allocate space and zero-initialize. Note, the two step process
7034        of zeroing when in debug mode, thus anything assigned has to
7035        happen after that */
7036     rx = (REGEXP*) newSV_type(SVt_REGEXP);
7037     r = ReANY(rx);
7038     Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
7039          char, regexp_internal);
7040     if ( r == NULL || ri == NULL )
7041         FAIL("Regexp out of space");
7042 #ifdef DEBUGGING
7043     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
7044     Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
7045          char);
7046 #else
7047     /* bulk initialize base fields with 0. */
7048     Zero(ri, sizeof(regexp_internal), char);
7049 #endif
7050
7051     /* non-zero initialization begins here */
7052     RXi_SET( r, ri );
7053     r->engine= eng;
7054     r->extflags = rx_flags;
7055     RXp_COMPFLAGS(r) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
7056
7057     if (pm_flags & PMf_IS_QR) {
7058         ri->code_blocks = pRExC_state->code_blocks;
7059         ri->num_code_blocks = pRExC_state->num_code_blocks;
7060     }
7061     else
7062     {
7063         int n;
7064         for (n = 0; n < pRExC_state->num_code_blocks; n++)
7065             if (pRExC_state->code_blocks[n].src_regex)
7066                 SAVEFREESV(pRExC_state->code_blocks[n].src_regex);
7067         if(pRExC_state->code_blocks)
7068             SAVEFREEPV(pRExC_state->code_blocks); /* often null */
7069     }
7070
7071     {
7072         bool has_p     = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
7073         bool has_charset = (get_regex_charset(r->extflags)
7074                                                     != REGEX_DEPENDS_CHARSET);
7075
7076         /* The caret is output if there are any defaults: if not all the STD
7077          * flags are set, or if no character set specifier is needed */
7078         bool has_default =
7079                     (((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
7080                     || ! has_charset);
7081         bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN)
7082                                                    == REG_RUN_ON_COMMENT_SEEN);
7083         U8 reganch = (U8)((r->extflags & RXf_PMf_STD_PMMOD)
7084                             >> RXf_PMf_STD_PMMOD_SHIFT);
7085         const char *fptr = STD_PAT_MODS;        /*"msixn"*/
7086         char *p;
7087
7088         /* We output all the necessary flags; we never output a minus, as all
7089          * those are defaults, so are
7090          * covered by the caret */
7091         const STRLEN wraplen = plen + has_p + has_runon
7092             + has_default       /* If needs a caret */
7093             + PL_bitcount[reganch] /* 1 char for each set standard flag */
7094
7095                 /* If needs a character set specifier */
7096             + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
7097             + (sizeof("(?:)") - 1);
7098
7099         /* make sure PL_bitcount bounds not exceeded */
7100         assert(sizeof(STD_PAT_MODS) <= 8);
7101
7102         Newx(p, wraplen + 1, char); /* +1 for the ending NUL */
7103         r->xpv_len_u.xpvlenu_pv = p;
7104         if (RExC_utf8)
7105             SvFLAGS(rx) |= SVf_UTF8;
7106         *p++='('; *p++='?';
7107
7108         /* If a default, cover it using the caret */
7109         if (has_default) {
7110             *p++= DEFAULT_PAT_MOD;
7111         }
7112         if (has_charset) {
7113             STRLEN len;
7114             const char* const name = get_regex_charset_name(r->extflags, &len);
7115             Copy(name, p, len, char);
7116             p += len;
7117         }
7118         if (has_p)
7119             *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
7120         {
7121             char ch;
7122             while((ch = *fptr++)) {
7123                 if(reganch & 1)
7124                     *p++ = ch;
7125                 reganch >>= 1;
7126             }
7127         }
7128
7129         *p++ = ':';
7130         Copy(RExC_precomp, p, plen, char);
7131         assert ((RX_WRAPPED(rx) - p) < 16);
7132         r->pre_prefix = p - RX_WRAPPED(rx);
7133         p += plen;
7134         if (has_runon)
7135             *p++ = '\n';
7136         *p++ = ')';
7137         *p = 0;
7138         SvCUR_set(rx, p - RX_WRAPPED(rx));
7139     }
7140
7141     r->intflags = 0;
7142     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
7143
7144     /* setup various meta data about recursion, this all requires
7145      * RExC_npar to be correctly set, and a bit later on we clear it */
7146     if (RExC_seen & REG_RECURSE_SEEN) {
7147         Newxz(RExC_open_parens, RExC_npar,regnode *);
7148         SAVEFREEPV(RExC_open_parens);
7149         Newxz(RExC_close_parens,RExC_npar,regnode *);
7150         SAVEFREEPV(RExC_close_parens);
7151     }
7152     if (RExC_seen & (REG_RECURSE_SEEN | REG_GOSTART_SEEN)) {
7153         /* Note, RExC_npar is 1 + the number of parens in a pattern.
7154          * So its 1 if there are no parens. */
7155         RExC_study_chunk_recursed_bytes= (RExC_npar >> 3) +
7156                                          ((RExC_npar & 0x07) != 0);
7157         Newx(RExC_study_chunk_recursed,
7158              RExC_study_chunk_recursed_bytes * RExC_npar, U8);
7159         SAVEFREEPV(RExC_study_chunk_recursed);
7160     }
7161
7162     /* Useful during FAIL. */
7163 #ifdef RE_TRACK_PATTERN_OFFSETS
7164     Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
7165     DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
7166                           "%s %"UVuf" bytes for offset annotations.\n",
7167                           ri->u.offsets ? "Got" : "Couldn't get",
7168                           (UV)((2*RExC_size+1) * sizeof(U32))));
7169 #endif
7170     SetProgLen(ri,RExC_size);
7171     RExC_rx_sv = rx;
7172     RExC_rx = r;
7173     RExC_rxi = ri;
7174
7175     /* Second pass: emit code. */
7176     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
7177     RExC_pm_flags = pm_flags;
7178     RExC_parse = exp;
7179     RExC_end = exp + plen;
7180     RExC_naughty = 0;
7181     RExC_npar = 1;
7182     RExC_emit_start = ri->program;
7183     RExC_emit = ri->program;
7184     RExC_emit_bound = ri->program + RExC_size + 1;
7185     pRExC_state->code_index = 0;
7186
7187     *((char*) RExC_emit++) = (char) REG_MAGIC;
7188     if (reg(pRExC_state, 0, &flags,1) == NULL) {
7189         ReREFCNT_dec(rx);
7190         Perl_croak(aTHX_ "panic: reg returned NULL to re_op_compile for generation pass, flags=%#"UVxf"", (UV) flags);
7191     }
7192     /* XXXX To minimize changes to RE engine we always allocate
7193        3-units-long substrs field. */
7194     Newx(r->substrs, 1, struct reg_substr_data);
7195     if (RExC_recurse_count) {
7196         Newxz(RExC_recurse,RExC_recurse_count,regnode *);
7197         SAVEFREEPV(RExC_recurse);
7198     }
7199
7200   reStudy:
7201     r->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
7202     DEBUG_r(
7203         RExC_study_chunk_recursed_count= 0;
7204     );
7205     Zero(r->substrs, 1, struct reg_substr_data);
7206     if (RExC_study_chunk_recursed) {
7207         Zero(RExC_study_chunk_recursed,
7208              RExC_study_chunk_recursed_bytes * RExC_npar, U8);
7209     }
7210
7211
7212 #ifdef TRIE_STUDY_OPT
7213     if (!restudied) {
7214         StructCopy(&zero_scan_data, &data, scan_data_t);
7215         copyRExC_state = RExC_state;
7216     } else {
7217         U32 seen=RExC_seen;
7218         DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
7219
7220         RExC_state = copyRExC_state;
7221         if (seen & REG_TOP_LEVEL_BRANCHES_SEEN)
7222             RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
7223         else
7224             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN;
7225         StructCopy(&zero_scan_data, &data, scan_data_t);
7226     }
7227 #else
7228     StructCopy(&zero_scan_data, &data, scan_data_t);
7229 #endif
7230
7231     /* Dig out information for optimizations. */
7232     r->extflags = RExC_flags; /* was pm_op */
7233     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
7234
7235     if (UTF)
7236         SvUTF8_on(rx);  /* Unicode in it? */
7237     ri->regstclass = NULL;
7238     if (RExC_naughty >= TOO_NAUGHTY)    /* Probably an expensive pattern. */
7239         r->intflags |= PREGf_NAUGHTY;
7240     scan = ri->program + 1;             /* First BRANCH. */
7241
7242     /* testing for BRANCH here tells us whether there is "must appear"
7243        data in the pattern. If there is then we can use it for optimisations */
7244     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /*  Only one top-level choice.
7245                                                   */
7246         SSize_t fake;
7247         STRLEN longest_float_length, longest_fixed_length;
7248         regnode_ssc ch_class; /* pointed to by data */
7249         int stclass_flag;
7250         SSize_t last_close = 0; /* pointed to by data */
7251         regnode *first= scan;
7252         regnode *first_next= regnext(first);
7253         /*
7254          * Skip introductions and multiplicators >= 1
7255          * so that we can extract the 'meat' of the pattern that must
7256          * match in the large if() sequence following.
7257          * NOTE that EXACT is NOT covered here, as it is normally
7258          * picked up by the optimiser separately.
7259          *
7260          * This is unfortunate as the optimiser isnt handling lookahead
7261          * properly currently.
7262          *
7263          */
7264         while ((OP(first) == OPEN && (sawopen = 1)) ||
7265                /* An OR of *one* alternative - should not happen now. */
7266             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
7267             /* for now we can't handle lookbehind IFMATCH*/
7268             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
7269             (OP(first) == PLUS) ||
7270             (OP(first) == MINMOD) ||
7271                /* An {n,m} with n>0 */
7272             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
7273             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
7274         {
7275                 /*
7276                  * the only op that could be a regnode is PLUS, all the rest
7277                  * will be regnode_1 or regnode_2.
7278                  *
7279                  * (yves doesn't think this is true)
7280                  */
7281                 if (OP(first) == PLUS)
7282                     sawplus = 1;
7283                 else {
7284                     if (OP(first) == MINMOD)
7285                         sawminmod = 1;
7286                     first += regarglen[OP(first)];
7287                 }
7288                 first = NEXTOPER(first);
7289                 first_next= regnext(first);
7290         }
7291
7292         /* Starting-point info. */
7293       again:
7294         DEBUG_PEEP("first:",first,0);
7295         /* Ignore EXACT as we deal with it later. */
7296         if (PL_regkind[OP(first)] == EXACT) {
7297             if (OP(first) == EXACT || OP(first) == EXACTL)
7298                 NOOP;   /* Empty, get anchored substr later. */
7299             else
7300                 ri->regstclass = first;
7301         }
7302 #ifdef TRIE_STCLASS
7303         else if (PL_regkind[OP(first)] == TRIE &&
7304                 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0)
7305         {
7306             /* this can happen only on restudy */
7307             ri->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0);
7308         }
7309 #endif
7310         else if (REGNODE_SIMPLE(OP(first)))
7311             ri->regstclass = first;
7312         else if (PL_regkind[OP(first)] == BOUND ||
7313                  PL_regkind[OP(first)] == NBOUND)
7314             ri->regstclass = first;
7315         else if (PL_regkind[OP(first)] == BOL) {
7316             r->intflags |= (OP(first) == MBOL
7317                            ? PREGf_ANCH_MBOL
7318                            : PREGf_ANCH_SBOL);
7319             first = NEXTOPER(first);
7320             goto again;
7321         }
7322         else if (OP(first) == GPOS) {
7323             r->intflags |= PREGf_ANCH_GPOS;
7324             first = NEXTOPER(first);
7325             goto again;
7326         }
7327         else if ((!sawopen || !RExC_sawback) &&
7328             !sawlookahead &&
7329             (OP(first) == STAR &&
7330             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
7331             !(r->intflags & PREGf_ANCH) && !pRExC_state->num_code_blocks)
7332         {
7333             /* turn .* into ^.* with an implied $*=1 */
7334             const int type =
7335                 (OP(NEXTOPER(first)) == REG_ANY)
7336                     ? PREGf_ANCH_MBOL
7337                     : PREGf_ANCH_SBOL;
7338             r->intflags |= (type | PREGf_IMPLICIT);
7339             first = NEXTOPER(first);
7340             goto again;
7341         }
7342         if (sawplus && !sawminmod && !sawlookahead
7343             && (!sawopen || !RExC_sawback)
7344             && !pRExC_state->num_code_blocks) /* May examine pos and $& */
7345             /* x+ must match at the 1st pos of run of x's */
7346             r->intflags |= PREGf_SKIP;
7347
7348         /* Scan is after the zeroth branch, first is atomic matcher. */
7349 #ifdef TRIE_STUDY_OPT
7350         DEBUG_PARSE_r(
7351             if (!restudied)
7352                 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
7353                               (IV)(first - scan + 1))
7354         );
7355 #else
7356         DEBUG_PARSE_r(
7357             PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
7358                 (IV)(first - scan + 1))
7359         );
7360 #endif
7361
7362
7363         /*
7364         * If there's something expensive in the r.e., find the
7365         * longest literal string that must appear and make it the
7366         * regmust.  Resolve ties in favor of later strings, since
7367         * the regstart check works with the beginning of the r.e.
7368         * and avoiding duplication strengthens checking.  Not a
7369         * strong reason, but sufficient in the absence of others.
7370         * [Now we resolve ties in favor of the earlier string if
7371         * it happens that c_offset_min has been invalidated, since the
7372         * earlier string may buy us something the later one won't.]
7373         */
7374
7375         data.longest_fixed = newSVpvs("");
7376         data.longest_float = newSVpvs("");
7377         data.last_found = newSVpvs("");
7378         data.longest = &(data.longest_fixed);
7379         ENTER_with_name("study_chunk");
7380         SAVEFREESV(data.longest_fixed);
7381         SAVEFREESV(data.longest_float);
7382         SAVEFREESV(data.last_found);
7383         first = scan;
7384         if (!ri->regstclass) {
7385             ssc_init(pRExC_state, &ch_class);
7386             data.start_class = &ch_class;
7387             stclass_flag = SCF_DO_STCLASS_AND;
7388         } else                          /* XXXX Check for BOUND? */
7389             stclass_flag = 0;
7390         data.last_closep = &last_close;
7391
7392         DEBUG_RExC_seen();
7393         minlen = study_chunk(pRExC_state, &first, &minlen, &fake,
7394                              scan + RExC_size, /* Up to end */
7395             &data, -1, 0, NULL,
7396             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
7397                           | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
7398             0);
7399
7400
7401         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
7402
7403
7404         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
7405              && data.last_start_min == 0 && data.last_end > 0
7406              && !RExC_seen_zerolen
7407              && !(RExC_seen & REG_VERBARG_SEEN)
7408              && !(RExC_seen & REG_GPOS_SEEN)
7409         ){
7410             r->extflags |= RXf_CHECK_ALL;
7411         }
7412         scan_commit(pRExC_state, &data,&minlen,0);
7413
7414         longest_float_length = CHR_SVLEN(data.longest_float);
7415
7416         if (! ((SvCUR(data.longest_fixed)  /* ok to leave SvCUR */
7417                    && data.offset_fixed == data.offset_float_min
7418                    && SvCUR(data.longest_fixed) == SvCUR(data.longest_float)))
7419             && S_setup_longest (aTHX_ pRExC_state,
7420                                     data.longest_float,
7421                                     &(r->float_utf8),
7422                                     &(r->float_substr),
7423                                     &(r->float_end_shift),
7424                                     data.lookbehind_float,
7425                                     data.offset_float_min,
7426                                     data.minlen_float,
7427                                     longest_float_length,
7428                                     cBOOL(data.flags & SF_FL_BEFORE_EOL),
7429                                     cBOOL(data.flags & SF_FL_BEFORE_MEOL)))
7430         {
7431             r->float_min_offset = data.offset_float_min - data.lookbehind_float;
7432             r->float_max_offset = data.offset_float_max;
7433             if (data.offset_float_max < SSize_t_MAX) /* Don't offset infinity */
7434                 r->float_max_offset -= data.lookbehind_float;
7435             SvREFCNT_inc_simple_void_NN(data.longest_float);
7436         }
7437         else {
7438             r->float_substr = r->float_utf8 = NULL;
7439             longest_float_length = 0;
7440         }
7441
7442         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
7443
7444         if (S_setup_longest (aTHX_ pRExC_state,
7445                                 data.longest_fixed,
7446                                 &(r->anchored_utf8),
7447                                 &(r->anchored_substr),
7448                                 &(r->anchored_end_shift),
7449                                 data.lookbehind_fixed,
7450                                 data.offset_fixed,
7451                                 data.minlen_fixed,
7452                                 longest_fixed_length,
7453                                 cBOOL(data.flags & SF_FIX_BEFORE_EOL),
7454                                 cBOOL(data.flags & SF_FIX_BEFORE_MEOL)))
7455         {
7456             r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
7457             SvREFCNT_inc_simple_void_NN(data.longest_fixed);
7458         }
7459         else {
7460             r->anchored_substr = r->anchored_utf8 = NULL;
7461             longest_fixed_length = 0;
7462         }
7463         LEAVE_with_name("study_chunk");
7464
7465         if (ri->regstclass
7466             && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
7467             ri->regstclass = NULL;
7468
7469         if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
7470             && stclass_flag
7471             && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
7472             && is_ssc_worth_it(pRExC_state, data.start_class))
7473         {
7474             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
7475
7476             ssc_finalize(pRExC_state, data.start_class);
7477
7478             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
7479             StructCopy(data.start_class,
7480                        (regnode_ssc*)RExC_rxi->data->data[n],
7481                        regnode_ssc);
7482             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
7483             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
7484             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
7485                       regprop(r, sv, (regnode*)data.start_class, NULL, pRExC_state);
7486                       PerlIO_printf(Perl_debug_log,
7487                                     "synthetic stclass \"%s\".\n",
7488                                     SvPVX_const(sv));});
7489             data.start_class = NULL;
7490         }
7491
7492         /* A temporary algorithm prefers floated substr to fixed one to dig
7493          * more info. */
7494         if (longest_fixed_length > longest_float_length) {
7495             r->substrs->check_ix = 0;
7496             r->check_end_shift = r->anchored_end_shift;
7497             r->check_substr = r->anchored_substr;
7498             r->check_utf8 = r->anchored_utf8;
7499             r->check_offset_min = r->check_offset_max = r->anchored_offset;
7500             if (r->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))
7501                 r->intflags |= PREGf_NOSCAN;
7502         }
7503         else {
7504             r->substrs->check_ix = 1;
7505             r->check_end_shift = r->float_end_shift;
7506             r->check_substr = r->float_substr;
7507             r->check_utf8 = r->float_utf8;
7508             r->check_offset_min = r->float_min_offset;
7509             r->check_offset_max = r->float_max_offset;
7510         }
7511         if ((r->check_substr || r->check_utf8) ) {
7512             r->extflags |= RXf_USE_INTUIT;
7513             if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
7514                 r->extflags |= RXf_INTUIT_TAIL;
7515         }
7516         r->substrs->data[0].max_offset = r->substrs->data[0].min_offset;
7517
7518         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
7519         if ( (STRLEN)minlen < longest_float_length )
7520             minlen= longest_float_length;
7521         if ( (STRLEN)minlen < longest_fixed_length )
7522             minlen= longest_fixed_length;
7523         */
7524     }
7525     else {
7526         /* Several toplevels. Best we can is to set minlen. */
7527         SSize_t fake;
7528         regnode_ssc ch_class;
7529         SSize_t last_close = 0;
7530
7531         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
7532
7533         scan = ri->program + 1;
7534         ssc_init(pRExC_state, &ch_class);
7535         data.start_class = &ch_class;
7536         data.last_closep = &last_close;
7537
7538         DEBUG_RExC_seen();
7539         minlen = study_chunk(pRExC_state,
7540             &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL,
7541             SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
7542                                                       ? SCF_TRIE_DOING_RESTUDY
7543                                                       : 0),
7544             0);
7545
7546         CHECK_RESTUDY_GOTO_butfirst(NOOP);
7547
7548         r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
7549                 = r->float_substr = r->float_utf8 = NULL;
7550
7551         if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING)
7552             && is_ssc_worth_it(pRExC_state, data.start_class))
7553         {
7554             const U32 n = add_data(pRExC_state, STR_WITH_LEN("f"));
7555
7556             ssc_finalize(pRExC_state, data.start_class);
7557
7558             Newx(RExC_rxi->data->data[n], 1, regnode_ssc);
7559             StructCopy(data.start_class,
7560                        (regnode_ssc*)RExC_rxi->data->data[n],
7561                        regnode_ssc);
7562             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
7563             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
7564             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
7565                       regprop(r, sv, (regnode*)data.start_class, NULL, pRExC_state);
7566                       PerlIO_printf(Perl_debug_log,
7567                                     "synthetic stclass \"%s\".\n",
7568                                     SvPVX_const(sv));});
7569             data.start_class = NULL;
7570         }
7571     }
7572
7573     if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) {
7574         r->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN;
7575         r->maxlen = REG_INFTY;
7576     }
7577     else {
7578         r->maxlen = RExC_maxlen;
7579     }
7580
7581     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
7582        the "real" pattern. */
7583     DEBUG_OPTIMISE_r({
7584         PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf" maxlen:%"IVdf"\n",
7585                       (IV)minlen, (IV)r->minlen, (IV)RExC_maxlen);
7586     });
7587     r->minlenret = minlen;
7588     if (r->minlen < minlen)
7589         r->minlen = minlen;
7590
7591     if (RExC_seen & REG_GPOS_SEEN)
7592         r->intflags |= PREGf_GPOS_SEEN;
7593     if (RExC_seen & REG_LOOKBEHIND_SEEN)
7594         r->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the
7595                                                 lookbehind */
7596     if (pRExC_state->num_code_blocks)
7597         r->extflags |= RXf_EVAL_SEEN;
7598     if (RExC_seen & REG_VERBARG_SEEN)
7599     {
7600         r->intflags |= PREGf_VERBARG_SEEN;
7601         r->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
7602     }
7603     if (RExC_seen & REG_CUTGROUP_SEEN)
7604         r->intflags |= PREGf_CUTGROUP_SEEN;
7605     if (pm_flags & PMf_USE_RE_EVAL)
7606         r->intflags |= PREGf_USE_RE_EVAL;
7607     if (RExC_paren_names)
7608         RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
7609     else
7610         RXp_PAREN_NAMES(r) = NULL;
7611
7612     /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED
7613      * so it can be used in pp.c */
7614     if (r->intflags & PREGf_ANCH)
7615         r->extflags |= RXf_IS_ANCHORED;
7616
7617
7618     {
7619         /* this is used to identify "special" patterns that might result
7620          * in Perl NOT calling the regex engine and instead doing the match "itself",
7621          * particularly special cases in split//. By having the regex compiler
7622          * do this pattern matching at a regop level (instead of by inspecting the pattern)
7623          * we avoid weird issues with equivalent patterns resulting in different behavior,
7624          * AND we allow non Perl engines to get the same optimizations by the setting the
7625          * flags appropriately - Yves */
7626         regnode *first = ri->program + 1;
7627         U8 fop = OP(first);
7628         regnode *next = regnext(first);
7629         U8 nop = OP(next);
7630
7631         if (PL_regkind[fop] == NOTHING && nop == END)
7632             r->extflags |= RXf_NULL;
7633         else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END)
7634             /* when fop is SBOL first->flags will be true only when it was
7635              * produced by parsing /\A/, and not when parsing /^/. This is
7636              * very important for the split code as there we want to
7637              * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m.
7638              * See rt #122761 for more details. -- Yves */
7639             r->extflags |= RXf_START_ONLY;
7640         else if (fop == PLUS
7641                  && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE
7642                  && nop == END)
7643             r->extflags |= RXf_WHITE;
7644         else if ( r->extflags & RXf_SPLIT
7645                   && (fop == EXACT || fop == EXACTL)
7646                   && STR_LEN(first) == 1
7647                   && *(STRING(first)) == ' '
7648                   && nop == END )
7649             r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
7650
7651     }
7652
7653     if (RExC_contains_locale) {
7654         RXp_EXTFLAGS(r) |= RXf_TAINTED;
7655     }
7656
7657 #ifdef DEBUGGING
7658     if (RExC_paren_names) {
7659         ri->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a"));
7660         ri->data->data[ri->name_list_idx]
7661                                    = (void*)SvREFCNT_inc(RExC_paren_name_list);
7662     } else
7663 #endif
7664         ri->name_list_idx = 0;
7665
7666     if (RExC_recurse_count) {
7667         for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
7668             const regnode *scan = RExC_recurse[RExC_recurse_count-1];
7669             ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
7670         }
7671     }
7672     Newxz(r->offs, RExC_npar, regexp_paren_pair);
7673     /* assume we don't need to swap parens around before we match */
7674     DEBUG_TEST_r({
7675         PerlIO_printf(Perl_debug_log,"study_chunk_recursed_count: %lu\n",
7676             (unsigned long)RExC_study_chunk_recursed_count);
7677     });
7678     DEBUG_DUMP_r({
7679         DEBUG_RExC_seen();
7680         PerlIO_printf(Perl_debug_log,"Final program:\n");
7681         regdump(r);
7682     });
7683 #ifdef RE_TRACK_PATTERN_OFFSETS
7684     DEBUG_OFFSETS_r(if (ri->u.offsets) {
7685         const STRLEN len = ri->u.offsets[0];
7686         STRLEN i;
7687         GET_RE_DEBUG_FLAGS_DECL;
7688         PerlIO_printf(Perl_debug_log,
7689                       "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
7690         for (i = 1; i <= len; i++) {
7691             if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
7692                 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
7693                 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
7694             }
7695         PerlIO_printf(Perl_debug_log, "\n");
7696     });
7697 #endif
7698
7699 #ifdef USE_ITHREADS
7700     /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
7701      * by setting the regexp SV to readonly-only instead. If the
7702      * pattern's been recompiled, the USEDness should remain. */
7703     if (old_re && SvREADONLY(old_re))
7704         SvREADONLY_on(rx);
7705 #endif
7706     return rx;
7707 }
7708
7709
7710 SV*
7711 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
7712                     const U32 flags)
7713 {
7714     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
7715
7716     PERL_UNUSED_ARG(value);
7717
7718     if (flags & RXapif_FETCH) {
7719         return reg_named_buff_fetch(rx, key, flags);
7720     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
7721         Perl_croak_no_modify();
7722         return NULL;
7723     } else if (flags & RXapif_EXISTS) {
7724         return reg_named_buff_exists(rx, key, flags)
7725             ? &PL_sv_yes
7726             : &PL_sv_no;
7727     } else if (flags & RXapif_REGNAMES) {
7728         return reg_named_buff_all(rx, flags);
7729     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
7730         return reg_named_buff_scalar(rx, flags);
7731     } else {
7732         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
7733         return NULL;
7734     }
7735 }
7736
7737 SV*
7738 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
7739                          const U32 flags)
7740 {
7741     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
7742     PERL_UNUSED_ARG(lastkey);
7743
7744     if (flags & RXapif_FIRSTKEY)
7745         return reg_named_buff_firstkey(rx, flags);
7746     else if (flags & RXapif_NEXTKEY)
7747         return reg_named_buff_nextkey(rx, flags);
7748     else {
7749         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter",
7750                                             (int)flags);
7751         return NULL;
7752     }
7753 }
7754
7755 SV*
7756 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
7757                           const U32 flags)
7758 {
7759     AV *retarray = NULL;
7760     SV *ret;
7761     struct regexp *const rx = ReANY(r);
7762
7763     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
7764
7765     if (flags & RXapif_ALL)
7766         retarray=newAV();
7767
7768     if (rx && RXp_PAREN_NAMES(rx)) {
7769         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
7770         if (he_str) {
7771             IV i;
7772             SV* sv_dat=HeVAL(he_str);
7773             I32 *nums=(I32*)SvPVX(sv_dat);
7774             for ( i=0; i<SvIVX(sv_dat); i++ ) {
7775                 if ((I32)(rx->nparens) >= nums[i]
7776                     && rx->offs[nums[i]].start != -1
7777                     && rx->offs[nums[i]].end != -1)
7778                 {
7779                     ret = newSVpvs("");
7780                     CALLREG_NUMBUF_FETCH(r,nums[i],ret);
7781                     if (!retarray)
7782                         return ret;
7783                 } else {
7784                     if (retarray)
7785                         ret = newSVsv(&PL_sv_undef);
7786                 }
7787                 if (retarray)
7788                     av_push(retarray, ret);
7789             }
7790             if (retarray)
7791                 return newRV_noinc(MUTABLE_SV(retarray));
7792         }
7793     }
7794     return NULL;
7795 }
7796
7797 bool
7798 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
7799                            const U32 flags)
7800 {
7801     struct regexp *const rx = ReANY(r);
7802
7803     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
7804
7805     if (rx && RXp_PAREN_NAMES(rx)) {
7806         if (flags & RXapif_ALL) {
7807             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
7808         } else {
7809             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
7810             if (sv) {
7811                 SvREFCNT_dec_NN(sv);
7812                 return TRUE;
7813             } else {
7814                 return FALSE;
7815             }
7816         }
7817     } else {
7818         return FALSE;
7819     }
7820 }
7821
7822 SV*
7823 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
7824 {
7825     struct regexp *const rx = ReANY(r);
7826
7827     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
7828
7829     if ( rx && RXp_PAREN_NAMES(rx) ) {
7830         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
7831
7832         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
7833     } else {
7834         return FALSE;
7835     }
7836 }
7837
7838 SV*
7839 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
7840 {
7841     struct regexp *const rx = ReANY(r);
7842     GET_RE_DEBUG_FLAGS_DECL;
7843
7844     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
7845
7846     if (rx && RXp_PAREN_NAMES(rx)) {
7847         HV *hv = RXp_PAREN_NAMES(rx);
7848         HE *temphe;
7849         while ( (temphe = hv_iternext_flags(hv,0)) ) {
7850             IV i;
7851             IV parno = 0;
7852             SV* sv_dat = HeVAL(temphe);
7853             I32 *nums = (I32*)SvPVX(sv_dat);
7854             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
7855                 if ((I32)(rx->lastparen) >= nums[i] &&
7856                     rx->offs[nums[i]].start != -1 &&
7857                     rx->offs[nums[i]].end != -1)
7858                 {
7859                     parno = nums[i];
7860                     break;
7861                 }
7862             }
7863             if (parno || flags & RXapif_ALL) {
7864                 return newSVhek(HeKEY_hek(temphe));
7865             }
7866         }
7867     }
7868     return NULL;
7869 }
7870
7871 SV*
7872 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
7873 {
7874     SV *ret;
7875     AV *av;
7876     SSize_t length;
7877     struct regexp *const rx = ReANY(r);
7878
7879     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
7880
7881     if (rx && RXp_PAREN_NAMES(rx)) {
7882         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
7883             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
7884         } else if (flags & RXapif_ONE) {
7885             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
7886             av = MUTABLE_AV(SvRV(ret));
7887             length = av_tindex(av);
7888             SvREFCNT_dec_NN(ret);
7889             return newSViv(length + 1);
7890         } else {
7891             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar",
7892                                                 (int)flags);
7893             return NULL;
7894         }
7895     }
7896     return &PL_sv_undef;
7897 }
7898
7899 SV*
7900 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
7901 {
7902     struct regexp *const rx = ReANY(r);
7903     AV *av = newAV();
7904
7905     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
7906
7907     if (rx && RXp_PAREN_NAMES(rx)) {
7908         HV *hv= RXp_PAREN_NAMES(rx);
7909         HE *temphe;
7910         (void)hv_iterinit(hv);
7911         while ( (temphe = hv_iternext_flags(hv,0)) ) {
7912             IV i;
7913             IV parno = 0;
7914             SV* sv_dat = HeVAL(temphe);
7915             I32 *nums = (I32*)SvPVX(sv_dat);
7916             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
7917                 if ((I32)(rx->lastparen) >= nums[i] &&
7918                     rx->offs[nums[i]].start != -1 &&
7919                     rx->offs[nums[i]].end != -1)
7920                 {
7921                     parno = nums[i];
7922                     break;
7923                 }
7924             }
7925             if (parno || flags & RXapif_ALL) {
7926                 av_push(av, newSVhek(HeKEY_hek(temphe)));
7927             }
7928         }
7929     }
7930
7931     return newRV_noinc(MUTABLE_SV(av));
7932 }
7933
7934 void
7935 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
7936                              SV * const sv)
7937 {
7938     struct regexp *const rx = ReANY(r);
7939     char *s = NULL;
7940     SSize_t i = 0;
7941     SSize_t s1, t1;
7942     I32 n = paren;
7943
7944     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
7945
7946     if (      n == RX_BUFF_IDX_CARET_PREMATCH
7947            || n == RX_BUFF_IDX_CARET_FULLMATCH
7948            || n == RX_BUFF_IDX_CARET_POSTMATCH
7949        )
7950     {
7951         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
7952         if (!keepcopy) {
7953             /* on something like
7954              *    $r = qr/.../;
7955              *    /$qr/p;
7956              * the KEEPCOPY is set on the PMOP rather than the regex */
7957             if (PL_curpm && r == PM_GETRE(PL_curpm))
7958                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
7959         }
7960         if (!keepcopy)
7961             goto ret_undef;
7962     }
7963
7964     if (!rx->subbeg)
7965         goto ret_undef;
7966
7967     if (n == RX_BUFF_IDX_CARET_FULLMATCH)
7968         /* no need to distinguish between them any more */
7969         n = RX_BUFF_IDX_FULLMATCH;
7970
7971     if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
7972         && rx->offs[0].start != -1)
7973     {
7974         /* $`, ${^PREMATCH} */
7975         i = rx->offs[0].start;
7976         s = rx->subbeg;
7977     }
7978     else
7979     if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
7980         && rx->offs[0].end != -1)
7981     {
7982         /* $', ${^POSTMATCH} */
7983         s = rx->subbeg - rx->suboffset + rx->offs[0].end;
7984         i = rx->sublen + rx->suboffset - rx->offs[0].end;
7985     }
7986     else
7987     if ( 0 <= n && n <= (I32)rx->nparens &&
7988         (s1 = rx->offs[n].start) != -1 &&
7989         (t1 = rx->offs[n].end) != -1)
7990     {
7991         /* $&, ${^MATCH},  $1 ... */
7992         i = t1 - s1;
7993         s = rx->subbeg + s1 - rx->suboffset;
7994     } else {
7995         goto ret_undef;
7996     }
7997
7998     assert(s >= rx->subbeg);
7999     assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) );
8000     if (i >= 0) {
8001 #ifdef NO_TAINT_SUPPORT
8002         sv_setpvn(sv, s, i);
8003 #else
8004         const int oldtainted = TAINT_get;
8005         TAINT_NOT;
8006         sv_setpvn(sv, s, i);
8007         TAINT_set(oldtainted);
8008 #endif
8009         if (RXp_MATCH_UTF8(rx))
8010             SvUTF8_on(sv);
8011         else
8012             SvUTF8_off(sv);
8013         if (TAINTING_get) {
8014             if (RXp_MATCH_TAINTED(rx)) {
8015                 if (SvTYPE(sv) >= SVt_PVMG) {
8016                     MAGIC* const mg = SvMAGIC(sv);
8017                     MAGIC* mgt;
8018                     TAINT;
8019                     SvMAGIC_set(sv, mg->mg_moremagic);
8020                     SvTAINT(sv);
8021                     if ((mgt = SvMAGIC(sv))) {
8022                         mg->mg_moremagic = mgt;
8023                         SvMAGIC_set(sv, mg);
8024                     }
8025                 } else {
8026                     TAINT;
8027                     SvTAINT(sv);
8028                 }
8029             } else
8030                 SvTAINTED_off(sv);
8031         }
8032     } else {
8033       ret_undef:
8034         sv_setsv(sv,&PL_sv_undef);
8035         return;
8036     }
8037 }
8038
8039 void
8040 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
8041                                                          SV const * const value)
8042 {
8043     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
8044
8045     PERL_UNUSED_ARG(rx);
8046     PERL_UNUSED_ARG(paren);
8047     PERL_UNUSED_ARG(value);
8048
8049     if (!PL_localizing)
8050         Perl_croak_no_modify();
8051 }
8052
8053 I32
8054 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
8055                               const I32 paren)
8056 {
8057     struct regexp *const rx = ReANY(r);
8058     I32 i;
8059     I32 s1, t1;
8060
8061     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
8062
8063     if (   paren == RX_BUFF_IDX_CARET_PREMATCH
8064         || paren == RX_BUFF_IDX_CARET_FULLMATCH
8065         || paren == RX_BUFF_IDX_CARET_POSTMATCH
8066     )
8067     {
8068         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
8069         if (!keepcopy) {
8070             /* on something like
8071              *    $r = qr/.../;
8072              *    /$qr/p;
8073              * the KEEPCOPY is set on the PMOP rather than the regex */
8074             if (PL_curpm && r == PM_GETRE(PL_curpm))
8075                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
8076         }
8077         if (!keepcopy)
8078             goto warn_undef;
8079     }
8080
8081     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
8082     switch (paren) {
8083       case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
8084       case RX_BUFF_IDX_PREMATCH:       /* $` */
8085         if (rx->offs[0].start != -1) {
8086                         i = rx->offs[0].start;
8087                         if (i > 0) {
8088                                 s1 = 0;
8089                                 t1 = i;
8090                                 goto getlen;
8091                         }
8092             }
8093         return 0;
8094
8095       case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
8096       case RX_BUFF_IDX_POSTMATCH:       /* $' */
8097             if (rx->offs[0].end != -1) {
8098                         i = rx->sublen - rx->offs[0].end;
8099                         if (i > 0) {
8100                                 s1 = rx->offs[0].end;
8101                                 t1 = rx->sublen;
8102                                 goto getlen;
8103                         }
8104             }
8105         return 0;
8106
8107       default: /* $& / ${^MATCH}, $1, $2, ... */
8108             if (paren <= (I32)rx->nparens &&
8109             (s1 = rx->offs[paren].start) != -1 &&
8110             (t1 = rx->offs[paren].end) != -1)
8111             {
8112             i = t1 - s1;
8113             goto getlen;
8114         } else {
8115           warn_undef:
8116             if (ckWARN(WARN_UNINITIALIZED))
8117                 report_uninit((const SV *)sv);
8118             return 0;
8119         }
8120     }
8121   getlen:
8122     if (i > 0 && RXp_MATCH_UTF8(rx)) {
8123         const char * const s = rx->subbeg - rx->suboffset + s1;
8124         const U8 *ep;
8125         STRLEN el;
8126
8127         i = t1 - s1;
8128         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
8129                         i = el;
8130     }
8131     return i;
8132 }
8133
8134 SV*
8135 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
8136 {
8137     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
8138         PERL_UNUSED_ARG(rx);
8139         if (0)
8140             return NULL;
8141         else
8142             return newSVpvs("Regexp");
8143 }
8144
8145 /* Scans the name of a named buffer from the pattern.
8146  * If flags is REG_RSN_RETURN_NULL returns null.
8147  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
8148  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
8149  * to the parsed name as looked up in the RExC_paren_names hash.
8150  * If there is an error throws a vFAIL().. type exception.
8151  */
8152
8153 #define REG_RSN_RETURN_NULL    0
8154 #define REG_RSN_RETURN_NAME    1
8155 #define REG_RSN_RETURN_DATA    2
8156
8157 STATIC SV*
8158 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
8159 {
8160     char *name_start = RExC_parse;
8161
8162     PERL_ARGS_ASSERT_REG_SCAN_NAME;
8163
8164     assert (RExC_parse <= RExC_end);
8165     if (RExC_parse == RExC_end) NOOP;
8166     else if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
8167          /* Note that the code here assumes well-formed UTF-8.  Skip IDFIRST by
8168           * using do...while */
8169         if (UTF)
8170             do {
8171                 RExC_parse += UTF8SKIP(RExC_parse);
8172             } while (isWORDCHAR_utf8((U8*)RExC_parse));
8173         else
8174             do {
8175                 RExC_parse++;
8176             } while (isWORDCHAR(*RExC_parse));
8177     } else {
8178         RExC_parse++; /* so the <- from the vFAIL is after the offending
8179                          character */
8180         vFAIL("Group name must start with a non-digit word character");
8181     }
8182     if ( flags ) {
8183         SV* sv_name
8184             = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
8185                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
8186         if ( flags == REG_RSN_RETURN_NAME)
8187             return sv_name;
8188         else if (flags==REG_RSN_RETURN_DATA) {
8189             HE *he_str = NULL;
8190             SV *sv_dat = NULL;
8191             if ( ! sv_name )      /* should not happen*/
8192                 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
8193             if (RExC_paren_names)
8194                 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
8195             if ( he_str )
8196                 sv_dat = HeVAL(he_str);
8197             if ( ! sv_dat )
8198                 vFAIL("Reference to nonexistent named group");
8199             return sv_dat;
8200         }
8201         else {
8202             Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
8203                        (unsigned long) flags);
8204         }
8205         NOT_REACHED; /* NOTREACHED */
8206     }
8207     return NULL;
8208 }
8209
8210 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
8211     int num;                                                    \
8212     if (RExC_lastparse!=RExC_parse) {                           \
8213         PerlIO_printf(Perl_debug_log, "%s",                     \
8214             Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse,        \
8215                 RExC_end - RExC_parse, 16,                      \
8216                 "", "",                                         \
8217                 PERL_PV_ESCAPE_UNI_DETECT |                     \
8218                 PERL_PV_PRETTY_ELLIPSES   |                     \
8219                 PERL_PV_PRETTY_LTGT       |                     \
8220                 PERL_PV_ESCAPE_RE         |                     \
8221                 PERL_PV_PRETTY_EXACTSIZE                        \
8222             )                                                   \
8223         );                                                      \
8224     } else                                                      \
8225         PerlIO_printf(Perl_debug_log,"%16s","");                \
8226                                                                 \
8227     if (SIZE_ONLY)                                              \
8228        num = RExC_size + 1;                                     \
8229     else                                                        \
8230        num=REG_NODE_NUM(RExC_emit);                             \
8231     if (RExC_lastnum!=num)                                      \
8232        PerlIO_printf(Perl_debug_log,"|%4d",num);                \
8233     else                                                        \
8234        PerlIO_printf(Perl_debug_log,"|%4s","");                 \
8235     PerlIO_printf(Perl_debug_log,"|%*s%-4s",                    \
8236         (int)((depth*2)), "",                                   \
8237         (funcname)                                              \
8238     );                                                          \
8239     RExC_lastnum=num;                                           \
8240     RExC_lastparse=RExC_parse;                                  \
8241 })
8242
8243
8244
8245 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
8246     DEBUG_PARSE_MSG((funcname));                            \
8247     PerlIO_printf(Perl_debug_log,"%4s","\n");               \
8248 })
8249 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({           \
8250     DEBUG_PARSE_MSG((funcname));                            \
8251     PerlIO_printf(Perl_debug_log,fmt "\n",args);               \
8252 })
8253
8254 /* This section of code defines the inversion list object and its methods.  The
8255  * interfaces are highly subject to change, so as much as possible is static to
8256  * this file.  An inversion list is here implemented as a malloc'd C UV array
8257  * as an SVt_INVLIST scalar.
8258  *
8259  * An inversion list for Unicode is an array of code points, sorted by ordinal
8260  * number.  The zeroth element is the first code point in the list.  The 1th
8261  * element is the first element beyond that not in the list.  In other words,
8262  * the first range is
8263  *  invlist[0]..(invlist[1]-1)
8264  * The other ranges follow.  Thus every element whose index is divisible by two
8265  * marks the beginning of a range that is in the list, and every element not
8266  * divisible by two marks the beginning of a range not in the list.  A single
8267  * element inversion list that contains the single code point N generally
8268  * consists of two elements
8269  *  invlist[0] == N
8270  *  invlist[1] == N+1
8271  * (The exception is when N is the highest representable value on the
8272  * machine, in which case the list containing just it would be a single
8273  * element, itself.  By extension, if the last range in the list extends to
8274  * infinity, then the first element of that range will be in the inversion list
8275  * at a position that is divisible by two, and is the final element in the
8276  * list.)
8277  * Taking the complement (inverting) an inversion list is quite simple, if the
8278  * first element is 0, remove it; otherwise add a 0 element at the beginning.
8279  * This implementation reserves an element at the beginning of each inversion
8280  * list to always contain 0; there is an additional flag in the header which
8281  * indicates if the list begins at the 0, or is offset to begin at the next
8282  * element.
8283  *
8284  * More about inversion lists can be found in "Unicode Demystified"
8285  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
8286  * More will be coming when functionality is added later.
8287  *
8288  * The inversion list data structure is currently implemented as an SV pointing
8289  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
8290  * array of UV whose memory management is automatically handled by the existing
8291  * facilities for SV's.
8292  *
8293  * Some of the methods should always be private to the implementation, and some
8294  * should eventually be made public */
8295
8296 /* The header definitions are in F<invlist_inline.h> */
8297
8298 PERL_STATIC_INLINE UV*
8299 S__invlist_array_init(SV* const invlist, const bool will_have_0)
8300 {
8301     /* Returns a pointer to the first element in the inversion list's array.
8302      * This is called upon initialization of an inversion list.  Where the
8303      * array begins depends on whether the list has the code point U+0000 in it
8304      * or not.  The other parameter tells it whether the code that follows this
8305      * call is about to put a 0 in the inversion list or not.  The first
8306      * element is either the element reserved for 0, if TRUE, or the element
8307      * after it, if FALSE */
8308
8309     bool* offset = get_invlist_offset_addr(invlist);
8310     UV* zero_addr = (UV *) SvPVX(invlist);
8311
8312     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
8313
8314     /* Must be empty */
8315     assert(! _invlist_len(invlist));
8316
8317     *zero_addr = 0;
8318
8319     /* 1^1 = 0; 1^0 = 1 */
8320     *offset = 1 ^ will_have_0;
8321     return zero_addr + *offset;
8322 }
8323
8324 PERL_STATIC_INLINE void
8325 S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
8326 {
8327     /* Sets the current number of elements stored in the inversion list.
8328      * Updates SvCUR correspondingly */
8329     PERL_UNUSED_CONTEXT;
8330     PERL_ARGS_ASSERT_INVLIST_SET_LEN;
8331
8332     assert(SvTYPE(invlist) == SVt_INVLIST);
8333
8334     SvCUR_set(invlist,
8335               (len == 0)
8336                ? 0
8337                : TO_INTERNAL_SIZE(len + offset));
8338     assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
8339 }
8340
8341 #ifndef PERL_IN_XSUB_RE
8342
8343 PERL_STATIC_INLINE IV*
8344 S_get_invlist_previous_index_addr(SV* invlist)
8345 {
8346     /* Return the address of the IV that is reserved to hold the cached index
8347      * */
8348     PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
8349
8350     assert(SvTYPE(invlist) == SVt_INVLIST);
8351
8352     return &(((XINVLIST*) SvANY(invlist))->prev_index);
8353 }
8354
8355 PERL_STATIC_INLINE IV
8356 S_invlist_previous_index(SV* const invlist)
8357 {
8358     /* Returns cached index of previous search */
8359
8360     PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
8361
8362     return *get_invlist_previous_index_addr(invlist);
8363 }
8364
8365 PERL_STATIC_INLINE void
8366 S_invlist_set_previous_index(SV* const invlist, const IV index)
8367 {
8368     /* Caches <index> for later retrieval */
8369
8370     PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
8371
8372     assert(index == 0 || index < (int) _invlist_len(invlist));
8373
8374     *get_invlist_previous_index_addr(invlist) = index;
8375 }
8376
8377 PERL_STATIC_INLINE void
8378 S_invlist_trim(SV* const invlist)
8379 {
8380     PERL_ARGS_ASSERT_INVLIST_TRIM;
8381
8382     assert(SvTYPE(invlist) == SVt_INVLIST);
8383
8384     /* Change the length of the inversion list to how many entries it currently
8385      * has */
8386     SvPV_shrink_to_cur((SV *) invlist);
8387 }
8388
8389 PERL_STATIC_INLINE bool
8390 S_invlist_is_iterating(SV* const invlist)
8391 {
8392     PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
8393
8394     return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
8395 }
8396
8397 #endif /* ifndef PERL_IN_XSUB_RE */
8398
8399 PERL_STATIC_INLINE UV
8400 S_invlist_max(SV* const invlist)
8401 {
8402     /* Returns the maximum number of elements storable in the inversion list's
8403      * array, without having to realloc() */
8404
8405     PERL_ARGS_ASSERT_INVLIST_MAX;
8406
8407     assert(SvTYPE(invlist) == SVt_INVLIST);
8408
8409     /* Assumes worst case, in which the 0 element is not counted in the
8410      * inversion list, so subtracts 1 for that */
8411     return SvLEN(invlist) == 0  /* This happens under _new_invlist_C_array */
8412            ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
8413            : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
8414 }
8415
8416 #ifndef PERL_IN_XSUB_RE
8417 SV*
8418 Perl__new_invlist(pTHX_ IV initial_size)
8419 {
8420
8421     /* Return a pointer to a newly constructed inversion list, with enough
8422      * space to store 'initial_size' elements.  If that number is negative, a
8423      * system default is used instead */
8424
8425     SV* new_list;
8426
8427     if (initial_size < 0) {
8428         initial_size = 10;
8429     }
8430
8431     /* Allocate the initial space */
8432     new_list = newSV_type(SVt_INVLIST);
8433
8434     /* First 1 is in case the zero element isn't in the list; second 1 is for
8435      * trailing NUL */
8436     SvGROW(new_list, TO_INTERNAL_SIZE(initial_size + 1) + 1);
8437     invlist_set_len(new_list, 0, 0);
8438
8439     /* Force iterinit() to be used to get iteration to work */
8440     *get_invlist_iter_addr(new_list) = (STRLEN) UV_MAX;
8441
8442     *get_invlist_previous_index_addr(new_list) = 0;
8443
8444     return new_list;
8445 }
8446
8447 SV*
8448 Perl__new_invlist_C_array(pTHX_ const UV* const list)
8449 {
8450     /* Return a pointer to a newly constructed inversion list, initialized to
8451      * point to <list>, which has to be in the exact correct inversion list
8452      * form, including internal fields.  Thus this is a dangerous routine that
8453      * should not be used in the wrong hands.  The passed in 'list' contains
8454      * several header fields at the beginning that are not part of the
8455      * inversion list body proper */
8456
8457     const STRLEN length = (STRLEN) list[0];
8458     const UV version_id =          list[1];
8459     const bool offset   =    cBOOL(list[2]);
8460 #define HEADER_LENGTH 3
8461     /* If any of the above changes in any way, you must change HEADER_LENGTH
8462      * (if appropriate) and regenerate INVLIST_VERSION_ID by running
8463      *      perl -E 'say int(rand 2**31-1)'
8464      */
8465 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
8466                                         data structure type, so that one being
8467                                         passed in can be validated to be an
8468                                         inversion list of the correct vintage.
8469                                        */
8470
8471     SV* invlist = newSV_type(SVt_INVLIST);
8472
8473     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
8474
8475     if (version_id != INVLIST_VERSION_ID) {
8476         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
8477     }
8478
8479     /* The generated array passed in includes header elements that aren't part
8480      * of the list proper, so start it just after them */
8481     SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
8482
8483     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
8484                                shouldn't touch it */
8485
8486     *(get_invlist_offset_addr(invlist)) = offset;
8487
8488     /* The 'length' passed to us is the physical number of elements in the
8489      * inversion list.  But if there is an offset the logical number is one
8490      * less than that */
8491     invlist_set_len(invlist, length  - offset, offset);
8492
8493     invlist_set_previous_index(invlist, 0);
8494
8495     /* Initialize the iteration pointer. */
8496     invlist_iterfinish(invlist);
8497
8498     SvREADONLY_on(invlist);
8499
8500     return invlist;
8501 }
8502 #endif /* ifndef PERL_IN_XSUB_RE */
8503
8504 STATIC void
8505 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
8506 {
8507     /* Grow the maximum size of an inversion list */
8508
8509     PERL_ARGS_ASSERT_INVLIST_EXTEND;
8510
8511     assert(SvTYPE(invlist) == SVt_INVLIST);
8512
8513     /* Add one to account for the zero element at the beginning which may not
8514      * be counted by the calling parameters */
8515     SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
8516 }
8517
8518 STATIC void
8519 S__append_range_to_invlist(pTHX_ SV* const invlist,
8520                                  const UV start, const UV end)
8521 {
8522    /* Subject to change or removal.  Append the range from 'start' to 'end' at
8523     * the end of the inversion list.  The range must be above any existing
8524     * ones. */
8525
8526     UV* array;
8527     UV max = invlist_max(invlist);
8528     UV len = _invlist_len(invlist);
8529     bool offset;
8530
8531     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
8532
8533     if (len == 0) { /* Empty lists must be initialized */
8534         offset = start != 0;
8535         array = _invlist_array_init(invlist, ! offset);
8536     }
8537     else {
8538         /* Here, the existing list is non-empty. The current max entry in the
8539          * list is generally the first value not in the set, except when the
8540          * set extends to the end of permissible values, in which case it is
8541          * the first entry in that final set, and so this call is an attempt to
8542          * append out-of-order */
8543
8544         UV final_element = len - 1;
8545         array = invlist_array(invlist);
8546         if (array[final_element] > start
8547             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
8548         {
8549             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",
8550                      array[final_element], start,
8551                      ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
8552         }
8553
8554         /* Here, it is a legal append.  If the new range begins with the first
8555          * value not in the set, it is extending the set, so the new first
8556          * value not in the set is one greater than the newly extended range.
8557          * */
8558         offset = *get_invlist_offset_addr(invlist);
8559         if (array[final_element] == start) {
8560             if (end != UV_MAX) {
8561                 array[final_element] = end + 1;
8562             }
8563             else {
8564                 /* But if the end is the maximum representable on the machine,
8565                  * just let the range that this would extend to have no end */
8566                 invlist_set_len(invlist, len - 1, offset);
8567             }
8568             return;
8569         }
8570     }
8571
8572     /* Here the new range doesn't extend any existing set.  Add it */
8573
8574     len += 2;   /* Includes an element each for the start and end of range */
8575
8576     /* If wll overflow the existing space, extend, which may cause the array to
8577      * be moved */
8578     if (max < len) {
8579         invlist_extend(invlist, len);
8580
8581         /* Have to set len here to avoid assert failure in invlist_array() */
8582         invlist_set_len(invlist, len, offset);
8583
8584         array = invlist_array(invlist);
8585     }
8586     else {
8587         invlist_set_len(invlist, len, offset);
8588     }
8589
8590     /* The next item on the list starts the range, the one after that is
8591      * one past the new range.  */
8592     array[len - 2] = start;
8593     if (end != UV_MAX) {
8594         array[len - 1] = end + 1;
8595     }
8596     else {
8597         /* But if the end is the maximum representable on the machine, just let
8598          * the range have no end */
8599         invlist_set_len(invlist, len - 1, offset);
8600     }
8601 }
8602
8603 #ifndef PERL_IN_XSUB_RE
8604
8605 IV
8606 Perl__invlist_search(SV* const invlist, const UV cp)
8607 {
8608     /* Searches the inversion list for the entry that contains the input code
8609      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
8610      * return value is the index into the list's array of the range that
8611      * contains <cp>, that is, 'i' such that
8612      *  array[i] <= cp < array[i+1]
8613      */
8614
8615     IV low = 0;
8616     IV mid;
8617     IV high = _invlist_len(invlist);
8618     const IV highest_element = high - 1;
8619     const UV* array;
8620
8621     PERL_ARGS_ASSERT__INVLIST_SEARCH;
8622
8623     /* If list is empty, return failure. */
8624     if (high == 0) {
8625         return -1;
8626     }
8627
8628     /* (We can't get the array unless we know the list is non-empty) */
8629     array = invlist_array(invlist);
8630
8631     mid = invlist_previous_index(invlist);
8632     assert(mid >=0);
8633     if (mid > highest_element) {
8634         mid = highest_element;
8635     }
8636
8637     /* <mid> contains the cache of the result of the previous call to this
8638      * function (0 the first time).  See if this call is for the same result,
8639      * or if it is for mid-1.  This is under the theory that calls to this
8640      * function will often be for related code points that are near each other.
8641      * And benchmarks show that caching gives better results.  We also test
8642      * here if the code point is within the bounds of the list.  These tests
8643      * replace others that would have had to be made anyway to make sure that
8644      * the array bounds were not exceeded, and these give us extra information
8645      * at the same time */
8646     if (cp >= array[mid]) {
8647         if (cp >= array[highest_element]) {
8648             return highest_element;
8649         }
8650
8651         /* Here, array[mid] <= cp < array[highest_element].  This means that
8652          * the final element is not the answer, so can exclude it; it also
8653          * means that <mid> is not the final element, so can refer to 'mid + 1'
8654          * safely */
8655         if (cp < array[mid + 1]) {
8656             return mid;
8657         }
8658         high--;
8659         low = mid + 1;
8660     }
8661     else { /* cp < aray[mid] */
8662         if (cp < array[0]) { /* Fail if outside the array */
8663             return -1;
8664         }
8665         high = mid;
8666         if (cp >= array[mid - 1]) {
8667             goto found_entry;
8668         }
8669     }
8670
8671     /* Binary search.  What we are looking for is <i> such that
8672      *  array[i] <= cp < array[i+1]
8673      * The loop below converges on the i+1.  Note that there may not be an
8674      * (i+1)th element in the array, and things work nonetheless */
8675     while (low < high) {
8676         mid = (low + high) / 2;
8677         assert(mid <= highest_element);
8678         if (array[mid] <= cp) { /* cp >= array[mid] */
8679             low = mid + 1;
8680
8681             /* We could do this extra test to exit the loop early.
8682             if (cp < array[low]) {
8683                 return mid;
8684             }
8685             */
8686         }
8687         else { /* cp < array[mid] */
8688             high = mid;
8689         }
8690     }
8691
8692   found_entry:
8693     high--;
8694     invlist_set_previous_index(invlist, high);
8695     return high;
8696 }
8697
8698 void
8699 Perl__invlist_populate_swatch(SV* const invlist,
8700                               const UV start, const UV end, U8* swatch)
8701 {
8702     /* populates a swatch of a swash the same way swatch_get() does in utf8.c,
8703      * but is used when the swash has an inversion list.  This makes this much
8704      * faster, as it uses a binary search instead of a linear one.  This is
8705      * intimately tied to that function, and perhaps should be in utf8.c,
8706      * except it is intimately tied to inversion lists as well.  It assumes
8707      * that <swatch> is all 0's on input */
8708
8709     UV current = start;
8710     const IV len = _invlist_len(invlist);
8711     IV i;
8712     const UV * array;
8713
8714     PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
8715
8716     if (len == 0) { /* Empty inversion list */
8717         return;
8718     }
8719
8720     array = invlist_array(invlist);
8721
8722     /* Find which element it is */
8723     i = _invlist_search(invlist, start);
8724
8725     /* We populate from <start> to <end> */
8726     while (current < end) {
8727         UV upper;
8728
8729         /* The inversion list gives the results for every possible code point
8730          * after the first one in the list.  Only those ranges whose index is
8731          * even are ones that the inversion list matches.  For the odd ones,
8732          * and if the initial code point is not in the list, we have to skip
8733          * forward to the next element */
8734         if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
8735             i++;
8736             if (i >= len) { /* Finished if beyond the end of the array */
8737                 return;
8738             }
8739             current = array[i];
8740             if (current >= end) {   /* Finished if beyond the end of what we
8741                                        are populating */
8742                 if (LIKELY(end < UV_MAX)) {
8743                     return;
8744                 }
8745
8746                 /* We get here when the upper bound is the maximum
8747                  * representable on the machine, and we are looking for just
8748                  * that code point.  Have to special case it */
8749                 i = len;
8750                 goto join_end_of_list;
8751             }
8752         }
8753         assert(current >= start);
8754
8755         /* The current range ends one below the next one, except don't go past
8756          * <end> */
8757         i++;
8758         upper = (i < len && array[i] < end) ? array[i] : end;
8759
8760         /* Here we are in a range that matches.  Populate a bit in the 3-bit U8
8761          * for each code point in it */
8762         for (; current < upper; current++) {
8763             const STRLEN offset = (STRLEN)(current - start);
8764             swatch[offset >> 3] |= 1 << (offset & 7);
8765         }
8766
8767       join_end_of_list:
8768
8769         /* Quit if at the end of the list */
8770         if (i >= len) {
8771
8772             /* But first, have to deal with the highest possible code point on
8773              * the platform.  The previous code assumes that <end> is one
8774              * beyond where we want to populate, but that is impossible at the
8775              * platform's infinity, so have to handle it specially */
8776             if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
8777             {
8778                 const STRLEN offset = (STRLEN)(end - start);
8779                 swatch[offset >> 3] |= 1 << (offset & 7);
8780             }
8781             return;
8782         }
8783
8784         /* Advance to the next range, which will be for code points not in the
8785          * inversion list */
8786         current = array[i];
8787     }
8788
8789     return;
8790 }
8791
8792 void
8793 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
8794                                          const bool complement_b, SV** output)
8795 {
8796     /* Take the union of two inversion lists and point <output> to it.  *output
8797      * SHOULD BE DEFINED upon input, and if it points to one of the two lists,
8798      * the reference count to that list will be decremented if not already a
8799      * temporary (mortal); otherwise *output will be made correspondingly
8800      * mortal.  The first list, <a>, may be NULL, in which case a copy of the
8801      * second list is returned.  If <complement_b> is TRUE, the union is taken
8802      * of the complement (inversion) of <b> instead of b itself.
8803      *
8804      * The basis for this comes from "Unicode Demystified" Chapter 13 by
8805      * Richard Gillam, published by Addison-Wesley, and explained at some
8806      * length there.  The preface says to incorporate its examples into your
8807      * code at your own risk.
8808      *
8809      * The algorithm is like a merge sort.
8810      *
8811      * XXX A potential performance improvement is to keep track as we go along
8812      * if only one of the inputs contributes to the result, meaning the other
8813      * is a subset of that one.  In that case, we can skip the final copy and
8814      * return the larger of the input lists, but then outside code might need
8815      * to keep track of whether to free the input list or not */
8816
8817     const UV* array_a;    /* a's array */
8818     const UV* array_b;
8819     UV len_a;       /* length of a's array */
8820     UV len_b;
8821
8822     SV* u;                      /* the resulting union */
8823     UV* array_u;
8824     UV len_u;
8825
8826     UV i_a = 0;             /* current index into a's array */
8827     UV i_b = 0;
8828     UV i_u = 0;
8829
8830     /* running count, as explained in the algorithm source book; items are
8831      * stopped accumulating and are output when the count changes to/from 0.
8832      * The count is incremented when we start a range that's in the set, and
8833      * decremented when we start a range that's not in the set.  So its range
8834      * is 0 to 2.  Only when the count is zero is something not in the set.
8835      */
8836     UV count = 0;
8837
8838     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
8839     assert(a != b);
8840
8841     /* If either one is empty, the union is the other one */
8842     if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
8843         bool make_temp = FALSE; /* Should we mortalize the result? */
8844
8845         if (*output == a) {
8846             if (a != NULL) {
8847                 if (! (make_temp = cBOOL(SvTEMP(a)))) {
8848                     SvREFCNT_dec_NN(a);
8849                 }
8850             }
8851         }
8852         if (*output != b) {
8853             *output = invlist_clone(b);
8854             if (complement_b) {
8855                 _invlist_invert(*output);
8856             }
8857         } /* else *output already = b; */
8858
8859         if (make_temp) {
8860             sv_2mortal(*output);
8861         }
8862         return;
8863     }
8864     else if ((len_b = _invlist_len(b)) == 0) {
8865         bool make_temp = FALSE;
8866         if (*output == b) {
8867             if (! (make_temp = cBOOL(SvTEMP(b)))) {
8868                 SvREFCNT_dec_NN(b);
8869             }
8870         }
8871
8872         /* The complement of an empty list is a list that has everything in it,
8873          * so the union with <a> includes everything too */
8874         if (complement_b) {
8875             if (a == *output) {
8876                 if (! (make_temp = cBOOL(SvTEMP(a)))) {
8877                     SvREFCNT_dec_NN(a);
8878                 }
8879             }
8880             *output = _new_invlist(1);
8881             _append_range_to_invlist(*output, 0, UV_MAX);
8882         }
8883         else if (*output != a) {
8884             *output = invlist_clone(a);
8885         }
8886         /* else *output already = a; */
8887
8888         if (make_temp) {
8889             sv_2mortal(*output);
8890         }
8891         return;
8892     }
8893
8894     /* Here both lists exist and are non-empty */
8895     array_a = invlist_array(a);
8896     array_b = invlist_array(b);
8897
8898     /* If are to take the union of 'a' with the complement of b, set it
8899      * up so are looking at b's complement. */
8900     if (complement_b) {
8901
8902         /* To complement, we invert: if the first element is 0, remove it.  To
8903          * do this, we just pretend the array starts one later */
8904         if (array_b[0] == 0) {
8905             array_b++;
8906             len_b--;
8907         }
8908         else {
8909
8910             /* But if the first element is not zero, we pretend the list starts
8911              * at the 0 that is always stored immediately before the array. */
8912             array_b--;
8913             len_b++;
8914         }
8915     }
8916
8917     /* Size the union for the worst case: that the sets are completely
8918      * disjoint */
8919     u = _new_invlist(len_a + len_b);
8920
8921     /* Will contain U+0000 if either component does */
8922     array_u = _invlist_array_init(u, (len_a > 0 && array_a[0] == 0)
8923                                       || (len_b > 0 && array_b[0] == 0));
8924
8925     /* Go through each list item by item, stopping when exhausted one of
8926      * them */
8927     while (i_a < len_a && i_b < len_b) {
8928         UV cp;      /* The element to potentially add to the union's array */
8929         bool cp_in_set;   /* is it in the the input list's set or not */
8930
8931         /* We need to take one or the other of the two inputs for the union.
8932          * Since we are merging two sorted lists, we take the smaller of the
8933          * next items.  In case of a tie, we take the one that is in its set
8934          * first.  If we took one not in the set first, it would decrement the
8935          * count, possibly to 0 which would cause it to be output as ending the
8936          * range, and the next time through we would take the same number, and
8937          * output it again as beginning the next range.  By doing it the
8938          * opposite way, there is no possibility that the count will be
8939          * momentarily decremented to 0, and thus the two adjoining ranges will
8940          * be seamlessly merged.  (In a tie and both are in the set or both not
8941          * in the set, it doesn't matter which we take first.) */
8942         if (array_a[i_a] < array_b[i_b]
8943             || (array_a[i_a] == array_b[i_b]
8944                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
8945         {
8946             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
8947             cp= array_a[i_a++];
8948         }
8949         else {
8950             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
8951             cp = array_b[i_b++];
8952         }
8953
8954         /* Here, have chosen which of the two inputs to look at.  Only output
8955          * if the running count changes to/from 0, which marks the
8956          * beginning/end of a range in that's in the set */
8957         if (cp_in_set) {
8958             if (count == 0) {
8959                 array_u[i_u++] = cp;
8960             }
8961             count++;
8962         }
8963         else {
8964             count--;
8965             if (count == 0) {
8966                 array_u[i_u++] = cp;
8967             }
8968         }
8969     }
8970
8971     /* Here, we are finished going through at least one of the lists, which
8972      * means there is something remaining in at most one.  We check if the list
8973      * that hasn't been exhausted is positioned such that we are in the middle
8974      * of a range in its set or not.  (i_a and i_b point to the element beyond
8975      * the one we care about.) If in the set, we decrement 'count'; if 0, there
8976      * is potentially more to output.
8977      * There are four cases:
8978      *  1) Both weren't in their sets, count is 0, and remains 0.  What's left
8979      *     in the union is entirely from the non-exhausted set.
8980      *  2) Both were in their sets, count is 2.  Nothing further should
8981      *     be output, as everything that remains will be in the exhausted
8982      *     list's set, hence in the union; decrementing to 1 but not 0 insures
8983      *     that
8984      *  3) the exhausted was in its set, non-exhausted isn't, count is 1.
8985      *     Nothing further should be output because the union includes
8986      *     everything from the exhausted set.  Not decrementing ensures that.
8987      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1;
8988      *     decrementing to 0 insures that we look at the remainder of the
8989      *     non-exhausted set */
8990     if ((i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
8991         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
8992     {
8993         count--;
8994     }
8995
8996     /* The final length is what we've output so far, plus what else is about to
8997      * be output.  (If 'count' is non-zero, then the input list we exhausted
8998      * has everything remaining up to the machine's limit in its set, and hence
8999      * in the union, so there will be no further output. */
9000     len_u = i_u;
9001     if (count == 0) {
9002         /* At most one of the subexpressions will be non-zero */
9003         len_u += (len_a - i_a) + (len_b - i_b);
9004     }
9005
9006     /* Set result to final length, which can change the pointer to array_u, so
9007      * re-find it */
9008     if (len_u != _invlist_len(u)) {
9009         invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
9010         invlist_trim(u);
9011         array_u = invlist_array(u);
9012     }
9013
9014     /* When 'count' is 0, the list that was exhausted (if one was shorter than
9015      * the other) ended with everything above it not in its set.  That means
9016      * that the remaining part of the union is precisely the same as the
9017      * non-exhausted list, so can just copy it unchanged.  (If both list were
9018      * exhausted at the same time, then the operations below will be both 0.)
9019      */
9020     if (count == 0) {
9021         IV copy_count; /* At most one will have a non-zero copy count */
9022         if ((copy_count = len_a - i_a) > 0) {
9023             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
9024         }
9025         else if ((copy_count = len_b - i_b) > 0) {
9026             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
9027         }
9028     }
9029
9030     /*  We may be removing a reference to one of the inputs.  If so, the output
9031      *  is made mortal if the input was.  (Mortal SVs shouldn't have their ref
9032      *  count decremented) */
9033     if (a == *output || b == *output) {
9034         assert(! invlist_is_iterating(*output));
9035         if ((SvTEMP(*output))) {
9036             sv_2mortal(u);
9037         }
9038         else {
9039             SvREFCNT_dec_NN(*output);
9040         }
9041     }
9042
9043     *output = u;
9044
9045     return;
9046 }
9047
9048 void
9049 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b,
9050                                                const bool complement_b, SV** i)
9051 {
9052     /* Take the intersection of two inversion lists and point <i> to it.  *i
9053      * SHOULD BE DEFINED upon input, and if it points to one of the two lists,
9054      * the reference count to that list will be decremented if not already a
9055      * temporary (mortal); otherwise *i will be made correspondingly mortal.
9056      * The first list, <a>, may be NULL, in which case an empty list is
9057      * returned.  If <complement_b> is TRUE, the result will be the
9058      * intersection of <a> and the complement (or inversion) of <b> instead of
9059      * <b> directly.
9060      *
9061      * The basis for this comes from "Unicode Demystified" Chapter 13 by
9062      * Richard Gillam, published by Addison-Wesley, and explained at some
9063      * length there.  The preface says to incorporate its examples into your
9064      * code at your own risk.  In fact, it had bugs
9065      *
9066      * The algorithm is like a merge sort, and is essentially the same as the
9067      * union above
9068      */
9069
9070     const UV* array_a;          /* a's array */
9071     const UV* array_b;
9072     UV len_a;   /* length of a's array */
9073     UV len_b;
9074
9075     SV* r;                   /* the resulting intersection */
9076     UV* array_r;
9077     UV len_r;
9078
9079     UV i_a = 0;             /* current index into a's array */
9080     UV i_b = 0;
9081     UV i_r = 0;
9082
9083     /* running count, as explained in the algorithm source book; items are
9084      * stopped accumulating and are output when the count changes to/from 2.
9085      * The count is incremented when we start a range that's in the set, and
9086      * decremented when we start a range that's not in the set.  So its range
9087      * is 0 to 2.  Only when the count is 2 is something in the intersection.
9088      */
9089     UV count = 0;
9090
9091     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
9092     assert(a != b);
9093
9094     /* Special case if either one is empty */
9095     len_a = (a == NULL) ? 0 : _invlist_len(a);
9096     if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
9097         bool make_temp = FALSE;
9098
9099         if (len_a != 0 && complement_b) {
9100
9101             /* Here, 'a' is not empty, therefore from the above 'if', 'b' must
9102              * be empty.  Here, also we are using 'b's complement, which hence
9103              * must be every possible code point.  Thus the intersection is
9104              * simply 'a'. */
9105             if (*i != a) {
9106                 if (*i == b) {
9107                     if (! (make_temp = cBOOL(SvTEMP(b)))) {
9108                         SvREFCNT_dec_NN(b);
9109                     }
9110                 }
9111
9112                 *i = invlist_clone(a);
9113             }
9114             /* else *i is already 'a' */
9115
9116             if (make_temp) {
9117                 sv_2mortal(*i);
9118             }
9119             return;
9120         }
9121
9122         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
9123          * intersection must be empty */
9124         if (*i == a) {
9125             if (! (make_temp = cBOOL(SvTEMP(a)))) {
9126                 SvREFCNT_dec_NN(a);
9127             }
9128         }
9129         else if (*i == b) {
9130             if (! (make_temp = cBOOL(SvTEMP(b)))) {
9131                 SvREFCNT_dec_NN(b);
9132             }
9133         }
9134         *i = _new_invlist(0);
9135         if (make_temp) {
9136             sv_2mortal(*i);
9137         }
9138
9139         return;
9140     }
9141
9142     /* Here both lists exist and are non-empty */
9143     array_a = invlist_array(a);
9144     array_b = invlist_array(b);
9145
9146     /* If are to take the intersection of 'a' with the complement of b, set it
9147      * up so are looking at b's complement. */
9148     if (complement_b) {
9149
9150         /* To complement, we invert: if the first element is 0, remove it.  To
9151          * do this, we just pretend the array starts one later */
9152         if (array_b[0] == 0) {
9153             array_b++;
9154             len_b--;
9155         }
9156         else {
9157
9158             /* But if the first element is not zero, we pretend the list starts
9159              * at the 0 that is always stored immediately before the array. */
9160             array_b--;
9161             len_b++;
9162         }
9163     }
9164
9165     /* Size the intersection for the worst case: that the intersection ends up
9166      * fragmenting everything to be completely disjoint */
9167     r= _new_invlist(len_a + len_b);
9168
9169     /* Will contain U+0000 iff both components do */
9170     array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
9171                                      && len_b > 0 && array_b[0] == 0);
9172
9173     /* Go through each list item by item, stopping when exhausted one of
9174      * them */
9175     while (i_a < len_a && i_b < len_b) {
9176         UV cp;      /* The element to potentially add to the intersection's
9177                        array */
9178         bool cp_in_set; /* Is it in the input list's set or not */
9179
9180         /* We need to take one or the other of the two inputs for the
9181          * intersection.  Since we are merging two sorted lists, we take the
9182          * smaller of the next items.  In case of a tie, we take the one that
9183          * is not in its set first (a difference from the union algorithm).  If
9184          * we took one in the set first, it would increment the count, possibly
9185          * to 2 which would cause it to be output as starting a range in the
9186          * intersection, and the next time through we would take that same
9187          * number, and output it again as ending the set.  By doing it the
9188          * opposite of this, there is no possibility that the count will be
9189          * momentarily incremented to 2.  (In a tie and both are in the set or
9190          * both not in the set, it doesn't matter which we take first.) */
9191         if (array_a[i_a] < array_b[i_b]
9192             || (array_a[i_a] == array_b[i_b]
9193                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
9194         {
9195             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
9196             cp= array_a[i_a++];
9197         }
9198         else {
9199             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
9200             cp= array_b[i_b++];
9201         }
9202
9203         /* Here, have chosen which of the two inputs to look at.  Only output
9204          * if the running count changes to/from 2, which marks the
9205          * beginning/end of a range that's in the intersection */
9206         if (cp_in_set) {
9207             count++;
9208             if (count == 2) {
9209                 array_r[i_r++] = cp;
9210             }
9211         }
9212         else {
9213             if (count == 2) {
9214                 array_r[i_r++] = cp;
9215             }
9216             count--;
9217         }
9218     }
9219
9220     /* Here, we are finished going through at least one of the lists, which
9221      * means there is something remaining in at most one.  We check if the list
9222      * that has been exhausted is positioned such that we are in the middle
9223      * of a range in its set or not.  (i_a and i_b point to elements 1 beyond
9224      * the ones we care about.)  There are four cases:
9225      *  1) Both weren't in their sets, count is 0, and remains 0.  There's
9226      *     nothing left in the intersection.
9227      *  2) Both were in their sets, count is 2 and perhaps is incremented to
9228      *     above 2.  What should be output is exactly that which is in the
9229      *     non-exhausted set, as everything it has is also in the intersection
9230      *     set, and everything it doesn't have can't be in the intersection
9231      *  3) The exhausted was in its set, non-exhausted isn't, count is 1, and
9232      *     gets incremented to 2.  Like the previous case, the intersection is
9233      *     everything that remains in the non-exhausted set.
9234      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1, and
9235      *     remains 1.  And the intersection has nothing more. */
9236     if ((i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
9237         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
9238     {
9239         count++;
9240     }
9241
9242     /* The final length is what we've output so far plus what else is in the
9243      * intersection.  At most one of the subexpressions below will be non-zero
9244      * */
9245     len_r = i_r;
9246     if (count >= 2) {
9247         len_r += (len_a - i_a) + (len_b - i_b);
9248     }
9249
9250     /* Set result to final length, which can change the pointer to array_r, so
9251      * re-find it */
9252     if (len_r != _invlist_len(r)) {
9253         invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
9254         invlist_trim(r);
9255         array_r = invlist_array(r);
9256     }
9257
9258     /* Finish outputting any remaining */
9259     if (count >= 2) { /* At most one will have a non-zero copy count */
9260         IV copy_count;
9261         if ((copy_count = len_a - i_a) > 0) {
9262             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
9263         }
9264         else if ((copy_count = len_b - i_b) > 0) {
9265             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
9266         }
9267     }
9268
9269     /*  We may be removing a reference to one of the inputs.  If so, the output
9270      *  is made mortal if the input was.  (Mortal SVs shouldn't have their ref
9271      *  count decremented) */
9272     if (a == *i || b == *i) {
9273         assert(! invlist_is_iterating(*i));
9274         if (SvTEMP(*i)) {
9275             sv_2mortal(r);
9276         }
9277         else {
9278             SvREFCNT_dec_NN(*i);
9279         }
9280     }
9281
9282     *i = r;
9283
9284     return;
9285 }
9286
9287 SV*
9288 Perl__add_range_to_invlist(pTHX_ SV* invlist, const UV start, const UV end)
9289 {
9290     /* Add the range from 'start' to 'end' inclusive to the inversion list's
9291      * set.  A pointer to the inversion list is returned.  This may actually be
9292      * a new list, in which case the passed in one has been destroyed.  The
9293      * passed-in inversion list can be NULL, in which case a new one is created
9294      * with just the one range in it */
9295
9296     SV* range_invlist;
9297     UV len;
9298
9299     if (invlist == NULL) {
9300         invlist = _new_invlist(2);
9301         len = 0;
9302     }
9303     else {
9304         len = _invlist_len(invlist);
9305     }
9306
9307     /* If comes after the final entry actually in the list, can just append it
9308      * to the end, */
9309     if (len == 0
9310         || (! ELEMENT_RANGE_MATCHES_INVLIST(len - 1)
9311             && start >= invlist_array(invlist)[len - 1]))
9312     {
9313         _append_range_to_invlist(invlist, start, end);
9314         return invlist;
9315     }
9316
9317     /* Here, can't just append things, create and return a new inversion list
9318      * which is the union of this range and the existing inversion list.  (If
9319      * the new range is well-behaved wrt to the old one, we could just insert
9320      * it, doing a Move() down on the tail of the old one (potentially growing
9321      * it first).  But to determine that means we would have the extra
9322      * (possibly throw-away) work of first finding where the new one goes and
9323      * whether it disrupts (splits) an existing range, so it doesn't appear to
9324      * me (khw) that it's worth it) */
9325     range_invlist = _new_invlist(2);
9326     _append_range_to_invlist(range_invlist, start, end);
9327
9328     _invlist_union(invlist, range_invlist, &invlist);
9329
9330     /* The temporary can be freed */
9331     SvREFCNT_dec_NN(range_invlist);
9332
9333     return invlist;
9334 }
9335
9336 SV*
9337 Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0,
9338                                  UV** other_elements_ptr)
9339 {
9340     /* Create and return an inversion list whose contents are to be populated
9341      * by the caller.  The caller gives the number of elements (in 'size') and
9342      * the very first element ('element0').  This function will set
9343      * '*other_elements_ptr' to an array of UVs, where the remaining elements
9344      * are to be placed.
9345      *
9346      * Obviously there is some trust involved that the caller will properly
9347      * fill in the other elements of the array.
9348      *
9349      * (The first element needs to be passed in, as the underlying code does
9350      * things differently depending on whether it is zero or non-zero) */
9351
9352     SV* invlist = _new_invlist(size);
9353     bool offset;
9354
9355     PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST;
9356
9357     _append_range_to_invlist(invlist, element0, element0);
9358     offset = *get_invlist_offset_addr(invlist);
9359
9360     invlist_set_len(invlist, size, offset);
9361     *other_elements_ptr = invlist_array(invlist) + 1;
9362     return invlist;
9363 }
9364
9365 #endif
9366
9367 PERL_STATIC_INLINE SV*
9368 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
9369     return _add_range_to_invlist(invlist, cp, cp);
9370 }
9371
9372 #ifndef PERL_IN_XSUB_RE
9373 void
9374 Perl__invlist_invert(pTHX_ SV* const invlist)
9375 {
9376     /* Complement the input inversion list.  This adds a 0 if the list didn't
9377      * have a zero; removes it otherwise.  As described above, the data
9378      * structure is set up so that this is very efficient */
9379
9380     PERL_ARGS_ASSERT__INVLIST_INVERT;
9381
9382     assert(! invlist_is_iterating(invlist));
9383
9384     /* The inverse of matching nothing is matching everything */
9385     if (_invlist_len(invlist) == 0) {
9386         _append_range_to_invlist(invlist, 0, UV_MAX);
9387         return;
9388     }
9389
9390     *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
9391 }
9392
9393 #endif
9394
9395 PERL_STATIC_INLINE SV*
9396 S_invlist_clone(pTHX_ SV* const invlist)
9397 {
9398
9399     /* Return a new inversion list that is a copy of the input one, which is
9400      * unchanged.  The new list will not be mortal even if the old one was. */
9401
9402     /* Need to allocate extra space to accommodate Perl's addition of a
9403      * trailing NUL to SvPV's, since it thinks they are always strings */
9404     SV* new_invlist = _new_invlist(_invlist_len(invlist) + 1);
9405     STRLEN physical_length = SvCUR(invlist);
9406     bool offset = *(get_invlist_offset_addr(invlist));
9407
9408     PERL_ARGS_ASSERT_INVLIST_CLONE;
9409
9410     *(get_invlist_offset_addr(new_invlist)) = offset;
9411     invlist_set_len(new_invlist, _invlist_len(invlist), offset);
9412     Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
9413
9414     return new_invlist;
9415 }
9416
9417 PERL_STATIC_INLINE STRLEN*
9418 S_get_invlist_iter_addr(SV* invlist)
9419 {
9420     /* Return the address of the UV that contains the current iteration
9421      * position */
9422
9423     PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
9424
9425     assert(SvTYPE(invlist) == SVt_INVLIST);
9426
9427     return &(((XINVLIST*) SvANY(invlist))->iterator);
9428 }
9429
9430 PERL_STATIC_INLINE void
9431 S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */
9432 {
9433     PERL_ARGS_ASSERT_INVLIST_ITERINIT;
9434
9435     *get_invlist_iter_addr(invlist) = 0;
9436 }
9437
9438 PERL_STATIC_INLINE void
9439 S_invlist_iterfinish(SV* invlist)
9440 {
9441     /* Terminate iterator for invlist.  This is to catch development errors.
9442      * Any iteration that is interrupted before completed should call this
9443      * function.  Functions that add code points anywhere else but to the end
9444      * of an inversion list assert that they are not in the middle of an
9445      * iteration.  If they were, the addition would make the iteration
9446      * problematical: if the iteration hadn't reached the place where things
9447      * were being added, it would be ok */
9448
9449     PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
9450
9451     *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
9452 }
9453
9454 STATIC bool
9455 S_invlist_iternext(SV* invlist, UV* start, UV* end)
9456 {
9457     /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
9458      * This call sets in <*start> and <*end>, the next range in <invlist>.
9459      * Returns <TRUE> if successful and the next call will return the next
9460      * range; <FALSE> if was already at the end of the list.  If the latter,
9461      * <*start> and <*end> are unchanged, and the next call to this function
9462      * will start over at the beginning of the list */
9463
9464     STRLEN* pos = get_invlist_iter_addr(invlist);
9465     UV len = _invlist_len(invlist);
9466     UV *array;
9467
9468     PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
9469
9470     if (*pos >= len) {
9471         *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
9472         return FALSE;
9473     }
9474
9475     array = invlist_array(invlist);
9476
9477     *start = array[(*pos)++];
9478
9479     if (*pos >= len) {
9480         *end = UV_MAX;
9481     }
9482     else {
9483         *end = array[(*pos)++] - 1;
9484     }
9485
9486     return TRUE;
9487 }
9488
9489 PERL_STATIC_INLINE UV
9490 S_invlist_highest(SV* const invlist)
9491 {
9492     /* Returns the highest code point that matches an inversion list.  This API
9493      * has an ambiguity, as it returns 0 under either the highest is actually
9494      * 0, or if the list is empty.  If this distinction matters to you, check
9495      * for emptiness before calling this function */
9496
9497     UV len = _invlist_len(invlist);
9498     UV *array;
9499
9500     PERL_ARGS_ASSERT_INVLIST_HIGHEST;
9501
9502     if (len == 0) {
9503         return 0;
9504     }
9505
9506     array = invlist_array(invlist);
9507
9508     /* The last element in the array in the inversion list always starts a
9509      * range that goes to infinity.  That range may be for code points that are
9510      * matched in the inversion list, or it may be for ones that aren't
9511      * matched.  In the latter case, the highest code point in the set is one
9512      * less than the beginning of this range; otherwise it is the final element
9513      * of this range: infinity */
9514     return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
9515            ? UV_MAX
9516            : array[len - 1] - 1;
9517 }
9518
9519 #ifndef PERL_IN_XSUB_RE
9520 SV *
9521 Perl__invlist_contents(pTHX_ SV* const invlist)
9522 {
9523     /* Get the contents of an inversion list into a string SV so that they can
9524      * be printed out.  It uses the format traditionally done for debug tracing
9525      */
9526
9527     UV start, end;
9528     SV* output = newSVpvs("\n");
9529
9530     PERL_ARGS_ASSERT__INVLIST_CONTENTS;
9531
9532     assert(! invlist_is_iterating(invlist));
9533
9534     invlist_iterinit(invlist);
9535     while (invlist_iternext(invlist, &start, &end)) {
9536         if (end == UV_MAX) {
9537             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\tINFINITY\n", start);
9538         }
9539         else if (end != start) {
9540             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\t%04"UVXf"\n",
9541                     start,       end);
9542         }
9543         else {
9544             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\n", start);
9545         }
9546     }
9547
9548     return output;
9549 }
9550 #endif
9551
9552 #ifndef PERL_IN_XSUB_RE
9553 void
9554 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level,
9555                          const char * const indent, SV* const invlist)
9556 {
9557     /* Designed to be called only by do_sv_dump().  Dumps out the ranges of the
9558      * inversion list 'invlist' to 'file' at 'level'  Each line is prefixed by
9559      * the string 'indent'.  The output looks like this:
9560          [0] 0x000A .. 0x000D
9561          [2] 0x0085
9562          [4] 0x2028 .. 0x2029
9563          [6] 0x3104 .. INFINITY
9564      * This means that the first range of code points matched by the list are
9565      * 0xA through 0xD; the second range contains only the single code point
9566      * 0x85, etc.  An inversion list is an array of UVs.  Two array elements
9567      * are used to define each range (except if the final range extends to
9568      * infinity, only a single element is needed).  The array index of the
9569      * first element for the corresponding range is given in brackets. */
9570
9571     UV start, end;
9572     STRLEN count = 0;
9573
9574     PERL_ARGS_ASSERT__INVLIST_DUMP;
9575
9576     if (invlist_is_iterating(invlist)) {
9577         Perl_dump_indent(aTHX_ level, file,
9578              "%sCan't dump inversion list because is in middle of iterating\n",
9579              indent);
9580         return;
9581     }
9582
9583     invlist_iterinit(invlist);
9584     while (invlist_iternext(invlist, &start, &end)) {
9585         if (end == UV_MAX) {
9586             Perl_dump_indent(aTHX_ level, file,
9587                                        "%s[%"UVuf"] 0x%04"UVXf" .. INFINITY\n",
9588                                    indent, (UV)count, start);
9589         }
9590         else if (end != start) {
9591             Perl_dump_indent(aTHX_ level, file,
9592                                     "%s[%"UVuf"] 0x%04"UVXf" .. 0x%04"UVXf"\n",
9593                                 indent, (UV)count, start,         end);
9594         }
9595         else {
9596             Perl_dump_indent(aTHX_ level, file, "%s[%"UVuf"] 0x%04"UVXf"\n",
9597                                             indent, (UV)count, start);
9598         }
9599         count += 2;
9600     }
9601 }
9602
9603 void
9604 Perl__load_PL_utf8_foldclosures (pTHX)
9605 {
9606     assert(! PL_utf8_foldclosures);
9607
9608     /* If the folds haven't been read in, call a fold function
9609      * to force that */
9610     if (! PL_utf8_tofold) {
9611         U8 dummy[UTF8_MAXBYTES_CASE+1];
9612
9613         /* This string is just a short named one above \xff */
9614         to_utf8_fold((U8*) HYPHEN_UTF8, dummy, NULL);
9615         assert(PL_utf8_tofold); /* Verify that worked */
9616     }
9617     PL_utf8_foldclosures = _swash_inversion_hash(PL_utf8_tofold);
9618 }
9619 #endif
9620
9621 #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE)
9622 bool
9623 Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
9624 {
9625     /* Return a boolean as to if the two passed in inversion lists are
9626      * identical.  The final argument, if TRUE, says to take the complement of
9627      * the second inversion list before doing the comparison */
9628
9629     const UV* array_a = invlist_array(a);
9630     const UV* array_b = invlist_array(b);
9631     UV len_a = _invlist_len(a);
9632     UV len_b = _invlist_len(b);
9633
9634     UV i = 0;               /* current index into the arrays */
9635     bool retval = TRUE;     /* Assume are identical until proven otherwise */
9636
9637     PERL_ARGS_ASSERT__INVLISTEQ;
9638
9639     /* If are to compare 'a' with the complement of b, set it
9640      * up so are looking at b's complement. */
9641     if (complement_b) {
9642
9643         /* The complement of nothing is everything, so <a> would have to have
9644          * just one element, starting at zero (ending at infinity) */
9645         if (len_b == 0) {
9646             return (len_a == 1 && array_a[0] == 0);
9647         }
9648         else if (array_b[0] == 0) {
9649
9650             /* Otherwise, to complement, we invert.  Here, the first element is
9651              * 0, just remove it.  To do this, we just pretend the array starts
9652              * one later */
9653
9654             array_b++;
9655             len_b--;
9656         }
9657         else {
9658
9659             /* But if the first element is not zero, we pretend the list starts
9660              * at the 0 that is always stored immediately before the array. */
9661             array_b--;
9662             len_b++;
9663         }
9664     }
9665
9666     /* Make sure that the lengths are the same, as well as the final element
9667      * before looping through the remainder.  (Thus we test the length, final,
9668      * and first elements right off the bat) */
9669     if (len_a != len_b || array_a[len_a-1] != array_b[len_a-1]) {
9670         retval = FALSE;
9671     }
9672     else for (i = 0; i < len_a - 1; i++) {
9673         if (array_a[i] != array_b[i]) {
9674             retval = FALSE;
9675             break;
9676         }
9677     }
9678
9679     return retval;
9680 }
9681 #endif
9682
9683 /*
9684  * As best we can, determine the characters that can match the start of
9685  * the given EXACTF-ish node.
9686  *
9687  * Returns the invlist as a new SV*; it is the caller's responsibility to
9688  * call SvREFCNT_dec() when done with it.
9689  */
9690 STATIC SV*
9691 S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node)
9692 {
9693     const U8 * s = (U8*)STRING(node);
9694     SSize_t bytelen = STR_LEN(node);
9695     UV uc;
9696     /* Start out big enough for 2 separate code points */
9697     SV* invlist = _new_invlist(4);
9698
9699     PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST;
9700
9701     if (! UTF) {
9702         uc = *s;
9703
9704         /* We punt and assume can match anything if the node begins
9705          * with a multi-character fold.  Things are complicated.  For
9706          * example, /ffi/i could match any of:
9707          *  "\N{LATIN SMALL LIGATURE FFI}"
9708          *  "\N{LATIN SMALL LIGATURE FF}I"
9709          *  "F\N{LATIN SMALL LIGATURE FI}"
9710          *  plus several other things; and making sure we have all the
9711          *  possibilities is hard. */
9712         if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) {
9713             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
9714         }
9715         else {
9716             /* Any Latin1 range character can potentially match any
9717              * other depending on the locale */
9718             if (OP(node) == EXACTFL) {
9719                 _invlist_union(invlist, PL_Latin1, &invlist);
9720             }
9721             else {
9722                 /* But otherwise, it matches at least itself.  We can
9723                  * quickly tell if it has a distinct fold, and if so,
9724                  * it matches that as well */
9725                 invlist = add_cp_to_invlist(invlist, uc);
9726                 if (IS_IN_SOME_FOLD_L1(uc))
9727                     invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]);
9728             }
9729
9730             /* Some characters match above-Latin1 ones under /i.  This
9731              * is true of EXACTFL ones when the locale is UTF-8 */
9732             if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc)
9733                 && (! isASCII(uc) || (OP(node) != EXACTFA
9734                                     && OP(node) != EXACTFA_NO_TRIE)))
9735             {
9736                 add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist);
9737             }
9738         }
9739     }
9740     else {  /* Pattern is UTF-8 */
9741         U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
9742         STRLEN foldlen = UTF8SKIP(s);
9743         const U8* e = s + bytelen;
9744         SV** listp;
9745
9746         uc = utf8_to_uvchr_buf(s, s + bytelen, NULL);
9747
9748         /* The only code points that aren't folded in a UTF EXACTFish
9749          * node are are the problematic ones in EXACTFL nodes */
9750         if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) {
9751             /* We need to check for the possibility that this EXACTFL
9752              * node begins with a multi-char fold.  Therefore we fold
9753              * the first few characters of it so that we can make that
9754              * check */
9755             U8 *d = folded;
9756             int i;
9757
9758             for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) {
9759                 if (isASCII(*s)) {
9760                     *(d++) = (U8) toFOLD(*s);
9761                     s++;
9762                 }
9763                 else {
9764                     STRLEN len;
9765                     to_utf8_fold(s, d, &len);
9766                     d += len;
9767                     s += UTF8SKIP(s);
9768                 }
9769             }
9770
9771             /* And set up so the code below that looks in this folded
9772              * buffer instead of the node's string */
9773             e = d;
9774             foldlen = UTF8SKIP(folded);
9775             s = folded;
9776         }
9777
9778         /* When we reach here 's' points to the fold of the first
9779          * character(s) of the node; and 'e' points to far enough along
9780          * the folded string to be just past any possible multi-char
9781          * fold. 'foldlen' is the length in bytes of the first
9782          * character in 's'
9783          *
9784          * Unlike the non-UTF-8 case, the macro for determining if a
9785          * string is a multi-char fold requires all the characters to
9786          * already be folded.  This is because of all the complications
9787          * if not.  Note that they are folded anyway, except in EXACTFL
9788          * nodes.  Like the non-UTF case above, we punt if the node
9789          * begins with a multi-char fold  */
9790
9791         if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) {
9792             invlist = _add_range_to_invlist(invlist, 0, UV_MAX);
9793         }
9794         else {  /* Single char fold */
9795
9796             /* It matches all the things that fold to it, which are
9797              * found in PL_utf8_foldclosures (including itself) */
9798             invlist = add_cp_to_invlist(invlist, uc);
9799             if (! PL_utf8_foldclosures)
9800                 _load_PL_utf8_foldclosures();
9801             if ((listp = hv_fetch(PL_utf8_foldclosures,
9802                                 (char *) s, foldlen, FALSE)))
9803             {
9804                 AV* list = (AV*) *listp;
9805                 IV k;
9806                 for (k = 0; k <= av_tindex(list); k++) {
9807                     SV** c_p = av_fetch(list, k, FALSE);
9808                     UV c;
9809                     assert(c_p);
9810
9811                     c = SvUV(*c_p);
9812
9813                     /* /aa doesn't allow folds between ASCII and non- */
9814                     if ((OP(node) == EXACTFA || OP(node) == EXACTFA_NO_TRIE)
9815                         && isASCII(c) != isASCII(uc))
9816                     {
9817                         continue;
9818                     }
9819
9820                     invlist = add_cp_to_invlist(invlist, c);
9821                 }
9822             }
9823         }
9824     }
9825
9826     return invlist;
9827 }
9828
9829 #undef HEADER_LENGTH
9830 #undef TO_INTERNAL_SIZE
9831 #undef FROM_INTERNAL_SIZE
9832 #undef INVLIST_VERSION_ID
9833
9834 /* End of inversion list object */
9835
9836 STATIC void
9837 S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state)
9838 {
9839     /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
9840      * constructs, and updates RExC_flags with them.  On input, RExC_parse
9841      * should point to the first flag; it is updated on output to point to the
9842      * final ')' or ':'.  There needs to be at least one flag, or this will
9843      * abort */
9844
9845     /* for (?g), (?gc), and (?o) warnings; warning
9846        about (?c) will warn about (?g) -- japhy    */
9847
9848 #define WASTED_O  0x01
9849 #define WASTED_G  0x02
9850 #define WASTED_C  0x04
9851 #define WASTED_GC (WASTED_G|WASTED_C)
9852     I32 wastedflags = 0x00;
9853     U32 posflags = 0, negflags = 0;
9854     U32 *flagsp = &posflags;
9855     char has_charset_modifier = '\0';
9856     regex_charset cs;
9857     bool has_use_defaults = FALSE;
9858     const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
9859     int x_mod_count = 0;
9860
9861     PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
9862
9863     /* '^' as an initial flag sets certain defaults */
9864     if (UCHARAT(RExC_parse) == '^') {
9865         RExC_parse++;
9866         has_use_defaults = TRUE;
9867         STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
9868         set_regex_charset(&RExC_flags, (RExC_utf8 || RExC_uni_semantics)
9869                                         ? REGEX_UNICODE_CHARSET
9870                                         : REGEX_DEPENDS_CHARSET);
9871     }
9872
9873     cs = get_regex_charset(RExC_flags);
9874     if (cs == REGEX_DEPENDS_CHARSET
9875         && (RExC_utf8 || RExC_uni_semantics))
9876     {
9877         cs = REGEX_UNICODE_CHARSET;
9878     }
9879
9880     while (RExC_parse < RExC_end) {
9881         /* && strchr("iogcmsx", *RExC_parse) */
9882         /* (?g), (?gc) and (?o) are useless here
9883            and must be globally applied -- japhy */
9884         switch (*RExC_parse) {
9885
9886             /* Code for the imsxn flags */
9887             CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count);
9888
9889             case LOCALE_PAT_MOD:
9890                 if (has_charset_modifier) {
9891                     goto excess_modifier;
9892                 }
9893                 else if (flagsp == &negflags) {
9894                     goto neg_modifier;
9895                 }
9896                 cs = REGEX_LOCALE_CHARSET;
9897                 has_charset_modifier = LOCALE_PAT_MOD;
9898                 break;
9899             case UNICODE_PAT_MOD:
9900                 if (has_charset_modifier) {
9901                     goto excess_modifier;
9902                 }
9903                 else if (flagsp == &negflags) {
9904                     goto neg_modifier;
9905                 }
9906                 cs = REGEX_UNICODE_CHARSET;
9907                 has_charset_modifier = UNICODE_PAT_MOD;
9908                 break;
9909             case ASCII_RESTRICT_PAT_MOD:
9910                 if (flagsp == &negflags) {
9911                     goto neg_modifier;
9912                 }
9913                 if (has_charset_modifier) {
9914                     if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
9915                         goto excess_modifier;
9916                     }
9917                     /* Doubled modifier implies more restricted */
9918                     cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
9919                 }
9920                 else {
9921                     cs = REGEX_ASCII_RESTRICTED_CHARSET;
9922                 }
9923                 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
9924                 break;
9925             case DEPENDS_PAT_MOD:
9926                 if (has_use_defaults) {
9927                     goto fail_modifiers;
9928                 }
9929                 else if (flagsp == &negflags) {
9930                     goto neg_modifier;
9931                 }
9932                 else if (has_charset_modifier) {
9933                     goto excess_modifier;
9934                 }
9935
9936                 /* The dual charset means unicode semantics if the
9937                  * pattern (or target, not known until runtime) are
9938                  * utf8, or something in the pattern indicates unicode
9939                  * semantics */
9940                 cs = (RExC_utf8 || RExC_uni_semantics)
9941                      ? REGEX_UNICODE_CHARSET
9942                      : REGEX_DEPENDS_CHARSET;
9943                 has_charset_modifier = DEPENDS_PAT_MOD;
9944                 break;
9945               excess_modifier:
9946                 RExC_parse++;
9947                 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
9948                     vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
9949                 }
9950                 else if (has_charset_modifier == *(RExC_parse - 1)) {
9951                     vFAIL2("Regexp modifier \"%c\" may not appear twice",
9952                                         *(RExC_parse - 1));
9953                 }
9954                 else {
9955                     vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
9956                 }
9957                 NOT_REACHED; /*NOTREACHED*/
9958               neg_modifier:
9959                 RExC_parse++;
9960                 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"",
9961                                     *(RExC_parse - 1));
9962                 NOT_REACHED; /*NOTREACHED*/
9963             case ONCE_PAT_MOD: /* 'o' */
9964             case GLOBAL_PAT_MOD: /* 'g' */
9965                 if (PASS2 && ckWARN(WARN_REGEXP)) {
9966                     const I32 wflagbit = *RExC_parse == 'o'
9967                                          ? WASTED_O
9968                                          : WASTED_G;
9969                     if (! (wastedflags & wflagbit) ) {
9970                         wastedflags |= wflagbit;
9971                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
9972                         vWARN5(
9973                             RExC_parse + 1,
9974                             "Useless (%s%c) - %suse /%c modifier",
9975                             flagsp == &negflags ? "?-" : "?",
9976                             *RExC_parse,
9977                             flagsp == &negflags ? "don't " : "",
9978                             *RExC_parse
9979                         );
9980                     }
9981                 }
9982                 break;
9983
9984             case CONTINUE_PAT_MOD: /* 'c' */
9985                 if (PASS2 && ckWARN(WARN_REGEXP)) {
9986                     if (! (wastedflags & WASTED_C) ) {
9987                         wastedflags |= WASTED_GC;
9988                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
9989                         vWARN3(
9990                             RExC_parse + 1,
9991                             "Useless (%sc) - %suse /gc modifier",
9992                             flagsp == &negflags ? "?-" : "?",
9993                             flagsp == &negflags ? "don't " : ""
9994                         );
9995                     }
9996                 }
9997                 break;
9998             case KEEPCOPY_PAT_MOD: /* 'p' */
9999                 if (flagsp == &negflags) {
10000                     if (PASS2)
10001                         ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
10002                 } else {
10003                     *flagsp |= RXf_PMf_KEEPCOPY;
10004                 }
10005                 break;
10006             case '-':
10007                 /* A flag is a default iff it is following a minus, so
10008                  * if there is a minus, it means will be trying to
10009                  * re-specify a default which is an error */
10010                 if (has_use_defaults || flagsp == &negflags) {
10011                     goto fail_modifiers;
10012                 }
10013                 flagsp = &negflags;
10014                 wastedflags = 0;  /* reset so (?g-c) warns twice */
10015                 break;
10016             case ':':
10017             case ')':
10018                 RExC_flags |= posflags;
10019                 RExC_flags &= ~negflags;
10020                 set_regex_charset(&RExC_flags, cs);
10021                 if (RExC_flags & RXf_PMf_FOLD) {
10022                     RExC_contains_i = 1;
10023                 }
10024                 if (PASS2) {
10025                     STD_PMMOD_FLAGS_PARSE_X_WARN(x_mod_count);
10026                 }
10027                 return;
10028                 /*NOTREACHED*/
10029             default:
10030               fail_modifiers:
10031                 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10032                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10033                 vFAIL2utf8f("Sequence (%"UTF8f"...) not recognized",
10034                       UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10035                 NOT_REACHED; /*NOTREACHED*/
10036         }
10037
10038         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10039     }
10040
10041     vFAIL("Sequence (?... not terminated");
10042 }
10043
10044 /*
10045  - reg - regular expression, i.e. main body or parenthesized thing
10046  *
10047  * Caller must absorb opening parenthesis.
10048  *
10049  * Combining parenthesis handling with the base level of regular expression
10050  * is a trifle forced, but the need to tie the tails of the branches to what
10051  * follows makes it hard to avoid.
10052  */
10053 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
10054 #ifdef DEBUGGING
10055 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
10056 #else
10057 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
10058 #endif
10059
10060 PERL_STATIC_INLINE regnode *
10061 S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state,
10062                              I32 *flagp,
10063                              char * parse_start,
10064                              char ch
10065                       )
10066 {
10067     regnode *ret;
10068     char* name_start = RExC_parse;
10069     U32 num = 0;
10070     SV *sv_dat = reg_scan_name(pRExC_state, SIZE_ONLY
10071                                             ? REG_RSN_RETURN_NULL
10072                                             : REG_RSN_RETURN_DATA);
10073     GET_RE_DEBUG_FLAGS_DECL;
10074
10075     PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF;
10076
10077     if (RExC_parse == name_start || *RExC_parse != ch) {
10078         /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
10079         vFAIL2("Sequence %.3s... not terminated",parse_start);
10080     }
10081
10082     if (!SIZE_ONLY) {
10083         num = add_data( pRExC_state, STR_WITH_LEN("S"));
10084         RExC_rxi->data->data[num]=(void*)sv_dat;
10085         SvREFCNT_inc_simple_void(sv_dat);
10086     }
10087     RExC_sawback = 1;
10088     ret = reganode(pRExC_state,
10089                    ((! FOLD)
10090                      ? NREF
10091                      : (ASCII_FOLD_RESTRICTED)
10092                        ? NREFFA
10093                        : (AT_LEAST_UNI_SEMANTICS)
10094                          ? NREFFU
10095                          : (LOC)
10096                            ? NREFFL
10097                            : NREFF),
10098                     num);
10099     *flagp |= HASWIDTH;
10100
10101     Set_Node_Offset(ret, parse_start+1);
10102     Set_Node_Cur_Length(ret, parse_start);
10103
10104     nextchar(pRExC_state);
10105     return ret;
10106 }
10107
10108 /* Returns NULL, setting *flagp to TRYAGAIN at the end of (?) that only sets
10109    flags. Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan
10110    needs to be restarted, or'd with NEED_UTF8 if the pattern needs to be
10111    upgraded to UTF-8.  Otherwise would only return NULL if regbranch() returns
10112    NULL, which cannot happen.  */
10113 STATIC regnode *
10114 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
10115     /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
10116      * 2 is like 1, but indicates that nextchar() has been called to advance
10117      * RExC_parse beyond the '('.  Things like '(?' are indivisible tokens, and
10118      * this flag alerts us to the need to check for that */
10119 {
10120     regnode *ret;               /* Will be the head of the group. */
10121     regnode *br;
10122     regnode *lastbr;
10123     regnode *ender = NULL;
10124     I32 parno = 0;
10125     I32 flags;
10126     U32 oregflags = RExC_flags;
10127     bool have_branch = 0;
10128     bool is_open = 0;
10129     I32 freeze_paren = 0;
10130     I32 after_freeze = 0;
10131     I32 num; /* numeric backreferences */
10132
10133     char * parse_start = RExC_parse; /* MJD */
10134     char * const oregcomp_parse = RExC_parse;
10135
10136     GET_RE_DEBUG_FLAGS_DECL;
10137
10138     PERL_ARGS_ASSERT_REG;
10139     DEBUG_PARSE("reg ");
10140
10141     *flagp = 0;                         /* Tentatively. */
10142
10143     /* Having this true makes it feasible to have a lot fewer tests for the
10144      * parse pointer being in scope.  For example, we can write
10145      *      while(isFOO(*RExC_parse)) RExC_parse++;
10146      * instead of
10147      *      while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++;
10148      */
10149     assert(*RExC_end == '\0');
10150
10151     /* Make an OPEN node, if parenthesized. */
10152     if (paren) {
10153
10154         /* Under /x, space and comments can be gobbled up between the '(' and
10155          * here (if paren ==2).  The forms '(*VERB' and '(?...' disallow such
10156          * intervening space, as the sequence is a token, and a token should be
10157          * indivisible */
10158         bool has_intervening_patws = paren == 2 && *(RExC_parse - 1) != '(';
10159
10160         assert(RExC_parse < RExC_end);
10161
10162         if ( *RExC_parse == '*') { /* (*VERB:ARG) */
10163             char *start_verb = RExC_parse + 1;
10164             STRLEN verb_len;
10165             char *start_arg = NULL;
10166             unsigned char op = 0;
10167             int arg_required = 0;
10168             int internal_argval = -1; /* if >-1 we are not allowed an argument*/
10169
10170             if (has_intervening_patws) {
10171                 RExC_parse++;   /* past the '*' */
10172                 vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent");
10173             }
10174             while (RExC_parse < RExC_end && *RExC_parse != ')' ) {
10175                 if ( *RExC_parse == ':' ) {
10176                     start_arg = RExC_parse + 1;
10177                     break;
10178                 }
10179                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10180             }
10181             verb_len = RExC_parse - start_verb;
10182             if ( start_arg ) {
10183                 if (RExC_parse >= RExC_end) {
10184                     goto unterminated_verb_pattern;
10185                 }
10186                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10187                 while ( RExC_parse < RExC_end && *RExC_parse != ')' )
10188                     RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10189                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' )
10190                   unterminated_verb_pattern:
10191                     vFAIL("Unterminated verb pattern argument");
10192                 if ( RExC_parse == start_arg )
10193                     start_arg = NULL;
10194             } else {
10195                 if ( RExC_parse >= RExC_end || *RExC_parse != ')' )
10196                     vFAIL("Unterminated verb pattern");
10197             }
10198
10199             /* Here, we know that RExC_parse < RExC_end */
10200
10201             switch ( *start_verb ) {
10202             case 'A':  /* (*ACCEPT) */
10203                 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
10204                     op = ACCEPT;
10205                     internal_argval = RExC_nestroot;
10206                 }
10207                 break;
10208             case 'C':  /* (*COMMIT) */
10209                 if ( memEQs(start_verb,verb_len,"COMMIT") )
10210                     op = COMMIT;
10211                 break;
10212             case 'F':  /* (*FAIL) */
10213                 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
10214                     op = OPFAIL;
10215                 }
10216                 break;
10217             case ':':  /* (*:NAME) */
10218             case 'M':  /* (*MARK:NAME) */
10219                 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
10220                     op = MARKPOINT;
10221                     arg_required = 1;
10222                 }
10223                 break;
10224             case 'P':  /* (*PRUNE) */
10225                 if ( memEQs(start_verb,verb_len,"PRUNE") )
10226                     op = PRUNE;
10227                 break;
10228             case 'S':   /* (*SKIP) */
10229                 if ( memEQs(start_verb,verb_len,"SKIP") )
10230                     op = SKIP;
10231                 break;
10232             case 'T':  /* (*THEN) */
10233                 /* [19:06] <TimToady> :: is then */
10234                 if ( memEQs(start_verb,verb_len,"THEN") ) {
10235                     op = CUTGROUP;
10236                     RExC_seen |= REG_CUTGROUP_SEEN;
10237                 }
10238                 break;
10239             }
10240             if ( ! op ) {
10241                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10242                 vFAIL2utf8f(
10243                     "Unknown verb pattern '%"UTF8f"'",
10244                     UTF8fARG(UTF, verb_len, start_verb));
10245             }
10246             if ( arg_required && !start_arg ) {
10247                 vFAIL3("Verb pattern '%.*s' has a mandatory argument",
10248                     verb_len, start_verb);
10249             }
10250             if (internal_argval == -1) {
10251                 ret = reganode(pRExC_state, op, 0);
10252             } else {
10253                 ret = reg2Lanode(pRExC_state, op, 0, internal_argval);
10254             }
10255             RExC_seen |= REG_VERBARG_SEEN;
10256             if ( ! SIZE_ONLY ) {
10257                 if (start_arg) {
10258                     SV *sv = newSVpvn( start_arg,
10259                                        RExC_parse - start_arg);
10260                     ARG(ret) = add_data( pRExC_state,
10261                                          STR_WITH_LEN("S"));
10262                     RExC_rxi->data->data[ARG(ret)]=(void*)sv;
10263                     ret->flags = 1;
10264                 } else {
10265                     ret->flags = 0;
10266                 }
10267                 if ( internal_argval != -1 )
10268                     ARG2L_SET(ret, internal_argval);
10269             }
10270             nextchar(pRExC_state);
10271             return ret;
10272         }
10273         else if (*RExC_parse == '?') { /* (?...) */
10274             bool is_logical = 0;
10275             const char * const seqstart = RExC_parse;
10276             const char * endptr;
10277             if (has_intervening_patws) {
10278                 RExC_parse++;
10279                 vFAIL("In '(?...)', the '(' and '?' must be adjacent");
10280             }
10281
10282             RExC_parse++;           /* past the '?' */
10283             paren = *RExC_parse;    /* might be a trailing NUL, if not
10284                                        well-formed */
10285             RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10286             if (RExC_parse > RExC_end) {
10287                 paren = '\0';
10288             }
10289             ret = NULL;                 /* For look-ahead/behind. */
10290             switch (paren) {
10291
10292             case 'P':   /* (?P...) variants for those used to PCRE/Python */
10293                 paren = *RExC_parse;
10294                 if ( paren == '<') {    /* (?P<...>) named capture */
10295                     RExC_parse++;
10296                     if (RExC_parse >= RExC_end) {
10297                         vFAIL("Sequence (?P<... not terminated");
10298                     }
10299                     goto named_capture;
10300                 }
10301                 else if (paren == '>') {   /* (?P>name) named recursion */
10302                     RExC_parse++;
10303                     if (RExC_parse >= RExC_end) {
10304                         vFAIL("Sequence (?P>... not terminated");
10305                     }
10306                     goto named_recursion;
10307                 }
10308                 else if (paren == '=') {   /* (?P=...)  named backref */
10309                     RExC_parse++;
10310                     return handle_named_backref(pRExC_state, flagp,
10311                                                 parse_start, ')');
10312                 }
10313                 RExC_parse += SKIP_IF_CHAR(RExC_parse);
10314                 /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10315                 vFAIL3("Sequence (%.*s...) not recognized",
10316                                 RExC_parse-seqstart, seqstart);
10317                 NOT_REACHED; /*NOTREACHED*/
10318             case '<':           /* (?<...) */
10319                 if (*RExC_parse == '!')
10320                     paren = ',';
10321                 else if (*RExC_parse != '=')
10322               named_capture:
10323                 {               /* (?<...>) */
10324                     char *name_start;
10325                     SV *svname;
10326                     paren= '>';
10327                 /* FALLTHROUGH */
10328             case '\'':          /* (?'...') */
10329                     name_start = RExC_parse;
10330                     svname = reg_scan_name(pRExC_state,
10331                         SIZE_ONLY    /* reverse test from the others */
10332                         ? REG_RSN_RETURN_NAME
10333                         : REG_RSN_RETURN_NULL);
10334                     if (   RExC_parse == name_start
10335                         || RExC_parse >= RExC_end
10336                         || *RExC_parse != paren)
10337                     {
10338                         vFAIL2("Sequence (?%c... not terminated",
10339                             paren=='>' ? '<' : paren);
10340                     }
10341                     if (SIZE_ONLY) {
10342                         HE *he_str;
10343                         SV *sv_dat = NULL;
10344                         if (!svname) /* shouldn't happen */
10345                             Perl_croak(aTHX_
10346                                 "panic: reg_scan_name returned NULL");
10347                         if (!RExC_paren_names) {
10348                             RExC_paren_names= newHV();
10349                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
10350 #ifdef DEBUGGING
10351                             RExC_paren_name_list= newAV();
10352                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
10353 #endif
10354                         }
10355                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
10356                         if ( he_str )
10357                             sv_dat = HeVAL(he_str);
10358                         if ( ! sv_dat ) {
10359                             /* croak baby croak */
10360                             Perl_croak(aTHX_
10361                                 "panic: paren_name hash element allocation failed");
10362                         } else if ( SvPOK(sv_dat) ) {
10363                             /* (?|...) can mean we have dupes so scan to check
10364                                its already been stored. Maybe a flag indicating
10365                                we are inside such a construct would be useful,
10366                                but the arrays are likely to be quite small, so
10367                                for now we punt -- dmq */
10368                             IV count = SvIV(sv_dat);
10369                             I32 *pv = (I32*)SvPVX(sv_dat);
10370                             IV i;
10371                             for ( i = 0 ; i < count ; i++ ) {
10372                                 if ( pv[i] == RExC_npar ) {
10373                                     count = 0;
10374                                     break;
10375                                 }
10376                             }
10377                             if ( count ) {
10378                                 pv = (I32*)SvGROW(sv_dat,
10379                                                 SvCUR(sv_dat) + sizeof(I32)+1);
10380                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
10381                                 pv[count] = RExC_npar;
10382                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
10383                             }
10384                         } else {
10385                             (void)SvUPGRADE(sv_dat,SVt_PVNV);
10386                             sv_setpvn(sv_dat, (char *)&(RExC_npar),
10387                                                                 sizeof(I32));
10388                             SvIOK_on(sv_dat);
10389                             SvIV_set(sv_dat, 1);
10390                         }
10391 #ifdef DEBUGGING
10392                         /* Yes this does cause a memory leak in debugging Perls
10393                          * */
10394                         if (!av_store(RExC_paren_name_list,
10395                                       RExC_npar, SvREFCNT_inc(svname)))
10396                             SvREFCNT_dec_NN(svname);
10397 #endif
10398
10399                         /*sv_dump(sv_dat);*/
10400                     }
10401                     nextchar(pRExC_state);
10402                     paren = 1;
10403                     goto capturing_parens;
10404                 }
10405                 RExC_seen |= REG_LOOKBEHIND_SEEN;
10406                 RExC_in_lookbehind++;
10407                 RExC_parse++;
10408                 assert(RExC_parse < RExC_end);
10409                 /* FALLTHROUGH */
10410             case '=':           /* (?=...) */
10411                 RExC_seen_zerolen++;
10412                 break;
10413             case '!':           /* (?!...) */
10414                 RExC_seen_zerolen++;
10415                 /* check if we're really just a "FAIL" assertion */
10416                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
10417                                         FALSE /* Don't force to /x */ );
10418                 if (*RExC_parse == ')') {
10419                     ret=reganode(pRExC_state, OPFAIL, 0);
10420                     nextchar(pRExC_state);
10421                     return ret;
10422                 }
10423                 break;
10424             case '|':           /* (?|...) */
10425                 /* branch reset, behave like a (?:...) except that
10426                    buffers in alternations share the same numbers */
10427                 paren = ':';
10428                 after_freeze = freeze_paren = RExC_npar;
10429                 break;
10430             case ':':           /* (?:...) */
10431             case '>':           /* (?>...) */
10432                 break;
10433             case '$':           /* (?$...) */
10434             case '@':           /* (?@...) */
10435                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
10436                 break;
10437             case '0' :           /* (?0) */
10438             case 'R' :           /* (?R) */
10439                 if (*RExC_parse != ')')
10440                     FAIL("Sequence (?R) not terminated");
10441                 ret = reg_node(pRExC_state, GOSTART);
10442                     RExC_seen |= REG_GOSTART_SEEN;
10443                 *flagp |= POSTPONED;
10444                 nextchar(pRExC_state);
10445                 return ret;
10446                 /*notreached*/
10447             /* named and numeric backreferences */
10448             case '&':            /* (?&NAME) */
10449                 parse_start = RExC_parse - 1;
10450               named_recursion:
10451                 {
10452                     SV *sv_dat = reg_scan_name(pRExC_state,
10453                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
10454                      num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
10455                 }
10456                 if (RExC_parse >= RExC_end || *RExC_parse != ')')
10457                     vFAIL("Sequence (?&... not terminated");
10458                 goto gen_recurse_regop;
10459                 /* NOTREACHED */
10460             case '+':
10461                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
10462                     RExC_parse++;
10463                     vFAIL("Illegal pattern");
10464                 }
10465                 goto parse_recursion;
10466                 /* NOTREACHED*/
10467             case '-': /* (?-1) */
10468                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
10469                     RExC_parse--; /* rewind to let it be handled later */
10470                     goto parse_flags;
10471                 }
10472                 /* FALLTHROUGH */
10473             case '1': case '2': case '3': case '4': /* (?1) */
10474             case '5': case '6': case '7': case '8': case '9':
10475                 RExC_parse = (char *) seqstart + 1;  /* Point to the digit */
10476               parse_recursion:
10477                 {
10478                     bool is_neg = FALSE;
10479                     UV unum;
10480                     parse_start = RExC_parse - 1; /* MJD */
10481                     if (*RExC_parse == '-') {
10482                         RExC_parse++;
10483                         is_neg = TRUE;
10484                     }
10485                     if (grok_atoUV(RExC_parse, &unum, &endptr)
10486                         && unum <= I32_MAX
10487                     ) {
10488                         num = (I32)unum;
10489                         RExC_parse = (char*)endptr;
10490                     } else
10491                         num = I32_MAX;
10492                     if (is_neg) {
10493                         /* Some limit for num? */
10494                         num = -num;
10495                     }
10496                 }
10497                 if (*RExC_parse!=')')
10498                     vFAIL("Expecting close bracket");
10499
10500               gen_recurse_regop:
10501                 if ( paren == '-' ) {
10502                     /*
10503                     Diagram of capture buffer numbering.
10504                     Top line is the normal capture buffer numbers
10505                     Bottom line is the negative indexing as from
10506                     the X (the (?-2))
10507
10508                     +   1 2    3 4 5 X          6 7
10509                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
10510                     -   5 4    3 2 1 X          x x
10511
10512                     */
10513                     num = RExC_npar + num;
10514                     if (num < 1)  {
10515                         RExC_parse++;
10516                         vFAIL("Reference to nonexistent group");
10517                     }
10518                 } else if ( paren == '+' ) {
10519                     num = RExC_npar + num - 1;
10520                 }
10521
10522                 ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count);
10523                 if (!SIZE_ONLY) {
10524                     if (num > (I32)RExC_rx->nparens) {
10525                         RExC_parse++;
10526                         vFAIL("Reference to nonexistent group");
10527                     }
10528                     RExC_recurse_count++;
10529                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
10530                         "%*s%*s Recurse #%"UVuf" to %"IVdf"\n",
10531                               22, "|    |", (int)(depth * 2 + 1), "",
10532                               (UV)ARG(ret), (IV)ARG2L(ret)));
10533                 }
10534                 RExC_seen |= REG_RECURSE_SEEN;
10535                 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
10536                 Set_Node_Offset(ret, parse_start); /* MJD */
10537
10538                 *flagp |= POSTPONED;
10539                 nextchar(pRExC_state);
10540                 return ret;
10541
10542             /* NOTREACHED */
10543
10544             case '?':           /* (??...) */
10545                 is_logical = 1;
10546                 if (*RExC_parse != '{') {
10547                     RExC_parse += SKIP_IF_CHAR(RExC_parse);
10548                     /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */
10549                     vFAIL2utf8f(
10550                         "Sequence (%"UTF8f"...) not recognized",
10551                         UTF8fARG(UTF, RExC_parse-seqstart, seqstart));
10552                     NOT_REACHED; /*NOTREACHED*/
10553                 }
10554                 *flagp |= POSTPONED;
10555                 paren = '{';
10556                 RExC_parse++;
10557                 /* FALLTHROUGH */
10558             case '{':           /* (?{...}) */
10559             {
10560                 U32 n = 0;
10561                 struct reg_code_block *cb;
10562
10563                 RExC_seen_zerolen++;
10564
10565                 if (   !pRExC_state->num_code_blocks
10566                     || pRExC_state->code_index >= pRExC_state->num_code_blocks
10567                     || pRExC_state->code_blocks[pRExC_state->code_index].start
10568                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
10569                             - RExC_start)
10570                 ) {
10571                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
10572                         FAIL("panic: Sequence (?{...}): no code block found\n");
10573                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
10574                 }
10575                 /* this is a pre-compiled code block (?{...}) */
10576                 cb = &pRExC_state->code_blocks[pRExC_state->code_index];
10577                 RExC_parse = RExC_start + cb->end;
10578                 if (!SIZE_ONLY) {
10579                     OP *o = cb->block;
10580                     if (cb->src_regex) {
10581                         n = add_data(pRExC_state, STR_WITH_LEN("rl"));
10582                         RExC_rxi->data->data[n] =
10583                             (void*)SvREFCNT_inc((SV*)cb->src_regex);
10584                         RExC_rxi->data->data[n+1] = (void*)o;
10585                     }
10586                     else {
10587                         n = add_data(pRExC_state,
10588                                (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1);
10589                         RExC_rxi->data->data[n] = (void*)o;
10590                     }
10591                 }
10592                 pRExC_state->code_index++;
10593                 nextchar(pRExC_state);
10594
10595                 if (is_logical) {
10596                     regnode *eval;
10597                     ret = reg_node(pRExC_state, LOGICAL);
10598
10599                     eval = reg2Lanode(pRExC_state, EVAL,
10600                                        n,
10601
10602                                        /* for later propagation into (??{})
10603                                         * return value */
10604                                        RExC_flags & RXf_PMf_COMPILETIME
10605                                       );
10606                     if (!SIZE_ONLY) {
10607                         ret->flags = 2;
10608                     }
10609                     REGTAIL(pRExC_state, ret, eval);
10610                     /* deal with the length of this later - MJD */
10611                     return ret;
10612                 }
10613                 ret = reg2Lanode(pRExC_state, EVAL, n, 0);
10614                 Set_Node_Length(ret, RExC_parse - parse_start + 1);
10615                 Set_Node_Offset(ret, parse_start);
10616                 return ret;
10617             }
10618             case '(':           /* (?(?{...})...) and (?(?=...)...) */
10619             {
10620                 int is_define= 0;
10621                 const int DEFINE_len = sizeof("DEFINE") - 1;
10622                 if (RExC_parse[0] == '?') {        /* (?(?...)) */
10623                     if (   RExC_parse < RExC_end - 1
10624                         && (   RExC_parse[1] == '='
10625                             || RExC_parse[1] == '!'
10626                             || RExC_parse[1] == '<'
10627                             || RExC_parse[1] == '{')
10628                     ) { /* Lookahead or eval. */
10629                         I32 flag;
10630                         regnode *tail;
10631
10632                         ret = reg_node(pRExC_state, LOGICAL);
10633                         if (!SIZE_ONLY)
10634                             ret->flags = 1;
10635
10636                         tail = reg(pRExC_state, 1, &flag, depth+1);
10637                         if (flag & (RESTART_PASS1|NEED_UTF8)) {
10638                             *flagp = flag & (RESTART_PASS1|NEED_UTF8);
10639                             return NULL;
10640                         }
10641                         REGTAIL(pRExC_state, ret, tail);
10642                         goto insert_if;
10643                     }
10644                     /* Fall through to ‘Unknown switch condition’ at the
10645                        end of the if/else chain. */
10646                 }
10647                 else if ( RExC_parse[0] == '<'     /* (?(<NAME>)...) */
10648                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
10649                 {
10650                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
10651                     char *name_start= RExC_parse++;
10652                     U32 num = 0;
10653                     SV *sv_dat=reg_scan_name(pRExC_state,
10654                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
10655                     if (   RExC_parse == name_start
10656                         || RExC_parse >= RExC_end
10657                         || *RExC_parse != ch)
10658                     {
10659                         vFAIL2("Sequence (?(%c... not terminated",
10660                             (ch == '>' ? '<' : ch));
10661                     }
10662                     RExC_parse++;
10663                     if (!SIZE_ONLY) {
10664                         num = add_data( pRExC_state, STR_WITH_LEN("S"));
10665                         RExC_rxi->data->data[num]=(void*)sv_dat;
10666                         SvREFCNT_inc_simple_void(sv_dat);
10667                     }
10668                     ret = reganode(pRExC_state,NGROUPP,num);
10669                     goto insert_if_check_paren;
10670                 }
10671                 else if (RExC_end - RExC_parse >= DEFINE_len
10672                         && strnEQ(RExC_parse, "DEFINE", DEFINE_len))
10673                 {
10674                     ret = reganode(pRExC_state,DEFINEP,0);
10675                     RExC_parse += DEFINE_len;
10676                     is_define = 1;
10677                     goto insert_if_check_paren;
10678                 }
10679                 else if (RExC_parse[0] == 'R') {
10680                     RExC_parse++;
10681                     parno = 0;
10682                     if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
10683                         UV uv;
10684                         if (grok_atoUV(RExC_parse, &uv, &endptr)
10685                             && uv <= I32_MAX
10686                         ) {
10687                             parno = (I32)uv;
10688                             RExC_parse = (char*)endptr;
10689                         }
10690                         /* else "Switch condition not recognized" below */
10691                     } else if (RExC_parse[0] == '&') {
10692                         SV *sv_dat;
10693                         RExC_parse++;
10694                         sv_dat = reg_scan_name(pRExC_state,
10695                             SIZE_ONLY
10696                             ? REG_RSN_RETURN_NULL
10697                             : REG_RSN_RETURN_DATA);
10698                         parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
10699                     }
10700                     ret = reganode(pRExC_state,INSUBP,parno);
10701                     goto insert_if_check_paren;
10702                 }
10703                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
10704                     /* (?(1)...) */
10705                     char c;
10706                     UV uv;
10707                     if (grok_atoUV(RExC_parse, &uv, &endptr)
10708                         && uv <= I32_MAX
10709                     ) {
10710                         parno = (I32)uv;
10711                         RExC_parse = (char*)endptr;
10712                     }
10713                     else {
10714                         vFAIL("panic: grok_atoUV returned FALSE");
10715                     }
10716                     ret = reganode(pRExC_state, GROUPP, parno);
10717
10718                  insert_if_check_paren:
10719                     if (UCHARAT(RExC_parse) != ')') {
10720                         RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10721                         vFAIL("Switch condition not recognized");
10722                     }
10723                     nextchar(pRExC_state);
10724                   insert_if:
10725                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
10726                     br = regbranch(pRExC_state, &flags, 1,depth+1);
10727                     if (br == NULL) {
10728                         if (flags & (RESTART_PASS1|NEED_UTF8)) {
10729                             *flagp = flags & (RESTART_PASS1|NEED_UTF8);
10730                             return NULL;
10731                         }
10732                         FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"",
10733                               (UV) flags);
10734                     } else
10735                         REGTAIL(pRExC_state, br, reganode(pRExC_state,
10736                                                           LONGJMP, 0));
10737                     c = UCHARAT(RExC_parse);
10738                     nextchar(pRExC_state);
10739                     if (flags&HASWIDTH)
10740                         *flagp |= HASWIDTH;
10741                     if (c == '|') {
10742                         if (is_define)
10743                             vFAIL("(?(DEFINE)....) does not allow branches");
10744
10745                         /* Fake one for optimizer.  */
10746                         lastbr = reganode(pRExC_state, IFTHEN, 0);
10747
10748                         if (!regbranch(pRExC_state, &flags, 1,depth+1)) {
10749                             if (flags & (RESTART_PASS1|NEED_UTF8)) {
10750                                 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
10751                                 return NULL;
10752                             }
10753                             FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"",
10754                                   (UV) flags);
10755                         }
10756                         REGTAIL(pRExC_state, ret, lastbr);
10757                         if (flags&HASWIDTH)
10758                             *flagp |= HASWIDTH;
10759                         c = UCHARAT(RExC_parse);
10760                         nextchar(pRExC_state);
10761                     }
10762                     else
10763                         lastbr = NULL;
10764                     if (c != ')') {
10765                         if (RExC_parse >= RExC_end)
10766                             vFAIL("Switch (?(condition)... not terminated");
10767                         else
10768                             vFAIL("Switch (?(condition)... contains too many branches");
10769                     }
10770                     ender = reg_node(pRExC_state, TAIL);
10771                     REGTAIL(pRExC_state, br, ender);
10772                     if (lastbr) {
10773                         REGTAIL(pRExC_state, lastbr, ender);
10774                         REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
10775                     }
10776                     else
10777                         REGTAIL(pRExC_state, ret, ender);
10778                     RExC_size++; /* XXX WHY do we need this?!!
10779                                     For large programs it seems to be required
10780                                     but I can't figure out why. -- dmq*/
10781                     return ret;
10782                 }
10783                 RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
10784                 vFAIL("Unknown switch condition (?(...))");
10785             }
10786             case '[':           /* (?[ ... ]) */
10787                 return handle_regex_sets(pRExC_state, NULL, flagp, depth,
10788                                          oregcomp_parse);
10789             case 0: /* A NUL */
10790                 RExC_parse--; /* for vFAIL to print correctly */
10791                 vFAIL("Sequence (? incomplete");
10792                 break;
10793             default: /* e.g., (?i) */
10794                 RExC_parse = (char *) seqstart + 1;
10795               parse_flags:
10796                 parse_lparen_question_flags(pRExC_state);
10797                 if (UCHARAT(RExC_parse) != ':') {
10798                     if (RExC_parse < RExC_end)
10799                         nextchar(pRExC_state);
10800                     *flagp = TRYAGAIN;
10801                     return NULL;
10802                 }
10803                 paren = ':';
10804                 nextchar(pRExC_state);
10805                 ret = NULL;
10806                 goto parse_rest;
10807             } /* end switch */
10808         }
10809         else if (!(RExC_flags & RXf_PMf_NOCAPTURE)) {   /* (...) */
10810           capturing_parens:
10811             parno = RExC_npar;
10812             RExC_npar++;
10813
10814             ret = reganode(pRExC_state, OPEN, parno);
10815             if (!SIZE_ONLY ){
10816                 if (!RExC_nestroot)
10817                     RExC_nestroot = parno;
10818                 if (RExC_seen & REG_RECURSE_SEEN
10819                     && !RExC_open_parens[parno-1])
10820                 {
10821                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
10822                         "%*s%*s Setting open paren #%"IVdf" to %d\n",
10823                         22, "|    |", (int)(depth * 2 + 1), "",
10824                         (IV)parno, REG_NODE_NUM(ret)));
10825                     RExC_open_parens[parno-1]= ret;
10826                 }
10827             }
10828             Set_Node_Length(ret, 1); /* MJD */
10829             Set_Node_Offset(ret, RExC_parse); /* MJD */
10830             is_open = 1;
10831         } else {
10832             /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */
10833             paren = ':';
10834             ret = NULL;
10835         }
10836     }
10837     else                        /* ! paren */
10838         ret = NULL;
10839
10840    parse_rest:
10841     /* Pick up the branches, linking them together. */
10842     parse_start = RExC_parse;   /* MJD */
10843     br = regbranch(pRExC_state, &flags, 1,depth+1);
10844
10845     /*     branch_len = (paren != 0); */
10846
10847     if (br == NULL) {
10848         if (flags & (RESTART_PASS1|NEED_UTF8)) {
10849             *flagp = flags & (RESTART_PASS1|NEED_UTF8);
10850             return NULL;
10851         }
10852         FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"", (UV) flags);
10853     }
10854     if (*RExC_parse == '|') {
10855         if (!SIZE_ONLY && RExC_extralen) {
10856             reginsert(pRExC_state, BRANCHJ, br, depth+1);
10857         }
10858         else {                  /* MJD */
10859             reginsert(pRExC_state, BRANCH, br, depth+1);
10860             Set_Node_Length(br, paren != 0);
10861             Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
10862         }
10863         have_branch = 1;
10864         if (SIZE_ONLY)
10865             RExC_extralen += 1;         /* For BRANCHJ-BRANCH. */
10866     }
10867     else if (paren == ':') {
10868         *flagp |= flags&SIMPLE;
10869     }
10870     if (is_open) {                              /* Starts with OPEN. */
10871         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
10872     }
10873     else if (paren != '?')              /* Not Conditional */
10874         ret = br;
10875     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
10876     lastbr = br;
10877     while (*RExC_parse == '|') {
10878         if (!SIZE_ONLY && RExC_extralen) {
10879             ender = reganode(pRExC_state, LONGJMP,0);
10880
10881             /* Append to the previous. */
10882             REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
10883         }
10884         if (SIZE_ONLY)
10885             RExC_extralen += 2;         /* Account for LONGJMP. */
10886         nextchar(pRExC_state);
10887         if (freeze_paren) {
10888             if (RExC_npar > after_freeze)
10889                 after_freeze = RExC_npar;
10890             RExC_npar = freeze_paren;
10891         }
10892         br = regbranch(pRExC_state, &flags, 0, depth+1);
10893
10894         if (br == NULL) {
10895             if (flags & (RESTART_PASS1|NEED_UTF8)) {
10896                 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
10897                 return NULL;
10898             }
10899             FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"", (UV) flags);
10900         }
10901         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
10902         lastbr = br;
10903         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
10904     }
10905
10906     if (have_branch || paren != ':') {
10907         /* Make a closing node, and hook it on the end. */
10908         switch (paren) {
10909         case ':':
10910             ender = reg_node(pRExC_state, TAIL);
10911             break;
10912         case 1: case 2:
10913             ender = reganode(pRExC_state, CLOSE, parno);
10914             if (!SIZE_ONLY && RExC_seen & REG_RECURSE_SEEN) {
10915                 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
10916                         "%*s%*s Setting close paren #%"IVdf" to %d\n",
10917                         22, "|    |", (int)(depth * 2 + 1), "", (IV)parno, REG_NODE_NUM(ender)));
10918                 RExC_close_parens[parno-1]= ender;
10919                 if (RExC_nestroot == parno)
10920                     RExC_nestroot = 0;
10921             }
10922             Set_Node_Offset(ender,RExC_parse+1); /* MJD */
10923             Set_Node_Length(ender,1); /* MJD */
10924             break;
10925         case '<':
10926         case ',':
10927         case '=':
10928         case '!':
10929             *flagp &= ~HASWIDTH;
10930             /* FALLTHROUGH */
10931         case '>':
10932             ender = reg_node(pRExC_state, SUCCEED);
10933             break;
10934         case 0:
10935             ender = reg_node(pRExC_state, END);
10936             if (!SIZE_ONLY) {
10937                 assert(!RExC_opend); /* there can only be one! */
10938                 RExC_opend = ender;
10939             }
10940             break;
10941         }
10942         DEBUG_PARSE_r(if (!SIZE_ONLY) {
10943             DEBUG_PARSE_MSG("lsbr");
10944             regprop(RExC_rx, RExC_mysv1, lastbr, NULL, pRExC_state);
10945             regprop(RExC_rx, RExC_mysv2, ender, NULL, pRExC_state);
10946             PerlIO_printf(Perl_debug_log, "~ tying lastbr %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
10947                           SvPV_nolen_const(RExC_mysv1),
10948                           (IV)REG_NODE_NUM(lastbr),
10949                           SvPV_nolen_const(RExC_mysv2),
10950                           (IV)REG_NODE_NUM(ender),
10951                           (IV)(ender - lastbr)
10952             );
10953         });
10954         REGTAIL(pRExC_state, lastbr, ender);
10955
10956         if (have_branch && !SIZE_ONLY) {
10957             char is_nothing= 1;
10958             if (depth==1)
10959                 RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN;
10960
10961             /* Hook the tails of the branches to the closing node. */
10962             for (br = ret; br; br = regnext(br)) {
10963                 const U8 op = PL_regkind[OP(br)];
10964                 if (op == BRANCH) {
10965                     REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
10966                     if ( OP(NEXTOPER(br)) != NOTHING
10967                          || regnext(NEXTOPER(br)) != ender)
10968                         is_nothing= 0;
10969                 }
10970                 else if (op == BRANCHJ) {
10971                     REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
10972                     /* for now we always disable this optimisation * /
10973                     if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING
10974                          || regnext(NEXTOPER(NEXTOPER(br))) != ender)
10975                     */
10976                         is_nothing= 0;
10977                 }
10978             }
10979             if (is_nothing) {
10980                 br= PL_regkind[OP(ret)] != BRANCH ? regnext(ret) : ret;
10981                 DEBUG_PARSE_r(if (!SIZE_ONLY) {
10982                     DEBUG_PARSE_MSG("NADA");
10983                     regprop(RExC_rx, RExC_mysv1, ret, NULL, pRExC_state);
10984                     regprop(RExC_rx, RExC_mysv2, ender, NULL, pRExC_state);
10985                     PerlIO_printf(Perl_debug_log, "~ converting ret %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
10986                                   SvPV_nolen_const(RExC_mysv1),
10987                                   (IV)REG_NODE_NUM(ret),
10988                                   SvPV_nolen_const(RExC_mysv2),
10989                                   (IV)REG_NODE_NUM(ender),
10990                                   (IV)(ender - ret)
10991                     );
10992                 });
10993                 OP(br)= NOTHING;
10994                 if (OP(ender) == TAIL) {
10995                     NEXT_OFF(br)= 0;
10996                     RExC_emit= br + 1;
10997                 } else {
10998                     regnode *opt;
10999                     for ( opt= br + 1; opt < ender ; opt++ )
11000                         OP(opt)= OPTIMIZED;
11001                     NEXT_OFF(br)= ender - br;
11002                 }
11003             }
11004         }
11005     }
11006
11007     {
11008         const char *p;
11009         static const char parens[] = "=!<,>";
11010
11011         if (paren && (p = strchr(parens, paren))) {
11012             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
11013             int flag = (p - parens) > 1;
11014
11015             if (paren == '>')
11016                 node = SUSPEND, flag = 0;
11017             reginsert(pRExC_state, node,ret, depth+1);
11018             Set_Node_Cur_Length(ret, parse_start);
11019             Set_Node_Offset(ret, parse_start + 1);
11020             ret->flags = flag;
11021             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
11022         }
11023     }
11024
11025     /* Check for proper termination. */
11026     if (paren) {
11027         /* restore original flags, but keep (?p) and, if we've changed from /d
11028          * rules to /u, keep the /u */
11029         RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
11030         if (DEPENDS_SEMANTICS && RExC_uni_semantics) {
11031             set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
11032         }
11033         if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') {
11034             RExC_parse = oregcomp_parse;
11035             vFAIL("Unmatched (");
11036         }
11037         nextchar(pRExC_state);
11038     }
11039     else if (!paren && RExC_parse < RExC_end) {
11040         if (*RExC_parse == ')') {
11041             RExC_parse++;
11042             vFAIL("Unmatched )");
11043         }
11044         else
11045             FAIL("Junk on end of regexp");      /* "Can't happen". */
11046         NOT_REACHED; /* NOTREACHED */
11047     }
11048
11049     if (RExC_in_lookbehind) {
11050         RExC_in_lookbehind--;
11051     }
11052     if (after_freeze > RExC_npar)
11053         RExC_npar = after_freeze;
11054     return(ret);
11055 }
11056
11057 /*
11058  - regbranch - one alternative of an | operator
11059  *
11060  * Implements the concatenation operator.
11061  *
11062  * Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
11063  * restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
11064  */
11065 STATIC regnode *
11066 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
11067 {
11068     regnode *ret;
11069     regnode *chain = NULL;
11070     regnode *latest;
11071     I32 flags = 0, c = 0;
11072     GET_RE_DEBUG_FLAGS_DECL;
11073
11074     PERL_ARGS_ASSERT_REGBRANCH;
11075
11076     DEBUG_PARSE("brnc");
11077
11078     if (first)
11079         ret = NULL;
11080     else {
11081         if (!SIZE_ONLY && RExC_extralen)
11082             ret = reganode(pRExC_state, BRANCHJ,0);
11083         else {
11084             ret = reg_node(pRExC_state, BRANCH);
11085             Set_Node_Length(ret, 1);
11086         }
11087     }
11088
11089     if (!first && SIZE_ONLY)
11090         RExC_extralen += 1;                     /* BRANCHJ */
11091
11092     *flagp = WORST;                     /* Tentatively. */
11093
11094     skip_to_be_ignored_text(pRExC_state, &RExC_parse,
11095                             FALSE /* Don't force to /x */ );
11096     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
11097         flags &= ~TRYAGAIN;
11098         latest = regpiece(pRExC_state, &flags,depth+1);
11099         if (latest == NULL) {
11100             if (flags & TRYAGAIN)
11101                 continue;
11102             if (flags & (RESTART_PASS1|NEED_UTF8)) {
11103                 *flagp = flags & (RESTART_PASS1|NEED_UTF8);
11104                 return NULL;
11105             }
11106             FAIL2("panic: regpiece returned NULL, flags=%#"UVxf"", (UV) flags);
11107         }
11108         else if (ret == NULL)
11109             ret = latest;
11110         *flagp |= flags&(HASWIDTH|POSTPONED);
11111         if (chain == NULL)      /* First piece. */
11112             *flagp |= flags&SPSTART;
11113         else {
11114             /* FIXME adding one for every branch after the first is probably
11115              * excessive now we have TRIE support. (hv) */
11116             MARK_NAUGHTY(1);
11117             REGTAIL(pRExC_state, chain, latest);
11118         }
11119         chain = latest;
11120         c++;
11121     }
11122     if (chain == NULL) {        /* Loop ran zero times. */
11123         chain = reg_node(pRExC_state, NOTHING);
11124         if (ret == NULL)
11125             ret = chain;
11126     }
11127     if (c == 1) {
11128         *flagp |= flags&SIMPLE;
11129     }
11130
11131     return ret;
11132 }
11133
11134 /*
11135  - regpiece - something followed by possible [*+?]
11136  *
11137  * Note that the branching code sequences used for ? and the general cases
11138  * of * and + are somewhat optimized:  they use the same NOTHING node as
11139  * both the endmarker for their branch list and the body of the last branch.
11140  * It might seem that this node could be dispensed with entirely, but the
11141  * endmarker role is not redundant.
11142  *
11143  * Returns NULL, setting *flagp to TRYAGAIN if regatom() returns NULL with
11144  * TRYAGAIN.
11145  * Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
11146  * restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
11147  */
11148 STATIC regnode *
11149 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
11150 {
11151     regnode *ret;
11152     char op;
11153     char *next;
11154     I32 flags;
11155     const char * const origparse = RExC_parse;
11156     I32 min;
11157     I32 max = REG_INFTY;
11158 #ifdef RE_TRACK_PATTERN_OFFSETS
11159     char *parse_start;
11160 #endif
11161     const char *maxpos = NULL;
11162     UV uv;
11163
11164     /* Save the original in case we change the emitted regop to a FAIL. */
11165     regnode * const orig_emit = RExC_emit;
11166
11167     GET_RE_DEBUG_FLAGS_DECL;
11168
11169     PERL_ARGS_ASSERT_REGPIECE;
11170
11171     DEBUG_PARSE("piec");
11172
11173     ret = regatom(pRExC_state, &flags,depth+1);
11174     if (ret == NULL) {
11175         if (flags & (TRYAGAIN|RESTART_PASS1|NEED_UTF8))
11176             *flagp |= flags & (TRYAGAIN|RESTART_PASS1|NEED_UTF8);
11177         else
11178             FAIL2("panic: regatom returned NULL, flags=%#"UVxf"", (UV) flags);
11179         return(NULL);
11180     }
11181
11182     op = *RExC_parse;
11183
11184     if (op == '{' && regcurly(RExC_parse)) {
11185         maxpos = NULL;
11186 #ifdef RE_TRACK_PATTERN_OFFSETS
11187         parse_start = RExC_parse; /* MJD */
11188 #endif
11189         next = RExC_parse + 1;
11190         while (isDIGIT(*next) || *next == ',') {
11191             if (*next == ',') {
11192                 if (maxpos)
11193                     break;
11194                 else
11195                     maxpos = next;
11196             }
11197             next++;
11198         }
11199         if (*next == '}') {             /* got one */
11200             const char* endptr;
11201             if (!maxpos)
11202                 maxpos = next;
11203             RExC_parse++;
11204             if (isDIGIT(*RExC_parse)) {
11205                 if (!grok_atoUV(RExC_parse, &uv, &endptr))
11206                     vFAIL("Invalid quantifier in {,}");
11207                 if (uv >= REG_INFTY)
11208                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
11209                 min = (I32)uv;
11210             } else {
11211                 min = 0;
11212             }
11213             if (*maxpos == ',')
11214                 maxpos++;
11215             else
11216                 maxpos = RExC_parse;
11217             if (isDIGIT(*maxpos)) {
11218                 if (!grok_atoUV(maxpos, &uv, &endptr))
11219                     vFAIL("Invalid quantifier in {,}");
11220                 if (uv >= REG_INFTY)
11221                     vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
11222                 max = (I32)uv;
11223             } else {
11224                 max = REG_INFTY;                /* meaning "infinity" */
11225             }
11226             RExC_parse = next;
11227             nextchar(pRExC_state);
11228             if (max < min) {    /* If can't match, warn and optimize to fail
11229                                    unconditionally */
11230                 if (SIZE_ONLY) {
11231
11232                     /* We can't back off the size because we have to reserve
11233                      * enough space for all the things we are about to throw
11234                      * away, but we can shrink it by the amount we are about
11235                      * to re-use here */
11236                     RExC_size += PREVOPER(RExC_size) - regarglen[(U8)OPFAIL];
11237                 }
11238                 else {
11239                     ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
11240                     RExC_emit = orig_emit;
11241                 }
11242                 ret = reganode(pRExC_state, OPFAIL, 0);
11243                 return ret;
11244             }
11245             else if (min == max && *RExC_parse == '?')
11246             {
11247                 if (PASS2) {
11248                     ckWARN2reg(RExC_parse + 1,
11249                                "Useless use of greediness modifier '%c'",
11250                                *RExC_parse);
11251                 }
11252             }
11253
11254           do_curly:
11255             if ((flags&SIMPLE)) {
11256                 if (min == 0 && max == REG_INFTY) {
11257                     reginsert(pRExC_state, STAR, ret, depth+1);
11258                     ret->flags = 0;
11259                     MARK_NAUGHTY(4);
11260                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
11261                     goto nest_check;
11262                 }
11263                 if (min == 1 && max == REG_INFTY) {
11264                     reginsert(pRExC_state, PLUS, ret, depth+1);
11265                     ret->flags = 0;
11266                     MARK_NAUGHTY(3);
11267                     RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
11268                     goto nest_check;
11269                 }
11270                 MARK_NAUGHTY_EXP(2, 2);
11271                 reginsert(pRExC_state, CURLY, ret, depth+1);
11272                 Set_Node_Offset(ret, parse_start+1); /* MJD */
11273                 Set_Node_Cur_Length(ret, parse_start);
11274             }
11275             else {
11276                 regnode * const w = reg_node(pRExC_state, WHILEM);
11277
11278                 w->flags = 0;
11279                 REGTAIL(pRExC_state, ret, w);
11280                 if (!SIZE_ONLY && RExC_extralen) {
11281                     reginsert(pRExC_state, LONGJMP,ret, depth+1);
11282                     reginsert(pRExC_state, NOTHING,ret, depth+1);
11283                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
11284                 }
11285                 reginsert(pRExC_state, CURLYX,ret, depth+1);
11286                                 /* MJD hk */
11287                 Set_Node_Offset(ret, parse_start+1);
11288                 Set_Node_Length(ret,
11289                                 op == '{' ? (RExC_parse - parse_start) : 1);
11290
11291                 if (!SIZE_ONLY && RExC_extralen)
11292                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
11293                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
11294                 if (SIZE_ONLY)
11295                     RExC_whilem_seen++, RExC_extralen += 3;
11296                 MARK_NAUGHTY_EXP(1, 4);     /* compound interest */
11297             }
11298             ret->flags = 0;
11299
11300             if (min > 0)
11301                 *flagp = WORST;
11302             if (max > 0)
11303                 *flagp |= HASWIDTH;
11304             if (!SIZE_ONLY) {
11305                 ARG1_SET(ret, (U16)min);
11306                 ARG2_SET(ret, (U16)max);
11307             }
11308             if (max == REG_INFTY)
11309                 RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN;
11310
11311             goto nest_check;
11312         }
11313     }
11314
11315     if (!ISMULT1(op)) {
11316         *flagp = flags;
11317         return(ret);
11318     }
11319
11320 #if 0                           /* Now runtime fix should be reliable. */
11321
11322     /* if this is reinstated, don't forget to put this back into perldiag:
11323
11324             =item Regexp *+ operand could be empty at {#} in regex m/%s/
11325
11326            (F) The part of the regexp subject to either the * or + quantifier
11327            could match an empty string. The {#} shows in the regular
11328            expression about where the problem was discovered.
11329
11330     */
11331
11332     if (!(flags&HASWIDTH) && op != '?')
11333       vFAIL("Regexp *+ operand could be empty");
11334 #endif
11335
11336 #ifdef RE_TRACK_PATTERN_OFFSETS
11337     parse_start = RExC_parse;
11338 #endif
11339     nextchar(pRExC_state);
11340
11341     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
11342
11343     if (op == '*') {
11344         min = 0;
11345         goto do_curly;
11346     }
11347     else if (op == '+') {
11348         min = 1;
11349         goto do_curly;
11350     }
11351     else if (op == '?') {
11352         min = 0; max = 1;
11353         goto do_curly;
11354     }
11355   nest_check:
11356     if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
11357         SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
11358         ckWARN2reg(RExC_parse,
11359                    "%"UTF8f" matches null string many times",
11360                    UTF8fARG(UTF, (RExC_parse >= origparse
11361                                  ? RExC_parse - origparse
11362                                  : 0),
11363                    origparse));
11364         (void)ReREFCNT_inc(RExC_rx_sv);
11365     }
11366
11367     if (*RExC_parse == '?') {
11368         nextchar(pRExC_state);
11369         reginsert(pRExC_state, MINMOD, ret, depth+1);
11370         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
11371     }
11372     else if (*RExC_parse == '+') {
11373         regnode *ender;
11374         nextchar(pRExC_state);
11375         ender = reg_node(pRExC_state, SUCCEED);
11376         REGTAIL(pRExC_state, ret, ender);
11377         reginsert(pRExC_state, SUSPEND, ret, depth+1);
11378         ret->flags = 0;
11379         ender = reg_node(pRExC_state, TAIL);
11380         REGTAIL(pRExC_state, ret, ender);
11381     }
11382
11383     if (ISMULT2(RExC_parse)) {
11384         RExC_parse++;
11385         vFAIL("Nested quantifiers");
11386     }
11387
11388     return(ret);
11389 }
11390
11391 STATIC bool
11392 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state,
11393                 regnode ** node_p,
11394                 UV * code_point_p,
11395                 int * cp_count,
11396                 I32 * flagp,
11397                 const U32 depth
11398     )
11399 {
11400  /* This routine teases apart the various meanings of \N and returns
11401   * accordingly.  The input parameters constrain which meaning(s) is/are valid
11402   * in the current context.
11403   *
11404   * Exactly one of <node_p> and <code_point_p> must be non-NULL.
11405   *
11406   * If <code_point_p> is not NULL, the context is expecting the result to be a
11407   * single code point.  If this \N instance turns out to a single code point,
11408   * the function returns TRUE and sets *code_point_p to that code point.
11409   *
11410   * If <node_p> is not NULL, the context is expecting the result to be one of
11411   * the things representable by a regnode.  If this \N instance turns out to be
11412   * one such, the function generates the regnode, returns TRUE and sets *node_p
11413   * to point to that regnode.
11414   *
11415   * If this instance of \N isn't legal in any context, this function will
11416   * generate a fatal error and not return.
11417   *
11418   * On input, RExC_parse should point to the first char following the \N at the
11419   * time of the call.  On successful return, RExC_parse will have been updated
11420   * to point to just after the sequence identified by this routine.  Also
11421   * *flagp has been updated as needed.
11422   *
11423   * When there is some problem with the current context and this \N instance,
11424   * the function returns FALSE, without advancing RExC_parse, nor setting
11425   * *node_p, nor *code_point_p, nor *flagp.
11426   *
11427   * If <cp_count> is not NULL, the caller wants to know the length (in code
11428   * points) that this \N sequence matches.  This is set even if the function
11429   * returns FALSE, as detailed below.
11430   *
11431   * There are 5 possibilities here, as detailed in the next 5 paragraphs.
11432   *
11433   * Probably the most common case is for the \N to specify a single code point.
11434   * *cp_count will be set to 1, and *code_point_p will be set to that code
11435   * point.
11436   *
11437   * Another possibility is for the input to be an empty \N{}, which for
11438   * backwards compatibility we accept.  *cp_count will be set to 0. *node_p
11439   * will be set to a generated NOTHING node.
11440   *
11441   * Still another possibility is for the \N to mean [^\n]. *cp_count will be
11442   * set to 0. *node_p will be set to a generated REG_ANY node.
11443   *
11444   * The fourth possibility is that \N resolves to a sequence of more than one
11445   * code points.  *cp_count will be set to the number of code points in the
11446   * sequence. *node_p * will be set to a generated node returned by this
11447   * function calling S_reg().
11448   *
11449   * The final possibility is that it is premature to be calling this function;
11450   * that pass1 needs to be restarted.  This can happen when this changes from
11451   * /d to /u rules, or when the pattern needs to be upgraded to UTF-8.  The
11452   * latter occurs only when the fourth possibility would otherwise be in
11453   * effect, and is because one of those code points requires the pattern to be
11454   * recompiled as UTF-8.  The function returns FALSE, and sets the
11455   * RESTART_PASS1 and NEED_UTF8 flags in *flagp, as appropriate.  When this
11456   * happens, the caller needs to desist from continuing parsing, and return
11457   * this information to its caller.  This is not set for when there is only one
11458   * code point, as this can be called as part of an ANYOF node, and they can
11459   * store above-Latin1 code points without the pattern having to be in UTF-8.
11460   *
11461   * For non-single-quoted regexes, the tokenizer has resolved character and
11462   * sequence names inside \N{...} into their Unicode values, normalizing the
11463   * result into what we should see here: '\N{U+c1.c2...}', where c1... are the
11464   * hex-represented code points in the sequence.  This is done there because
11465   * the names can vary based on what charnames pragma is in scope at the time,
11466   * so we need a way to take a snapshot of what they resolve to at the time of
11467   * the original parse. [perl #56444].
11468   *
11469   * That parsing is skipped for single-quoted regexes, so we may here get
11470   * '\N{NAME}'.  This is a fatal error.  These names have to be resolved by the
11471   * parser.  But if the single-quoted regex is something like '\N{U+41}', that
11472   * is legal and handled here.  The code point is Unicode, and has to be
11473   * translated into the native character set for non-ASCII platforms.
11474   */
11475
11476     char * endbrace;    /* points to '}' following the name */
11477     char *endchar;      /* Points to '.' or '}' ending cur char in the input
11478                            stream */
11479     char* p = RExC_parse; /* Temporary */
11480
11481     GET_RE_DEBUG_FLAGS_DECL;
11482
11483     PERL_ARGS_ASSERT_GROK_BSLASH_N;
11484
11485     GET_RE_DEBUG_FLAGS;
11486
11487     assert(cBOOL(node_p) ^ cBOOL(code_point_p));  /* Exactly one should be set */
11488     assert(! (node_p && cp_count));               /* At most 1 should be set */
11489
11490     if (cp_count) {     /* Initialize return for the most common case */
11491         *cp_count = 1;
11492     }
11493
11494     /* The [^\n] meaning of \N ignores spaces and comments under the /x
11495      * modifier.  The other meanings do not, so use a temporary until we find
11496      * out which we are being called with */
11497     skip_to_be_ignored_text(pRExC_state, &p,
11498                             FALSE /* Don't force to /x */ );
11499
11500     /* Disambiguate between \N meaning a named character versus \N meaning
11501      * [^\n].  The latter is assumed when the {...} following the \N is a legal
11502      * quantifier, or there is no '{' at all */
11503     if (*p != '{' || regcurly(p)) {
11504         RExC_parse = p;
11505         if (cp_count) {
11506             *cp_count = -1;
11507         }
11508
11509         if (! node_p) {
11510             return FALSE;
11511         }
11512
11513         *node_p = reg_node(pRExC_state, REG_ANY);
11514         *flagp |= HASWIDTH|SIMPLE;
11515         MARK_NAUGHTY(1);
11516         Set_Node_Length(*node_p, 1); /* MJD */
11517         return TRUE;
11518     }
11519
11520     /* Here, we have decided it should be a named character or sequence */
11521
11522     /* The test above made sure that the next real character is a '{', but
11523      * under the /x modifier, it could be separated by space (or a comment and
11524      * \n) and this is not allowed (for consistency with \x{...} and the
11525      * tokenizer handling of \N{NAME}). */
11526     if (*RExC_parse != '{') {
11527         vFAIL("Missing braces on \\N{}");
11528     }
11529
11530     RExC_parse++;       /* Skip past the '{' */
11531
11532     if (! (endbrace = strchr(RExC_parse, '}'))  /* no trailing brace */
11533         || ! (endbrace == RExC_parse            /* nothing between the {} */
11534               || (endbrace - RExC_parse >= 2    /* U+ (bad hex is checked... */
11535                   && strnEQ(RExC_parse, "U+", 2)))) /* ... below for a better
11536                                                        error msg) */
11537     {
11538         if (endbrace) RExC_parse = endbrace;    /* position msg's '<--HERE' */
11539         vFAIL("\\N{NAME} must be resolved by the lexer");
11540     }
11541
11542     REQUIRE_UNI_RULES(flagp, FALSE); /* Unicode named chars imply Unicode
11543                                         semantics */
11544
11545     if (endbrace == RExC_parse) {   /* empty: \N{} */
11546         if (cp_count) {
11547             *cp_count = 0;
11548         }
11549         nextchar(pRExC_state);
11550         if (! node_p) {
11551             return FALSE;
11552         }
11553
11554         *node_p = reg_node(pRExC_state,NOTHING);
11555         return TRUE;
11556     }
11557
11558     RExC_parse += 2;    /* Skip past the 'U+' */
11559
11560     /* Because toke.c has generated a special construct for us guaranteed not
11561      * to have NULs, we can use a str function */
11562     endchar = RExC_parse + strcspn(RExC_parse, ".}");
11563
11564     /* Code points are separated by dots.  If none, there is only one code
11565      * point, and is terminated by the brace */
11566
11567     if (endchar >= endbrace) {
11568         STRLEN length_of_hex;
11569         I32 grok_hex_flags;
11570
11571         /* Here, exactly one code point.  If that isn't what is wanted, fail */
11572         if (! code_point_p) {
11573             RExC_parse = p;
11574             return FALSE;
11575         }
11576
11577         /* Convert code point from hex */
11578         length_of_hex = (STRLEN)(endchar - RExC_parse);
11579         grok_hex_flags = PERL_SCAN_ALLOW_UNDERSCORES
11580                            | PERL_SCAN_DISALLOW_PREFIX
11581
11582                              /* No errors in the first pass (See [perl
11583                               * #122671].)  We let the code below find the
11584                               * errors when there are multiple chars. */
11585                            | ((SIZE_ONLY)
11586                               ? PERL_SCAN_SILENT_ILLDIGIT
11587                               : 0);
11588
11589         /* This routine is the one place where both single- and double-quotish
11590          * \N{U+xxxx} are evaluated.  The value is a Unicode code point which
11591          * must be converted to native. */
11592         *code_point_p = UNI_TO_NATIVE(grok_hex(RExC_parse,
11593                                          &length_of_hex,
11594                                          &grok_hex_flags,
11595                                          NULL));
11596
11597         /* The tokenizer should have guaranteed validity, but it's possible to
11598          * bypass it by using single quoting, so check.  Don't do the check
11599          * here when there are multiple chars; we do it below anyway. */
11600         if (length_of_hex == 0
11601             || length_of_hex != (STRLEN)(endchar - RExC_parse) )
11602         {
11603             RExC_parse += length_of_hex;        /* Includes all the valid */
11604             RExC_parse += (RExC_orig_utf8)      /* point to after 1st invalid */
11605                             ? UTF8SKIP(RExC_parse)
11606                             : 1;
11607             /* Guard against malformed utf8 */
11608             if (RExC_parse >= endchar) {
11609                 RExC_parse = endchar;
11610             }
11611             vFAIL("Invalid hexadecimal number in \\N{U+...}");
11612         }
11613
11614         RExC_parse = endbrace + 1;
11615         return TRUE;
11616     }
11617     else {  /* Is a multiple character sequence */
11618         SV * substitute_parse;
11619         STRLEN len;
11620         char *orig_end = RExC_end;
11621         char *save_start = RExC_start;
11622         I32 flags;
11623
11624         /* Count the code points, if desired, in the sequence */
11625         if (cp_count) {
11626             *cp_count = 0;
11627             while (RExC_parse < endbrace) {
11628                 /* Point to the beginning of the next character in the sequence. */
11629                 RExC_parse = endchar + 1;
11630                 endchar = RExC_parse + strcspn(RExC_parse, ".}");
11631                 (*cp_count)++;
11632             }
11633         }
11634
11635         /* Fail if caller doesn't want to handle a multi-code-point sequence.
11636          * But don't backup up the pointer if the caller want to know how many
11637          * code points there are (they can then handle things) */
11638         if (! node_p) {
11639             if (! cp_count) {
11640                 RExC_parse = p;
11641             }
11642             return FALSE;
11643         }
11644
11645         /* What is done here is to convert this to a sub-pattern of the form
11646          * \x{char1}\x{char2}...  and then call reg recursively to parse it
11647          * (enclosing in "(?: ... )" ).  That way, it retains its atomicness,
11648          * while not having to worry about special handling that some code
11649          * points may have. */
11650
11651         substitute_parse = newSVpvs("?:");
11652
11653         while (RExC_parse < endbrace) {
11654
11655             /* Convert to notation the rest of the code understands */
11656             sv_catpv(substitute_parse, "\\x{");
11657             sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse);
11658             sv_catpv(substitute_parse, "}");
11659
11660             /* Point to the beginning of the next character in the sequence. */
11661             RExC_parse = endchar + 1;
11662             endchar = RExC_parse + strcspn(RExC_parse, ".}");
11663
11664         }
11665         sv_catpv(substitute_parse, ")");
11666
11667         RExC_parse = RExC_start = RExC_adjusted_start = SvPV(substitute_parse,
11668                                                              len);
11669
11670         /* Don't allow empty number */
11671         if (len < (STRLEN) 8) {
11672             RExC_parse = endbrace;
11673             vFAIL("Invalid hexadecimal number in \\N{U+...}");
11674         }
11675         RExC_end = RExC_parse + len;
11676
11677         /* The values are Unicode, and therefore not subject to recoding, but
11678          * have to be converted to native on a non-Unicode (meaning non-ASCII)
11679          * platform. */
11680         RExC_override_recoding = 1;
11681 #ifdef EBCDIC
11682         RExC_recode_x_to_native = 1;
11683 #endif
11684
11685         if (node_p) {
11686             if (!(*node_p = reg(pRExC_state, 1, &flags, depth+1))) {
11687                 if (flags & (RESTART_PASS1|NEED_UTF8)) {
11688                     *flagp = flags & (RESTART_PASS1|NEED_UTF8);
11689                     return FALSE;
11690                 }
11691                 FAIL2("panic: reg returned NULL to grok_bslash_N, flags=%#"UVxf"",
11692                     (UV) flags);
11693             }
11694             *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
11695         }
11696
11697         /* Restore the saved values */
11698         RExC_start = RExC_adjusted_start = save_start;
11699         RExC_parse = endbrace;
11700         RExC_end = orig_end;
11701         RExC_override_recoding = 0;
11702 #ifdef EBCDIC
11703         RExC_recode_x_to_native = 0;
11704 #endif
11705
11706         SvREFCNT_dec_NN(substitute_parse);
11707         nextchar(pRExC_state);
11708
11709         return TRUE;
11710     }
11711 }
11712
11713
11714 /*
11715  * reg_recode
11716  *
11717  * It returns the code point in utf8 for the value in *encp.
11718  *    value: a code value in the source encoding
11719  *    encp:  a pointer to an Encode object
11720  *
11721  * If the result from Encode is not a single character,
11722  * it returns U+FFFD (Replacement character) and sets *encp to NULL.
11723  */
11724 STATIC UV
11725 S_reg_recode(pTHX_ const U8 value, SV **encp)
11726 {
11727     STRLEN numlen = 1;
11728     SV * const sv = newSVpvn_flags((const char *) &value, numlen, SVs_TEMP);
11729     const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
11730     const STRLEN newlen = SvCUR(sv);
11731     UV uv = UNICODE_REPLACEMENT;
11732
11733     PERL_ARGS_ASSERT_REG_RECODE;
11734
11735     if (newlen)
11736         uv = SvUTF8(sv)
11737              ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
11738              : *(U8*)s;
11739
11740     if (!newlen || numlen != newlen) {
11741         uv = UNICODE_REPLACEMENT;
11742         *encp = NULL;
11743     }
11744     return uv;
11745 }
11746
11747 PERL_STATIC_INLINE U8
11748 S_compute_EXACTish(RExC_state_t *pRExC_state)
11749 {
11750     U8 op;
11751
11752     PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
11753
11754     if (! FOLD) {
11755         return (LOC)
11756                 ? EXACTL
11757                 : EXACT;
11758     }
11759
11760     op = get_regex_charset(RExC_flags);
11761     if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
11762         op--; /* /a is same as /u, and map /aa's offset to what /a's would have
11763                  been, so there is no hole */
11764     }
11765
11766     return op + EXACTF;
11767 }
11768
11769 PERL_STATIC_INLINE void
11770 S_alloc_maybe_populate_EXACT(pTHX_ RExC_state_t *pRExC_state,
11771                          regnode *node, I32* flagp, STRLEN len, UV code_point,
11772                          bool downgradable)
11773 {
11774     /* This knows the details about sizing an EXACTish node, setting flags for
11775      * it (by setting <*flagp>, and potentially populating it with a single
11776      * character.
11777      *
11778      * If <len> (the length in bytes) is non-zero, this function assumes that
11779      * the node has already been populated, and just does the sizing.  In this
11780      * case <code_point> should be the final code point that has already been
11781      * placed into the node.  This value will be ignored except that under some
11782      * circumstances <*flagp> is set based on it.
11783      *
11784      * If <len> is zero, the function assumes that the node is to contain only
11785      * the single character given by <code_point> and calculates what <len>
11786      * should be.  In pass 1, it sizes the node appropriately.  In pass 2, it
11787      * additionally will populate the node's STRING with <code_point> or its
11788      * fold if folding.
11789      *
11790      * In both cases <*flagp> is appropriately set
11791      *
11792      * It knows that under FOLD, the Latin Sharp S and UTF characters above
11793      * 255, must be folded (the former only when the rules indicate it can
11794      * match 'ss')
11795      *
11796      * When it does the populating, it looks at the flag 'downgradable'.  If
11797      * true with a node that folds, it checks if the single code point
11798      * participates in a fold, and if not downgrades the node to an EXACT.
11799      * This helps the optimizer */
11800
11801     bool len_passed_in = cBOOL(len != 0);
11802     U8 character[UTF8_MAXBYTES_CASE+1];
11803
11804     PERL_ARGS_ASSERT_ALLOC_MAYBE_POPULATE_EXACT;
11805
11806     /* Don't bother to check for downgrading in PASS1, as it doesn't make any
11807      * sizing difference, and is extra work that is thrown away */
11808     if (downgradable && ! PASS2) {
11809         downgradable = FALSE;
11810     }
11811
11812     if (! len_passed_in) {
11813         if (UTF) {
11814             if (UVCHR_IS_INVARIANT(code_point)) {
11815                 if (LOC || ! FOLD) {    /* /l defers folding until runtime */
11816                     *character = (U8) code_point;
11817                 }
11818                 else { /* Here is /i and not /l. (toFOLD() is defined on just
11819                           ASCII, which isn't the same thing as INVARIANT on
11820                           EBCDIC, but it works there, as the extra invariants
11821                           fold to themselves) */
11822                     *character = toFOLD((U8) code_point);
11823
11824                     /* We can downgrade to an EXACT node if this character
11825                      * isn't a folding one.  Note that this assumes that
11826                      * nothing above Latin1 folds to some other invariant than
11827                      * one of these alphabetics; otherwise we would also have
11828                      * to check:
11829                      *  && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
11830                      *      || ASCII_FOLD_RESTRICTED))
11831                      */
11832                     if (downgradable && PL_fold[code_point] == code_point) {
11833                         OP(node) = EXACT;
11834                     }
11835                 }
11836                 len = 1;
11837             }
11838             else if (FOLD && (! LOC
11839                               || ! is_PROBLEMATIC_LOCALE_FOLD_cp(code_point)))
11840             {   /* Folding, and ok to do so now */
11841                 UV folded = _to_uni_fold_flags(
11842                                    code_point,
11843                                    character,
11844                                    &len,
11845                                    FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
11846                                                       ? FOLD_FLAGS_NOMIX_ASCII
11847                                                       : 0));
11848                 if (downgradable
11849                     && folded == code_point /* This quickly rules out many
11850                                                cases, avoiding the
11851                                                _invlist_contains_cp() overhead
11852                                                for those.  */
11853                     && ! _invlist_contains_cp(PL_utf8_foldable, code_point))
11854                 {
11855                     OP(node) = (LOC)
11856                                ? EXACTL
11857                                : EXACT;
11858                 }
11859             }
11860             else if (code_point <= MAX_UTF8_TWO_BYTE) {
11861
11862                 /* Not folding this cp, and can output it directly */
11863                 *character = UTF8_TWO_BYTE_HI(code_point);
11864                 *(character + 1) = UTF8_TWO_BYTE_LO(code_point);
11865                 len = 2;
11866             }
11867             else {
11868                 uvchr_to_utf8( character, code_point);
11869                 len = UTF8SKIP(character);
11870             }
11871         } /* Else pattern isn't UTF8.  */
11872         else if (! FOLD) {
11873             *character = (U8) code_point;
11874             len = 1;
11875         } /* Else is folded non-UTF8 */
11876 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
11877    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
11878                                       || UNICODE_DOT_DOT_VERSION > 0)
11879         else if (LIKELY(code_point != LATIN_SMALL_LETTER_SHARP_S)) {
11880 #else
11881         else if (1) {
11882 #endif
11883             /* We don't fold any non-UTF8 except possibly the Sharp s  (see
11884              * comments at join_exact()); */
11885             *character = (U8) code_point;
11886             len = 1;
11887
11888             /* Can turn into an EXACT node if we know the fold at compile time,
11889              * and it folds to itself and doesn't particpate in other folds */
11890             if (downgradable
11891                 && ! LOC
11892                 && PL_fold_latin1[code_point] == code_point
11893                 && (! HAS_NONLATIN1_FOLD_CLOSURE(code_point)
11894                     || (isASCII(code_point) && ASCII_FOLD_RESTRICTED)))
11895             {
11896                 OP(node) = EXACT;
11897             }
11898         } /* else is Sharp s.  May need to fold it */
11899         else if (AT_LEAST_UNI_SEMANTICS && ! ASCII_FOLD_RESTRICTED) {
11900             *character = 's';
11901             *(character + 1) = 's';
11902             len = 2;
11903         }
11904         else {
11905             *character = LATIN_SMALL_LETTER_SHARP_S;
11906             len = 1;
11907         }
11908     }
11909
11910     if (SIZE_ONLY) {
11911         RExC_size += STR_SZ(len);
11912     }
11913     else {
11914         RExC_emit += STR_SZ(len);
11915         STR_LEN(node) = len;
11916         if (! len_passed_in) {
11917             Copy((char *) character, STRING(node), len, char);
11918         }
11919     }
11920
11921     *flagp |= HASWIDTH;
11922
11923     /* A single character node is SIMPLE, except for the special-cased SHARP S
11924      * under /di. */
11925     if ((len == 1 || (UTF && len == UVCHR_SKIP(code_point)))
11926 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
11927    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
11928                                       || UNICODE_DOT_DOT_VERSION > 0)
11929         && ( code_point != LATIN_SMALL_LETTER_SHARP_S
11930             || ! FOLD || ! DEPENDS_SEMANTICS)
11931 #endif
11932     ) {
11933         *flagp |= SIMPLE;
11934     }
11935
11936     /* The OP may not be well defined in PASS1 */
11937     if (PASS2 && OP(node) == EXACTFL) {
11938         RExC_contains_locale = 1;
11939     }
11940 }
11941
11942
11943 /* Parse backref decimal value, unless it's too big to sensibly be a backref,
11944  * in which case return I32_MAX (rather than possibly 32-bit wrapping) */
11945
11946 static I32
11947 S_backref_value(char *p)
11948 {
11949     const char* endptr;
11950     UV val;
11951     if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX)
11952         return (I32)val;
11953     return I32_MAX;
11954 }
11955
11956
11957 /*
11958  - regatom - the lowest level
11959
11960    Try to identify anything special at the start of the pattern. If there
11961    is, then handle it as required. This may involve generating a single regop,
11962    such as for an assertion; or it may involve recursing, such as to
11963    handle a () structure.
11964
11965    If the string doesn't start with something special then we gobble up
11966    as much literal text as we can.
11967
11968    Once we have been able to handle whatever type of thing started the
11969    sequence, we return.
11970
11971    Note: we have to be careful with escapes, as they can be both literal
11972    and special, and in the case of \10 and friends, context determines which.
11973
11974    A summary of the code structure is:
11975
11976    switch (first_byte) {
11977         cases for each special:
11978             handle this special;
11979             break;
11980         case '\\':
11981             switch (2nd byte) {
11982                 cases for each unambiguous special:
11983                     handle this special;
11984                     break;
11985                 cases for each ambigous special/literal:
11986                     disambiguate;
11987                     if (special)  handle here
11988                     else goto defchar;
11989                 default: // unambiguously literal:
11990                     goto defchar;
11991             }
11992         default:  // is a literal char
11993             // FALL THROUGH
11994         defchar:
11995             create EXACTish node for literal;
11996             while (more input and node isn't full) {
11997                 switch (input_byte) {
11998                    cases for each special;
11999                        make sure parse pointer is set so that the next call to
12000                            regatom will see this special first
12001                        goto loopdone; // EXACTish node terminated by prev. char
12002                    default:
12003                        append char to EXACTISH node;
12004                 }
12005                 get next input byte;
12006             }
12007         loopdone:
12008    }
12009    return the generated node;
12010
12011    Specifically there are two separate switches for handling
12012    escape sequences, with the one for handling literal escapes requiring
12013    a dummy entry for all of the special escapes that are actually handled
12014    by the other.
12015
12016    Returns NULL, setting *flagp to TRYAGAIN if reg() returns NULL with
12017    TRYAGAIN.
12018    Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs to be
12019    restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8
12020    Otherwise does not return NULL.
12021 */
12022
12023 STATIC regnode *
12024 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
12025 {
12026     regnode *ret = NULL;
12027     I32 flags = 0;
12028     char *parse_start;
12029     U8 op;
12030     int invert = 0;
12031     U8 arg;
12032
12033     GET_RE_DEBUG_FLAGS_DECL;
12034
12035     *flagp = WORST;             /* Tentatively. */
12036
12037     DEBUG_PARSE("atom");
12038
12039     PERL_ARGS_ASSERT_REGATOM;
12040
12041   tryagain:
12042     parse_start = RExC_parse;
12043     assert(RExC_parse < RExC_end);
12044     switch ((U8)*RExC_parse) {
12045     case '^':
12046         RExC_seen_zerolen++;
12047         nextchar(pRExC_state);
12048         if (RExC_flags & RXf_PMf_MULTILINE)
12049             ret = reg_node(pRExC_state, MBOL);
12050         else
12051             ret = reg_node(pRExC_state, SBOL);
12052         Set_Node_Length(ret, 1); /* MJD */
12053         break;
12054     case '$':
12055         nextchar(pRExC_state);
12056         if (*RExC_parse)
12057             RExC_seen_zerolen++;
12058         if (RExC_flags & RXf_PMf_MULTILINE)
12059             ret = reg_node(pRExC_state, MEOL);
12060         else
12061             ret = reg_node(pRExC_state, SEOL);
12062         Set_Node_Length(ret, 1); /* MJD */
12063         break;
12064     case '.':
12065         nextchar(pRExC_state);
12066         if (RExC_flags & RXf_PMf_SINGLELINE)
12067             ret = reg_node(pRExC_state, SANY);
12068         else
12069             ret = reg_node(pRExC_state, REG_ANY);
12070         *flagp |= HASWIDTH|SIMPLE;
12071         MARK_NAUGHTY(1);
12072         Set_Node_Length(ret, 1); /* MJD */
12073         break;
12074     case '[':
12075     {
12076         char * const oregcomp_parse = ++RExC_parse;
12077         ret = regclass(pRExC_state, flagp,depth+1,
12078                        FALSE, /* means parse the whole char class */
12079                        TRUE, /* allow multi-char folds */
12080                        FALSE, /* don't silence non-portable warnings. */
12081                        (bool) RExC_strict,
12082                        TRUE, /* Allow an optimized regnode result */
12083                        NULL,
12084                        NULL);
12085         if (ret == NULL) {
12086             if (*flagp & (RESTART_PASS1|NEED_UTF8))
12087                 return NULL;
12088             FAIL2("panic: regclass returned NULL to regatom, flags=%#"UVxf"",
12089                   (UV) *flagp);
12090         }
12091         if (*RExC_parse != ']') {
12092             RExC_parse = oregcomp_parse;
12093             vFAIL("Unmatched [");
12094         }
12095         nextchar(pRExC_state);
12096         Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
12097         break;
12098     }
12099     case '(':
12100         nextchar(pRExC_state);
12101         ret = reg(pRExC_state, 2, &flags,depth+1);
12102         if (ret == NULL) {
12103                 if (flags & TRYAGAIN) {
12104                     if (RExC_parse >= RExC_end) {
12105                          /* Make parent create an empty node if needed. */
12106                         *flagp |= TRYAGAIN;
12107                         return(NULL);
12108                     }
12109                     goto tryagain;
12110                 }
12111                 if (flags & (RESTART_PASS1|NEED_UTF8)) {
12112                     *flagp = flags & (RESTART_PASS1|NEED_UTF8);
12113                     return NULL;
12114                 }
12115                 FAIL2("panic: reg returned NULL to regatom, flags=%#"UVxf"",
12116                                                                  (UV) flags);
12117         }
12118         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
12119         break;
12120     case '|':
12121     case ')':
12122         if (flags & TRYAGAIN) {
12123             *flagp |= TRYAGAIN;
12124             return NULL;
12125         }
12126         vFAIL("Internal urp");
12127                                 /* Supposed to be caught earlier. */
12128         break;
12129     case '?':
12130     case '+':
12131     case '*':
12132         RExC_parse++;
12133         vFAIL("Quantifier follows nothing");
12134         break;
12135     case '\\':
12136         /* Special Escapes
12137
12138            This switch handles escape sequences that resolve to some kind
12139            of special regop and not to literal text. Escape sequnces that
12140            resolve to literal text are handled below in the switch marked
12141            "Literal Escapes".
12142
12143            Every entry in this switch *must* have a corresponding entry
12144            in the literal escape switch. However, the opposite is not
12145            required, as the default for this switch is to jump to the
12146            literal text handling code.
12147         */
12148         RExC_parse++;
12149         switch ((U8)*RExC_parse) {
12150         /* Special Escapes */
12151         case 'A':
12152             RExC_seen_zerolen++;
12153             ret = reg_node(pRExC_state, SBOL);
12154             /* SBOL is shared with /^/ so we set the flags so we can tell
12155              * /\A/ from /^/ in split. We check ret because first pass we
12156              * have no regop struct to set the flags on. */
12157             if (PASS2)
12158                 ret->flags = 1;
12159             *flagp |= SIMPLE;
12160             goto finish_meta_pat;
12161         case 'G':
12162             ret = reg_node(pRExC_state, GPOS);
12163             RExC_seen |= REG_GPOS_SEEN;
12164             *flagp |= SIMPLE;
12165             goto finish_meta_pat;
12166         case 'K':
12167             RExC_seen_zerolen++;
12168             ret = reg_node(pRExC_state, KEEPS);
12169             *flagp |= SIMPLE;
12170             /* XXX:dmq : disabling in-place substitution seems to
12171              * be necessary here to avoid cases of memory corruption, as
12172              * with: C<$_="x" x 80; s/x\K/y/> -- rgs
12173              */
12174             RExC_seen |= REG_LOOKBEHIND_SEEN;
12175             goto finish_meta_pat;
12176         case 'Z':
12177             ret = reg_node(pRExC_state, SEOL);
12178             *flagp |= SIMPLE;
12179             RExC_seen_zerolen++;                /* Do not optimize RE away */
12180             goto finish_meta_pat;
12181         case 'z':
12182             ret = reg_node(pRExC_state, EOS);
12183             *flagp |= SIMPLE;
12184             RExC_seen_zerolen++;                /* Do not optimize RE away */
12185             goto finish_meta_pat;
12186         case 'C':
12187             vFAIL("\\C no longer supported");
12188         case 'X':
12189             ret = reg_node(pRExC_state, CLUMP);
12190             *flagp |= HASWIDTH;
12191             goto finish_meta_pat;
12192
12193         case 'W':
12194             invert = 1;
12195             /* FALLTHROUGH */
12196         case 'w':
12197             arg = ANYOF_WORDCHAR;
12198             goto join_posix;
12199
12200         case 'B':
12201             invert = 1;
12202             /* FALLTHROUGH */
12203         case 'b':
12204           {
12205             regex_charset charset = get_regex_charset(RExC_flags);
12206
12207             RExC_seen_zerolen++;
12208             RExC_seen |= REG_LOOKBEHIND_SEEN;
12209             op = BOUND + charset;
12210
12211             if (op == BOUNDL) {
12212                 RExC_contains_locale = 1;
12213             }
12214
12215             ret = reg_node(pRExC_state, op);
12216             *flagp |= SIMPLE;
12217             if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') {
12218                 FLAGS(ret) = TRADITIONAL_BOUND;
12219                 if (PASS2 && op > BOUNDA) {  /* /aa is same as /a */
12220                     OP(ret) = BOUNDA;
12221                 }
12222             }
12223             else {
12224                 STRLEN length;
12225                 char name = *RExC_parse;
12226                 char * endbrace;
12227                 RExC_parse += 2;
12228                 endbrace = strchr(RExC_parse, '}');
12229
12230                 if (! endbrace) {
12231                     vFAIL2("Missing right brace on \\%c{}", name);
12232                 }
12233                 /* XXX Need to decide whether to take spaces or not.  Should be
12234                  * consistent with \p{}, but that currently is SPACE, which
12235                  * means vertical too, which seems wrong
12236                  * while (isBLANK(*RExC_parse)) {
12237                     RExC_parse++;
12238                 }*/
12239                 if (endbrace == RExC_parse) {
12240                     RExC_parse++;  /* After the '}' */
12241                     vFAIL2("Empty \\%c{}", name);
12242                 }
12243                 length = endbrace - RExC_parse;
12244                 /*while (isBLANK(*(RExC_parse + length - 1))) {
12245                     length--;
12246                 }*/
12247                 switch (*RExC_parse) {
12248                     case 'g':
12249                         if (length != 1
12250                             && (length != 3 || strnNE(RExC_parse + 1, "cb", 2)))
12251                         {
12252                             goto bad_bound_type;
12253                         }
12254                         FLAGS(ret) = GCB_BOUND;
12255                         break;
12256                     case 'l':
12257                         if (length != 2 || *(RExC_parse + 1) != 'b') {
12258                             goto bad_bound_type;
12259                         }
12260                         FLAGS(ret) = LB_BOUND;
12261                         break;
12262                     case 's':
12263                         if (length != 2 || *(RExC_parse + 1) != 'b') {
12264                             goto bad_bound_type;
12265                         }
12266                         FLAGS(ret) = SB_BOUND;
12267                         break;
12268                     case 'w':
12269                         if (length != 2 || *(RExC_parse + 1) != 'b') {
12270                             goto bad_bound_type;
12271                         }
12272                         FLAGS(ret) = WB_BOUND;
12273                         break;
12274                     default:
12275                       bad_bound_type:
12276                         RExC_parse = endbrace;
12277                         vFAIL2utf8f(
12278                             "'%"UTF8f"' is an unknown bound type",
12279                             UTF8fARG(UTF, length, endbrace - length));
12280                         NOT_REACHED; /*NOTREACHED*/
12281                 }
12282                 RExC_parse = endbrace;
12283                 REQUIRE_UNI_RULES(flagp, NULL);
12284
12285                 if (PASS2 && op >= BOUNDA) {  /* /aa is same as /a */
12286                     OP(ret) = BOUNDU;
12287                     length += 4;
12288
12289                     /* Don't have to worry about UTF-8, in this message because
12290                      * to get here the contents of the \b must be ASCII */
12291                     ckWARN4reg(RExC_parse + 1,  /* Include the '}' in msg */
12292                               "Using /u for '%.*s' instead of /%s",
12293                               (unsigned) length,
12294                               endbrace - length + 1,
12295                               (charset == REGEX_ASCII_RESTRICTED_CHARSET)
12296                               ? ASCII_RESTRICT_PAT_MODS
12297                               : ASCII_MORE_RESTRICT_PAT_MODS);
12298                 }
12299             }
12300
12301             if (PASS2 && invert) {
12302                 OP(ret) += NBOUND - BOUND;
12303             }
12304             goto finish_meta_pat;
12305           }
12306
12307         case 'D':
12308             invert = 1;
12309             /* FALLTHROUGH */
12310         case 'd':
12311             arg = ANYOF_DIGIT;
12312             if (! DEPENDS_SEMANTICS) {
12313                 goto join_posix;
12314             }
12315
12316             /* \d doesn't have any matches in the upper Latin1 range, hence /d
12317              * is equivalent to /u.  Changing to /u saves some branches at
12318              * runtime */
12319             op = POSIXU;
12320             goto join_posix_op_known;
12321
12322         case 'R':
12323             ret = reg_node(pRExC_state, LNBREAK);
12324             *flagp |= HASWIDTH|SIMPLE;
12325             goto finish_meta_pat;
12326
12327         case 'H':
12328             invert = 1;
12329             /* FALLTHROUGH */
12330         case 'h':
12331             arg = ANYOF_BLANK;
12332             op = POSIXU;
12333             goto join_posix_op_known;
12334
12335         case 'V':
12336             invert = 1;
12337             /* FALLTHROUGH */
12338         case 'v':
12339             arg = ANYOF_VERTWS;
12340             op = POSIXU;
12341             goto join_posix_op_known;
12342
12343         case 'S':
12344             invert = 1;
12345             /* FALLTHROUGH */
12346         case 's':
12347             arg = ANYOF_SPACE;
12348
12349           join_posix:
12350
12351             op = POSIXD + get_regex_charset(RExC_flags);
12352             if (op > POSIXA) {  /* /aa is same as /a */
12353                 op = POSIXA;
12354             }
12355             else if (op == POSIXL) {
12356                 RExC_contains_locale = 1;
12357             }
12358
12359           join_posix_op_known:
12360
12361             if (invert) {
12362                 op += NPOSIXD - POSIXD;
12363             }
12364
12365             ret = reg_node(pRExC_state, op);
12366             if (! SIZE_ONLY) {
12367                 FLAGS(ret) = namedclass_to_classnum(arg);
12368             }
12369
12370             *flagp |= HASWIDTH|SIMPLE;
12371             /* FALLTHROUGH */
12372
12373           finish_meta_pat:
12374             nextchar(pRExC_state);
12375             Set_Node_Length(ret, 2); /* MJD */
12376             break;
12377         case 'p':
12378         case 'P':
12379             RExC_parse--;
12380
12381             ret = regclass(pRExC_state, flagp,depth+1,
12382                            TRUE, /* means just parse this element */
12383                            FALSE, /* don't allow multi-char folds */
12384                            FALSE, /* don't silence non-portable warnings.  It
12385                                      would be a bug if these returned
12386                                      non-portables */
12387                            (bool) RExC_strict,
12388                            TRUE, /* Allow an optimized regnode result */
12389                            NULL,
12390                            NULL);
12391             if (*flagp & RESTART_PASS1)
12392                 return NULL;
12393             /* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
12394              * multi-char folds are allowed.  */
12395             if (!ret)
12396                 FAIL2("panic: regclass returned NULL to regatom, flags=%#"UVxf"",
12397                       (UV) *flagp);
12398
12399             RExC_parse--;
12400
12401             Set_Node_Offset(ret, parse_start);
12402             Set_Node_Cur_Length(ret, parse_start - 2);
12403             nextchar(pRExC_state);
12404             break;
12405         case 'N':
12406             /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the
12407              * \N{...} evaluates to a sequence of more than one code points).
12408              * The function call below returns a regnode, which is our result.
12409              * The parameters cause it to fail if the \N{} evaluates to a
12410              * single code point; we handle those like any other literal.  The
12411              * reason that the multicharacter case is handled here and not as
12412              * part of the EXACtish code is because of quantifiers.  In
12413              * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it
12414              * this way makes that Just Happen. dmq.
12415              * join_exact() will join this up with adjacent EXACTish nodes
12416              * later on, if appropriate. */
12417             ++RExC_parse;
12418             if (grok_bslash_N(pRExC_state,
12419                               &ret,     /* Want a regnode returned */
12420                               NULL,     /* Fail if evaluates to a single code
12421                                            point */
12422                               NULL,     /* Don't need a count of how many code
12423                                            points */
12424                               flagp,
12425                               depth)
12426             ) {
12427                 break;
12428             }
12429
12430             if (*flagp & RESTART_PASS1)
12431                 return NULL;
12432
12433             /* Here, evaluates to a single code point.  Go get that */
12434             RExC_parse = parse_start;
12435             goto defchar;
12436
12437         case 'k':    /* Handle \k<NAME> and \k'NAME' */
12438       parse_named_seq:
12439         {
12440             char ch;
12441             if (   RExC_parse >= RExC_end - 1
12442                 || ((   ch = RExC_parse[1]) != '<'
12443                                       && ch != '\''
12444                                       && ch != '{'))
12445             {
12446                 RExC_parse++;
12447                 /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */
12448                 vFAIL2("Sequence %.2s... not terminated",parse_start);
12449             } else {
12450                 RExC_parse += 2;
12451                 ret = handle_named_backref(pRExC_state,
12452                                            flagp,
12453                                            parse_start,
12454                                            (ch == '<')
12455                                            ? '>'
12456                                            : (ch == '{')
12457                                              ? '}'
12458                                              : '\'');
12459             }
12460             break;
12461         }
12462         case 'g':
12463         case '1': case '2': case '3': case '4':
12464         case '5': case '6': case '7': case '8': case '9':
12465             {
12466                 I32 num;
12467                 bool hasbrace = 0;
12468
12469                 if (*RExC_parse == 'g') {
12470                     bool isrel = 0;
12471
12472                     RExC_parse++;
12473                     if (*RExC_parse == '{') {
12474                         RExC_parse++;
12475                         hasbrace = 1;
12476                     }
12477                     if (*RExC_parse == '-') {
12478                         RExC_parse++;
12479                         isrel = 1;
12480                     }
12481                     if (hasbrace && !isDIGIT(*RExC_parse)) {
12482                         if (isrel) RExC_parse--;
12483                         RExC_parse -= 2;
12484                         goto parse_named_seq;
12485                     }
12486
12487                     if (RExC_parse >= RExC_end) {
12488                         goto unterminated_g;
12489                     }
12490                     num = S_backref_value(RExC_parse);
12491                     if (num == 0)
12492                         vFAIL("Reference to invalid group 0");
12493                     else if (num == I32_MAX) {
12494                          if (isDIGIT(*RExC_parse))
12495                             vFAIL("Reference to nonexistent group");
12496                         else
12497                           unterminated_g:
12498                             vFAIL("Unterminated \\g... pattern");
12499                     }
12500
12501                     if (isrel) {
12502                         num = RExC_npar - num;
12503                         if (num < 1)
12504                             vFAIL("Reference to nonexistent or unclosed group");
12505                     }
12506                 }
12507                 else {
12508                     num = S_backref_value(RExC_parse);
12509                     /* bare \NNN might be backref or octal - if it is larger
12510                      * than or equal RExC_npar then it is assumed to be an
12511                      * octal escape. Note RExC_npar is +1 from the actual
12512                      * number of parens. */
12513                     /* Note we do NOT check if num == I32_MAX here, as that is
12514                      * handled by the RExC_npar check */
12515
12516                     if (
12517                         /* any numeric escape < 10 is always a backref */
12518                         num > 9
12519                         /* any numeric escape < RExC_npar is a backref */
12520                         && num >= RExC_npar
12521                         /* cannot be an octal escape if it starts with 8 */
12522                         && *RExC_parse != '8'
12523                         /* cannot be an octal escape it it starts with 9 */
12524                         && *RExC_parse != '9'
12525                     )
12526                     {
12527                         /* Probably not a backref, instead likely to be an
12528                          * octal character escape, e.g. \35 or \777.
12529                          * The above logic should make it obvious why using
12530                          * octal escapes in patterns is problematic. - Yves */
12531                         RExC_parse = parse_start;
12532                         goto defchar;
12533                     }
12534                 }
12535
12536                 /* At this point RExC_parse points at a numeric escape like
12537                  * \12 or \88 or something similar, which we should NOT treat
12538                  * as an octal escape. It may or may not be a valid backref
12539                  * escape. For instance \88888888 is unlikely to be a valid
12540                  * backref. */
12541                 while (isDIGIT(*RExC_parse))
12542                     RExC_parse++;
12543                 if (hasbrace) {
12544                     if (*RExC_parse != '}')
12545                         vFAIL("Unterminated \\g{...} pattern");
12546                     RExC_parse++;
12547                 }
12548                 if (!SIZE_ONLY) {
12549                     if (num > (I32)RExC_rx->nparens)
12550                         vFAIL("Reference to nonexistent group");
12551                 }
12552                 RExC_sawback = 1;
12553                 ret = reganode(pRExC_state,
12554                                ((! FOLD)
12555                                  ? REF
12556                                  : (ASCII_FOLD_RESTRICTED)
12557                                    ? REFFA
12558                                    : (AT_LEAST_UNI_SEMANTICS)
12559                                      ? REFFU
12560                                      : (LOC)
12561                                        ? REFFL
12562                                        : REFF),
12563                                 num);
12564                 *flagp |= HASWIDTH;
12565
12566                 /* override incorrect value set in reganode MJD */
12567                 Set_Node_Offset(ret, parse_start);
12568                 Set_Node_Cur_Length(ret, parse_start-1);
12569                 skip_to_be_ignored_text(pRExC_state, &RExC_parse,
12570                                         FALSE /* Don't force to /x */ );
12571             }
12572             break;
12573         case '\0':
12574             if (RExC_parse >= RExC_end)
12575                 FAIL("Trailing \\");
12576             /* FALLTHROUGH */
12577         default:
12578             /* Do not generate "unrecognized" warnings here, we fall
12579                back into the quick-grab loop below */
12580             RExC_parse = parse_start;
12581             goto defchar;
12582         } /* end of switch on a \foo sequence */
12583         break;
12584
12585     case '#':
12586
12587         /* '#' comments should have been spaced over before this function was
12588          * called */
12589         assert((RExC_flags & RXf_PMf_EXTENDED) == 0);
12590         /*
12591         if (RExC_flags & RXf_PMf_EXTENDED) {
12592             RExC_parse = reg_skipcomment( pRExC_state, RExC_parse );
12593             if (RExC_parse < RExC_end)
12594                 goto tryagain;
12595         }
12596         */
12597
12598         /* FALLTHROUGH */
12599
12600     default:
12601           defchar: {
12602
12603             /* Here, we have determined that the next thing is probably a
12604              * literal character.  RExC_parse points to the first byte of its
12605              * definition.  (It still may be an escape sequence that evaluates
12606              * to a single character) */
12607
12608             STRLEN len = 0;
12609             UV ender = 0;
12610             char *p;
12611             char *s;
12612 #define MAX_NODE_STRING_SIZE 127
12613             char foldbuf[MAX_NODE_STRING_SIZE+UTF8_MAXBYTES_CASE];
12614             char *s0;
12615             U8 upper_parse = MAX_NODE_STRING_SIZE;
12616             U8 node_type = compute_EXACTish(pRExC_state);
12617             bool next_is_quantifier;
12618             char * oldp = NULL;
12619
12620             /* We can convert EXACTF nodes to EXACTFU if they contain only
12621              * characters that match identically regardless of the target
12622              * string's UTF8ness.  The reason to do this is that EXACTF is not
12623              * trie-able, EXACTFU is.
12624              *
12625              * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they
12626              * contain only above-Latin1 characters (hence must be in UTF8),
12627              * which don't participate in folds with Latin1-range characters,
12628              * as the latter's folds aren't known until runtime.  (We don't
12629              * need to figure this out until pass 2) */
12630             bool maybe_exactfu = PASS2
12631                                && (node_type == EXACTF || node_type == EXACTFL);
12632
12633             /* If a folding node contains only code points that don't
12634              * participate in folds, it can be changed into an EXACT node,
12635              * which allows the optimizer more things to look for */
12636             bool maybe_exact;
12637
12638             ret = reg_node(pRExC_state, node_type);
12639
12640             /* In pass1, folded, we use a temporary buffer instead of the
12641              * actual node, as the node doesn't exist yet */
12642             s = (SIZE_ONLY && FOLD) ? foldbuf : STRING(ret);
12643
12644             s0 = s;
12645
12646           reparse:
12647
12648             /* We look for the EXACTFish to EXACT node optimizaton only if
12649              * folding.  (And we don't need to figure this out until pass 2).
12650              * XXX It might actually make sense to split the node into portions
12651              * that are exact and ones that aren't, so that we could later use
12652              * the exact ones to find the longest fixed and floating strings.
12653              * One would want to join them back into a larger node.  One could
12654              * use a pseudo regnode like 'EXACT_ORIG_FOLD' */
12655             maybe_exact = FOLD && PASS2;
12656
12657             /* XXX The node can hold up to 255 bytes, yet this only goes to
12658              * 127.  I (khw) do not know why.  Keeping it somewhat less than
12659              * 255 allows us to not have to worry about overflow due to
12660              * converting to utf8 and fold expansion, but that value is
12661              * 255-UTF8_MAXBYTES_CASE.  join_exact() may join adjacent nodes
12662              * split up by this limit into a single one using the real max of
12663              * 255.  Even at 127, this breaks under rare circumstances.  If
12664              * folding, we do not want to split a node at a character that is a
12665              * non-final in a multi-char fold, as an input string could just
12666              * happen to want to match across the node boundary.  The join
12667              * would solve that problem if the join actually happens.  But a
12668              * series of more than two nodes in a row each of 127 would cause
12669              * the first join to succeed to get to 254, but then there wouldn't
12670              * be room for the next one, which could at be one of those split
12671              * multi-char folds.  I don't know of any fool-proof solution.  One
12672              * could back off to end with only a code point that isn't such a
12673              * non-final, but it is possible for there not to be any in the
12674              * entire node. */
12675
12676             assert(   ! UTF     /* Is at the beginning of a character */
12677                    || UTF8_IS_INVARIANT(UCHARAT(RExC_parse))
12678                    || UTF8_IS_START(UCHARAT(RExC_parse)));
12679
12680             for (p = RExC_parse;
12681                  len < upper_parse && p < RExC_end;
12682                  len++)
12683             {
12684                 oldp = p;
12685
12686                 /* White space has already been ignored */
12687                 assert(   (RExC_flags & RXf_PMf_EXTENDED) == 0
12688                        || ! is_PATWS_safe((p), RExC_end, UTF));
12689
12690                 switch ((U8)*p) {
12691                 case '^':
12692                 case '$':
12693                 case '.':
12694                 case '[':
12695                 case '(':
12696                 case ')':
12697                 case '|':
12698                     goto loopdone;
12699                 case '\\':
12700                     /* Literal Escapes Switch
12701
12702                        This switch is meant to handle escape sequences that
12703                        resolve to a literal character.
12704
12705                        Every escape sequence that represents something
12706                        else, like an assertion or a char class, is handled
12707                        in the switch marked 'Special Escapes' above in this
12708                        routine, but also has an entry here as anything that
12709                        isn't explicitly mentioned here will be treated as
12710                        an unescaped equivalent literal.
12711                     */
12712
12713                     switch ((U8)*++p) {
12714                     /* These are all the special escapes. */
12715                     case 'A':             /* Start assertion */
12716                     case 'b': case 'B':   /* Word-boundary assertion*/
12717                     case 'C':             /* Single char !DANGEROUS! */
12718                     case 'd': case 'D':   /* digit class */
12719                     case 'g': case 'G':   /* generic-backref, pos assertion */
12720                     case 'h': case 'H':   /* HORIZWS */
12721                     case 'k': case 'K':   /* named backref, keep marker */
12722                     case 'p': case 'P':   /* Unicode property */
12723                               case 'R':   /* LNBREAK */
12724                     case 's': case 'S':   /* space class */
12725                     case 'v': case 'V':   /* VERTWS */
12726                     case 'w': case 'W':   /* word class */
12727                     case 'X':             /* eXtended Unicode "combining
12728                                              character sequence" */
12729                     case 'z': case 'Z':   /* End of line/string assertion */
12730                         --p;
12731                         goto loopdone;
12732
12733                     /* Anything after here is an escape that resolves to a
12734                        literal. (Except digits, which may or may not)
12735                      */
12736                     case 'n':
12737                         ender = '\n';
12738                         p++;
12739                         break;
12740                     case 'N': /* Handle a single-code point named character. */
12741                         RExC_parse = p + 1;
12742                         if (! grok_bslash_N(pRExC_state,
12743                                             NULL,   /* Fail if evaluates to
12744                                                        anything other than a
12745                                                        single code point */
12746                                             &ender, /* The returned single code
12747                                                        point */
12748                                             NULL,   /* Don't need a count of
12749                                                        how many code points */
12750                                             flagp,
12751                                             depth)
12752                         ) {
12753                             if (*flagp & NEED_UTF8)
12754                                 FAIL("panic: grok_bslash_N set NEED_UTF8");
12755                             if (*flagp & RESTART_PASS1)
12756                                 return NULL;
12757
12758                             /* Here, it wasn't a single code point.  Go close
12759                              * up this EXACTish node.  The switch() prior to
12760                              * this switch handles the other cases */
12761                             RExC_parse = p = oldp;
12762                             goto loopdone;
12763                         }
12764                         p = RExC_parse;
12765                         if (ender > 0xff) {
12766                             REQUIRE_UTF8(flagp);
12767                         }
12768                         break;
12769                     case 'r':
12770                         ender = '\r';
12771                         p++;
12772                         break;
12773                     case 't':
12774                         ender = '\t';
12775                         p++;
12776                         break;
12777                     case 'f':
12778                         ender = '\f';
12779                         p++;
12780                         break;
12781                     case 'e':
12782                         ender = ESC_NATIVE;
12783                         p++;
12784                         break;
12785                     case 'a':
12786                         ender = '\a';
12787                         p++;
12788                         break;
12789                     case 'o':
12790                         {
12791                             UV result;
12792                             const char* error_msg;
12793
12794                             bool valid = grok_bslash_o(&p,
12795                                                        &result,
12796                                                        &error_msg,
12797                                                        PASS2, /* out warnings */
12798                                                        (bool) RExC_strict,
12799                                                        TRUE, /* Output warnings
12800                                                                 for non-
12801                                                                 portables */
12802                                                        UTF);
12803                             if (! valid) {
12804                                 RExC_parse = p; /* going to die anyway; point
12805                                                    to exact spot of failure */
12806                                 vFAIL(error_msg);
12807                             }
12808                             ender = result;
12809                             if (IN_ENCODING && ender < 0x100) {
12810                                 goto recode_encoding;
12811                             }
12812                             if (ender > 0xff) {
12813                                 REQUIRE_UTF8(flagp);
12814                             }
12815                             break;
12816                         }
12817                     case 'x':
12818                         {
12819                             UV result = UV_MAX; /* initialize to erroneous
12820                                                    value */
12821                             const char* error_msg;
12822
12823                             bool valid = grok_bslash_x(&p,
12824                                                        &result,
12825                                                        &error_msg,
12826                                                        PASS2, /* out warnings */
12827                                                        (bool) RExC_strict,
12828                                                        TRUE, /* Silence warnings
12829                                                                 for non-
12830                                                                 portables */
12831                                                        UTF);
12832                             if (! valid) {
12833                                 RExC_parse = p; /* going to die anyway; point
12834                                                    to exact spot of failure */
12835                                 vFAIL(error_msg);
12836                             }
12837                             ender = result;
12838
12839                             if (ender < 0x100) {
12840 #ifdef EBCDIC
12841                                 if (RExC_recode_x_to_native) {
12842                                     ender = LATIN1_TO_NATIVE(ender);
12843                                 }
12844                                 else
12845 #endif
12846                                 if (IN_ENCODING) {
12847                                     goto recode_encoding;
12848                                 }
12849                             }
12850                             else {
12851                                 REQUIRE_UTF8(flagp);
12852                             }
12853                             break;
12854                         }
12855                     case 'c':
12856                         p++;
12857                         ender = grok_bslash_c(*p++, PASS2);
12858                         break;
12859                     case '8': case '9': /* must be a backreference */
12860                         --p;
12861                         /* we have an escape like \8 which cannot be an octal escape
12862                          * so we exit the loop, and let the outer loop handle this
12863                          * escape which may or may not be a legitimate backref. */
12864                         goto loopdone;
12865                     case '1': case '2': case '3':case '4':
12866                     case '5': case '6': case '7':
12867                         /* When we parse backslash escapes there is ambiguity
12868                          * between backreferences and octal escapes. Any escape
12869                          * from \1 - \9 is a backreference, any multi-digit
12870                          * escape which does not start with 0 and which when
12871                          * evaluated as decimal could refer to an already
12872                          * parsed capture buffer is a back reference. Anything
12873                          * else is octal.
12874                          *
12875                          * Note this implies that \118 could be interpreted as
12876                          * 118 OR as "\11" . "8" depending on whether there
12877                          * were 118 capture buffers defined already in the
12878                          * pattern.  */
12879
12880                         /* NOTE, RExC_npar is 1 more than the actual number of
12881                          * parens we have seen so far, hence the < RExC_npar below. */
12882
12883                         if ( !isDIGIT(p[1]) || S_backref_value(p) < RExC_npar)
12884                         {  /* Not to be treated as an octal constant, go
12885                                    find backref */
12886                             --p;
12887                             goto loopdone;
12888                         }
12889                         /* FALLTHROUGH */
12890                     case '0':
12891                         {
12892                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
12893                             STRLEN numlen = 3;
12894                             ender = grok_oct(p, &numlen, &flags, NULL);
12895                             if (ender > 0xff) {
12896                                 REQUIRE_UTF8(flagp);
12897                             }
12898                             p += numlen;
12899                             if (PASS2   /* like \08, \178 */
12900                                 && numlen < 3
12901                                 && isDIGIT(*p) && ckWARN(WARN_REGEXP))
12902                             {
12903                                 reg_warn_non_literal_string(
12904                                          p + 1,
12905                                          form_short_octal_warning(p, numlen));
12906                             }
12907                         }
12908                         if (IN_ENCODING && ender < 0x100)
12909                             goto recode_encoding;
12910                         break;
12911                       recode_encoding:
12912                         if (! RExC_override_recoding) {
12913                             SV* enc = _get_encoding();
12914                             ender = reg_recode((U8)ender, &enc);
12915                             if (!enc && PASS2)
12916                                 ckWARNreg(p, "Invalid escape in the specified encoding");
12917                             REQUIRE_UTF8(flagp);
12918                         }
12919                         break;
12920                     case '\0':
12921                         if (p >= RExC_end)
12922                             FAIL("Trailing \\");
12923                         /* FALLTHROUGH */
12924                     default:
12925                         if (!SIZE_ONLY&& isALPHANUMERIC(*p)) {
12926                             /* Include any left brace following the alpha to emphasize
12927                              * that it could be part of an escape at some point
12928                              * in the future */
12929                             int len = (isALPHA(*p) && *(p + 1) == '{') ? 2 : 1;
12930                             ckWARN3reg(p + len, "Unrecognized escape \\%.*s passed through", len, p);
12931                         }
12932                         goto normal_default;
12933                     } /* End of switch on '\' */
12934                     break;
12935                 case '{':
12936                     /* Currently we don't warn when the lbrace is at the start
12937                      * of a construct.  This catches it in the middle of a
12938                      * literal string, or when it's the first thing after
12939                      * something like "\b" */
12940                     if (! SIZE_ONLY
12941                         && (len || (p > RExC_start && isALPHA_A(*(p -1)))))
12942                     {
12943                         ckWARNregdep(p + 1, "Unescaped left brace in regex is deprecated, passed through");
12944                     }
12945                     /*FALLTHROUGH*/
12946                 default:    /* A literal character */
12947                   normal_default:
12948                     if (! UTF8_IS_INVARIANT(*p) && UTF) {
12949                         STRLEN numlen;
12950                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
12951                                                &numlen, UTF8_ALLOW_DEFAULT);
12952                         p += numlen;
12953                     }
12954                     else
12955                         ender = (U8) *p++;
12956                     break;
12957                 } /* End of switch on the literal */
12958
12959                 /* Here, have looked at the literal character and <ender>
12960                  * contains its ordinal, <p> points to the character after it.
12961                  * We need to check if the next non-ignored thing is a
12962                  * quantifier.  Move <p> to after anything that should be
12963                  * ignored, which, as a side effect, positions <p> for the next
12964                  * loop iteration */
12965                 skip_to_be_ignored_text(pRExC_state, &p,
12966                                         FALSE /* Don't force to /x */ );
12967
12968                 /* If the next thing is a quantifier, it applies to this
12969                  * character only, which means that this character has to be in
12970                  * its own node and can't just be appended to the string in an
12971                  * existing node, so if there are already other characters in
12972                  * the node, close the node with just them, and set up to do
12973                  * this character again next time through, when it will be the
12974                  * only thing in its new node */
12975                 if ((next_is_quantifier = (   LIKELY(p < RExC_end)
12976                                            && UNLIKELY(ISMULT2(p))))
12977                     && LIKELY(len))
12978                 {
12979                     p = oldp;
12980                     goto loopdone;
12981                 }
12982
12983                 /* Ready to add 'ender' to the node */
12984
12985                 if (! FOLD) {  /* The simple case, just append the literal */
12986
12987                     /* In the sizing pass, we need only the size of the
12988                      * character we are appending, hence we can delay getting
12989                      * its representation until PASS2. */
12990                     if (SIZE_ONLY) {
12991                         if (UTF) {
12992                             const STRLEN unilen = UVCHR_SKIP(ender);
12993                             s += unilen;
12994
12995                             /* We have to subtract 1 just below (and again in
12996                              * the corresponding PASS2 code) because the loop
12997                              * increments <len> each time, as all but this path
12998                              * (and one other) through it add a single byte to
12999                              * the EXACTish node.  But these paths would change
13000                              * len to be the correct final value, so cancel out
13001                              * the increment that follows */
13002                             len += unilen - 1;
13003                         }
13004                         else {
13005                             s++;
13006                         }
13007                     } else { /* PASS2 */
13008                       not_fold_common:
13009                         if (UTF) {
13010                             U8 * new_s = uvchr_to_utf8((U8*)s, ender);
13011                             len += (char *) new_s - s - 1;
13012                             s = (char *) new_s;
13013                         }
13014                         else {
13015                             *(s++) = (char) ender;
13016                         }
13017                     }
13018                 }
13019                 else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) {
13020
13021                     /* Here are folding under /l, and the code point is
13022                      * problematic.  First, we know we can't simplify things */
13023                     maybe_exact = FALSE;
13024                     maybe_exactfu = FALSE;
13025
13026                     /* A problematic code point in this context means that its
13027                      * fold isn't known until runtime, so we can't fold it now.
13028                      * (The non-problematic code points are the above-Latin1
13029                      * ones that fold to also all above-Latin1.  Their folds
13030                      * don't vary no matter what the locale is.) But here we
13031                      * have characters whose fold depends on the locale.
13032                      * Unlike the non-folding case above, we have to keep track
13033                      * of these in the sizing pass, so that we can make sure we
13034                      * don't split too-long nodes in the middle of a potential
13035                      * multi-char fold.  And unlike the regular fold case
13036                      * handled in the else clauses below, we don't actually
13037                      * fold and don't have special cases to consider.  What we
13038                      * do for both passes is the PASS2 code for non-folding */
13039                     goto not_fold_common;
13040                 }
13041                 else /* A regular FOLD code point */
13042                     if (! (   UTF
13043 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
13044    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
13045                                       || UNICODE_DOT_DOT_VERSION > 0)
13046                             /* See comments for join_exact() as to why we fold
13047                              * this non-UTF at compile time */
13048                             || (   node_type == EXACTFU
13049                                 && ender == LATIN_SMALL_LETTER_SHARP_S)
13050 #endif
13051                 )) {
13052                     /* Here, are folding and are not UTF-8 encoded; therefore
13053                      * the character must be in the range 0-255, and is not /l
13054                      * (Not /l because we already handled these under /l in
13055                      * is_PROBLEMATIC_LOCALE_FOLD_cp) */
13056                     if (IS_IN_SOME_FOLD_L1(ender)) {
13057                         maybe_exact = FALSE;
13058
13059                         /* See if the character's fold differs between /d and
13060                          * /u.  This includes the multi-char fold SHARP S to
13061                          * 'ss' */
13062                         if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) {
13063                             RExC_seen_unfolded_sharp_s = 1;
13064                             maybe_exactfu = FALSE;
13065                         }
13066                         else if (maybe_exactfu
13067                             && (PL_fold[ender] != PL_fold_latin1[ender]
13068 #if    UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */   \
13069    || (UNICODE_MAJOR_VERSION == 3 && (   UNICODE_DOT_VERSION > 0)       \
13070                                       || UNICODE_DOT_DOT_VERSION > 0)
13071                                 || (   len > 0
13072                                     && isALPHA_FOLD_EQ(ender, 's')
13073                                     && isALPHA_FOLD_EQ(*(s-1), 's'))
13074 #endif
13075                         )) {
13076                             maybe_exactfu = FALSE;
13077                         }
13078                     }
13079
13080                     /* Even when folding, we store just the input character, as
13081                      * we have an array that finds its fold quickly */
13082                     *(s++) = (char) ender;
13083                 }
13084                 else {  /* FOLD, and UTF (or sharp s) */
13085                     /* Unlike the non-fold case, we do actually have to
13086                      * calculate the results here in pass 1.  This is for two
13087                      * reasons, the folded length may be longer than the
13088                      * unfolded, and we have to calculate how many EXACTish
13089                      * nodes it will take; and we may run out of room in a node
13090                      * in the middle of a potential multi-char fold, and have
13091                      * to back off accordingly.  */
13092
13093                     UV folded;
13094                     if (isASCII_uni(ender)) {
13095                         folded = toFOLD(ender);
13096                         *(s)++ = (U8) folded;
13097                     }
13098                     else {
13099                         STRLEN foldlen;
13100
13101                         folded = _to_uni_fold_flags(
13102                                      ender,
13103                                      (U8 *) s,
13104                                      &foldlen,
13105                                      FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED)
13106                                                         ? FOLD_FLAGS_NOMIX_ASCII
13107                                                         : 0));
13108                         s += foldlen;
13109
13110                         /* The loop increments <len> each time, as all but this
13111                          * path (and one other) through it add a single byte to
13112                          * the EXACTish node.  But this one has changed len to
13113                          * be the correct final value, so subtract one to
13114                          * cancel out the increment that follows */
13115                         len += foldlen - 1;
13116                     }
13117                     /* If this node only contains non-folding code points so
13118                      * far, see if this new one is also non-folding */
13119                     if (maybe_exact) {
13120                         if (folded != ender) {
13121                             maybe_exact = FALSE;
13122                         }
13123                         else {
13124                             /* Here the fold is the original; we have to check
13125                              * further to see if anything folds to it */
13126                             if (_invlist_contains_cp(PL_utf8_foldable,
13127                                                         ender))
13128                             {
13129                                 maybe_exact = FALSE;
13130                             }
13131                         }
13132                     }
13133                     ender = folded;
13134                 }
13135
13136                 if (next_is_quantifier) {
13137
13138                     /* Here, the next input is a quantifier, and to get here,
13139                      * the current character is the only one in the node.
13140                      * Also, here <len> doesn't include the final byte for this
13141                      * character */
13142                     len++;
13143                     goto loopdone;
13144                 }
13145
13146             } /* End of loop through literal characters */
13147
13148             /* Here we have either exhausted the input or ran out of room in
13149              * the node.  (If we encountered a character that can't be in the
13150              * node, transfer is made directly to <loopdone>, and so we
13151              * wouldn't have fallen off the end of the loop.)  In the latter
13152              * case, we artificially have to split the node into two, because
13153              * we just don't have enough space to hold everything.  This
13154              * creates a problem if the final character participates in a
13155              * multi-character fold in the non-final position, as a match that
13156              * should have occurred won't, due to the way nodes are matched,
13157              * and our artificial boundary.  So back off until we find a non-
13158              * problematic character -- one that isn't at the beginning or
13159              * middle of such a fold.  (Either it doesn't participate in any
13160              * folds, or appears only in the final position of all the folds it
13161              * does participate in.)  A better solution with far fewer false
13162              * positives, and that would fill the nodes more completely, would
13163              * be to actually have available all the multi-character folds to
13164              * test against, and to back-off only far enough to be sure that
13165              * this node isn't ending with a partial one.  <upper_parse> is set
13166              * further below (if we need to reparse the node) to include just
13167              * up through that final non-problematic character that this code
13168              * identifies, so when it is set to less than the full node, we can
13169              * skip the rest of this */
13170             if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
13171
13172                 const STRLEN full_len = len;
13173
13174                 assert(len >= MAX_NODE_STRING_SIZE);
13175
13176                 /* Here, <s> points to the final byte of the final character.
13177                  * Look backwards through the string until find a non-
13178                  * problematic character */
13179
13180                 if (! UTF) {
13181
13182                     /* This has no multi-char folds to non-UTF characters */
13183                     if (ASCII_FOLD_RESTRICTED) {
13184                         goto loopdone;
13185                     }
13186
13187                     while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { }
13188                     len = s - s0 + 1;
13189                 }
13190                 else {
13191                     if (!  PL_NonL1NonFinalFold) {
13192                         PL_NonL1NonFinalFold = _new_invlist_C_array(
13193                                         NonL1_Perl_Non_Final_Folds_invlist);
13194                     }
13195
13196                     /* Point to the first byte of the final character */
13197                     s = (char *) utf8_hop((U8 *) s, -1);
13198
13199                     while (s >= s0) {   /* Search backwards until find
13200                                            non-problematic char */
13201                         if (UTF8_IS_INVARIANT(*s)) {
13202
13203                             /* There are no ascii characters that participate
13204                              * in multi-char folds under /aa.  In EBCDIC, the
13205                              * non-ascii invariants are all control characters,
13206                              * so don't ever participate in any folds. */
13207                             if (ASCII_FOLD_RESTRICTED
13208                                 || ! IS_NON_FINAL_FOLD(*s))
13209                             {
13210                                 break;
13211                             }
13212                         }
13213                         else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
13214                             if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE(
13215                                                                   *s, *(s+1))))
13216                             {
13217                                 break;
13218                             }
13219                         }
13220                         else if (! _invlist_contains_cp(
13221                                         PL_NonL1NonFinalFold,
13222                                         valid_utf8_to_uvchr((U8 *) s, NULL)))
13223                         {
13224                             break;
13225                         }
13226
13227                         /* Here, the current character is problematic in that
13228                          * it does occur in the non-final position of some
13229                          * fold, so try the character before it, but have to
13230                          * special case the very first byte in the string, so
13231                          * we don't read outside the string */
13232                         s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
13233                     } /* End of loop backwards through the string */
13234
13235                     /* If there were only problematic characters in the string,
13236                      * <s> will point to before s0, in which case the length
13237                      * should be 0, otherwise include the length of the
13238                      * non-problematic character just found */
13239                     len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
13240                 }
13241
13242                 /* Here, have found the final character, if any, that is
13243                  * non-problematic as far as ending the node without splitting
13244                  * it across a potential multi-char fold.  <len> contains the
13245                  * number of bytes in the node up-to and including that
13246                  * character, or is 0 if there is no such character, meaning
13247                  * the whole node contains only problematic characters.  In
13248                  * this case, give up and just take the node as-is.  We can't
13249                  * do any better */
13250                 if (len == 0) {
13251                     len = full_len;
13252
13253                     /* If the node ends in an 's' we make sure it stays EXACTF,
13254                      * as if it turns into an EXACTFU, it could later get
13255                      * joined with another 's' that would then wrongly match
13256                      * the sharp s */
13257                     if (maybe_exactfu && isALPHA_FOLD_EQ(ender, 's'))
13258                     {
13259                         maybe_exactfu = FALSE;
13260                     }
13261                 } else {
13262
13263                     /* Here, the node does contain some characters that aren't
13264                      * problematic.  If one such is the final character in the
13265                      * node, we are done */
13266                     if (len == full_len) {
13267                         goto loopdone;
13268                     }
13269                     else if (len + ((UTF) ? UTF8SKIP(s) : 1) == full_len) {
13270
13271                         /* If the final character is problematic, but the
13272                          * penultimate is not, back-off that last character to
13273                          * later start a new node with it */
13274                         p = oldp;
13275                         goto loopdone;
13276                     }
13277
13278                     /* Here, the final non-problematic character is earlier
13279                      * in the input than the penultimate character.  What we do
13280                      * is reparse from the beginning, going up only as far as
13281                      * this final ok one, thus guaranteeing that the node ends
13282                      * in an acceptable character.  The reason we reparse is
13283                      * that we know how far in the character is, but we don't
13284                      * know how to correlate its position with the input parse.
13285                      * An alternate implementation would be to build that
13286                      * correlation as we go along during the original parse,
13287                      * but that would entail extra work for every node, whereas
13288                      * this code gets executed only when the string is too
13289                      * large for the node, and the final two characters are
13290                      * problematic, an infrequent occurrence.  Yet another
13291                      * possible strategy would be to save the tail of the
13292                      * string, and the next time regatom is called, initialize
13293                      * with that.  The problem with this is that unless you
13294                      * back off one more character, you won't be guaranteed
13295                      * regatom will get called again, unless regbranch,
13296                      * regpiece ... are also changed.  If you do back off that
13297                      * extra character, so that there is input guaranteed to
13298                      * force calling regatom, you can't handle the case where
13299                      * just the first character in the node is acceptable.  I
13300                      * (khw) decided to try this method which doesn't have that
13301                      * pitfall; if performance issues are found, we can do a
13302                      * combination of the current approach plus that one */
13303                     upper_parse = len;
13304                     len = 0;
13305                     s = s0;
13306                     goto reparse;
13307                 }
13308             }   /* End of verifying node ends with an appropriate char */
13309
13310           loopdone:   /* Jumped to when encounters something that shouldn't be
13311                          in the node */
13312
13313             /* I (khw) don't know if you can get here with zero length, but the
13314              * old code handled this situation by creating a zero-length EXACT
13315              * node.  Might as well be NOTHING instead */
13316             if (len == 0) {
13317                 OP(ret) = NOTHING;
13318             }
13319             else {
13320                 if (FOLD) {
13321                     /* If 'maybe_exact' is still set here, means there are no
13322                      * code points in the node that participate in folds;
13323                      * similarly for 'maybe_exactfu' and code points that match
13324                      * differently depending on UTF8ness of the target string
13325                      * (for /u), or depending on locale for /l */
13326                     if (maybe_exact) {
13327                         OP(ret) = (LOC)
13328                                   ? EXACTL
13329                                   : EXACT;
13330                     }
13331                     else if (maybe_exactfu) {
13332                         OP(ret) = (LOC)
13333                                   ? EXACTFLU8
13334                                   : EXACTFU;
13335                     }
13336                 }
13337                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, len, ender,
13338                                            FALSE /* Don't look to see if could
13339                                                     be turned into an EXACT
13340                                                     node, as we have already
13341                                                     computed that */
13342                                           );
13343             }
13344
13345             RExC_parse = p - 1;
13346             Set_Node_Cur_Length(ret, parse_start);
13347             RExC_parse = p;
13348             skip_to_be_ignored_text(pRExC_state, &RExC_parse,
13349                                     FALSE /* Don't force to /x */ );
13350             {
13351                 /* len is STRLEN which is unsigned, need to copy to signed */
13352                 IV iv = len;
13353                 if (iv < 0)
13354                     vFAIL("Internal disaster");
13355             }
13356
13357         } /* End of label 'defchar:' */
13358         break;
13359     } /* End of giant switch on input character */
13360
13361     return(ret);
13362 }
13363
13364
13365 STATIC void
13366 S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr)
13367 {
13368     /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'.  It
13369      * sets up the bitmap and any flags, removing those code points from the
13370      * inversion list, setting it to NULL should it become completely empty */
13371
13372     PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST;
13373     assert(PL_regkind[OP(node)] == ANYOF);
13374
13375     ANYOF_BITMAP_ZERO(node);
13376     if (*invlist_ptr) {
13377
13378         /* This gets set if we actually need to modify things */
13379         bool change_invlist = FALSE;
13380
13381         UV start, end;
13382
13383         /* Start looking through *invlist_ptr */
13384         invlist_iterinit(*invlist_ptr);
13385         while (invlist_iternext(*invlist_ptr, &start, &end)) {
13386             UV high;
13387             int i;
13388
13389             if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) {
13390                 ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP;
13391             }
13392
13393             /* Quit if are above what we should change */
13394             if (start >= NUM_ANYOF_CODE_POINTS) {
13395                 break;
13396             }
13397
13398             change_invlist = TRUE;
13399
13400             /* Set all the bits in the range, up to the max that we are doing */
13401             high = (end < NUM_ANYOF_CODE_POINTS - 1)
13402                    ? end
13403                    : NUM_ANYOF_CODE_POINTS - 1;
13404             for (i = start; i <= (int) high; i++) {
13405                 if (! ANYOF_BITMAP_TEST(node, i)) {
13406                     ANYOF_BITMAP_SET(node, i);
13407                 }
13408             }
13409         }
13410         invlist_iterfinish(*invlist_ptr);
13411
13412         /* Done with loop; remove any code points that are in the bitmap from
13413          * *invlist_ptr; similarly for code points above the bitmap if we have
13414          * a flag to match all of them anyways */
13415         if (change_invlist) {
13416             _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr);
13417         }
13418         if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
13419             _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr);
13420         }
13421
13422         /* If have completely emptied it, remove it completely */
13423         if (_invlist_len(*invlist_ptr) == 0) {
13424             SvREFCNT_dec_NN(*invlist_ptr);
13425             *invlist_ptr = NULL;
13426         }
13427     }
13428 }
13429
13430 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
13431    Character classes ([:foo:]) can also be negated ([:^foo:]).
13432    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
13433    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
13434    but trigger failures because they are currently unimplemented. */
13435
13436 #define POSIXCC_DONE(c)   ((c) == ':')
13437 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
13438 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
13439 #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';')
13440
13441 #define WARNING_PREFIX              "Assuming NOT a POSIX class since "
13442 #define NO_BLANKS_POSIX_WARNING     "no blanks are allowed in one"
13443 #define SEMI_COLON_POSIX_WARNING    "a semi-colon was found instead of a colon"
13444
13445 #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1)
13446
13447 /* 'posix_warnings' and 'warn_text' are names of variables in the following
13448  * routine. q.v. */
13449 #define ADD_POSIX_WARNING(p, text)  STMT_START {                            \
13450         if (posix_warnings && (   posix_warnings != (AV **) -1              \
13451                                || (PASS2 && ckWARN(WARN_REGEXP))))          \
13452         {                                                                   \
13453             if (! warn_text) warn_text = newAV();                           \
13454             av_push(warn_text, Perl_newSVpvf(aTHX_                          \
13455                                              WARNING_PREFIX                 \
13456                                              text                           \
13457                                              REPORT_LOCATION,               \
13458                                              REPORT_LOCATION_ARGS(p)));     \
13459         }                                                                   \
13460     } STMT_END
13461
13462 STATIC int
13463 S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state,
13464
13465     const char * const s,      /* Where the putative posix class begins.
13466                                   Normally, this is one past the '['.  This
13467                                   parameter exists so it can be somewhere
13468                                   besides RExC_parse. */
13469     char ** updated_parse_ptr, /* Where to set the updated parse pointer, or
13470                                   NULL */
13471     AV ** posix_warnings       /* Where to place any generated warnings, or -1
13472                                   if to output them, or NULL */
13473 )
13474 {
13475     /* This parses what the caller thinks may be one of the three POSIX
13476      * constructs:
13477      *  1) a character class, like [:blank:]
13478      *  2) a collating symbol, like [. .]
13479      *  3) an equivalence class, like [= =]
13480      * In the latter two cases, it croaks if it finds a syntactically legal
13481      * one, as these are not handled by Perl.
13482      *
13483      * The main purpose is to look for a POSIX character class.  It returns:
13484      *  a) the class number
13485      *      if it is a completely syntactically and semantically legal class.
13486      *      'updated_parse_ptr', if not NULL, is set to point to just after the
13487      *      closing ']' of the class
13488      *  b) OOB_NAMEDCLASS
13489      *      if it appears that one of the three POSIX constructs was meant, but
13490      *      its specification was somehow defective.  'updated_parse_ptr', if
13491      *      not NULL, is set to point to the character just after the end
13492      *      character of the class.  See below for handling of warnings.
13493      *  c) NOT_MEANT_TO_BE_A_POSIX_CLASS
13494      *      if it  doesn't appear that a POSIX construct was intended.
13495      *      'updated_parse_ptr' is not changed.  No warnings nor errors are
13496      *      raised.
13497      *
13498      * In b) there may be warnings and even errors generated.  What to do about
13499      * these is determined by the 'posix_warnings' parameter.  If it is NULL,
13500      * this call is treated as a check-only, scouting-out-the-territory call,
13501      * and no warnings nor errors are generated at all.  Otherwise, any errors
13502      * are raised if found.  If 'posix_warnings' is -1 (appropriately cast),
13503      * warnings are generated and displayed (in pass 2), just as they would be
13504      * for any other message of the same type from this file.  If it isn't NULL
13505      * and not -1, warnings aren't displayed, but instead an AV is generated
13506      * with all the warning messages (that aren't to be ignored) stored into
13507      * it, so that the caller can output them if it wants.  This is done in all
13508      * passes.  The reason for this is that the rest of the parsing is heavily
13509      * dependent on whether this routine found a valid posix class or not.  If
13510      * it did, the closing ']' is absorbed as part of the class.  If no class
13511      * or an invalid one is found, any ']' will be considered the terminator of
13512      * the outer bracketed character class, leading to very different results.
13513      * In particular, a '(?[ ])' construct will likely have a syntax error if
13514      * the class is parsed other than intended, and this will happen in pass1,
13515      * before the warnings would normally be output.  This mechanism allows the
13516      * caller to output those warnings in pass1 just before dieing, giving a
13517      * much better clue as to what is wrong.
13518      *
13519      * The reason for this function, and its complexity is that a bracketed
13520      * character class can contain just about anything.  But it's easy to
13521      * mistype the very specific posix class syntax but yielding a valid
13522      * regular bracketed class, so it silently gets compiled into something
13523      * quite unintended.
13524      *
13525      * The solution adopted here maintains backward compatibility except that
13526      * it adds a warning if it looks like a posix class was intended but
13527      * improperly specified.  The warning is not raised unless what is input
13528      * very closely resembles one of the 14 legal posix classes.  To do this,
13529      * it uses fuzzy parsing.  It calculates how many single-character edits it
13530      * would take to transform what was input into a legal posix class.  Only
13531      * if that number is quite small does it think that the intention was a
13532      * posix class.  Obviously these are heuristics, and there will be cases
13533      * where it errs on one side or another, and they can be tweaked as
13534      * experience informs.
13535      *
13536      * The syntax for a legal posix class is:
13537      *
13538      * qr/(?xa: \[ : \^? [:lower:]{4,6} : \] )/
13539      *
13540      * What this routine considers syntactically to be an intended posix class
13541      * is this (the comments indicate some restrictions that the pattern
13542      * doesn't show):
13543      *
13544      *  qr/(?x: \[?                         # The left bracket, possibly
13545      *                                      # omitted
13546      *          \h*                         # possibly followed by blanks
13547      *          (?: \^ \h* )?               # possibly a misplaced caret
13548      *          [:;]?                       # The opening class character,
13549      *                                      # possibly omitted.  A typo
13550      *                                      # semi-colon can also be used.
13551      *          \h*
13552      *          \^?                         # possibly a correctly placed
13553      *                                      # caret, but not if there was also
13554      *                                      # a misplaced one
13555      *          \h*
13556      *          .{3,15}                     # The class name.  If there are
13557      *                                      # deviations from the legal syntax,
13558      *                                      # its edit distance must be close
13559      *                                      # to a real class name in order
13560      *                                      # for it to be considered to be
13561      *                                      # an intended posix class.
13562      *          \h*
13563      *          [:punct:]?                  # The closing class character,
13564      *                                      # possibly omitted.  If not a colon
13565      *                                      # nor semi colon, the class name
13566      *                                      # must be even closer to a valid
13567      *                                      # one
13568      *          \h*
13569      *          \]?                         # The right bracket, possibly
13570      *                                      # omitted.
13571      *     )/
13572      *
13573      * In the above, \h must be ASCII-only.
13574      *
13575      * These are heuristics, and can be tweaked as field experience dictates.
13576      * There will be cases when someone didn't intend to specify a posix class
13577      * that this warns as being so.  The goal is to minimize these, while
13578      * maximizing the catching of things intended to be a posix class that
13579      * aren't parsed as such.
13580      */
13581
13582     const char* p             = s;
13583     const char * const e      = RExC_end;
13584     unsigned complement       = 0;      /* If to complement the class */
13585     bool found_problem        = FALSE;  /* Assume OK until proven otherwise */
13586     bool has_opening_bracket  = FALSE;
13587     bool has_opening_colon    = FALSE;
13588     int class_number          = OOB_NAMEDCLASS; /* Out-of-bounds until find
13589                                                    valid class */
13590     AV* warn_text             = NULL;   /* any warning messages */
13591     const char * possible_end = NULL;   /* used for a 2nd parse pass */
13592     const char* name_start;             /* ptr to class name first char */
13593
13594     /* If the number of single-character typos the input name is away from a
13595      * legal name is no more than this number, it is considered to have meant
13596      * the legal name */
13597     int max_distance          = 2;
13598
13599     /* to store the name.  The size determines the maximum length before we
13600      * decide that no posix class was intended.  Should be at least
13601      * sizeof("alphanumeric") */
13602     UV input_text[15];
13603
13604     PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX;
13605
13606     if (p >= e) {
13607         return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13608     }
13609
13610     if (*(p - 1) != '[') {
13611         ADD_POSIX_WARNING(p, "it doesn't start with a '['");
13612         found_problem = TRUE;
13613     }
13614     else {
13615         has_opening_bracket = TRUE;
13616     }
13617
13618     /* They could be confused and think you can put spaces between the
13619      * components */
13620     if (isBLANK(*p)) {
13621         found_problem = TRUE;
13622
13623         do {
13624             p++;
13625         } while (p < e && isBLANK(*p));
13626
13627         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
13628     }
13629
13630     /* For [. .] and [= =].  These are quite different internally from [: :],
13631      * so they are handled separately.  */
13632     if (POSIXCC_NOTYET(*p)) {
13633         const char open_char  = *p;
13634         const char * temp_ptr = p + 1;
13635         unsigned int len      = 0;
13636
13637         /* These two constructs are not handled by perl, and if we find a
13638          * syntactically valid one, we croak.  It looks like just about any
13639          * byte can be in them, but they are likely very short, like [.ch.] to
13640          * denote a ligature 'ch' single character.  If we find something that
13641          * started out to look like one of these constructs, but isn't, we
13642          * break so that it can be checked for being a class name with a typo
13643          * of '.' or '=' instead of a colon */
13644         while (temp_ptr < e) {
13645             len++;
13646
13647             /* qr/[[.].]]/, for example, is valid.  But otherwise we quit on an
13648              * unexpected ']'.  It is possible, it appears, for such a ']' to
13649              * be not in the final position, but that's so unlikely that that
13650              * case is not handled. */
13651             if (*temp_ptr == ']' && temp_ptr[1] != open_char) {
13652                 break;
13653             }
13654
13655             /* XXX this could be cut down, but this value is certainly large
13656              * enough */
13657             if (len > 10) {
13658                 break;
13659             }
13660
13661             if (*temp_ptr == open_char) {
13662                 temp_ptr++;
13663                 if (*temp_ptr == ']') {
13664                     temp_ptr++;
13665                     if (! found_problem && posix_warnings) {
13666                         RExC_parse = (char *) temp_ptr;
13667                         vFAIL3("POSIX syntax [%c %c] is reserved for future "
13668                                "extensions", open_char, open_char);
13669                     }
13670
13671                     /* Here, the syntax wasn't completely valid, or else the
13672                      * call is to check-only */
13673                     if (updated_parse_ptr) {
13674                         *updated_parse_ptr = (char *) temp_ptr;
13675                     }
13676
13677                     return OOB_NAMEDCLASS;
13678                 }
13679             }
13680             else if (*temp_ptr == '\\') {
13681
13682                 /* A backslash is treate as like any other character, unless it
13683                  * precedes a comment starter.  XXX multiple backslashes in a
13684                  * row are not handled specially here, nor would they ever
13685                  * likely to be handled specially in one of these constructs */
13686                 if (temp_ptr[1] == '#' && (RExC_flags & RXf_PMf_EXTENDED)) {
13687                     temp_ptr++;
13688                 }
13689                 temp_ptr++;
13690             }
13691             else if (*temp_ptr == '#' && (RExC_flags & RXf_PMf_EXTENDED)) {
13692                 break;  /* Under no circumstances can we look at the interior
13693                            of a comment */
13694             }
13695             else if (*temp_ptr == '\n') {   /* And we don't allow newlines
13696                                                either as it's extremely
13697                                                unlikely that one could be in an
13698                                                intended class */
13699                 break;
13700             }
13701             else if (UTF && ! UTF8_IS_INVARIANT(*temp_ptr)) {
13702                 /* XXX Since perl will never handle multi-byte locales, except
13703                  * for UTF-8, we could break if we found a byte above latin1,
13704                  * but perhaps the person intended to use one. */
13705                 temp_ptr += UTF8SKIP(temp_ptr);
13706             }
13707             else {
13708                 temp_ptr++;
13709             }
13710         }
13711     }
13712
13713     /* Here, we think there is a possibility that a [: :] class was meant, and
13714      * we have the first real character.  It could be they think the '^' comes
13715      * first */
13716     if (*p == '^') {
13717         found_problem = TRUE;
13718         ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon");
13719         complement = 1;
13720         p++;
13721
13722         if (isBLANK(*p)) {
13723             found_problem = TRUE;
13724
13725             do {
13726                 p++;
13727             } while (p < e && isBLANK(*p));
13728
13729             ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
13730         }
13731     }
13732
13733     /* But the first character should be a colon, which they could have easily
13734      * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to
13735      * distinguish from a colon, so treat that as a colon).  */
13736     if (*p == ':') {
13737         p++;
13738         has_opening_colon = TRUE;
13739     }
13740     else if (*p == ';') {
13741         found_problem = TRUE;
13742         p++;
13743         ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
13744         has_opening_colon = TRUE;
13745     }
13746     else {
13747         found_problem = TRUE;
13748         ADD_POSIX_WARNING(p, "there must be a starting ':'");
13749
13750         /* Consider an initial punctuation (not one of the recognized ones) to
13751          * be a left terminator */
13752         if (*p != '^' && *p != ']' && isPUNCT(*p)) {
13753             p++;
13754         }
13755     }
13756
13757     /* They may think that you can put spaces between the components */
13758     if (isBLANK(*p)) {
13759         found_problem = TRUE;
13760
13761         do {
13762             p++;
13763         } while (p < e && isBLANK(*p));
13764
13765         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
13766     }
13767
13768     if (*p == '^') {
13769
13770         /* We consider something like [^:^alnum:]] to not have been intended to
13771          * be a posix class, but XXX maybe we should */
13772         if (complement) {
13773             return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13774         }
13775
13776         complement = 1;
13777         p++;
13778     }
13779
13780     /* Again, they may think that you can put spaces between the components */
13781     if (isBLANK(*p)) {
13782         found_problem = TRUE;
13783
13784         do {
13785             p++;
13786         } while (p < e && isBLANK(*p));
13787
13788         ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
13789     }
13790
13791     if (*p == ']') {
13792
13793         /* XXX This ']' may be a typo, and something else was meant.  But
13794          * treating it as such creates enough complications, that that
13795          * possibility isn't currently considered here.  So we assume that the
13796          * ']' is what is intended, and if we've already found an initial '[',
13797          * this leaves this construct looking like [:] or [:^], which almost
13798          * certainly weren't intended to be posix classes */
13799         if (has_opening_bracket) {
13800             return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13801         }
13802
13803         /* But this function can be called when we parse the colon for
13804          * something like qr/[alpha:]]/, so we back up to look for the
13805          * beginning */
13806         p--;
13807
13808         if (*p == ';') {
13809             found_problem = TRUE;
13810             ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
13811         }
13812         else if (*p != ':') {
13813
13814             /* XXX We are currently very restrictive here, so this code doesn't
13815              * consider the possibility that, say, /[alpha.]]/ was intended to
13816              * be a posix class. */
13817             return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13818         }
13819
13820         /* Here we have something like 'foo:]'.  There was no initial colon,
13821          * and we back up over 'foo.  XXX Unlike the going forward case, we
13822          * don't handle typos of non-word chars in the middle */
13823         has_opening_colon = FALSE;
13824         p--;
13825
13826         while (p > RExC_start && isWORDCHAR(*p)) {
13827             p--;
13828         }
13829         p++;
13830
13831         /* Here, we have positioned ourselves to where we think the first
13832          * character in the potential class is */
13833     }
13834
13835     /* Now the interior really starts.  There are certain key characters that
13836      * can end the interior, or these could just be typos.  To catch both
13837      * cases, we may have to do two passes.  In the first pass, we keep on
13838      * going unless we come to a sequence that matches
13839      *      qr/ [[:punct:]] [[:blank:]]* \] /xa
13840      * This means it takes a sequence to end the pass, so two typos in a row if
13841      * that wasn't what was intended.  If the class is perfectly formed, just
13842      * this one pass is needed.  We also stop if there are too many characters
13843      * being accumulated, but this number is deliberately set higher than any
13844      * real class.  It is set high enough so that someone who thinks that
13845      * 'alphanumeric' is a correct name would get warned that it wasn't.
13846      * While doing the pass, we keep track of where the key characters were in
13847      * it.  If we don't find an end to the class, and one of the key characters
13848      * was found, we redo the pass, but stop when we get to that character.
13849      * Thus the key character was considered a typo in the first pass, but a
13850      * terminator in the second.  If two key characters are found, we stop at
13851      * the second one in the first pass.  Again this can miss two typos, but
13852      * catches a single one
13853      *
13854      * In the first pass, 'possible_end' starts as NULL, and then gets set to
13855      * point to the first key character.  For the second pass, it starts as -1.
13856      * */
13857
13858     name_start = p;
13859   parse_name:
13860     {
13861         bool has_blank               = FALSE;
13862         bool has_upper               = FALSE;
13863         bool has_terminating_colon   = FALSE;
13864         bool has_terminating_bracket = FALSE;
13865         bool has_semi_colon          = FALSE;
13866         unsigned int name_len        = 0;
13867         int punct_count              = 0;
13868
13869         while (p < e) {
13870
13871             /* Squeeze out blanks when looking up the class name below */
13872             if (isBLANK(*p) ) {
13873                 has_blank = TRUE;
13874                 found_problem = TRUE;
13875                 p++;
13876                 continue;
13877             }
13878
13879             /* The name will end with a punctuation */
13880             if (isPUNCT(*p)) {
13881                 const char * peek = p + 1;
13882
13883                 /* Treat any non-']' punctuation followed by a ']' (possibly
13884                  * with intervening blanks) as trying to terminate the class.
13885                  * ']]' is very likely to mean a class was intended (but
13886                  * missing the colon), but the warning message that gets
13887                  * generated shows the error position better if we exit the
13888                  * loop at the bottom (eventually), so skip it here. */
13889                 if (*p != ']') {
13890                     if (peek < e && isBLANK(*peek)) {
13891                         has_blank = TRUE;
13892                         found_problem = TRUE;
13893                         do {
13894                             peek++;
13895                         } while (peek < e && isBLANK(*peek));
13896                     }
13897
13898                     if (peek < e && *peek == ']') {
13899                         has_terminating_bracket = TRUE;
13900                         if (*p == ':') {
13901                             has_terminating_colon = TRUE;
13902                         }
13903                         else if (*p == ';') {
13904                             has_semi_colon = TRUE;
13905                             has_terminating_colon = TRUE;
13906                         }
13907                         else {
13908                             found_problem = TRUE;
13909                         }
13910                         p = peek + 1;
13911                         goto try_posix;
13912                     }
13913                 }
13914
13915                 /* Here we have punctuation we thought didn't end the class.
13916                  * Keep track of the position of the key characters that are
13917                  * more likely to have been class-enders */
13918                 if (*p == ']' || *p == '[' || *p == ':' || *p == ';') {
13919
13920                     /* Allow just one such possible class-ender not actually
13921                      * ending the class. */
13922                     if (possible_end) {
13923                         break;
13924                     }
13925                     possible_end = p;
13926                 }
13927
13928                 /* If we have too many punctuation characters, no use in
13929                  * keeping going */
13930                 if (++punct_count > max_distance) {
13931                     break;
13932                 }
13933
13934                 /* Treat the punctuation as a typo. */
13935                 input_text[name_len++] = *p;
13936                 p++;
13937             }
13938             else if (isUPPER(*p)) { /* Use lowercase for lookup */
13939                 input_text[name_len++] = toLOWER(*p);
13940                 has_upper = TRUE;
13941                 found_problem = TRUE;
13942                 p++;
13943             } else if (! UTF || UTF8_IS_INVARIANT(*p)) {
13944                 input_text[name_len++] = *p;
13945                 p++;
13946             }
13947             else {
13948                 input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL);
13949                 p+= UTF8SKIP(p);
13950             }
13951
13952             /* The declaration of 'input_text' is how long we allow a potential
13953              * class name to be, before saying they didn't mean a class name at
13954              * all */
13955             if (name_len >= C_ARRAY_LENGTH(input_text)) {
13956                 break;
13957             }
13958         }
13959
13960         /* We get to here when the possible class name hasn't been properly
13961          * terminated before:
13962          *   1) we ran off the end of the pattern; or
13963          *   2) found two characters, each of which might have been intended to
13964          *      be the name's terminator
13965          *   3) found so many punctuation characters in the purported name,
13966          *      that the edit distance to a valid one is exceeded
13967          *   4) we decided it was more characters than anyone could have
13968          *      intended to be one. */
13969
13970         found_problem = TRUE;
13971
13972         /* In the final two cases, we know that looking up what we've
13973          * accumulated won't lead to a match, even a fuzzy one. */
13974         if (   name_len >= C_ARRAY_LENGTH(input_text)
13975             || punct_count > max_distance)
13976         {
13977             /* If there was an intermediate key character that could have been
13978              * an intended end, redo the parse, but stop there */
13979             if (possible_end && possible_end != (char *) -1) {
13980                 possible_end = (char *) -1; /* Special signal value to say
13981                                                we've done a first pass */
13982                 p = name_start;
13983                 goto parse_name;
13984             }
13985
13986             /* Otherwise, it can't have meant to have been a class */
13987             return NOT_MEANT_TO_BE_A_POSIX_CLASS;
13988         }
13989
13990         /* If we ran off the end, and the final character was a punctuation
13991          * one, back up one, to look at that final one just below.  Later, we
13992          * will restore the parse pointer if appropriate */
13993         if (name_len && p == e && isPUNCT(*(p-1))) {
13994             p--;
13995             name_len--;
13996         }
13997
13998         if (p < e && isPUNCT(*p)) {
13999             if (*p == ']') {
14000                 has_terminating_bracket = TRUE;
14001
14002                 /* If this is a 2nd ']', and the first one is just below this
14003                  * one, consider that to be the real terminator.  This gives a
14004                  * uniform and better positioning for the warning message  */
14005                 if (   possible_end
14006                     && possible_end != (char *) -1
14007                     && *possible_end == ']'
14008                     && name_len && input_text[name_len - 1] == ']')
14009                 {
14010                     name_len--;
14011                     p = possible_end;
14012
14013                     /* And this is actually equivalent to having done the 2nd
14014                      * pass now, so set it to not try again */
14015                     possible_end = (char *) -1;
14016                 }
14017             }
14018             else {
14019                 if (*p == ':') {
14020                     has_terminating_colon = TRUE;
14021                 }
14022                 else if (*p == ';') {
14023                     has_semi_colon = TRUE;
14024                     has_terminating_colon = TRUE;
14025                 }
14026                 p++;
14027             }
14028         }
14029
14030     try_posix:
14031
14032         /* Here, we have a class name to look up.  We can short circuit the
14033          * stuff below for short names that can't possibly be meant to be a
14034          * class name.  (We can do this on the first pass, as any second pass
14035          * will yield an even shorter name) */
14036         if (name_len < 3) {
14037             return NOT_MEANT_TO_BE_A_POSIX_CLASS;
14038         }
14039
14040         /* Find which class it is.  Initially switch on the length of the name.
14041          * */
14042         switch (name_len) {
14043             case 4:
14044                 if (memEQ(name_start, "word", 4)) {
14045                     /* this is not POSIX, this is the Perl \w */
14046                     class_number = ANYOF_WORDCHAR;
14047                 }
14048                 break;
14049             case 5:
14050                 /* Names all of length 5: alnum alpha ascii blank cntrl digit
14051                  *                        graph lower print punct space upper
14052                  * Offset 4 gives the best switch position.  */
14053                 switch (name_start[4]) {
14054                     case 'a':
14055                         if (memEQ(name_start, "alph", 4)) /* alpha */
14056                             class_number = ANYOF_ALPHA;
14057                         break;
14058                     case 'e':
14059                         if (memEQ(name_start, "spac", 4)) /* space */
14060                             class_number = ANYOF_SPACE;
14061                         break;
14062                     case 'h':
14063                         if (memEQ(name_start, "grap", 4)) /* graph */
14064                             class_number = ANYOF_GRAPH;
14065                         break;
14066                     case 'i':
14067                         if (memEQ(name_start, "asci", 4)) /* ascii */
14068                             class_number = ANYOF_ASCII;
14069                         break;
14070                     case 'k':
14071                         if (memEQ(name_start, "blan", 4)) /* blank */
14072                             class_number = ANYOF_BLANK;
14073                         break;
14074                     case 'l':
14075                         if (memEQ(name_start, "cntr", 4)) /* cntrl */
14076                             class_number = ANYOF_CNTRL;
14077                         break;
14078                     case 'm':
14079                         if (memEQ(name_start, "alnu", 4)) /* alnum */
14080                             class_number = ANYOF_ALPHANUMERIC;
14081                         break;
14082                     case 'r':
14083                         if (memEQ(name_start, "lowe", 4)) /* lower */
14084                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
14085                         else if (memEQ(name_start, "uppe", 4)) /* upper */
14086                             class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
14087                         break;
14088                     case 't':
14089                         if (memEQ(name_start, "digi", 4)) /* digit */
14090                             class_number = ANYOF_DIGIT;
14091                         else if (memEQ(name_start, "prin", 4)) /* print */
14092                             class_number = ANYOF_PRINT;
14093                         else if (memEQ(name_start, "punc", 4)) /* punct */
14094                             class_number = ANYOF_PUNCT;
14095                         break;
14096                 }
14097                 break;
14098             case 6:
14099                 if (memEQ(name_start, "xdigit", 6))
14100                     class_number = ANYOF_XDIGIT;
14101                 break;
14102         }
14103
14104         /* If the name exactly matches a posix class name the class number will
14105          * here be set to it, and the input almost certainly was meant to be a
14106          * posix class, so we can skip further checking.  If instead the syntax
14107          * is exactly correct, but the name isn't one of the legal ones, we
14108          * will return that as an error below.  But if neither of these apply,
14109          * it could be that no posix class was intended at all, or that one
14110          * was, but there was a typo.  We tease these apart by doing fuzzy
14111          * matching on the name */
14112         if (class_number == OOB_NAMEDCLASS && found_problem) {
14113             const UV posix_names[][6] = {
14114                                                 { 'a', 'l', 'n', 'u', 'm' },
14115                                                 { 'a', 'l', 'p', 'h', 'a' },
14116                                                 { 'a', 's', 'c', 'i', 'i' },
14117                                                 { 'b', 'l', 'a', 'n', 'k' },
14118                                                 { 'c', 'n', 't', 'r', 'l' },
14119                                                 { 'd', 'i', 'g', 'i', 't' },
14120                                                 { 'g', 'r', 'a', 'p', 'h' },
14121                                                 { 'l', 'o', 'w', 'e', 'r' },
14122                                                 { 'p', 'r', 'i', 'n', 't' },
14123                                                 { 'p', 'u', 'n', 'c', 't' },
14124                                                 { 's', 'p', 'a', 'c', 'e' },
14125                                                 { 'u', 'p', 'p', 'e', 'r' },
14126                                                 { 'w', 'o', 'r', 'd' },
14127                                                 { 'x', 'd', 'i', 'g', 'i', 't' }
14128                                             };
14129             /* The names of the above all have added NULs to make them the same
14130              * size, so we need to also have the real lengths */
14131             const UV posix_name_lengths[] = {
14132                                                 sizeof("alnum") - 1,
14133                                                 sizeof("alpha") - 1,
14134                                                 sizeof("ascii") - 1,
14135                                                 sizeof("blank") - 1,
14136                                                 sizeof("cntrl") - 1,
14137                                                 sizeof("digit") - 1,
14138                                                 sizeof("graph") - 1,
14139                                                 sizeof("lower") - 1,
14140                                                 sizeof("print") - 1,
14141                                                 sizeof("punct") - 1,
14142                                                 sizeof("space") - 1,
14143                                                 sizeof("upper") - 1,
14144                                                 sizeof("word")  - 1,
14145                                                 sizeof("xdigit")- 1
14146                                             };
14147             unsigned int i;
14148             int temp_max = max_distance;    /* Use a temporary, so if we
14149                                                reparse, we haven't changed the
14150                                                outer one */
14151
14152             /* Use a smaller max edit distance if we are missing one of the
14153              * delimiters */
14154             if (   has_opening_bracket + has_opening_colon < 2
14155                 || has_terminating_bracket + has_terminating_colon < 2)
14156             {
14157                 temp_max--;
14158             }
14159
14160             /* See if the input name is close to a legal one */
14161             for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) {
14162
14163                 /* Short circuit call if the lengths are too far apart to be
14164                  * able to match */
14165                 if (abs( (int) (name_len - posix_name_lengths[i]))
14166                     > temp_max)
14167                 {
14168                     continue;
14169                 }
14170
14171                 if (edit_distance(input_text,
14172                                   posix_names[i],
14173                                   name_len,
14174                                   posix_name_lengths[i],
14175                                   temp_max
14176                                  )
14177                     > -1)
14178                 { /* If it is close, it probably was intended to be a class */
14179                     goto probably_meant_to_be;
14180                 }
14181             }
14182
14183             /* Here the input name is not close enough to a valid class name
14184              * for us to consider it to be intended to be a posix class.  If
14185              * we haven't already done so, and the parse found a character that
14186              * could have been terminators for the name, but which we absorbed
14187              * as typos during the first pass, repeat the parse, signalling it
14188              * to stop at that character */
14189             if (possible_end && possible_end != (char *) -1) {
14190                 possible_end = (char *) -1;
14191                 p = name_start;
14192                 goto parse_name;
14193             }
14194
14195             /* Here neither pass found a close-enough class name */
14196             return NOT_MEANT_TO_BE_A_POSIX_CLASS;
14197         }
14198
14199     probably_meant_to_be:
14200
14201         /* Here we think that a posix specification was intended.  Update any
14202          * parse pointer */
14203         if (updated_parse_ptr) {
14204             *updated_parse_ptr = (char *) p;
14205         }
14206
14207         /* If a posix class name was intended but incorrectly specified, we
14208          * output or return the warnings */
14209         if (found_problem) {
14210
14211             /* We set flags for these issues in the parse loop above instead of
14212              * adding them to the list of warnings, because we can parse it
14213              * twice, and we only want one warning instance */
14214             if (has_upper) {
14215                 ADD_POSIX_WARNING(p, "the name must be all lowercase letters");
14216             }
14217             if (has_blank) {
14218                 ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING);
14219             }
14220             if (has_semi_colon) {
14221                 ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING);
14222             }
14223             else if (! has_terminating_colon) {
14224                 ADD_POSIX_WARNING(p, "there is no terminating ':'");
14225             }
14226             if (! has_terminating_bracket) {
14227                 ADD_POSIX_WARNING(p, "there is no terminating ']'");
14228             }
14229
14230             if (warn_text) {
14231                 if (posix_warnings != (AV **) -1) {
14232                     *posix_warnings = warn_text;
14233                 }
14234                 else {
14235                     SV * msg;
14236                     while ((msg = av_shift(warn_text)) != &PL_sv_undef) {
14237                         Perl_warner(aTHX_ packWARN(WARN_REGEXP),
14238                                     "%s", SvPVX(msg));
14239                         SvREFCNT_dec_NN(msg);
14240                     }
14241                     SvREFCNT_dec_NN(warn_text);
14242                 }
14243             }
14244         }
14245         else if (class_number != OOB_NAMEDCLASS) {
14246             /* If it is a known class, return the class.  The class number
14247              * #defines are structured so each complement is +1 to the normal
14248              * one */
14249             return class_number + complement;
14250         }
14251         else if (posix_warnings) {
14252
14253             /* Here, it is an unrecognized class.  This is an error (unless the
14254             * call is to check only, which we've already handled above) */
14255             const char * const complement_string = (complement)
14256                                                    ? "^"
14257                                                    : "";
14258             RExC_parse = (char *) p;
14259             vFAIL3utf8f("POSIX class [:%s%"UTF8f":] unknown",
14260                         complement_string,
14261                         UTF8fARG(UTF, RExC_parse - name_start - 2, name_start));
14262         }
14263     }
14264
14265     return OOB_NAMEDCLASS;
14266 }
14267 #undef ADD_POSIX_WARNING
14268
14269 STATIC unsigned  int
14270 S_regex_set_precedence(const U8 my_operator) {
14271
14272     /* Returns the precedence in the (?[...]) construct of the input operator,
14273      * specified by its character representation.  The precedence follows
14274      * general Perl rules, but it extends this so that ')' and ']' have (low)
14275      * precedence even though they aren't really operators */
14276
14277     switch (my_operator) {
14278         case '!':
14279             return 5;
14280         case '&':
14281             return 4;
14282         case '^':
14283         case '|':
14284         case '+':
14285         case '-':
14286             return 3;
14287         case ')':
14288             return 2;
14289         case ']':
14290             return 1;
14291     }
14292
14293     NOT_REACHED; /* NOTREACHED */
14294     return 0;   /* Silence compiler warning */
14295 }
14296
14297 STATIC regnode *
14298 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist,
14299                     I32 *flagp, U32 depth,
14300                     char * const oregcomp_parse)
14301 {
14302     /* Handle the (?[...]) construct to do set operations */
14303
14304     U8 curchar;                     /* Current character being parsed */
14305     UV start, end;                  /* End points of code point ranges */
14306     SV* final = NULL;               /* The end result inversion list */
14307     SV* result_string;              /* 'final' stringified */
14308     AV* stack;                      /* stack of operators and operands not yet
14309                                        resolved */
14310     AV* fence_stack = NULL;         /* A stack containing the positions in
14311                                        'stack' of where the undealt-with left
14312                                        parens would be if they were actually
14313                                        put there */
14314     IV fence = 0;                   /* Position of where most recent undealt-
14315                                        with left paren in stack is; -1 if none.
14316                                      */
14317     STRLEN len;                     /* Temporary */
14318     regnode* node;                  /* Temporary, and final regnode returned by
14319                                        this function */
14320     const bool save_fold = FOLD;    /* Temporary */
14321     char *save_end, *save_parse;    /* Temporaries */
14322     const bool in_locale = LOC;     /* we turn off /l during processing */
14323     AV* posix_warnings = NULL;
14324
14325     GET_RE_DEBUG_FLAGS_DECL;
14326
14327     PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
14328
14329     if (in_locale) {
14330         set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET);
14331     }
14332
14333     REQUIRE_UNI_RULES(flagp, NULL);   /* The use of this operator implies /u.
14334                                          This is required so that the compile
14335                                          time values are valid in all runtime
14336                                          cases */
14337
14338     /* This will return only an ANYOF regnode, or (unlikely) something smaller
14339      * (such as EXACT).  Thus we can skip most everything if just sizing.  We
14340      * call regclass to handle '[]' so as to not have to reinvent its parsing
14341      * rules here (throwing away the size it computes each time).  And, we exit
14342      * upon an unescaped ']' that isn't one ending a regclass.  To do both
14343      * these things, we need to realize that something preceded by a backslash
14344      * is escaped, so we have to keep track of backslashes */
14345     if (SIZE_ONLY) {
14346         UV depth = 0; /* how many nested (?[...]) constructs */
14347
14348         while (RExC_parse < RExC_end) {
14349             SV* current = NULL;
14350
14351             skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14352                                     TRUE /* Force /x */ );
14353
14354             switch (*RExC_parse) {
14355                 case '?':
14356                     if (RExC_parse[1] == '[') depth++, RExC_parse++;
14357                     /* FALLTHROUGH */
14358                 default:
14359                     break;
14360                 case '\\':
14361                     /* Skip past this, so the next character gets skipped, after
14362                      * the switch */
14363                     RExC_parse++;
14364                     if (*RExC_parse == 'c') {
14365                             /* Skip the \cX notation for control characters */
14366                             RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
14367                     }
14368                     break;
14369
14370                 case '[':
14371                 {
14372                     /* See if this is a [:posix:] class. */
14373                     bool is_posix_class = (OOB_NAMEDCLASS
14374                                            < handle_possible_posix(pRExC_state,
14375                                                                 RExC_parse + 1,
14376                                                                 NULL,
14377                                                                 NULL));
14378                     /* If it is a posix class, leave the parse pointer at the
14379                      * '[' to fool regclass() into thinking it is part of a
14380                      * '[[:posix:]]'. */
14381                     if (! is_posix_class) {
14382                         RExC_parse++;
14383                     }
14384
14385                     /* regclass() can only return RESTART_PASS1 and NEED_UTF8
14386                      * if multi-char folds are allowed.  */
14387                     if (!regclass(pRExC_state, flagp,depth+1,
14388                                   is_posix_class, /* parse the whole char
14389                                                      class only if not a
14390                                                      posix class */
14391                                   FALSE, /* don't allow multi-char folds */
14392                                   TRUE, /* silence non-portable warnings. */
14393                                   TRUE, /* strict */
14394                                   FALSE, /* Require return to be an ANYOF */
14395                                   &current,
14396                                   &posix_warnings
14397                                  ))
14398                         FAIL2("panic: regclass returned NULL to handle_sets, "
14399                               "flags=%#"UVxf"", (UV) *flagp);
14400
14401                     /* function call leaves parse pointing to the ']', except
14402                      * if we faked it */
14403                     if (is_posix_class) {
14404                         RExC_parse--;
14405                     }
14406
14407                     SvREFCNT_dec(current);   /* In case it returned something */
14408                     break;
14409                 }
14410
14411                 case ']':
14412                     if (depth--) break;
14413                     RExC_parse++;
14414                     if (*RExC_parse == ')') {
14415                         node = reganode(pRExC_state, ANYOF, 0);
14416                         RExC_size += ANYOF_SKIP;
14417                         nextchar(pRExC_state);
14418                         Set_Node_Length(node,
14419                                 RExC_parse - oregcomp_parse + 1); /* MJD */
14420                         if (in_locale) {
14421                             set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
14422                         }
14423
14424                         return node;
14425                     }
14426                     goto no_close;
14427             }
14428
14429             RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1;
14430         }
14431
14432       no_close:
14433         /* We output the messages even if warnings are off, because we'll fail
14434          * the very next thing, and these give a likely diagnosis for that */
14435         if (posix_warnings) {
14436             SV * msg;
14437             while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) {
14438                 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg));
14439                 SvREFCNT_dec_NN(msg);
14440             }
14441             SvREFCNT_dec_NN(posix_warnings);
14442         }
14443
14444         FAIL("Syntax error in (?[...])");
14445     }
14446
14447     /* Pass 2 only after this. */
14448     Perl_ck_warner_d(aTHX_
14449         packWARN(WARN_EXPERIMENTAL__REGEX_SETS),
14450         "The regex_sets feature is experimental" REPORT_LOCATION,
14451         REPORT_LOCATION_ARGS(RExC_parse));
14452
14453     /* Everything in this construct is a metacharacter.  Operands begin with
14454      * either a '\' (for an escape sequence), or a '[' for a bracketed
14455      * character class.  Any other character should be an operator, or
14456      * parenthesis for grouping.  Both types of operands are handled by calling
14457      * regclass() to parse them.  It is called with a parameter to indicate to
14458      * return the computed inversion list.  The parsing here is implemented via
14459      * a stack.  Each entry on the stack is a single character representing one
14460      * of the operators; or else a pointer to an operand inversion list. */
14461
14462 #define IS_OPERATOR(a) SvIOK(a)
14463 #define IS_OPERAND(a)  (! IS_OPERATOR(a))
14464
14465     /* The stack is kept in Łukasiewicz order.  (That's pronounced similar
14466      * to luke-a-shave-itch (or -itz), but people who didn't want to bother
14467      * with pronouncing it called it Reverse Polish instead, but now that YOU
14468      * know how to pronounce it you can use the correct term, thus giving due
14469      * credit to the person who invented it, and impressing your geek friends.
14470      * Wikipedia says that the pronounciation of "Ł" has been changing so that
14471      * it is now more like an English initial W (as in wonk) than an L.)
14472      *
14473      * This means that, for example, 'a | b & c' is stored on the stack as
14474      *
14475      * c  [4]
14476      * b  [3]
14477      * &  [2]
14478      * a  [1]
14479      * |  [0]
14480      *
14481      * where the numbers in brackets give the stack [array] element number.
14482      * In this implementation, parentheses are not stored on the stack.
14483      * Instead a '(' creates a "fence" so that the part of the stack below the
14484      * fence is invisible except to the corresponding ')' (this allows us to
14485      * replace testing for parens, by using instead subtraction of the fence
14486      * position).  As new operands are processed they are pushed onto the stack
14487      * (except as noted in the next paragraph).  New operators of higher
14488      * precedence than the current final one are inserted on the stack before
14489      * the lhs operand (so that when the rhs is pushed next, everything will be
14490      * in the correct positions shown above.  When an operator of equal or
14491      * lower precedence is encountered in parsing, all the stacked operations
14492      * of equal or higher precedence are evaluated, leaving the result as the
14493      * top entry on the stack.  This makes higher precedence operations
14494      * evaluate before lower precedence ones, and causes operations of equal
14495      * precedence to left associate.
14496      *
14497      * The only unary operator '!' is immediately pushed onto the stack when
14498      * encountered.  When an operand is encountered, if the top of the stack is
14499      * a '!", the complement is immediately performed, and the '!' popped.  The
14500      * resulting value is treated as a new operand, and the logic in the
14501      * previous paragraph is executed.  Thus in the expression
14502      *      [a] + ! [b]
14503      * the stack looks like
14504      *
14505      * !
14506      * a
14507      * +
14508      *
14509      * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack
14510      * becomes
14511      *
14512      * !b
14513      * a
14514      * +
14515      *
14516      * A ')' is treated as an operator with lower precedence than all the
14517      * aforementioned ones, which causes all operations on the stack above the
14518      * corresponding '(' to be evaluated down to a single resultant operand.
14519      * Then the fence for the '(' is removed, and the operand goes through the
14520      * algorithm above, without the fence.
14521      *
14522      * A separate stack is kept of the fence positions, so that the position of
14523      * the latest so-far unbalanced '(' is at the top of it.
14524      *
14525      * The ']' ending the construct is treated as the lowest operator of all,
14526      * so that everything gets evaluated down to a single operand, which is the
14527      * result */
14528
14529     sv_2mortal((SV *)(stack = newAV()));
14530     sv_2mortal((SV *)(fence_stack = newAV()));
14531
14532     while (RExC_parse < RExC_end) {
14533         I32 top_index;              /* Index of top-most element in 'stack' */
14534         SV** top_ptr;               /* Pointer to top 'stack' element */
14535         SV* current = NULL;         /* To contain the current inversion list
14536                                        operand */
14537         SV* only_to_avoid_leaks;
14538
14539         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
14540                                 TRUE /* Force /x */ );
14541         if (RExC_parse >= RExC_end) {
14542             Perl_croak(aTHX_ "panic: Read past end of '(?[ ])'");
14543         }
14544
14545         curchar = UCHARAT(RExC_parse);
14546
14547 redo_curchar:
14548
14549         top_index = av_tindex(stack);
14550
14551         switch (curchar) {
14552             SV** stacked_ptr;       /* Ptr to something already on 'stack' */
14553             char stacked_operator;  /* The topmost operator on the 'stack'. */
14554             SV* lhs;                /* Operand to the left of the operator */
14555             SV* rhs;                /* Operand to the right of the operator */
14556             SV* fence_ptr;          /* Pointer to top element of the fence
14557                                        stack */
14558
14559             case '(':
14560
14561                 if (   RExC_parse < RExC_end - 1
14562                     && (UCHARAT(RExC_parse + 1) == '?'))
14563                 {
14564                     /* If is a '(?', could be an embedded '(?flags:(?[...])'.
14565                      * This happens when we have some thing like
14566                      *
14567                      *   my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
14568                      *   ...
14569                      *   qr/(?[ \p{Digit} & $thai_or_lao ])/;
14570                      *
14571                      * Here we would be handling the interpolated
14572                      * '$thai_or_lao'.  We handle this by a recursive call to
14573                      * ourselves which returns the inversion list the
14574                      * interpolated expression evaluates to.  We use the flags
14575                      * from the interpolated pattern. */
14576                     U32 save_flags = RExC_flags;
14577                     const char * save_parse;
14578
14579                     RExC_parse += 2;        /* Skip past the '(?' */
14580                     save_parse = RExC_parse;
14581
14582                     /* Parse any flags for the '(?' */
14583                     parse_lparen_question_flags(pRExC_state);
14584
14585                     if (RExC_parse == save_parse  /* Makes sure there was at
14586                                                      least one flag (or else
14587                                                      this embedding wasn't
14588                                                      compiled) */
14589                         || RExC_parse >= RExC_end - 4
14590                         || UCHARAT(RExC_parse) != ':'
14591                         || UCHARAT(++RExC_parse) != '('
14592                         || UCHARAT(++RExC_parse) != '?'
14593                         || UCHARAT(++RExC_parse) != '[')
14594                     {
14595
14596                         /* In combination with the above, this moves the
14597                          * pointer to the point just after the first erroneous
14598                          * character (or if there are no flags, to where they
14599                          * should have been) */
14600                         if (RExC_parse >= RExC_end - 4) {
14601                             RExC_parse = RExC_end;
14602                         }
14603                         else if (RExC_parse != save_parse) {
14604                             RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
14605                         }
14606                         vFAIL("Expecting '(?flags:(?[...'");
14607                     }
14608
14609                     /* Recurse, with the meat of the embedded expression */
14610                     RExC_parse++;
14611                     (void) handle_regex_sets(pRExC_state, &current, flagp,
14612                                                     depth+1, oregcomp_parse);
14613
14614                     /* Here, 'current' contains the embedded expression's
14615                      * inversion list, and RExC_parse points to the trailing
14616                      * ']'; the next character should be the ')' */
14617                     RExC_parse++;
14618                     assert(UCHARAT(RExC_parse) == ')');
14619
14620                     /* Then the ')' matching the original '(' handled by this
14621                      * case: statement */
14622                     RExC_parse++;
14623                     assert(UCHARAT(RExC_parse) == ')');
14624
14625                     RExC_parse++;
14626                     RExC_flags = save_flags;
14627                     goto handle_operand;
14628                 }
14629
14630                 /* A regular '('.  Look behind for illegal syntax */
14631                 if (top_index - fence >= 0) {
14632                     /* If the top entry on the stack is an operator, it had
14633                      * better be a '!', otherwise the entry below the top
14634                      * operand should be an operator */
14635                     if (   ! (top_ptr = av_fetch(stack, top_index, FALSE))
14636                         || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!')
14637                         || (   IS_OPERAND(*top_ptr)
14638                             && (   top_index - fence < 1
14639                                 || ! (stacked_ptr = av_fetch(stack,
14640                                                              top_index - 1,
14641                                                              FALSE))
14642                                 || ! IS_OPERATOR(*stacked_ptr))))
14643                     {
14644                         RExC_parse++;
14645                         vFAIL("Unexpected '(' with no preceding operator");
14646                     }
14647                 }
14648
14649                 /* Stack the position of this undealt-with left paren */
14650                 fence = top_index + 1;
14651                 av_push(fence_stack, newSViv(fence));
14652                 break;
14653
14654             case '\\':
14655                 /* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
14656                  * multi-char folds are allowed.  */
14657                 if (!regclass(pRExC_state, flagp,depth+1,
14658                               TRUE, /* means parse just the next thing */
14659                               FALSE, /* don't allow multi-char folds */
14660                               FALSE, /* don't silence non-portable warnings.  */
14661                               TRUE,  /* strict */
14662                               FALSE, /* Require return to be an ANYOF */
14663                               &current,
14664                               NULL))
14665                 {
14666                     FAIL2("panic: regclass returned NULL to handle_sets, "
14667                           "flags=%#"UVxf"", (UV) *flagp);
14668                 }
14669
14670                 /* regclass() will return with parsing just the \ sequence,
14671                  * leaving the parse pointer at the next thing to parse */
14672                 RExC_parse--;
14673                 goto handle_operand;
14674
14675             case '[':   /* Is a bracketed character class */
14676             {
14677                 /* See if this is a [:posix:] class. */
14678                 bool is_posix_class = (OOB_NAMEDCLASS
14679                                         < handle_possible_posix(pRExC_state,
14680                                                             RExC_parse + 1,
14681                                                             NULL,
14682                                                             NULL));
14683                 /* If it is a posix class, leave the parse pointer at the '['
14684                  * to fool regclass() into thinking it is part of a
14685                  * '[[:posix:]]'. */
14686                 if (! is_posix_class) {
14687                     RExC_parse++;
14688                 }
14689
14690                 /* regclass() can only return RESTART_PASS1 and NEED_UTF8 if
14691                  * multi-char folds are allowed.  */
14692                 if (!regclass(pRExC_state, flagp,depth+1,
14693                                 is_posix_class, /* parse the whole char
14694                                                     class only if not a
14695                                                     posix class */
14696                                 FALSE, /* don't allow multi-char folds */
14697                                 TRUE, /* silence non-portable warnings. */
14698                                 TRUE, /* strict */
14699                                 FALSE, /* Require return to be an ANYOF */
14700                                 &current,
14701                                 NULL
14702                                 ))
14703                 {
14704                     FAIL2("panic: regclass returned NULL to handle_sets, "
14705                           "flags=%#"UVxf"", (UV) *flagp);
14706                 }
14707
14708                 /* function call leaves parse pointing to the ']', except if we
14709                  * faked it */
14710                 if (is_posix_class) {
14711                     RExC_parse--;
14712                 }
14713
14714                 goto handle_operand;
14715             }
14716
14717             case ']':
14718                 if (top_index >= 1) {
14719                     goto join_operators;
14720                 }
14721
14722                 /* Only a single operand on the stack: are done */
14723                 goto done;
14724
14725             case ')':
14726                 if (av_tindex(fence_stack) < 0) {
14727                     RExC_parse++;
14728                     vFAIL("Unexpected ')'");
14729                 }
14730
14731                  /* If at least two thing on the stack, treat this as an
14732                   * operator */
14733                 if (top_index - fence >= 1) {
14734                     goto join_operators;
14735                 }
14736
14737                 /* Here only a single thing on the fenced stack, and there is a
14738                  * fence.  Get rid of it */
14739                 fence_ptr = av_pop(fence_stack);
14740                 assert(fence_ptr);
14741                 fence = SvIV(fence_ptr) - 1;
14742                 SvREFCNT_dec_NN(fence_ptr);
14743                 fence_ptr = NULL;
14744
14745                 if (fence < 0) {
14746                     fence = 0;
14747                 }
14748
14749                 /* Having gotten rid of the fence, we pop the operand at the
14750                  * stack top and process it as a newly encountered operand */
14751                 current = av_pop(stack);
14752                 if (IS_OPERAND(current)) {
14753                     goto handle_operand;
14754                 }
14755
14756                 RExC_parse++;
14757                 goto bad_syntax;
14758
14759             case '&':
14760             case '|':
14761             case '+':
14762             case '-':
14763             case '^':
14764
14765                 /* These binary operators should have a left operand already
14766                  * parsed */
14767                 if (   top_index - fence < 0
14768                     || top_index - fence == 1
14769                     || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
14770                     || ! IS_OPERAND(*top_ptr))
14771                 {
14772                     goto unexpected_binary;
14773                 }
14774
14775                 /* If only the one operand is on the part of the stack visible
14776                  * to us, we just place this operator in the proper position */
14777                 if (top_index - fence < 2) {
14778
14779                     /* Place the operator before the operand */
14780
14781                     SV* lhs = av_pop(stack);
14782                     av_push(stack, newSVuv(curchar));
14783                     av_push(stack, lhs);
14784                     break;
14785                 }
14786
14787                 /* But if there is something else on the stack, we need to
14788                  * process it before this new operator if and only if the
14789                  * stacked operation has equal or higher precedence than the
14790                  * new one */
14791
14792              join_operators:
14793
14794                 /* The operator on the stack is supposed to be below both its
14795                  * operands */
14796                 if (   ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE))
14797                     || IS_OPERAND(*stacked_ptr))
14798                 {
14799                     /* But if not, it's legal and indicates we are completely
14800                      * done if and only if we're currently processing a ']',
14801                      * which should be the final thing in the expression */
14802                     if (curchar == ']') {
14803                         goto done;
14804                     }
14805
14806                   unexpected_binary:
14807                     RExC_parse++;
14808                     vFAIL2("Unexpected binary operator '%c' with no "
14809                            "preceding operand", curchar);
14810                 }
14811                 stacked_operator = (char) SvUV(*stacked_ptr);
14812
14813                 if (regex_set_precedence(curchar)
14814                     > regex_set_precedence(stacked_operator))
14815                 {
14816                     /* Here, the new operator has higher precedence than the
14817                      * stacked one.  This means we need to add the new one to
14818                      * the stack to await its rhs operand (and maybe more
14819                      * stuff).  We put it before the lhs operand, leaving
14820                      * untouched the stacked operator and everything below it
14821                      * */
14822                     lhs = av_pop(stack);
14823                     assert(IS_OPERAND(lhs));
14824
14825                     av_push(stack, newSVuv(curchar));
14826                     av_push(stack, lhs);
14827                     break;
14828                 }
14829
14830                 /* Here, the new operator has equal or lower precedence than
14831                  * what's already there.  This means the operation already
14832                  * there should be performed now, before the new one. */
14833
14834                 rhs = av_pop(stack);
14835                 if (! IS_OPERAND(rhs)) {
14836
14837                     /* This can happen when a ! is not followed by an operand,
14838                      * like in /(?[\t &!])/ */
14839                     goto bad_syntax;
14840                 }
14841
14842                 lhs = av_pop(stack);
14843
14844                 if (! IS_OPERAND(lhs)) {
14845
14846                     /* This can happen when there is an empty (), like in
14847                      * /(?[[0]+()+])/ */
14848                     goto bad_syntax;
14849                 }
14850
14851                 switch (stacked_operator) {
14852                     case '&':
14853                         _invlist_intersection(lhs, rhs, &rhs);
14854                         break;
14855
14856                     case '|':
14857                     case '+':
14858                         _invlist_union(lhs, rhs, &rhs);
14859                         break;
14860
14861                     case '-':
14862                         _invlist_subtract(lhs, rhs, &rhs);
14863                         break;
14864
14865                     case '^':   /* The union minus the intersection */
14866                     {
14867                         SV* i = NULL;
14868                         SV* u = NULL;
14869                         SV* element;
14870
14871                         _invlist_union(lhs, rhs, &u);
14872                         _invlist_intersection(lhs, rhs, &i);
14873                         /* _invlist_subtract will overwrite rhs
14874                             without freeing what it already contains */
14875                         element = rhs;
14876                         _invlist_subtract(u, i, &rhs);
14877                         SvREFCNT_dec_NN(i);
14878                         SvREFCNT_dec_NN(u);
14879                         SvREFCNT_dec_NN(element);
14880                         break;
14881                     }
14882                 }
14883                 SvREFCNT_dec(lhs);
14884
14885                 /* Here, the higher precedence operation has been done, and the
14886                  * result is in 'rhs'.  We overwrite the stacked operator with
14887                  * the result.  Then we redo this code to either push the new
14888                  * operator onto the stack or perform any higher precedence
14889                  * stacked operation */
14890                 only_to_avoid_leaks = av_pop(stack);
14891                 SvREFCNT_dec(only_to_avoid_leaks);
14892                 av_push(stack, rhs);
14893                 goto redo_curchar;
14894
14895             case '!':   /* Highest priority, right associative */
14896
14897                 /* If what's already at the top of the stack is another '!",
14898                  * they just cancel each other out */
14899                 if (   (top_ptr = av_fetch(stack, top_index, FALSE))
14900                     && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!'))
14901                 {
14902                     only_to_avoid_leaks = av_pop(stack);
14903                     SvREFCNT_dec(only_to_avoid_leaks);
14904                 }
14905                 else { /* Otherwise, since it's right associative, just push
14906                           onto the stack */
14907                     av_push(stack, newSVuv(curchar));
14908                 }
14909                 break;
14910
14911             default:
14912                 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
14913                 vFAIL("Unexpected character");
14914
14915           handle_operand:
14916
14917             /* Here 'current' is the operand.  If something is already on the
14918              * stack, we have to check if it is a !. */
14919             top_index = av_tindex(stack);   /* Code above may have altered the
14920                                              * stack in the time since we
14921                                              * earlier set 'top_index'. */
14922             if (top_index - fence >= 0) {
14923                 /* If the top entry on the stack is an operator, it had better
14924                  * be a '!', otherwise the entry below the top operand should
14925                  * be an operator */
14926                 top_ptr = av_fetch(stack, top_index, FALSE);
14927                 assert(top_ptr);
14928                 if (IS_OPERATOR(*top_ptr)) {
14929
14930                     /* The only permissible operator at the top of the stack is
14931                      * '!', which is applied immediately to this operand. */
14932                     curchar = (char) SvUV(*top_ptr);
14933                     if (curchar != '!') {
14934                         SvREFCNT_dec(current);
14935                         vFAIL2("Unexpected binary operator '%c' with no "
14936                                 "preceding operand", curchar);
14937                     }
14938
14939                     _invlist_invert(current);
14940
14941                     only_to_avoid_leaks = av_pop(stack);
14942                     SvREFCNT_dec(only_to_avoid_leaks);
14943                     top_index = av_tindex(stack);
14944
14945                     /* And we redo with the inverted operand.  This allows
14946                      * handling multiple ! in a row */
14947                     goto handle_operand;
14948                 }
14949                           /* Single operand is ok only for the non-binary ')'
14950                            * operator */
14951                 else if ((top_index - fence == 0 && curchar != ')')
14952                          || (top_index - fence > 0
14953                              && (! (stacked_ptr = av_fetch(stack,
14954                                                            top_index - 1,
14955                                                            FALSE))
14956                                  || IS_OPERAND(*stacked_ptr))))
14957                 {
14958                     SvREFCNT_dec(current);
14959                     vFAIL("Operand with no preceding operator");
14960                 }
14961             }
14962
14963             /* Here there was nothing on the stack or the top element was
14964              * another operand.  Just add this new one */
14965             av_push(stack, current);
14966
14967         } /* End of switch on next parse token */
14968
14969         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
14970     } /* End of loop parsing through the construct */
14971
14972   done:
14973     if (av_tindex(fence_stack) >= 0) {
14974         vFAIL("Unmatched (");
14975     }
14976
14977     if (av_tindex(stack) < 0   /* Was empty */
14978         || ((final = av_pop(stack)) == NULL)
14979         || ! IS_OPERAND(final)
14980         || SvTYPE(final) != SVt_INVLIST
14981         || av_tindex(stack) >= 0)  /* More left on stack */
14982     {
14983       bad_syntax:
14984         SvREFCNT_dec(final);
14985         vFAIL("Incomplete expression within '(?[ ])'");
14986     }
14987
14988     /* Here, 'final' is the resultant inversion list from evaluating the
14989      * expression.  Return it if so requested */
14990     if (return_invlist) {
14991         *return_invlist = final;
14992         return END;
14993     }
14994
14995     /* Otherwise generate a resultant node, based on 'final'.  regclass() is
14996      * expecting a string of ranges and individual code points */
14997     invlist_iterinit(final);
14998     result_string = newSVpvs("");
14999     while (invlist_iternext(final, &start, &end)) {
15000         if (start == end) {
15001             Perl_sv_catpvf(aTHX_ result_string, "\\x{%"UVXf"}", start);
15002         }
15003         else {
15004             Perl_sv_catpvf(aTHX_ result_string, "\\x{%"UVXf"}-\\x{%"UVXf"}",
15005                                                      start,          end);
15006         }
15007     }
15008
15009     /* About to generate an ANYOF (or similar) node from the inversion list we
15010      * have calculated */
15011     save_parse = RExC_parse;
15012     RExC_parse = SvPV(result_string, len);
15013     save_end = RExC_end;
15014     RExC_end = RExC_parse + len;
15015
15016     /* We turn off folding around the call, as the class we have constructed
15017      * already has all folding taken into consideration, and we don't want
15018      * regclass() to add to that */
15019     RExC_flags &= ~RXf_PMf_FOLD;
15020     /* regclass() can only return RESTART_PASS1 and NEED_UTF8 if multi-char
15021      * folds are allowed.  */
15022     node = regclass(pRExC_state, flagp,depth+1,
15023                     FALSE, /* means parse the whole char class */
15024                     FALSE, /* don't allow multi-char folds */
15025                     TRUE, /* silence non-portable warnings.  The above may very
15026                              well have generated non-portable code points, but
15027                              they're valid on this machine */
15028                     FALSE, /* similarly, no need for strict */
15029                     FALSE, /* Require return to be an ANYOF */
15030                     NULL,
15031                     NULL
15032                 );
15033     if (!node)
15034         FAIL2("panic: regclass returned NULL to handle_sets, flags=%#"UVxf,
15035                     PTR2UV(flagp));
15036
15037     /* Fix up the node type if we are in locale.  (We have pretended we are
15038      * under /u for the purposes of regclass(), as this construct will only
15039      * work under UTF-8 locales.  But now we change the opcode to be ANYOFL (so
15040      * as to cause any warnings about bad locales to be output in regexec.c),
15041      * and add the flag that indicates to check if not in a UTF-8 locale.  The
15042      * reason we above forbid optimization into something other than an ANYOF
15043      * node is simply to minimize the number of code changes in regexec.c.
15044      * Otherwise we would have to create new EXACTish node types and deal with
15045      * them.  This decision could be revisited should this construct become
15046      * popular.
15047      *
15048      * (One might think we could look at the resulting ANYOF node and suppress
15049      * the flag if everything is above 255, as those would be UTF-8 only,
15050      * but this isn't true, as the components that led to that result could
15051      * have been locale-affected, and just happen to cancel each other out
15052      * under UTF-8 locales.) */
15053     if (in_locale) {
15054         set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET);
15055
15056         assert(OP(node) == ANYOF);
15057
15058         OP(node) = ANYOFL;
15059         ANYOF_FLAGS(node)
15060                 |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
15061     }
15062
15063     if (save_fold) {
15064         RExC_flags |= RXf_PMf_FOLD;
15065     }
15066
15067     RExC_parse = save_parse + 1;
15068     RExC_end = save_end;
15069     SvREFCNT_dec_NN(final);
15070     SvREFCNT_dec_NN(result_string);
15071
15072     nextchar(pRExC_state);
15073     Set_Node_Length(node, RExC_parse - oregcomp_parse + 1); /* MJD */
15074     return node;
15075 }
15076 #undef IS_OPERATOR
15077 #undef IS_OPERAND
15078
15079 STATIC void
15080 S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist)
15081 {
15082     /* This hard-codes the Latin1/above-Latin1 folding rules, so that an
15083      * innocent-looking character class, like /[ks]/i won't have to go out to
15084      * disk to find the possible matches.
15085      *
15086      * This should be called only for a Latin1-range code points, cp, which is
15087      * known to be involved in a simple fold with other code points above
15088      * Latin1.  It would give false results if /aa has been specified.
15089      * Multi-char folds are outside the scope of this, and must be handled
15090      * specially.
15091      *
15092      * XXX It would be better to generate these via regen, in case a new
15093      * version of the Unicode standard adds new mappings, though that is not
15094      * really likely, and may be caught by the default: case of the switch
15095      * below. */
15096
15097     PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS;
15098
15099     assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp));
15100
15101     switch (cp) {
15102         case 'k':
15103         case 'K':
15104           *invlist =
15105              add_cp_to_invlist(*invlist, KELVIN_SIGN);
15106             break;
15107         case 's':
15108         case 'S':
15109           *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S);
15110             break;
15111         case MICRO_SIGN:
15112           *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU);
15113           *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU);
15114             break;
15115         case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
15116         case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
15117           *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN);
15118             break;
15119         case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
15120           *invlist = add_cp_to_invlist(*invlist,
15121                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
15122             break;
15123
15124 #ifdef LATIN_CAPITAL_LETTER_SHARP_S /* not defined in early Unicode releases */
15125
15126         case LATIN_SMALL_LETTER_SHARP_S:
15127           *invlist = add_cp_to_invlist(*invlist, LATIN_CAPITAL_LETTER_SHARP_S);
15128             break;
15129
15130 #endif
15131
15132 #if    UNICODE_MAJOR_VERSION < 3                                        \
15133    || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0)
15134
15135         /* In 3.0 and earlier, U+0130 folded simply to 'i'; and in 3.0.1 so did
15136          * U+0131.  */
15137         case 'i':
15138         case 'I':
15139           *invlist =
15140              add_cp_to_invlist(*invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE);
15141 #   if UNICODE_DOT_DOT_VERSION == 1
15142           *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_DOTLESS_I);
15143 #   endif
15144             break;
15145 #endif
15146
15147         default:
15148             /* Use deprecated warning to increase the chances of this being
15149              * output */
15150             if (PASS2) {
15151                 ckWARN2reg_d(RExC_parse, "Perl folding rules are not up-to-date for 0x%02X; please use the perlbug utility to report;", cp);
15152             }
15153             break;
15154     }
15155 }
15156
15157 STATIC AV *
15158 S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count)
15159 {
15160     /* This adds the string scalar <multi_string> to the array
15161      * <multi_char_matches>.  <multi_string> is known to have exactly
15162      * <cp_count> code points in it.  This is used when constructing a
15163      * bracketed character class and we find something that needs to match more
15164      * than a single character.
15165      *
15166      * <multi_char_matches> is actually an array of arrays.  Each top-level
15167      * element is an array that contains all the strings known so far that are
15168      * the same length.  And that length (in number of code points) is the same
15169      * as the index of the top-level array.  Hence, the [2] element is an
15170      * array, each element thereof is a string containing TWO code points;
15171      * while element [3] is for strings of THREE characters, and so on.  Since
15172      * this is for multi-char strings there can never be a [0] nor [1] element.
15173      *
15174      * When we rewrite the character class below, we will do so such that the
15175      * longest strings are written first, so that it prefers the longest
15176      * matching strings first.  This is done even if it turns out that any
15177      * quantifier is non-greedy, out of this programmer's (khw) laziness.  Tom
15178      * Christiansen has agreed that this is ok.  This makes the test for the
15179      * ligature 'ffi' come before the test for 'ff', for example */
15180
15181     AV* this_array;
15182     AV** this_array_ptr;
15183
15184     PERL_ARGS_ASSERT_ADD_MULTI_MATCH;
15185
15186     if (! multi_char_matches) {
15187         multi_char_matches = newAV();
15188     }
15189
15190     if (av_exists(multi_char_matches, cp_count)) {
15191         this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE);
15192         this_array = *this_array_ptr;
15193     }
15194     else {
15195         this_array = newAV();
15196         av_store(multi_char_matches, cp_count,
15197                  (SV*) this_array);
15198     }
15199     av_push(this_array, multi_string);
15200
15201     return multi_char_matches;
15202 }
15203
15204 /* The names of properties whose definitions are not known at compile time are
15205  * stored in this SV, after a constant heading.  So if the length has been
15206  * changed since initialization, then there is a run-time definition. */
15207 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION                            \
15208                                         (SvCUR(listsv) != initial_listsv_len)
15209
15210 /* There is a restricted set of white space characters that are legal when
15211  * ignoring white space in a bracketed character class.  This generates the
15212  * code to skip them.
15213  *
15214  * There is a line below that uses the same white space criteria but is outside
15215  * this macro.  Both here and there must use the same definition */
15216 #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p)                          \
15217     STMT_START {                                                        \
15218         if (do_skip) {                                                  \
15219             while (isBLANK_A(UCHARAT(p)))                               \
15220             {                                                           \
15221                 p++;                                                    \
15222             }                                                           \
15223         }                                                               \
15224     } STMT_END
15225
15226 STATIC regnode *
15227 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
15228                  const bool stop_at_1,  /* Just parse the next thing, don't
15229                                            look for a full character class */
15230                  bool allow_multi_folds,
15231                  const bool silence_non_portable,   /* Don't output warnings
15232                                                        about too large
15233                                                        characters */
15234                  const bool strict,
15235                  bool optimizable,                  /* ? Allow a non-ANYOF return
15236                                                        node */
15237                  SV** ret_invlist, /* Return an inversion list, not a node */
15238                  AV** posix_warnings
15239           )
15240 {
15241     /* parse a bracketed class specification.  Most of these will produce an
15242      * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
15243      * EXACTFish node; [[:ascii:]], a POSIXA node; etc.  It is more complex
15244      * under /i with multi-character folds: it will be rewritten following the
15245      * paradigm of this example, where the <multi-fold>s are characters which
15246      * fold to multiple character sequences:
15247      *      /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
15248      * gets effectively rewritten as:
15249      *      /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
15250      * reg() gets called (recursively) on the rewritten version, and this
15251      * function will return what it constructs.  (Actually the <multi-fold>s
15252      * aren't physically removed from the [abcdefghi], it's just that they are
15253      * ignored in the recursion by means of a flag:
15254      * <RExC_in_multi_char_class>.)
15255      *
15256      * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS
15257      * characters, with the corresponding bit set if that character is in the
15258      * list.  For characters above this, a range list or swash is used.  There
15259      * are extra bits for \w, etc. in locale ANYOFs, as what these match is not
15260      * determinable at compile time
15261      *
15262      * Returns NULL, setting *flagp to RESTART_PASS1 if the sizing scan needs
15263      * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded
15264      * to UTF-8.  This can only happen if ret_invlist is non-NULL.
15265      */
15266
15267     UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
15268     IV range = 0;
15269     UV value = OOB_UNICODE, save_value = OOB_UNICODE;
15270     regnode *ret;
15271     STRLEN numlen;
15272     int namedclass = OOB_NAMEDCLASS;
15273     char *rangebegin = NULL;
15274     bool need_class = 0;
15275     SV *listsv = NULL;
15276     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
15277                                       than just initialized.  */
15278     SV* properties = NULL;    /* Code points that match \p{} \P{} */
15279     SV* posixes = NULL;     /* Code points that match classes like [:word:],
15280                                extended beyond the Latin1 range.  These have to
15281                                be kept separate from other code points for much
15282                                of this function because their handling  is
15283                                different under /i, and for most classes under
15284                                /d as well */
15285     SV* nposixes = NULL;    /* Similarly for [:^word:].  These are kept
15286                                separate for a while from the non-complemented
15287                                versions because of complications with /d
15288                                matching */
15289     SV* simple_posixes = NULL; /* But under some conditions, the classes can be
15290                                   treated more simply than the general case,
15291                                   leading to less compilation and execution
15292                                   work */
15293     UV element_count = 0;   /* Number of distinct elements in the class.
15294                                Optimizations may be possible if this is tiny */
15295     AV * multi_char_matches = NULL; /* Code points that fold to more than one
15296                                        character; used under /i */
15297     UV n;
15298     char * stop_ptr = RExC_end;    /* where to stop parsing */
15299     const bool skip_white = cBOOL(ret_invlist); /* ignore unescaped white
15300                                                    space? */
15301
15302     /* Unicode properties are stored in a swash; this holds the current one
15303      * being parsed.  If this swash is the only above-latin1 component of the
15304      * character class, an optimization is to pass it directly on to the
15305      * execution engine.  Otherwise, it is set to NULL to indicate that there
15306      * are other things in the class that have to be dealt with at execution
15307      * time */
15308     SV* swash = NULL;           /* Code points that match \p{} \P{} */
15309
15310     /* Set if a component of this character class is user-defined; just passed
15311      * on to the engine */
15312     bool has_user_defined_property = FALSE;
15313
15314     /* inversion list of code points this node matches only when the target
15315      * string is in UTF-8.  These are all non-ASCII, < 256.  (Because is under
15316      * /d) */
15317     SV* has_upper_latin1_only_utf8_matches = NULL;
15318
15319     /* Inversion list of code points this node matches regardless of things
15320      * like locale, folding, utf8ness of the target string */
15321     SV* cp_list = NULL;
15322
15323     /* Like cp_list, but code points on this list need to be checked for things
15324      * that fold to/from them under /i */
15325     SV* cp_foldable_list = NULL;
15326
15327     /* Like cp_list, but code points on this list are valid only when the
15328      * runtime locale is UTF-8 */
15329     SV* only_utf8_locale_list = NULL;
15330
15331     /* In a range, if one of the endpoints is non-character-set portable,
15332      * meaning that it hard-codes a code point that may mean a different
15333      * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a
15334      * mnemonic '\t' which each mean the same character no matter which
15335      * character set the platform is on. */
15336     unsigned int non_portable_endpoint = 0;
15337
15338     /* Is the range unicode? which means on a platform that isn't 1-1 native
15339      * to Unicode (i.e. non-ASCII), each code point in it should be considered
15340      * to be a Unicode value.  */
15341     bool unicode_range = FALSE;
15342     bool invert = FALSE;    /* Is this class to be complemented */
15343
15344     bool warn_super = ALWAYS_WARN_SUPER;
15345
15346     regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
15347         case we need to change the emitted regop to an EXACT. */
15348     const char * orig_parse = RExC_parse;
15349     const SSize_t orig_size = RExC_size;
15350     bool posixl_matches_all = FALSE; /* Does /l class have both e.g. \W,\w ? */
15351
15352     /* This variable is used to mark where in the input something that looks
15353      * like a POSIX construct ends.  During the parse, when something looks
15354      * like it could be such a construct is encountered, it is checked for
15355      * being one, but not if we've already checked this area of the input.
15356      * Only after this position is reached do we check again */
15357     char *dont_check_for_posix_end = RExC_parse - 1;
15358
15359     GET_RE_DEBUG_FLAGS_DECL;
15360
15361     PERL_ARGS_ASSERT_REGCLASS;
15362 #ifndef DEBUGGING
15363     PERL_UNUSED_ARG(depth);
15364 #endif
15365
15366     DEBUG_PARSE("clas");
15367
15368 #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */      \
15369     || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0          \
15370                                    && UNICODE_DOT_DOT_VERSION == 0)
15371     allow_multi_folds = FALSE;
15372 #endif
15373
15374     if (posix_warnings == NULL) {
15375         posix_warnings = (AV **) -1;
15376     }
15377
15378     /* Assume we are going to generate an ANYOF node. */
15379     ret = reganode(pRExC_state,
15380                    (LOC)
15381                     ? ANYOFL
15382                     : ANYOF,
15383                    0);
15384
15385     if (SIZE_ONLY) {
15386         RExC_size += ANYOF_SKIP;
15387         listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
15388     }
15389     else {
15390         ANYOF_FLAGS(ret) = 0;
15391
15392         RExC_emit += ANYOF_SKIP;
15393         listsv = newSVpvs_flags("# comment\n", SVs_TEMP);
15394         initial_listsv_len = SvCUR(listsv);
15395         SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated.  */
15396     }
15397
15398     SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
15399
15400     assert(RExC_parse <= RExC_end);
15401
15402     if (UCHARAT(RExC_parse) == '^') {   /* Complement the class */
15403         RExC_parse++;
15404         invert = TRUE;
15405         allow_multi_folds = FALSE;
15406         MARK_NAUGHTY(1);
15407         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
15408     }
15409
15410     /* Check that they didn't say [:posix:] instead of [[:posix:]] */
15411     if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) {
15412         char *class_end;
15413         int maybe_class = handle_possible_posix(pRExC_state, RExC_parse,
15414                                              &class_end, NULL);
15415         if (maybe_class >= OOB_NAMEDCLASS) {
15416             dont_check_for_posix_end = class_end;
15417             if (PASS2 && posix_warnings == (AV **) -1) {
15418                 SAVEFREESV(RExC_rx_sv);
15419                 ckWARN4reg(class_end,
15420                         "POSIX syntax [%c %c] belongs inside character classes%s",
15421                         *RExC_parse, *RExC_parse,
15422                         (maybe_class == OOB_NAMEDCLASS)
15423                         ? ((POSIXCC_NOTYET(*RExC_parse))
15424                             ? " (but this one isn't implemented)"
15425                             : " (but this one isn't fully valid)")
15426                         : ""
15427                         );
15428                 (void)ReREFCNT_inc(RExC_rx_sv);
15429             }
15430         }
15431     }
15432
15433     /* If the caller wants us to just parse a single element, accomplish this
15434      * by faking the loop ending condition */
15435     if (stop_at_1 && RExC_end > RExC_parse) {
15436         stop_ptr = RExC_parse + 1;
15437     }
15438
15439     /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
15440     if (UCHARAT(RExC_parse) == ']')
15441         goto charclassloop;
15442
15443     while (1) {
15444         if  (RExC_parse >= stop_ptr) {
15445             break;
15446         }
15447
15448         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
15449
15450         if  (UCHARAT(RExC_parse) == ']') {
15451             break;
15452         }
15453
15454       charclassloop:
15455
15456         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
15457         save_value = value;
15458         save_prevvalue = prevvalue;
15459
15460         if (!range) {
15461             rangebegin = RExC_parse;
15462             element_count++;
15463             non_portable_endpoint = 0;
15464         }
15465         if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) {
15466             value = utf8n_to_uvchr((U8*)RExC_parse,
15467                                    RExC_end - RExC_parse,
15468                                    &numlen, UTF8_ALLOW_DEFAULT);
15469             RExC_parse += numlen;
15470         }
15471         else
15472             value = UCHARAT(RExC_parse++);
15473
15474         if (value == '[') {
15475             namedclass = handle_possible_posix(pRExC_state, RExC_parse, &dont_check_for_posix_end, posix_warnings);
15476             if (namedclass > OOB_NAMEDCLASS) {
15477                 RExC_parse = dont_check_for_posix_end;
15478             }
15479             else {
15480                 namedclass = OOB_NAMEDCLASS;
15481             }
15482         }
15483         else if (   RExC_parse - 1 > dont_check_for_posix_end
15484                  && MAYBE_POSIXCC(value))
15485         {
15486             (void) handle_possible_posix(pRExC_state, RExC_parse - 1,  /* -1 because parse has already been advanced */
15487                     &dont_check_for_posix_end, posix_warnings);
15488         }
15489         else if (value == '\\') {
15490             /* Is a backslash; get the code point of the char after it */
15491             if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) {
15492                 value = utf8n_to_uvchr((U8*)RExC_parse,
15493                                    RExC_end - RExC_parse,
15494                                    &numlen, UTF8_ALLOW_DEFAULT);
15495                 RExC_parse += numlen;
15496             }
15497             else
15498                 value = UCHARAT(RExC_parse++);
15499
15500             /* Some compilers cannot handle switching on 64-bit integer
15501              * values, therefore value cannot be an UV.  Yes, this will
15502              * be a problem later if we want switch on Unicode.
15503              * A similar issue a little bit later when switching on
15504              * namedclass. --jhi */
15505
15506             /* If the \ is escaping white space when white space is being
15507              * skipped, it means that that white space is wanted literally, and
15508              * is already in 'value'.  Otherwise, need to translate the escape
15509              * into what it signifies. */
15510             if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) {
15511
15512             case 'w':   namedclass = ANYOF_WORDCHAR;    break;
15513             case 'W':   namedclass = ANYOF_NWORDCHAR;   break;
15514             case 's':   namedclass = ANYOF_SPACE;       break;
15515             case 'S':   namedclass = ANYOF_NSPACE;      break;
15516             case 'd':   namedclass = ANYOF_DIGIT;       break;
15517             case 'D':   namedclass = ANYOF_NDIGIT;      break;
15518             case 'v':   namedclass = ANYOF_VERTWS;      break;
15519             case 'V':   namedclass = ANYOF_NVERTWS;     break;
15520             case 'h':   namedclass = ANYOF_HORIZWS;     break;
15521             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
15522             case 'N':  /* Handle \N{NAME} in class */
15523                 {
15524                     const char * const backslash_N_beg = RExC_parse - 2;
15525                     int cp_count;
15526
15527                     if (! grok_bslash_N(pRExC_state,
15528                                         NULL,      /* No regnode */
15529                                         &value,    /* Yes single value */
15530                                         &cp_count, /* Multiple code pt count */
15531                                         flagp,
15532                                         depth)
15533                     ) {
15534
15535                         if (*flagp & NEED_UTF8)
15536                             FAIL("panic: grok_bslash_N set NEED_UTF8");
15537                         if (*flagp & RESTART_PASS1)
15538                             return NULL;
15539
15540                         if (cp_count < 0) {
15541                             vFAIL("\\N in a character class must be a named character: \\N{...}");
15542                         }
15543                         else if (cp_count == 0) {
15544                             if (strict) {
15545                                 RExC_parse++;   /* Position after the "}" */
15546                                 vFAIL("Zero length \\N{}");
15547                             }
15548                             else if (PASS2) {
15549                                 ckWARNreg(RExC_parse,
15550                                         "Ignoring zero length \\N{} in character class");
15551                             }
15552                         }
15553                         else { /* cp_count > 1 */
15554                             if (! RExC_in_multi_char_class) {
15555                                 if (invert || range || *RExC_parse == '-') {
15556                                     if (strict) {
15557                                         RExC_parse--;
15558                                         vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character");
15559                                     }
15560                                     else if (PASS2) {
15561                                         ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class");
15562                                     }
15563                                     break; /* <value> contains the first code
15564                                               point. Drop out of the switch to
15565                                               process it */
15566                                 }
15567                                 else {
15568                                     SV * multi_char_N = newSVpvn(backslash_N_beg,
15569                                                  RExC_parse - backslash_N_beg);
15570                                     multi_char_matches
15571                                         = add_multi_match(multi_char_matches,
15572                                                           multi_char_N,
15573                                                           cp_count);
15574                                 }
15575                             }
15576                         } /* End of cp_count != 1 */
15577
15578                         /* This element should not be processed further in this
15579                          * class */
15580                         element_count--;
15581                         value = save_value;
15582                         prevvalue = save_prevvalue;
15583                         continue;   /* Back to top of loop to get next char */
15584                     }
15585
15586                     /* Here, is a single code point, and <value> contains it */
15587                     unicode_range = TRUE;   /* \N{} are Unicode */
15588                 }
15589                 break;
15590             case 'p':
15591             case 'P':
15592                 {
15593                 char *e;
15594
15595                 /* We will handle any undefined properties ourselves */
15596                 U8 swash_init_flags = _CORE_SWASH_INIT_RETURN_IF_UNDEF
15597                                        /* And we actually would prefer to get
15598                                         * the straight inversion list of the
15599                                         * swash, since we will be accessing it
15600                                         * anyway, to save a little time */
15601                                       |_CORE_SWASH_INIT_ACCEPT_INVLIST;
15602
15603                 if (RExC_parse >= RExC_end)
15604                     vFAIL2("Empty \\%c", (U8)value);
15605                 if (*RExC_parse == '{') {
15606                     const U8 c = (U8)value;
15607                     e = strchr(RExC_parse, '}');
15608                     if (!e) {
15609                         RExC_parse++;
15610                         vFAIL2("Missing right brace on \\%c{}", c);
15611                     }
15612
15613                     RExC_parse++;
15614                     while (isSPACE(*RExC_parse)) {
15615                          RExC_parse++;
15616                     }
15617
15618                     if (UCHARAT(RExC_parse) == '^') {
15619
15620                         /* toggle.  (The rhs xor gets the single bit that
15621                          * differs between P and p; the other xor inverts just
15622                          * that bit) */
15623                         value ^= 'P' ^ 'p';
15624
15625                         RExC_parse++;
15626                         while (isSPACE(*RExC_parse)) {
15627                             RExC_parse++;
15628                         }
15629                     }
15630
15631                     if (e == RExC_parse)
15632                         vFAIL2("Empty \\%c{}", c);
15633
15634                     n = e - RExC_parse;
15635                     while (isSPACE(*(RExC_parse + n - 1)))
15636                         n--;
15637                 }   /* The \p isn't immediately followed by a '{' */
15638                 else if (! isALPHA(*RExC_parse)) {
15639                     RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15640                     vFAIL2("Character following \\%c must be '{' or a "
15641                            "single-character Unicode property name",
15642                            (U8) value);
15643                 }
15644                 else {
15645                     e = RExC_parse;
15646                     n = 1;
15647                 }
15648                 if (!SIZE_ONLY) {
15649                     SV* invlist;
15650                     char* name;
15651                     char* base_name;    /* name after any packages are stripped */
15652                     const char * const colon_colon = "::";
15653
15654                     /* Try to get the definition of the property into
15655                      * <invlist>.  If /i is in effect, the effective property
15656                      * will have its name be <__NAME_i>.  The design is
15657                      * discussed in commit
15658                      * 2f833f5208e26b208886e51e09e2c072b5eabb46 */
15659                     name = savepv(Perl_form(aTHX_
15660                                           "%s%.*s%s\n",
15661                                           (FOLD) ? "__" : "",
15662                                           (int)n,
15663                                           RExC_parse,
15664                                           (FOLD) ? "_i" : ""
15665                                 ));
15666
15667                     /* Look up the property name, and get its swash and
15668                      * inversion list, if the property is found  */
15669                     if (swash) {    /* Return any left-overs */
15670                         SvREFCNT_dec_NN(swash);
15671                     }
15672                     swash = _core_swash_init("utf8", name, &PL_sv_undef,
15673                                              1, /* binary */
15674                                              0, /* not tr/// */
15675                                              NULL, /* No inversion list */
15676                                              &swash_init_flags
15677                                             );
15678                     if (! swash || ! (invlist = _get_swash_invlist(swash))) {
15679                         HV* curpkg = (IN_PERL_COMPILETIME)
15680                                       ? PL_curstash
15681                                       : CopSTASH(PL_curcop);
15682                         UV final_n = n;
15683                         bool has_pkg;
15684
15685                         if (swash) {    /* Got a swash but no inversion list.
15686                                            Something is likely wrong that will
15687                                            be sorted-out later */
15688                             SvREFCNT_dec_NN(swash);
15689                             swash = NULL;
15690                         }
15691
15692                         /* Here didn't find it.  It could be a an error (like a
15693                          * typo) in specifying a Unicode property, or it could
15694                          * be a user-defined property that will be available at
15695                          * run-time.  The names of these must begin with 'In'
15696                          * or 'Is' (after any packages are stripped off).  So
15697                          * if not one of those, or if we accept only
15698                          * compile-time properties, is an error; otherwise add
15699                          * it to the list for run-time look up. */
15700                         if ((base_name = rninstr(name, name + n,
15701                                                  colon_colon, colon_colon + 2)))
15702                         { /* Has ::.  We know this must be a user-defined
15703                              property */
15704                             base_name += 2;
15705                             final_n -= base_name - name;
15706                             has_pkg = TRUE;
15707                         }
15708                         else {
15709                             base_name = name;
15710                             has_pkg = FALSE;
15711                         }
15712
15713                         if (   final_n < 3
15714                             || base_name[0] != 'I'
15715                             || (base_name[1] != 's' && base_name[1] != 'n')
15716                             || ret_invlist)
15717                         {
15718                             const char * const msg
15719                                 = (has_pkg)
15720                                   ? "Illegal user-defined property name"
15721                                   : "Can't find Unicode property definition";
15722                             RExC_parse = e + 1;
15723
15724                             /* diag_listed_as: Can't find Unicode property definition "%s" */
15725                             vFAIL3utf8f("%s \"%"UTF8f"\"",
15726                                 msg, UTF8fARG(UTF, n, name));
15727                         }
15728
15729                         /* If the property name doesn't already have a package
15730                          * name, add the current one to it so that it can be
15731                          * referred to outside it. [perl #121777] */
15732                         if (! has_pkg && curpkg) {
15733                             char* pkgname = HvNAME(curpkg);
15734                             if (strNE(pkgname, "main")) {
15735                                 char* full_name = Perl_form(aTHX_
15736                                                             "%s::%s",
15737                                                             pkgname,
15738                                                             name);
15739                                 n = strlen(full_name);
15740                                 Safefree(name);
15741                                 name = savepvn(full_name, n);
15742                             }
15743                         }
15744                         Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%"UTF8f"\n",
15745                                         (value == 'p' ? '+' : '!'),
15746                                         UTF8fARG(UTF, n, name));
15747                         has_user_defined_property = TRUE;
15748                         optimizable = FALSE;    /* Will have to leave this an
15749                                                    ANYOF node */
15750
15751                         /* We don't know yet what this matches, so have to flag
15752                          * it */
15753                         ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
15754                     }
15755                     else {
15756
15757                         /* Here, did get the swash and its inversion list.  If
15758                          * the swash is from a user-defined property, then this
15759                          * whole character class should be regarded as such */
15760                         if (swash_init_flags
15761                             & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)
15762                         {
15763                             has_user_defined_property = TRUE;
15764                         }
15765                         else if
15766                             /* We warn on matching an above-Unicode code point
15767                              * if the match would return true, except don't
15768                              * warn for \p{All}, which has exactly one element
15769                              * = 0 */
15770                             (_invlist_contains_cp(invlist, 0x110000)
15771                                 && (! (_invlist_len(invlist) == 1
15772                                        && *invlist_array(invlist) == 0)))
15773                         {
15774                             warn_super = TRUE;
15775                         }
15776
15777
15778                         /* Invert if asking for the complement */
15779                         if (value == 'P') {
15780                             _invlist_union_complement_2nd(properties,
15781                                                           invlist,
15782                                                           &properties);
15783
15784                             /* The swash can't be used as-is, because we've
15785                              * inverted things; delay removing it to here after
15786                              * have copied its invlist above */
15787                             SvREFCNT_dec_NN(swash);
15788                             swash = NULL;
15789                         }
15790                         else {
15791                             _invlist_union(properties, invlist, &properties);
15792                         }
15793                     }
15794                     Safefree(name);
15795                 }
15796                 RExC_parse = e + 1;
15797                 namedclass = ANYOF_UNIPROP;  /* no official name, but it's
15798                                                 named */
15799
15800                 /* \p means they want Unicode semantics */
15801                 REQUIRE_UNI_RULES(flagp, NULL);
15802                 }
15803                 break;
15804             case 'n':   value = '\n';                   break;
15805             case 'r':   value = '\r';                   break;
15806             case 't':   value = '\t';                   break;
15807             case 'f':   value = '\f';                   break;
15808             case 'b':   value = '\b';                   break;
15809             case 'e':   value = ESC_NATIVE;             break;
15810             case 'a':   value = '\a';                   break;
15811             case 'o':
15812                 RExC_parse--;   /* function expects to be pointed at the 'o' */
15813                 {
15814                     const char* error_msg;
15815                     bool valid = grok_bslash_o(&RExC_parse,
15816                                                &value,
15817                                                &error_msg,
15818                                                PASS2,   /* warnings only in
15819                                                            pass 2 */
15820                                                strict,
15821                                                silence_non_portable,
15822                                                UTF);
15823                     if (! valid) {
15824                         vFAIL(error_msg);
15825                     }
15826                 }
15827                 non_portable_endpoint++;
15828                 if (IN_ENCODING && value < 0x100) {
15829                     goto recode_encoding;
15830                 }
15831                 break;
15832             case 'x':
15833                 RExC_parse--;   /* function expects to be pointed at the 'x' */
15834                 {
15835                     const char* error_msg;
15836                     bool valid = grok_bslash_x(&RExC_parse,
15837                                                &value,
15838                                                &error_msg,
15839                                                PASS2, /* Output warnings */
15840                                                strict,
15841                                                silence_non_portable,
15842                                                UTF);
15843                     if (! valid) {
15844                         vFAIL(error_msg);
15845                     }
15846                 }
15847                 non_portable_endpoint++;
15848                 if (IN_ENCODING && value < 0x100)
15849                     goto recode_encoding;
15850                 break;
15851             case 'c':
15852                 value = grok_bslash_c(*RExC_parse++, PASS2);
15853                 non_portable_endpoint++;
15854                 break;
15855             case '0': case '1': case '2': case '3': case '4':
15856             case '5': case '6': case '7':
15857                 {
15858                     /* Take 1-3 octal digits */
15859                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
15860                     numlen = (strict) ? 4 : 3;
15861                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
15862                     RExC_parse += numlen;
15863                     if (numlen != 3) {
15864                         if (strict) {
15865                             RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
15866                             vFAIL("Need exactly 3 octal digits");
15867                         }
15868                         else if (! SIZE_ONLY /* like \08, \178 */
15869                                  && numlen < 3
15870                                  && RExC_parse < RExC_end
15871                                  && isDIGIT(*RExC_parse)
15872                                  && ckWARN(WARN_REGEXP))
15873                         {
15874                             SAVEFREESV(RExC_rx_sv);
15875                             reg_warn_non_literal_string(
15876                                  RExC_parse + 1,
15877                                  form_short_octal_warning(RExC_parse, numlen));
15878                             (void)ReREFCNT_inc(RExC_rx_sv);
15879                         }
15880                     }
15881                     non_portable_endpoint++;
15882                     if (IN_ENCODING && value < 0x100)
15883                         goto recode_encoding;
15884                     break;
15885                 }
15886               recode_encoding:
15887                 if (! RExC_override_recoding) {
15888                     SV* enc = _get_encoding();
15889                     value = reg_recode((U8)value, &enc);
15890                     if (!enc) {
15891                         if (strict) {
15892                             vFAIL("Invalid escape in the specified encoding");
15893                         }
15894                         else if (PASS2) {
15895                             ckWARNreg(RExC_parse,
15896                                   "Invalid escape in the specified encoding");
15897                         }
15898                     }
15899                     break;
15900                 }
15901             default:
15902                 /* Allow \_ to not give an error */
15903                 if (!SIZE_ONLY && isWORDCHAR(value) && value != '_') {
15904                     if (strict) {
15905                         vFAIL2("Unrecognized escape \\%c in character class",
15906                                (int)value);
15907                     }
15908                     else {
15909                         SAVEFREESV(RExC_rx_sv);
15910                         ckWARN2reg(RExC_parse,
15911                             "Unrecognized escape \\%c in character class passed through",
15912                             (int)value);
15913                         (void)ReREFCNT_inc(RExC_rx_sv);
15914                     }
15915                 }
15916                 break;
15917             }   /* End of switch on char following backslash */
15918         } /* end of handling backslash escape sequences */
15919
15920         /* Here, we have the current token in 'value' */
15921
15922         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
15923             U8 classnum;
15924
15925             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
15926              * literal, as is the character that began the false range, i.e.
15927              * the 'a' in the examples */
15928             if (range) {
15929                 if (!SIZE_ONLY) {
15930                     const int w = (RExC_parse >= rangebegin)
15931                                   ? RExC_parse - rangebegin
15932                                   : 0;
15933                     if (strict) {
15934                         vFAIL2utf8f(
15935                             "False [] range \"%"UTF8f"\"",
15936                             UTF8fARG(UTF, w, rangebegin));
15937                     }
15938                     else {
15939                         SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
15940                         ckWARN2reg(RExC_parse,
15941                             "False [] range \"%"UTF8f"\"",
15942                             UTF8fARG(UTF, w, rangebegin));
15943                         (void)ReREFCNT_inc(RExC_rx_sv);
15944                         cp_list = add_cp_to_invlist(cp_list, '-');
15945                         cp_foldable_list = add_cp_to_invlist(cp_foldable_list,
15946                                                              prevvalue);
15947                     }
15948                 }
15949
15950                 range = 0; /* this was not a true range */
15951                 element_count += 2; /* So counts for three values */
15952             }
15953
15954             classnum = namedclass_to_classnum(namedclass);
15955
15956             if (LOC && namedclass < ANYOF_POSIXL_MAX
15957 #ifndef HAS_ISASCII
15958                 && classnum != _CC_ASCII
15959 #endif
15960             ) {
15961                 /* What the Posix classes (like \w, [:space:]) match in locale
15962                  * isn't knowable under locale until actual match time.  Room
15963                  * must be reserved (one time per outer bracketed class) to
15964                  * store such classes.  The space will contain a bit for each
15965                  * named class that is to be matched against.  This isn't
15966                  * needed for \p{} and pseudo-classes, as they are not affected
15967                  * by locale, and hence are dealt with separately */
15968                 if (! need_class) {
15969                     need_class = 1;
15970                     if (SIZE_ONLY) {
15971                         RExC_size += ANYOF_POSIXL_SKIP - ANYOF_SKIP;
15972                     }
15973                     else {
15974                         RExC_emit += ANYOF_POSIXL_SKIP - ANYOF_SKIP;
15975                     }
15976                     ANYOF_FLAGS(ret) |= ANYOF_MATCHES_POSIXL;
15977                     ANYOF_POSIXL_ZERO(ret);
15978
15979                     /* We can't change this into some other type of node
15980                      * (unless this is the only element, in which case there
15981                      * are nodes that mean exactly this) as has runtime
15982                      * dependencies */
15983                     optimizable = FALSE;
15984                 }
15985
15986                 /* Coverity thinks it is possible for this to be negative; both
15987                  * jhi and khw think it's not, but be safer */
15988                 assert(! (ANYOF_FLAGS(ret) & ANYOF_MATCHES_POSIXL)
15989                        || (namedclass + ((namedclass % 2) ? -1 : 1)) >= 0);
15990
15991                 /* See if it already matches the complement of this POSIX
15992                  * class */
15993                 if ((ANYOF_FLAGS(ret) & ANYOF_MATCHES_POSIXL)
15994                     && ANYOF_POSIXL_TEST(ret, namedclass + ((namedclass % 2)
15995                                                             ? -1
15996                                                             : 1)))
15997                 {
15998                     posixl_matches_all = TRUE;
15999                     break;  /* No need to continue.  Since it matches both
16000                                e.g., \w and \W, it matches everything, and the
16001                                bracketed class can be optimized into qr/./s */
16002                 }
16003
16004                 /* Add this class to those that should be checked at runtime */
16005                 ANYOF_POSIXL_SET(ret, namedclass);
16006
16007                 /* The above-Latin1 characters are not subject to locale rules.
16008                  * Just add them, in the second pass, to the
16009                  * unconditionally-matched list */
16010                 if (! SIZE_ONLY) {
16011                     SV* scratch_list = NULL;
16012
16013                     /* Get the list of the above-Latin1 code points this
16014                      * matches */
16015                     _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1,
16016                                           PL_XPosix_ptrs[classnum],
16017
16018                                           /* Odd numbers are complements, like
16019                                            * NDIGIT, NASCII, ... */
16020                                           namedclass % 2 != 0,
16021                                           &scratch_list);
16022                     /* Checking if 'cp_list' is NULL first saves an extra
16023                      * clone.  Its reference count will be decremented at the
16024                      * next union, etc, or if this is the only instance, at the
16025                      * end of the routine */
16026                     if (! cp_list) {
16027                         cp_list = scratch_list;
16028                     }
16029                     else {
16030                         _invlist_union(cp_list, scratch_list, &cp_list);
16031                         SvREFCNT_dec_NN(scratch_list);
16032                     }
16033                     continue;   /* Go get next character */
16034                 }
16035             }
16036             else if (! SIZE_ONLY) {
16037
16038                 /* Here, not in pass1 (in that pass we skip calculating the
16039                  * contents of this class), and is /l, or is a POSIX class for
16040                  * which /l doesn't matter (or is a Unicode property, which is
16041                  * skipped here). */
16042                 if (namedclass >= ANYOF_POSIXL_MAX) {  /* If a special class */
16043                     if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
16044
16045                         /* Here, should be \h, \H, \v, or \V.  None of /d, /i
16046                          * nor /l make a difference in what these match,
16047                          * therefore we just add what they match to cp_list. */
16048                         if (classnum != _CC_VERTSPACE) {
16049                             assert(   namedclass == ANYOF_HORIZWS
16050                                    || namedclass == ANYOF_NHORIZWS);
16051
16052                             /* It turns out that \h is just a synonym for
16053                              * XPosixBlank */
16054                             classnum = _CC_BLANK;
16055                         }
16056
16057                         _invlist_union_maybe_complement_2nd(
16058                                 cp_list,
16059                                 PL_XPosix_ptrs[classnum],
16060                                 namedclass % 2 != 0,    /* Complement if odd
16061                                                           (NHORIZWS, NVERTWS)
16062                                                         */
16063                                 &cp_list);
16064                     }
16065                 }
16066                 else if (UNI_SEMANTICS
16067                         || classnum == _CC_ASCII
16068                         || (DEPENDS_SEMANTICS && (classnum == _CC_DIGIT
16069                                                   || classnum == _CC_XDIGIT)))
16070                 {
16071                     /* We usually have to worry about /d and /a affecting what
16072                      * POSIX classes match, with special code needed for /d
16073                      * because we won't know until runtime what all matches.
16074                      * But there is no extra work needed under /u, and
16075                      * [:ascii:] is unaffected by /a and /d; and :digit: and
16076                      * :xdigit: don't have runtime differences under /d.  So we
16077                      * can special case these, and avoid some extra work below,
16078                      * and at runtime. */
16079                     _invlist_union_maybe_complement_2nd(
16080                                                      simple_posixes,
16081                                                      PL_XPosix_ptrs[classnum],
16082                                                      namedclass % 2 != 0,
16083                                                      &simple_posixes);
16084                 }
16085                 else {  /* Garden variety class.  If is NUPPER, NALPHA, ...
16086                            complement and use nposixes */
16087                     SV** posixes_ptr = namedclass % 2 == 0
16088                                        ? &posixes
16089                                        : &nposixes;
16090                     _invlist_union_maybe_complement_2nd(
16091                                                      *posixes_ptr,
16092                                                      PL_XPosix_ptrs[classnum],
16093                                                      namedclass % 2 != 0,
16094                                                      posixes_ptr);
16095                 }
16096             }
16097         } /* end of namedclass \blah */
16098
16099         SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse);
16100
16101         /* If 'range' is set, 'value' is the ending of a range--check its
16102          * validity.  (If value isn't a single code point in the case of a
16103          * range, we should have figured that out above in the code that
16104          * catches false ranges).  Later, we will handle each individual code
16105          * point in the range.  If 'range' isn't set, this could be the
16106          * beginning of a range, so check for that by looking ahead to see if
16107          * the next real character to be processed is the range indicator--the
16108          * minus sign */
16109
16110         if (range) {
16111 #ifdef EBCDIC
16112             /* For unicode ranges, we have to test that the Unicode as opposed
16113              * to the native values are not decreasing.  (Above 255, there is
16114              * no difference between native and Unicode) */
16115             if (unicode_range && prevvalue < 255 && value < 255) {
16116                 if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) {
16117                     goto backwards_range;
16118                 }
16119             }
16120             else
16121 #endif
16122             if (prevvalue > value) /* b-a */ {
16123                 int w;
16124 #ifdef EBCDIC
16125               backwards_range:
16126 #endif
16127                 w = RExC_parse - rangebegin;
16128                 vFAIL2utf8f(
16129                     "Invalid [] range \"%"UTF8f"\"",
16130                     UTF8fARG(UTF, w, rangebegin));
16131                 NOT_REACHED; /* NOTREACHED */
16132             }
16133         }
16134         else {
16135             prevvalue = value; /* save the beginning of the potential range */
16136             if (! stop_at_1     /* Can't be a range if parsing just one thing */
16137                 && *RExC_parse == '-')
16138             {
16139                 char* next_char_ptr = RExC_parse + 1;
16140
16141                 /* Get the next real char after the '-' */
16142                 SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr);
16143
16144                 /* If the '-' is at the end of the class (just before the ']',
16145                  * it is a literal minus; otherwise it is a range */
16146                 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
16147                     RExC_parse = next_char_ptr;
16148
16149                     /* a bad range like \w-, [:word:]- ? */
16150                     if (namedclass > OOB_NAMEDCLASS) {
16151                         if (strict || (PASS2 && ckWARN(WARN_REGEXP))) {
16152                             const int w = RExC_parse >= rangebegin
16153                                           ?  RExC_parse - rangebegin
16154                                           : 0;
16155                             if (strict) {
16156                                 vFAIL4("False [] range \"%*.*s\"",
16157                                     w, w, rangebegin);
16158                             }
16159                             else if (PASS2) {
16160                                 vWARN4(RExC_parse,
16161                                     "False [] range \"%*.*s\"",
16162                                     w, w, rangebegin);
16163                             }
16164                         }
16165                         if (!SIZE_ONLY) {
16166                             cp_list = add_cp_to_invlist(cp_list, '-');
16167                         }
16168                         element_count++;
16169                     } else
16170                         range = 1;      /* yeah, it's a range! */
16171                     continue;   /* but do it the next time */
16172                 }
16173             }
16174         }
16175
16176         if (namedclass > OOB_NAMEDCLASS) {
16177             continue;
16178         }
16179
16180         /* Here, we have a single value this time through the loop, and
16181          * <prevvalue> is the beginning of the range, if any; or <value> if
16182          * not. */
16183
16184         /* non-Latin1 code point implies unicode semantics.  Must be set in
16185          * pass1 so is there for the whole of pass 2 */
16186         if (value > 255) {
16187             REQUIRE_UNI_RULES(flagp, NULL);
16188         }
16189
16190         /* Ready to process either the single value, or the completed range.
16191          * For single-valued non-inverted ranges, we consider the possibility
16192          * of multi-char folds.  (We made a conscious decision to not do this
16193          * for the other cases because it can often lead to non-intuitive
16194          * results.  For example, you have the peculiar case that:
16195          *  "s s" =~ /^[^\xDF]+$/i => Y
16196          *  "ss"  =~ /^[^\xDF]+$/i => N
16197          *
16198          * See [perl #89750] */
16199         if (FOLD && allow_multi_folds && value == prevvalue) {
16200             if (value == LATIN_SMALL_LETTER_SHARP_S
16201                 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
16202                                                         value)))
16203             {
16204                 /* Here <value> is indeed a multi-char fold.  Get what it is */
16205
16206                 U8 foldbuf[UTF8_MAXBYTES_CASE];
16207                 STRLEN foldlen;
16208
16209                 UV folded = _to_uni_fold_flags(
16210                                 value,
16211                                 foldbuf,
16212                                 &foldlen,
16213                                 FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED
16214                                                    ? FOLD_FLAGS_NOMIX_ASCII
16215                                                    : 0)
16216                                 );
16217
16218                 /* Here, <folded> should be the first character of the
16219                  * multi-char fold of <value>, with <foldbuf> containing the
16220                  * whole thing.  But, if this fold is not allowed (because of
16221                  * the flags), <fold> will be the same as <value>, and should
16222                  * be processed like any other character, so skip the special
16223                  * handling */
16224                 if (folded != value) {
16225
16226                     /* Skip if we are recursed, currently parsing the class
16227                      * again.  Otherwise add this character to the list of
16228                      * multi-char folds. */
16229                     if (! RExC_in_multi_char_class) {
16230                         STRLEN cp_count = utf8_length(foldbuf,
16231                                                       foldbuf + foldlen);
16232                         SV* multi_fold = sv_2mortal(newSVpvs(""));
16233
16234                         Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%"UVXf"}", value);
16235
16236                         multi_char_matches
16237                                         = add_multi_match(multi_char_matches,
16238                                                           multi_fold,
16239                                                           cp_count);
16240
16241                     }
16242
16243                     /* This element should not be processed further in this
16244                      * class */
16245                     element_count--;
16246                     value = save_value;
16247                     prevvalue = save_prevvalue;
16248                     continue;
16249                 }
16250             }
16251         }
16252
16253         if (strict && PASS2 && ckWARN(WARN_REGEXP)) {
16254             if (range) {
16255
16256                 /* If the range starts above 255, everything is portable and
16257                  * likely to be so for any forseeable character set, so don't
16258                  * warn. */
16259                 if (unicode_range && non_portable_endpoint && prevvalue < 256) {
16260                     vWARN(RExC_parse, "Both or neither range ends should be Unicode");
16261                 }
16262                 else if (prevvalue != value) {
16263
16264                     /* Under strict, ranges that stop and/or end in an ASCII
16265                      * printable should have each end point be a portable value
16266                      * for it (preferably like 'A', but we don't warn if it is
16267                      * a (portable) Unicode name or code point), and the range
16268                      * must be be all digits or all letters of the same case.
16269                      * Otherwise, the range is non-portable and unclear as to
16270                      * what it contains */
16271                     if ((isPRINT_A(prevvalue) || isPRINT_A(value))
16272                         && (non_portable_endpoint
16273                             || ! ((isDIGIT_A(prevvalue) && isDIGIT_A(value))
16274                                    || (isLOWER_A(prevvalue) && isLOWER_A(value))
16275                                    || (isUPPER_A(prevvalue) && isUPPER_A(value)))))
16276                     {
16277                         vWARN(RExC_parse, "Ranges of ASCII printables should be some subset of \"0-9\", \"A-Z\", or \"a-z\"");
16278                     }
16279                     else if (prevvalue >= 0x660) { /* ARABIC_INDIC_DIGIT_ZERO */
16280
16281                         /* But the nature of Unicode and languages mean we
16282                          * can't do the same checks for above-ASCII ranges,
16283                          * except in the case of digit ones.  These should
16284                          * contain only digits from the same group of 10.  The
16285                          * ASCII case is handled just above.  0x660 is the
16286                          * first digit character beyond ASCII.  Hence here, the
16287                          * range could be a range of digits.  Find out.  */
16288                         IV index_start = _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
16289                                                          prevvalue);
16290                         IV index_final = _invlist_search(PL_XPosix_ptrs[_CC_DIGIT],
16291                                                          value);
16292
16293                         /* If the range start and final points are in the same
16294                          * inversion list element, it means that either both
16295                          * are not digits, or both are digits in a consecutive
16296                          * sequence of digits.  (So far, Unicode has kept all
16297                          * such sequences as distinct groups of 10, but assert
16298                          * to make sure).  If the end points are not in the
16299                          * same element, neither should be a digit. */
16300                         if (index_start == index_final) {
16301                             assert(! ELEMENT_RANGE_MATCHES_INVLIST(index_start)
16302                             || (invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start+1]
16303                                - invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start]
16304                                == 10)
16305                                /* But actually Unicode did have one group of 11
16306                                 * 'digits' in 5.2, so in case we are operating
16307                                 * on that version, let that pass */
16308                             || (invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start+1]
16309                                - invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start]
16310                                 == 11
16311                                && invlist_array(PL_XPosix_ptrs[_CC_DIGIT])[index_start]
16312                                 == 0x19D0)
16313                             );
16314                         }
16315                         else if ((index_start >= 0
16316                                   && ELEMENT_RANGE_MATCHES_INVLIST(index_start))
16317                                  || (index_final >= 0
16318                                      && ELEMENT_RANGE_MATCHES_INVLIST(index_final)))
16319                         {
16320                             vWARN(RExC_parse, "Ranges of digits should be from the same group of 10");
16321                         }
16322                     }
16323                 }
16324             }
16325             if ((! range || prevvalue == value) && non_portable_endpoint) {
16326                 if (isPRINT_A(value)) {
16327                     char literal[3];
16328                     unsigned d = 0;
16329                     if (isBACKSLASHED_PUNCT(value)) {
16330                         literal[d++] = '\\';
16331                     }
16332                     literal[d++] = (char) value;
16333                     literal[d++] = '\0';
16334
16335                     vWARN4(RExC_parse,
16336                            "\"%.*s\" is more clearly written simply as \"%s\"",
16337                            (int) (RExC_parse - rangebegin),
16338                            rangebegin,
16339                            literal
16340                         );
16341                 }
16342                 else if isMNEMONIC_CNTRL(value) {
16343                     vWARN4(RExC_parse,
16344                            "\"%.*s\" is more clearly written simply as \"%s\"",
16345                            (int) (RExC_parse - rangebegin),
16346                            rangebegin,
16347                            cntrl_to_mnemonic((char) value)
16348                         );
16349                 }
16350             }
16351         }
16352
16353         /* Deal with this element of the class */
16354         if (! SIZE_ONLY) {
16355
16356 #ifndef EBCDIC
16357             cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
16358                                                      prevvalue, value);
16359 #else
16360             /* On non-ASCII platforms, for ranges that span all of 0..255, and
16361              * ones that don't require special handling, we can just add the
16362              * range like we do for ASCII platforms */
16363             if ((UNLIKELY(prevvalue == 0) && value >= 255)
16364                 || ! (prevvalue < 256
16365                       && (unicode_range
16366                           || (! non_portable_endpoint
16367                               && ((isLOWER_A(prevvalue) && isLOWER_A(value))
16368                                   || (isUPPER_A(prevvalue)
16369                                       && isUPPER_A(value)))))))
16370             {
16371                 cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
16372                                                          prevvalue, value);
16373             }
16374             else {
16375                 /* Here, requires special handling.  This can be because it is
16376                  * a range whose code points are considered to be Unicode, and
16377                  * so must be individually translated into native, or because
16378                  * its a subrange of 'A-Z' or 'a-z' which each aren't
16379                  * contiguous in EBCDIC, but we have defined them to include
16380                  * only the "expected" upper or lower case ASCII alphabetics.
16381                  * Subranges above 255 are the same in native and Unicode, so
16382                  * can be added as a range */
16383                 U8 start = NATIVE_TO_LATIN1(prevvalue);
16384                 unsigned j;
16385                 U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255;
16386                 for (j = start; j <= end; j++) {
16387                     cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j));
16388                 }
16389                 if (value > 255) {
16390                     cp_foldable_list = _add_range_to_invlist(cp_foldable_list,
16391                                                              256, value);
16392                 }
16393             }
16394 #endif
16395         }
16396
16397         range = 0; /* this range (if it was one) is done now */
16398     } /* End of loop through all the text within the brackets */
16399
16400     /* If anything in the class expands to more than one character, we have to
16401      * deal with them by building up a substitute parse string, and recursively
16402      * calling reg() on it, instead of proceeding */
16403     if (multi_char_matches) {
16404         SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
16405         I32 cp_count;
16406         STRLEN len;
16407         char *save_end = RExC_end;
16408         char *save_parse = RExC_parse;
16409         char *save_start = RExC_start;
16410         STRLEN prefix_end = 0;      /* We copy the character class after a
16411                                        prefix supplied here.  This is the size
16412                                        + 1 of that prefix */
16413         bool first_time = TRUE;     /* First multi-char occurrence doesn't get
16414                                        a "|" */
16415         I32 reg_flags;
16416
16417         assert(! invert);
16418         assert(RExC_precomp_adj == 0); /* Only one level of recursion allowed */
16419
16420 #if 0   /* Have decided not to deal with multi-char folds in inverted classes,
16421            because too confusing */
16422         if (invert) {
16423             sv_catpv(substitute_parse, "(?:");
16424         }
16425 #endif
16426
16427         /* Look at the longest folds first */
16428         for (cp_count = av_tindex(multi_char_matches); cp_count > 0; cp_count--) {
16429
16430             if (av_exists(multi_char_matches, cp_count)) {
16431                 AV** this_array_ptr;
16432                 SV* this_sequence;
16433
16434                 this_array_ptr = (AV**) av_fetch(multi_char_matches,
16435                                                  cp_count, FALSE);
16436                 while ((this_sequence = av_pop(*this_array_ptr)) !=
16437                                                                 &PL_sv_undef)
16438                 {
16439                     if (! first_time) {
16440                         sv_catpv(substitute_parse, "|");
16441                     }
16442                     first_time = FALSE;
16443
16444                     sv_catpv(substitute_parse, SvPVX(this_sequence));
16445                 }
16446             }
16447         }
16448
16449         /* If the character class contains anything else besides these
16450          * multi-character folds, have to include it in recursive parsing */
16451         if (element_count) {
16452             sv_catpv(substitute_parse, "|[");
16453             prefix_end = SvCUR(substitute_parse);
16454             sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
16455
16456             /* Put in a closing ']' only if not going off the end, as otherwise
16457              * we are adding something that really isn't there */
16458             if (RExC_parse < RExC_end) {
16459                 sv_catpv(substitute_parse, "]");
16460             }
16461         }
16462
16463         sv_catpv(substitute_parse, ")");
16464 #if 0
16465         if (invert) {
16466             /* This is a way to get the parse to skip forward a whole named
16467              * sequence instead of matching the 2nd character when it fails the
16468              * first */
16469             sv_catpv(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
16470         }
16471 #endif
16472
16473         /* Set up the data structure so that any errors will be properly
16474          * reported.  See the comments at the definition of
16475          * REPORT_LOCATION_ARGS for details */
16476         RExC_precomp_adj = orig_parse - RExC_precomp;
16477         RExC_start =  RExC_parse = SvPV(substitute_parse, len);
16478         RExC_adjusted_start = RExC_start + prefix_end;
16479         RExC_end = RExC_parse + len;
16480         RExC_in_multi_char_class = 1;
16481         RExC_override_recoding = 1;
16482         RExC_emit = (regnode *)orig_emit;
16483
16484         ret = reg(pRExC_state, 1, &reg_flags, depth+1);
16485
16486         *flagp |= reg_flags&(HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PASS1|NEED_UTF8);
16487
16488         /* And restore so can parse the rest of the pattern */
16489         RExC_parse = save_parse;
16490         RExC_start = RExC_adjusted_start = save_start;
16491         RExC_precomp_adj = 0;
16492         RExC_end = save_end;
16493         RExC_in_multi_char_class = 0;
16494         RExC_override_recoding = 0;
16495         SvREFCNT_dec_NN(multi_char_matches);
16496         return ret;
16497     }
16498
16499     /* Here, we've gone through the entire class and dealt with multi-char
16500      * folds.  We are now in a position that we can do some checks to see if we
16501      * can optimize this ANYOF node into a simpler one, even in Pass 1.
16502      * Currently we only do two checks:
16503      * 1) is in the unlikely event that the user has specified both, eg. \w and
16504      *    \W under /l, then the class matches everything.  (This optimization
16505      *    is done only to make the optimizer code run later work.)
16506      * 2) if the character class contains only a single element (including a
16507      *    single range), we see if there is an equivalent node for it.
16508      * Other checks are possible */
16509     if (   optimizable
16510         && ! ret_invlist   /* Can't optimize if returning the constructed
16511                               inversion list */
16512         && (UNLIKELY(posixl_matches_all) || element_count == 1))
16513     {
16514         U8 op = END;
16515         U8 arg = 0;
16516
16517         if (UNLIKELY(posixl_matches_all)) {
16518             op = SANY;
16519         }
16520         else if (namedclass > OOB_NAMEDCLASS) { /* this is a single named
16521                                                    class, like \w or [:digit:]
16522                                                    or \p{foo} */
16523
16524             /* All named classes are mapped into POSIXish nodes, with its FLAG
16525              * argument giving which class it is */
16526             switch ((I32)namedclass) {
16527                 case ANYOF_UNIPROP:
16528                     break;
16529
16530                 /* These don't depend on the charset modifiers.  They always
16531                  * match under /u rules */
16532                 case ANYOF_NHORIZWS:
16533                 case ANYOF_HORIZWS:
16534                     namedclass = ANYOF_BLANK + namedclass - ANYOF_HORIZWS;
16535                     /* FALLTHROUGH */
16536
16537                 case ANYOF_NVERTWS:
16538                 case ANYOF_VERTWS:
16539                     op = POSIXU;
16540                     goto join_posix;
16541
16542                 /* The actual POSIXish node for all the rest depends on the
16543                  * charset modifier.  The ones in the first set depend only on
16544                  * ASCII or, if available on this platform, also locale */
16545                 case ANYOF_ASCII:
16546                 case ANYOF_NASCII:
16547 #ifdef HAS_ISASCII
16548                     op = (LOC) ? POSIXL : POSIXA;
16549 #else
16550                     op = POSIXA;
16551 #endif
16552                     goto join_posix;
16553
16554                 /* The following don't have any matches in the upper Latin1
16555                  * range, hence /d is equivalent to /u for them.  Making it /u
16556                  * saves some branches at runtime */
16557                 case ANYOF_DIGIT:
16558                 case ANYOF_NDIGIT:
16559                 case ANYOF_XDIGIT:
16560                 case ANYOF_NXDIGIT:
16561                     if (! DEPENDS_SEMANTICS) {
16562                         goto treat_as_default;
16563                     }
16564
16565                     op = POSIXU;
16566                     goto join_posix;
16567
16568                 /* The following change to CASED under /i */
16569                 case ANYOF_LOWER:
16570                 case ANYOF_NLOWER:
16571                 case ANYOF_UPPER:
16572                 case ANYOF_NUPPER:
16573                     if (FOLD) {
16574                         namedclass = ANYOF_CASED + (namedclass % 2);
16575                     }
16576                     /* FALLTHROUGH */
16577
16578                 /* The rest have more possibilities depending on the charset.
16579                  * We take advantage of the enum ordering of the charset
16580                  * modifiers to get the exact node type, */
16581                 default:
16582                   treat_as_default:
16583                     op = POSIXD + get_regex_charset(RExC_flags);
16584                     if (op > POSIXA) { /* /aa is same as /a */
16585                         op = POSIXA;
16586                     }
16587
16588                   join_posix:
16589                     /* The odd numbered ones are the complements of the
16590                      * next-lower even number one */
16591                     if (namedclass % 2 == 1) {
16592                         invert = ! invert;
16593                         namedclass--;
16594                     }
16595                     arg = namedclass_to_classnum(namedclass);
16596                     break;
16597             }
16598         }
16599         else if (value == prevvalue) {
16600
16601             /* Here, the class consists of just a single code point */
16602
16603             if (invert) {
16604                 if (! LOC && value == '\n') {
16605                     op = REG_ANY; /* Optimize [^\n] */
16606                     *flagp |= HASWIDTH|SIMPLE;
16607                     MARK_NAUGHTY(1);
16608                 }
16609             }
16610             else if (value < 256 || UTF) {
16611
16612                 /* Optimize a single value into an EXACTish node, but not if it
16613                  * would require converting the pattern to UTF-8. */
16614                 op = compute_EXACTish(pRExC_state);
16615             }
16616         } /* Otherwise is a range */
16617         else if (! LOC) {   /* locale could vary these */
16618             if (prevvalue == '0') {
16619                 if (value == '9') {
16620                     arg = _CC_DIGIT;
16621                     op = POSIXA;
16622                 }
16623             }
16624             else if (! FOLD || ASCII_FOLD_RESTRICTED) {
16625                 /* We can optimize A-Z or a-z, but not if they could match
16626                  * something like the KELVIN SIGN under /i. */
16627                 if (prevvalue == 'A') {
16628                     if (value == 'Z'
16629 #ifdef EBCDIC
16630                         && ! non_portable_endpoint
16631 #endif
16632                     ) {
16633                         arg = (FOLD) ? _CC_ALPHA : _CC_UPPER;
16634                         op = POSIXA;
16635                     }
16636                 }
16637                 else if (prevvalue == 'a') {
16638                     if (value == 'z'
16639 #ifdef EBCDIC
16640                         && ! non_portable_endpoint
16641 #endif
16642                     ) {
16643                         arg = (FOLD) ? _CC_ALPHA : _CC_LOWER;
16644                         op = POSIXA;
16645                     }
16646                 }
16647             }
16648         }
16649
16650         /* Here, we have changed <op> away from its initial value iff we found
16651          * an optimization */
16652         if (op != END) {
16653
16654             /* Throw away this ANYOF regnode, and emit the calculated one,
16655              * which should correspond to the beginning, not current, state of
16656              * the parse */
16657             const char * cur_parse = RExC_parse;
16658             RExC_parse = (char *)orig_parse;
16659             if ( SIZE_ONLY) {
16660                 if (! LOC) {
16661
16662                     /* To get locale nodes to not use the full ANYOF size would
16663                      * require moving the code above that writes the portions
16664                      * of it that aren't in other nodes to after this point.
16665                      * e.g.  ANYOF_POSIXL_SET */
16666                     RExC_size = orig_size;
16667                 }
16668             }
16669             else {
16670                 RExC_emit = (regnode *)orig_emit;
16671                 if (PL_regkind[op] == POSIXD) {
16672                     if (op == POSIXL) {
16673                         RExC_contains_locale = 1;
16674                     }
16675                     if (invert) {
16676                         op += NPOSIXD - POSIXD;
16677                     }
16678                 }
16679             }
16680
16681             ret = reg_node(pRExC_state, op);
16682
16683             if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
16684                 if (! SIZE_ONLY) {
16685                     FLAGS(ret) = arg;
16686                 }
16687                 *flagp |= HASWIDTH|SIMPLE;
16688             }
16689             else if (PL_regkind[op] == EXACT) {
16690                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value,
16691                                            TRUE /* downgradable to EXACT */
16692                                            );
16693             }
16694
16695             RExC_parse = (char *) cur_parse;
16696
16697             SvREFCNT_dec(posixes);
16698             SvREFCNT_dec(nposixes);
16699             SvREFCNT_dec(simple_posixes);
16700             SvREFCNT_dec(cp_list);
16701             SvREFCNT_dec(cp_foldable_list);
16702             return ret;
16703         }
16704     }
16705
16706     if (SIZE_ONLY)
16707         return ret;
16708     /****** !SIZE_ONLY (Pass 2) AFTER HERE *********/
16709
16710     /* If folding, we calculate all characters that could fold to or from the
16711      * ones already on the list */
16712     if (cp_foldable_list) {
16713         if (FOLD) {
16714             UV start, end;      /* End points of code point ranges */
16715
16716             SV* fold_intersection = NULL;
16717             SV** use_list;
16718
16719             /* Our calculated list will be for Unicode rules.  For locale
16720              * matching, we have to keep a separate list that is consulted at
16721              * runtime only when the locale indicates Unicode rules.  For
16722              * non-locale, we just use the general list */
16723             if (LOC) {
16724                 use_list = &only_utf8_locale_list;
16725             }
16726             else {
16727                 use_list = &cp_list;
16728             }
16729
16730             /* Only the characters in this class that participate in folds need
16731              * be checked.  Get the intersection of this class and all the
16732              * possible characters that are foldable.  This can quickly narrow
16733              * down a large class */
16734             _invlist_intersection(PL_utf8_foldable, cp_foldable_list,
16735                                   &fold_intersection);
16736
16737             /* The folds for all the Latin1 characters are hard-coded into this
16738              * program, but we have to go out to disk to get the others. */
16739             if (invlist_highest(cp_foldable_list) >= 256) {
16740
16741                 /* This is a hash that for a particular fold gives all
16742                  * characters that are involved in it */
16743                 if (! PL_utf8_foldclosures) {
16744                     _load_PL_utf8_foldclosures();
16745                 }
16746             }
16747
16748             /* Now look at the foldable characters in this class individually */
16749             invlist_iterinit(fold_intersection);
16750             while (invlist_iternext(fold_intersection, &start, &end)) {
16751                 UV j;
16752
16753                 /* Look at every character in the range */
16754                 for (j = start; j <= end; j++) {
16755                     U8 foldbuf[UTF8_MAXBYTES_CASE+1];
16756                     STRLEN foldlen;
16757                     SV** listp;
16758
16759                     if (j < 256) {
16760
16761                         if (IS_IN_SOME_FOLD_L1(j)) {
16762
16763                             /* ASCII is always matched; non-ASCII is matched
16764                              * only under Unicode rules (which could happen
16765                              * under /l if the locale is a UTF-8 one */
16766                             if (isASCII(j) || ! DEPENDS_SEMANTICS) {
16767                                 *use_list = add_cp_to_invlist(*use_list,
16768                                                             PL_fold_latin1[j]);
16769                             }
16770                             else {
16771                                 has_upper_latin1_only_utf8_matches
16772                                     = add_cp_to_invlist(
16773                                             has_upper_latin1_only_utf8_matches,
16774                                             PL_fold_latin1[j]);
16775                             }
16776                         }
16777
16778                         if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j)
16779                             && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
16780                         {
16781                             add_above_Latin1_folds(pRExC_state,
16782                                                    (U8) j,
16783                                                    use_list);
16784                         }
16785                         continue;
16786                     }
16787
16788                     /* Here is an above Latin1 character.  We don't have the
16789                      * rules hard-coded for it.  First, get its fold.  This is
16790                      * the simple fold, as the multi-character folds have been
16791                      * handled earlier and separated out */
16792                     _to_uni_fold_flags(j, foldbuf, &foldlen,
16793                                                         (ASCII_FOLD_RESTRICTED)
16794                                                         ? FOLD_FLAGS_NOMIX_ASCII
16795                                                         : 0);
16796
16797                     /* Single character fold of above Latin1.  Add everything in
16798                     * its fold closure to the list that this node should match.
16799                     * The fold closures data structure is a hash with the keys
16800                     * being the UTF-8 of every character that is folded to, like
16801                     * 'k', and the values each an array of all code points that
16802                     * fold to its key.  e.g. [ 'k', 'K', KELVIN_SIGN ].
16803                     * Multi-character folds are not included */
16804                     if ((listp = hv_fetch(PL_utf8_foldclosures,
16805                                         (char *) foldbuf, foldlen, FALSE)))
16806                     {
16807                         AV* list = (AV*) *listp;
16808                         IV k;
16809                         for (k = 0; k <= av_tindex(list); k++) {
16810                             SV** c_p = av_fetch(list, k, FALSE);
16811                             UV c;
16812                             assert(c_p);
16813
16814                             c = SvUV(*c_p);
16815
16816                             /* /aa doesn't allow folds between ASCII and non- */
16817                             if ((ASCII_FOLD_RESTRICTED
16818                                 && (isASCII(c) != isASCII(j))))
16819                             {
16820                                 continue;
16821                             }
16822
16823                             /* Folds under /l which cross the 255/256 boundary
16824                              * are added to a separate list.  (These are valid
16825                              * only when the locale is UTF-8.) */
16826                             if (c < 256 && LOC) {
16827                                 *use_list = add_cp_to_invlist(*use_list, c);
16828                                 continue;
16829                             }
16830
16831                             if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
16832                             {
16833                                 cp_list = add_cp_to_invlist(cp_list, c);
16834                             }
16835                             else {
16836                                 /* Similarly folds involving non-ascii Latin1
16837                                 * characters under /d are added to their list */
16838                                 has_upper_latin1_only_utf8_matches
16839                                         = add_cp_to_invlist(
16840                                            has_upper_latin1_only_utf8_matches,
16841                                            c);
16842                             }
16843                         }
16844                     }
16845                 }
16846             }
16847             SvREFCNT_dec_NN(fold_intersection);
16848         }
16849
16850         /* Now that we have finished adding all the folds, there is no reason
16851          * to keep the foldable list separate */
16852         _invlist_union(cp_list, cp_foldable_list, &cp_list);
16853         SvREFCNT_dec_NN(cp_foldable_list);
16854     }
16855
16856     /* And combine the result (if any) with any inversion list from posix
16857      * classes.  The lists are kept separate up to now because we don't want to
16858      * fold the classes (folding of those is automatically handled by the swash
16859      * fetching code) */
16860     if (simple_posixes) {
16861         _invlist_union(cp_list, simple_posixes, &cp_list);
16862         SvREFCNT_dec_NN(simple_posixes);
16863     }
16864     if (posixes || nposixes) {
16865         if (posixes && AT_LEAST_ASCII_RESTRICTED) {
16866             /* Under /a and /aa, nothing above ASCII matches these */
16867             _invlist_intersection(posixes,
16868                                   PL_XPosix_ptrs[_CC_ASCII],
16869                                   &posixes);
16870         }
16871         if (nposixes) {
16872             if (DEPENDS_SEMANTICS) {
16873                 /* Under /d, everything in the upper half of the Latin1 range
16874                  * matches these complements */
16875                 ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
16876             }
16877             else if (AT_LEAST_ASCII_RESTRICTED) {
16878                 /* Under /a and /aa, everything above ASCII matches these
16879                  * complements */
16880                 _invlist_union_complement_2nd(nposixes,
16881                                               PL_XPosix_ptrs[_CC_ASCII],
16882                                               &nposixes);
16883             }
16884             if (posixes) {
16885                 _invlist_union(posixes, nposixes, &posixes);
16886                 SvREFCNT_dec_NN(nposixes);
16887             }
16888             else {
16889                 posixes = nposixes;
16890             }
16891         }
16892         if (! DEPENDS_SEMANTICS) {
16893             if (cp_list) {
16894                 _invlist_union(cp_list, posixes, &cp_list);
16895                 SvREFCNT_dec_NN(posixes);
16896             }
16897             else {
16898                 cp_list = posixes;
16899             }
16900         }
16901         else {
16902             /* Under /d, we put into a separate list the Latin1 things that
16903              * match only when the target string is utf8 */
16904             SV* nonascii_but_latin1_properties = NULL;
16905             _invlist_intersection(posixes, PL_UpperLatin1,
16906                                   &nonascii_but_latin1_properties);
16907             _invlist_subtract(posixes, nonascii_but_latin1_properties,
16908                               &posixes);
16909             if (cp_list) {
16910                 _invlist_union(cp_list, posixes, &cp_list);
16911                 SvREFCNT_dec_NN(posixes);
16912             }
16913             else {
16914                 cp_list = posixes;
16915             }
16916
16917             if (has_upper_latin1_only_utf8_matches) {
16918                 _invlist_union(has_upper_latin1_only_utf8_matches,
16919                                nonascii_but_latin1_properties,
16920                                &has_upper_latin1_only_utf8_matches);
16921                 SvREFCNT_dec_NN(nonascii_but_latin1_properties);
16922             }
16923             else {
16924                 has_upper_latin1_only_utf8_matches
16925                                             = nonascii_but_latin1_properties;
16926             }
16927         }
16928     }
16929
16930     /* And combine the result (if any) with any inversion list from properties.
16931      * The lists are kept separate up to now so that we can distinguish the two
16932      * in regards to matching above-Unicode.  A run-time warning is generated
16933      * if a Unicode property is matched against a non-Unicode code point. But,
16934      * we allow user-defined properties to match anything, without any warning,
16935      * and we also suppress the warning if there is a portion of the character
16936      * class that isn't a Unicode property, and which matches above Unicode, \W
16937      * or [\x{110000}] for example.
16938      * (Note that in this case, unlike the Posix one above, there is no
16939      * <has_upper_latin1_only_utf8_matches>, because having a Unicode property
16940      * forces Unicode semantics */
16941     if (properties) {
16942         if (cp_list) {
16943
16944             /* If it matters to the final outcome, see if a non-property
16945              * component of the class matches above Unicode.  If so, the
16946              * warning gets suppressed.  This is true even if just a single
16947              * such code point is specified, as, though not strictly correct if
16948              * another such code point is matched against, the fact that they
16949              * are using above-Unicode code points indicates they should know
16950              * the issues involved */
16951             if (warn_super) {
16952                 warn_super = ! (invert
16953                                ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX));
16954             }
16955
16956             _invlist_union(properties, cp_list, &cp_list);
16957             SvREFCNT_dec_NN(properties);
16958         }
16959         else {
16960             cp_list = properties;
16961         }
16962
16963         if (warn_super) {
16964             ANYOF_FLAGS(ret)
16965              |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
16966
16967             /* Because an ANYOF node is the only one that warns, this node
16968              * can't be optimized into something else */
16969             optimizable = FALSE;
16970         }
16971     }
16972
16973     /* Here, we have calculated what code points should be in the character
16974      * class.
16975      *
16976      * Now we can see about various optimizations.  Fold calculation (which we
16977      * did above) needs to take place before inversion.  Otherwise /[^k]/i
16978      * would invert to include K, which under /i would match k, which it
16979      * shouldn't.  Therefore we can't invert folded locale now, as it won't be
16980      * folded until runtime */
16981
16982     /* If we didn't do folding, it's because some information isn't available
16983      * until runtime; set the run-time fold flag for these.  (We don't have to
16984      * worry about properties folding, as that is taken care of by the swash
16985      * fetching).  We know to set the flag if we have a non-NULL list for UTF-8
16986      * locales, or the class matches at least one 0-255 range code point */
16987     if (LOC && FOLD) {
16988         if (only_utf8_locale_list) {
16989             ANYOF_FLAGS(ret)
16990                  |=  ANYOFL_FOLD
16991                     |ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD;
16992         }
16993         else if (cp_list) { /* Look to see if a 0-255 code point is in list */
16994             UV start, end;
16995             invlist_iterinit(cp_list);
16996             if (invlist_iternext(cp_list, &start, &end) && start < 256) {
16997                 ANYOF_FLAGS(ret) |= ANYOFL_FOLD;
16998             }
16999             invlist_iterfinish(cp_list);
17000         }
17001     }
17002
17003 #define MATCHES_ALL_NON_UTF8_NON_ASCII(ret)                                 \
17004     (   DEPENDS_SEMANTICS                                                   \
17005      && (ANYOF_FLAGS(ret)                                                   \
17006         & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
17007
17008     /* See if we can simplify things under /d */
17009     if (   has_upper_latin1_only_utf8_matches
17010         || MATCHES_ALL_NON_UTF8_NON_ASCII(ret))
17011     {
17012         if (has_upper_latin1_only_utf8_matches) {
17013             if (MATCHES_ALL_NON_UTF8_NON_ASCII(ret)) {
17014
17015                 /* Here, we have both the flag and inversion list.  Any character in
17016                  * 'has_upper_latin1_only_utf8_matches' matches when UTF-8 is
17017                  * in effect, but it also matches when UTF-8 is not in effect
17018                  * because of MATCHES_ALL_NON_UTF8_NON_ASCII.  Therefore it
17019                  * matches unconditionally, so can be added to the regular
17020                  * list, and 'has_upper_latin1_only_utf8_matches' cleared */
17021                 _invlist_union(cp_list,
17022                                has_upper_latin1_only_utf8_matches,
17023                                &cp_list);
17024                 SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17025                 has_upper_latin1_only_utf8_matches = NULL;
17026             }
17027             else if (cp_list) {
17028
17029                 /* Here, 'cp_list' gives chars that always match, and
17030                  * 'has_upper_latin1_only_utf8_matches' gives chars that were
17031                  * specified to match only if the target string is in UTF-8.
17032                  * It may be that these overlap, so we can subtract the
17033                  * unconditionally matching from the conditional ones, to make
17034                  * the conditional list as small as possible, perhaps even
17035                  * clearing it, in which case more optimizations are possible
17036                  * later */
17037                 _invlist_subtract(has_upper_latin1_only_utf8_matches,
17038                                   cp_list,
17039                                   &has_upper_latin1_only_utf8_matches);
17040                 if (_invlist_len(has_upper_latin1_only_utf8_matches) == 0) {
17041                     SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17042                     has_upper_latin1_only_utf8_matches = NULL;
17043                 }
17044             }
17045         }
17046
17047         /* Similarly, if the unconditional matches include every upper latin1
17048          * character, we can clear that flag to permit later optimizations */
17049         if (cp_list && MATCHES_ALL_NON_UTF8_NON_ASCII(ret)) {
17050             SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1);
17051             _invlist_subtract(only_non_utf8_list, cp_list, &only_non_utf8_list);
17052             if (_invlist_len(only_non_utf8_list) == 0) {
17053                 ANYOF_FLAGS(ret) &= ~ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER;
17054             }
17055             SvREFCNT_dec_NN(only_non_utf8_list);
17056             only_non_utf8_list = NULL;;
17057         }
17058
17059         /* If we haven't gotten rid of all conditional matching, we change the
17060          * regnode type to indicate that */
17061         if (   has_upper_latin1_only_utf8_matches
17062             || MATCHES_ALL_NON_UTF8_NON_ASCII(ret))
17063         {
17064             OP(ret) = ANYOFD;
17065             optimizable = FALSE;
17066         }
17067     }
17068 #undef MATCHES_ALL_NON_UTF8_NON_ASCII
17069
17070     /* Optimize inverted simple patterns (e.g. [^a-z]) when everything is known
17071      * at compile time.  Besides not inverting folded locale now, we can't
17072      * invert if there are things such as \w, which aren't known until runtime
17073      * */
17074     if (cp_list
17075         && invert
17076         && OP(ret) != ANYOFD
17077         && ! (ANYOF_FLAGS(ret) & (ANYOF_LOCALE_FLAGS))
17078         && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
17079     {
17080         _invlist_invert(cp_list);
17081
17082         /* Any swash can't be used as-is, because we've inverted things */
17083         if (swash) {
17084             SvREFCNT_dec_NN(swash);
17085             swash = NULL;
17086         }
17087
17088         /* Clear the invert flag since have just done it here */
17089         invert = FALSE;
17090     }
17091
17092     if (ret_invlist) {
17093         assert(cp_list);
17094
17095         *ret_invlist = cp_list;
17096         SvREFCNT_dec(swash);
17097
17098         /* Discard the generated node */
17099         if (SIZE_ONLY) {
17100             RExC_size = orig_size;
17101         }
17102         else {
17103             RExC_emit = orig_emit;
17104         }
17105         return orig_emit;
17106     }
17107
17108     /* Some character classes are equivalent to other nodes.  Such nodes take
17109      * up less room and generally fewer operations to execute than ANYOF nodes.
17110      * Above, we checked for and optimized into some such equivalents for
17111      * certain common classes that are easy to test.  Getting to this point in
17112      * the code means that the class didn't get optimized there.  Since this
17113      * code is only executed in Pass 2, it is too late to save space--it has
17114      * been allocated in Pass 1, and currently isn't given back.  But turning
17115      * things into an EXACTish node can allow the optimizer to join it to any
17116      * adjacent such nodes.  And if the class is equivalent to things like /./,
17117      * expensive run-time swashes can be avoided.  Now that we have more
17118      * complete information, we can find things necessarily missed by the
17119      * earlier code.  Another possible "optimization" that isn't done is that
17120      * something like [Ee] could be changed into an EXACTFU.  khw tried this
17121      * and found that the ANYOF is faster, including for code points not in the
17122      * bitmap.  This still might make sense to do, provided it got joined with
17123      * an adjacent node(s) to create a longer EXACTFU one.  This could be
17124      * accomplished by creating a pseudo ANYOF_EXACTFU node type that the join
17125      * routine would know is joinable.  If that didn't happen, the node type
17126      * could then be made a straight ANYOF */
17127
17128     if (optimizable && cp_list && ! invert) {
17129         UV start, end;
17130         U8 op = END;  /* The optimzation node-type */
17131         int posix_class = -1;   /* Illegal value */
17132         const char * cur_parse= RExC_parse;
17133
17134         invlist_iterinit(cp_list);
17135         if (! invlist_iternext(cp_list, &start, &end)) {
17136
17137             /* Here, the list is empty.  This happens, for example, when a
17138              * Unicode property that doesn't match anything is the only element
17139              * in the character class (perluniprops.pod notes such properties).
17140              * */
17141             op = OPFAIL;
17142             *flagp |= HASWIDTH|SIMPLE;
17143         }
17144         else if (start == end) {    /* The range is a single code point */
17145             if (! invlist_iternext(cp_list, &start, &end)
17146
17147                     /* Don't do this optimization if it would require changing
17148                      * the pattern to UTF-8 */
17149                 && (start < 256 || UTF))
17150             {
17151                 /* Here, the list contains a single code point.  Can optimize
17152                  * into an EXACTish node */
17153
17154                 value = start;
17155
17156                 if (! FOLD) {
17157                     op = (LOC)
17158                          ? EXACTL
17159                          : EXACT;
17160                 }
17161                 else if (LOC) {
17162
17163                     /* A locale node under folding with one code point can be
17164                      * an EXACTFL, as its fold won't be calculated until
17165                      * runtime */
17166                     op = EXACTFL;
17167                 }
17168                 else {
17169
17170                     /* Here, we are generally folding, but there is only one
17171                      * code point to match.  If we have to, we use an EXACT
17172                      * node, but it would be better for joining with adjacent
17173                      * nodes in the optimization pass if we used the same
17174                      * EXACTFish node that any such are likely to be.  We can
17175                      * do this iff the code point doesn't participate in any
17176                      * folds.  For example, an EXACTF of a colon is the same as
17177                      * an EXACT one, since nothing folds to or from a colon. */
17178                     if (value < 256) {
17179                         if (IS_IN_SOME_FOLD_L1(value)) {
17180                             op = EXACT;
17181                         }
17182                     }
17183                     else {
17184                         if (_invlist_contains_cp(PL_utf8_foldable, value)) {
17185                             op = EXACT;
17186                         }
17187                     }
17188
17189                     /* If we haven't found the node type, above, it means we
17190                      * can use the prevailing one */
17191                     if (op == END) {
17192                         op = compute_EXACTish(pRExC_state);
17193                     }
17194                 }
17195             }
17196         }   /* End of first range contains just a single code point */
17197         else if (start == 0) {
17198             if (end == UV_MAX) {
17199                 op = SANY;
17200                 *flagp |= HASWIDTH|SIMPLE;
17201                 MARK_NAUGHTY(1);
17202             }
17203             else if (end == '\n' - 1
17204                     && invlist_iternext(cp_list, &start, &end)
17205                     && start == '\n' + 1 && end == UV_MAX)
17206             {
17207                 op = REG_ANY;
17208                 *flagp |= HASWIDTH|SIMPLE;
17209                 MARK_NAUGHTY(1);
17210             }
17211         }
17212         invlist_iterfinish(cp_list);
17213
17214         if (op == END) {
17215             const UV cp_list_len = _invlist_len(cp_list);
17216             const UV* cp_list_array = invlist_array(cp_list);
17217
17218             /* Here, didn't find an optimization.  See if this matches any of
17219              * the POSIX classes.  These run slightly faster for above-Unicode
17220              * code points, so don't bother with POSIXA ones nor the 2 that
17221              * have no above-Unicode matches.  We can avoid these checks unless
17222              * the ANYOF matches at least as high as the lowest POSIX one
17223              * (which was manually found to be \v.  The actual code point may
17224              * increase in later Unicode releases, if a higher code point is
17225              * assigned to be \v, but this code will never break.  It would
17226              * just mean we could execute the checks for posix optimizations
17227              * unnecessarily) */
17228
17229             if (cp_list_array[cp_list_len-1] > 0x2029) {
17230                 for (posix_class = 0;
17231                      posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC;
17232                      posix_class++)
17233                 {
17234                     int try_inverted;
17235                     if (posix_class == _CC_ASCII || posix_class == _CC_CNTRL) {
17236                         continue;
17237                     }
17238                     for (try_inverted = 0; try_inverted < 2; try_inverted++) {
17239
17240                         /* Check if matches normal or inverted */
17241                         if (_invlistEQ(cp_list,
17242                                        PL_XPosix_ptrs[posix_class],
17243                                        try_inverted))
17244                         {
17245                             op = (try_inverted)
17246                                  ? NPOSIXU
17247                                  : POSIXU;
17248                             *flagp |= HASWIDTH|SIMPLE;
17249                             goto found_posix;
17250                         }
17251                     }
17252                 }
17253               found_posix: ;
17254             }
17255         }
17256
17257         if (op != END) {
17258             RExC_parse = (char *)orig_parse;
17259             RExC_emit = (regnode *)orig_emit;
17260
17261             if (regarglen[op]) {
17262                 ret = reganode(pRExC_state, op, 0);
17263             } else {
17264                 ret = reg_node(pRExC_state, op);
17265             }
17266
17267             RExC_parse = (char *)cur_parse;
17268
17269             if (PL_regkind[op] == EXACT) {
17270                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value,
17271                                            TRUE /* downgradable to EXACT */
17272                                           );
17273             }
17274             else if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
17275                 FLAGS(ret) = posix_class;
17276             }
17277
17278             SvREFCNT_dec_NN(cp_list);
17279             return ret;
17280         }
17281     }
17282
17283     /* Here, <cp_list> contains all the code points we can determine at
17284      * compile time that match under all conditions.  Go through it, and
17285      * for things that belong in the bitmap, put them there, and delete from
17286      * <cp_list>.  While we are at it, see if everything above 255 is in the
17287      * list, and if so, set a flag to speed up execution */
17288
17289     populate_ANYOF_from_invlist(ret, &cp_list);
17290
17291     if (invert) {
17292         ANYOF_FLAGS(ret) |= ANYOF_INVERT;
17293     }
17294
17295     /* Here, the bitmap has been populated with all the Latin1 code points that
17296      * always match.  Can now add to the overall list those that match only
17297      * when the target string is UTF-8 (<has_upper_latin1_only_utf8_matches>).
17298      * */
17299     if (has_upper_latin1_only_utf8_matches) {
17300         if (cp_list) {
17301             _invlist_union(cp_list,
17302                            has_upper_latin1_only_utf8_matches,
17303                            &cp_list);
17304             SvREFCNT_dec_NN(has_upper_latin1_only_utf8_matches);
17305         }
17306         else {
17307             cp_list = has_upper_latin1_only_utf8_matches;
17308         }
17309         ANYOF_FLAGS(ret) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP;
17310     }
17311
17312     /* If there is a swash and more than one element, we can't use the swash in
17313      * the optimization below. */
17314     if (swash && element_count > 1) {
17315         SvREFCNT_dec_NN(swash);
17316         swash = NULL;
17317     }
17318
17319     /* Note that the optimization of using 'swash' if it is the only thing in
17320      * the class doesn't have us change swash at all, so it can include things
17321      * that are also in the bitmap; otherwise we have purposely deleted that
17322      * duplicate information */
17323     set_ANYOF_arg(pRExC_state, ret, cp_list,
17324                   (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
17325                    ? listsv : NULL,
17326                   only_utf8_locale_list,
17327                   swash, has_user_defined_property);
17328
17329     *flagp |= HASWIDTH|SIMPLE;
17330
17331     if (ANYOF_FLAGS(ret) & ANYOF_LOCALE_FLAGS) {
17332         RExC_contains_locale = 1;
17333     }
17334
17335     return ret;
17336 }
17337
17338 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
17339
17340 STATIC void
17341 S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state,
17342                 regnode* const node,
17343                 SV* const cp_list,
17344                 SV* const runtime_defns,
17345                 SV* const only_utf8_locale_list,
17346                 SV* const swash,
17347                 const bool has_user_defined_property)
17348 {
17349     /* Sets the arg field of an ANYOF-type node 'node', using information about
17350      * the node passed-in.  If there is nothing outside the node's bitmap, the
17351      * arg is set to ANYOF_ONLY_HAS_BITMAP.  Otherwise, it sets the argument to
17352      * the count returned by add_data(), having allocated and stored an array,
17353      * av, that that count references, as follows:
17354      *  av[0] stores the character class description in its textual form.
17355      *        This is used later (regexec.c:Perl_regclass_swash()) to
17356      *        initialize the appropriate swash, and is also useful for dumping
17357      *        the regnode.  This is set to &PL_sv_undef if the textual
17358      *        description is not needed at run-time (as happens if the other
17359      *        elements completely define the class)
17360      *  av[1] if &PL_sv_undef, is a placeholder to later contain the swash
17361      *        computed from av[0].  But if no further computation need be done,
17362      *        the swash is stored here now (and av[0] is &PL_sv_undef).
17363      *  av[2] stores the inversion list of code points that match only if the
17364      *        current locale is UTF-8
17365      *  av[3] stores the cp_list inversion list for use in addition or instead
17366      *        of av[0]; used only if cp_list exists and av[1] is &PL_sv_undef.
17367      *        (Otherwise everything needed is already in av[0] and av[1])
17368      *  av[4] is set if any component of the class is from a user-defined
17369      *        property; used only if av[3] exists */
17370
17371     UV n;
17372
17373     PERL_ARGS_ASSERT_SET_ANYOF_ARG;
17374
17375     if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) {
17376         assert(! (ANYOF_FLAGS(node)
17377                 & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP));
17378         ARG_SET(node, ANYOF_ONLY_HAS_BITMAP);
17379     }
17380     else {
17381         AV * const av = newAV();
17382         SV *rv;
17383
17384         av_store(av, 0, (runtime_defns)
17385                         ? SvREFCNT_inc(runtime_defns) : &PL_sv_undef);
17386         if (swash) {
17387             assert(cp_list);
17388             av_store(av, 1, swash);
17389             SvREFCNT_dec_NN(cp_list);
17390         }
17391         else {
17392             av_store(av, 1, &PL_sv_undef);
17393             if (cp_list) {
17394                 av_store(av, 3, cp_list);
17395                 av_store(av, 4, newSVuv(has_user_defined_property));
17396             }
17397         }
17398
17399         if (only_utf8_locale_list) {
17400             av_store(av, 2, only_utf8_locale_list);
17401         }
17402         else {
17403             av_store(av, 2, &PL_sv_undef);
17404         }
17405
17406         rv = newRV_noinc(MUTABLE_SV(av));
17407         n = add_data(pRExC_state, STR_WITH_LEN("s"));
17408         RExC_rxi->data->data[n] = (void*)rv;
17409         ARG_SET(node, n);
17410     }
17411 }
17412
17413 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
17414 SV *
17415 Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog,
17416                                         const regnode* node,
17417                                         bool doinit,
17418                                         SV** listsvp,
17419                                         SV** only_utf8_locale_ptr,
17420                                         SV*  exclude_list)
17421
17422 {
17423     /* For internal core use only.
17424      * Returns the swash for the input 'node' in the regex 'prog'.
17425      * If <doinit> is 'true', will attempt to create the swash if not already
17426      *    done.
17427      * If <listsvp> is non-null, will return the printable contents of the
17428      *    swash.  This can be used to get debugging information even before the
17429      *    swash exists, by calling this function with 'doinit' set to false, in
17430      *    which case the components that will be used to eventually create the
17431      *    swash are returned  (in a printable form).
17432      * If <exclude_list> is not NULL, it is an inversion list of things to
17433      *    exclude from what's returned in <listsvp>.
17434      * Tied intimately to how S_set_ANYOF_arg sets up the data structure.  Note
17435      * that, in spite of this function's name, the swash it returns may include
17436      * the bitmap data as well */
17437
17438     SV *sw  = NULL;
17439     SV *si  = NULL;         /* Input swash initialization string */
17440     SV*  invlist = NULL;
17441
17442     RXi_GET_DECL(prog,progi);
17443     const struct reg_data * const data = prog ? progi->data : NULL;
17444
17445     PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA;
17446
17447     if (data && data->count) {
17448         const U32 n = ARG(node);
17449
17450         if (data->what[n] == 's') {
17451             SV * const rv = MUTABLE_SV(data->data[n]);
17452             AV * const av = MUTABLE_AV(SvRV(rv));
17453             SV **const ary = AvARRAY(av);
17454             U8 swash_init_flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
17455
17456             si = *ary;  /* ary[0] = the string to initialize the swash with */
17457
17458             if (av_tindex(av) >= 2) {
17459                 if (only_utf8_locale_ptr
17460                     && ary[2]
17461                     && ary[2] != &PL_sv_undef)
17462                 {
17463                     *only_utf8_locale_ptr = ary[2];
17464                 }
17465                 else {
17466                     assert(only_utf8_locale_ptr);
17467                     *only_utf8_locale_ptr = NULL;
17468                 }
17469
17470                 /* Elements 3 and 4 are either both present or both absent. [3]
17471                  * is any inversion list generated at compile time; [4]
17472                  * indicates if that inversion list has any user-defined
17473                  * properties in it. */
17474                 if (av_tindex(av) >= 3) {
17475                     invlist = ary[3];
17476                     if (SvUV(ary[4])) {
17477                         swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
17478                     }
17479                 }
17480                 else {
17481                     invlist = NULL;
17482                 }
17483             }
17484
17485             /* Element [1] is reserved for the set-up swash.  If already there,
17486              * return it; if not, create it and store it there */
17487             if (ary[1] && SvROK(ary[1])) {
17488                 sw = ary[1];
17489             }
17490             else if (doinit && ((si && si != &PL_sv_undef)
17491                                  || (invlist && invlist != &PL_sv_undef))) {
17492                 assert(si);
17493                 sw = _core_swash_init("utf8", /* the utf8 package */
17494                                       "", /* nameless */
17495                                       si,
17496                                       1, /* binary */
17497                                       0, /* not from tr/// */
17498                                       invlist,
17499                                       &swash_init_flags);
17500                 (void)av_store(av, 1, sw);
17501             }
17502         }
17503     }
17504
17505     /* If requested, return a printable version of what this swash matches */
17506     if (listsvp) {
17507         SV* matches_string = newSVpvs("");
17508
17509         /* The swash should be used, if possible, to get the data, as it
17510          * contains the resolved data.  But this function can be called at
17511          * compile-time, before everything gets resolved, in which case we
17512          * return the currently best available information, which is the string
17513          * that will eventually be used to do that resolving, 'si' */
17514         if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
17515             && (si && si != &PL_sv_undef))
17516         {
17517             sv_catsv(matches_string, si);
17518         }
17519
17520         /* Add the inversion list to whatever we have.  This may have come from
17521          * the swash, or from an input parameter */
17522         if (invlist) {
17523             if (exclude_list) {
17524                 SV* clone = invlist_clone(invlist);
17525                 _invlist_subtract(clone, exclude_list, &clone);
17526                 sv_catsv(matches_string, _invlist_contents(clone));
17527                 SvREFCNT_dec_NN(clone);
17528             }
17529             else {
17530                 sv_catsv(matches_string, _invlist_contents(invlist));
17531             }
17532         }
17533         *listsvp = matches_string;
17534     }
17535
17536     return sw;
17537 }
17538 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
17539
17540 /* reg_skipcomment()
17541
17542    Absorbs an /x style # comment from the input stream,
17543    returning a pointer to the first character beyond the comment, or if the
17544    comment terminates the pattern without anything following it, this returns
17545    one past the final character of the pattern (in other words, RExC_end) and
17546    sets the REG_RUN_ON_COMMENT_SEEN flag.
17547
17548    Note it's the callers responsibility to ensure that we are
17549    actually in /x mode
17550
17551 */
17552
17553 PERL_STATIC_INLINE char*
17554 S_reg_skipcomment(RExC_state_t *pRExC_state, char* p)
17555 {
17556     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
17557
17558     assert(*p == '#');
17559
17560     while (p < RExC_end) {
17561         if (*(++p) == '\n') {
17562             return p+1;
17563         }
17564     }
17565
17566     /* we ran off the end of the pattern without ending the comment, so we have
17567      * to add an \n when wrapping */
17568     RExC_seen |= REG_RUN_ON_COMMENT_SEEN;
17569     return p;
17570 }
17571
17572 STATIC void
17573 S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state,
17574                                 char ** p,
17575                                 const bool force_to_xmod
17576                          )
17577 {
17578     /* If the text at the current parse position '*p' is a '(?#...)' comment,
17579      * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p'
17580      * is /x whitespace, advance '*p' so that on exit it points to the first
17581      * byte past all such white space and comments */
17582
17583     const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED);
17584
17585     PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT;
17586
17587     assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p));
17588
17589     for (;;) {
17590         if (RExC_end - (*p) >= 3
17591             && *(*p)     == '('
17592             && *(*p + 1) == '?'
17593             && *(*p + 2) == '#')
17594         {
17595             while (*(*p) != ')') {
17596                 if ((*p) == RExC_end)
17597                     FAIL("Sequence (?#... not terminated");
17598                 (*p)++;
17599             }
17600             (*p)++;
17601             continue;
17602         }
17603
17604         if (use_xmod) {
17605             const char * save_p = *p;
17606             while ((*p) < RExC_end) {
17607                 STRLEN len;
17608                 if ((len = is_PATWS_safe((*p), RExC_end, UTF))) {
17609                     (*p) += len;
17610                 }
17611                 else if (*(*p) == '#') {
17612                     (*p) = reg_skipcomment(pRExC_state, (*p));
17613                 }
17614                 else {
17615                     break;
17616                 }
17617             }
17618             if (*p != save_p) {
17619                 continue;
17620             }
17621         }
17622
17623         break;
17624     }
17625
17626     return;
17627 }
17628
17629 /* nextchar()
17630
17631    Advances the parse position by one byte, unless that byte is the beginning
17632    of a '(?#...)' style comment, or is /x whitespace and /x is in effect.  In
17633    those two cases, the parse position is advanced beyond all such comments and
17634    white space.
17635
17636    This is the UTF, (?#...), and /x friendly way of saying RExC_parse++.
17637 */
17638
17639 STATIC void
17640 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
17641 {
17642     PERL_ARGS_ASSERT_NEXTCHAR;
17643
17644     if (RExC_parse < RExC_end) {
17645         assert(   ! UTF
17646                || UTF8_IS_INVARIANT(*RExC_parse)
17647                || UTF8_IS_START(*RExC_parse));
17648
17649         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
17650
17651         skip_to_be_ignored_text(pRExC_state, &RExC_parse,
17652                                 FALSE /* Don't assume /x */ );
17653     }
17654 }
17655
17656 STATIC regnode *
17657 S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name)
17658 {
17659     /* Allocate a regnode for 'op' and returns it, with 'extra_size' extra
17660      * space.  In pass1, it aligns and increments RExC_size; in pass2,
17661      * RExC_emit */
17662
17663     regnode * const ret = RExC_emit;
17664     GET_RE_DEBUG_FLAGS_DECL;
17665
17666     PERL_ARGS_ASSERT_REGNODE_GUTS;
17667
17668     assert(extra_size >= regarglen[op]);
17669
17670     if (SIZE_ONLY) {
17671         SIZE_ALIGN(RExC_size);
17672         RExC_size += 1 + extra_size;
17673         return(ret);
17674     }
17675     if (RExC_emit >= RExC_emit_bound)
17676         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
17677                    op, (void*)RExC_emit, (void*)RExC_emit_bound);
17678
17679     NODE_ALIGN_FILL(ret);
17680 #ifndef RE_TRACK_PATTERN_OFFSETS
17681     PERL_UNUSED_ARG(name);
17682 #else
17683     if (RExC_offsets) {         /* MJD */
17684         MJD_OFFSET_DEBUG(
17685               ("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
17686               name, __LINE__,
17687               PL_reg_name[op],
17688               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
17689                 ? "Overwriting end of array!\n" : "OK",
17690               (UV)(RExC_emit - RExC_emit_start),
17691               (UV)(RExC_parse - RExC_start),
17692               (UV)RExC_offsets[0]));
17693         Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
17694     }
17695 #endif
17696     return(ret);
17697 }
17698
17699 /*
17700 - reg_node - emit a node
17701 */
17702 STATIC regnode *                        /* Location. */
17703 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
17704 {
17705     regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node");
17706
17707     PERL_ARGS_ASSERT_REG_NODE;
17708
17709     assert(regarglen[op] == 0);
17710
17711     if (PASS2) {
17712         regnode *ptr = ret;
17713         FILL_ADVANCE_NODE(ptr, op);
17714         RExC_emit = ptr;
17715     }
17716     return(ret);
17717 }
17718
17719 /*
17720 - reganode - emit a node with an argument
17721 */
17722 STATIC regnode *                        /* Location. */
17723 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
17724 {
17725     regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode");
17726
17727     PERL_ARGS_ASSERT_REGANODE;
17728
17729     assert(regarglen[op] == 1);
17730
17731     if (PASS2) {
17732         regnode *ptr = ret;
17733         FILL_ADVANCE_NODE_ARG(ptr, op, arg);
17734         RExC_emit = ptr;
17735     }
17736     return(ret);
17737 }
17738
17739 STATIC regnode *
17740 S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2)
17741 {
17742     /* emit a node with U32 and I32 arguments */
17743
17744     regnode * const ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode");
17745
17746     PERL_ARGS_ASSERT_REG2LANODE;
17747
17748     assert(regarglen[op] == 2);
17749
17750     if (PASS2) {
17751         regnode *ptr = ret;
17752         FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2);
17753         RExC_emit = ptr;
17754     }
17755     return(ret);
17756 }
17757
17758 /*
17759 - reginsert - insert an operator in front of already-emitted operand
17760 *
17761 * Means relocating the operand.
17762 */
17763 STATIC void
17764 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
17765 {
17766     regnode *src;
17767     regnode *dst;
17768     regnode *place;
17769     const int offset = regarglen[(U8)op];
17770     const int size = NODE_STEP_REGNODE + offset;
17771     GET_RE_DEBUG_FLAGS_DECL;
17772
17773     PERL_ARGS_ASSERT_REGINSERT;
17774     PERL_UNUSED_CONTEXT;
17775     PERL_UNUSED_ARG(depth);
17776 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
17777     DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
17778     if (SIZE_ONLY) {
17779         RExC_size += size;
17780         return;
17781     }
17782
17783     src = RExC_emit;
17784     RExC_emit += size;
17785     dst = RExC_emit;
17786     if (RExC_open_parens) {
17787         int paren;
17788         /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
17789         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
17790             if ( RExC_open_parens[paren] >= opnd ) {
17791                 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
17792                 RExC_open_parens[paren] += size;
17793             } else {
17794                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
17795             }
17796             if ( RExC_close_parens[paren] >= opnd ) {
17797                 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
17798                 RExC_close_parens[paren] += size;
17799             } else {
17800                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
17801             }
17802         }
17803     }
17804
17805     while (src > opnd) {
17806         StructCopy(--src, --dst, regnode);
17807 #ifdef RE_TRACK_PATTERN_OFFSETS
17808         if (RExC_offsets) {     /* MJD 20010112 */
17809             MJD_OFFSET_DEBUG(
17810                  ("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
17811                   "reg_insert",
17812                   __LINE__,
17813                   PL_reg_name[op],
17814                   (UV)(dst - RExC_emit_start) > RExC_offsets[0]
17815                     ? "Overwriting end of array!\n" : "OK",
17816                   (UV)(src - RExC_emit_start),
17817                   (UV)(dst - RExC_emit_start),
17818                   (UV)RExC_offsets[0]));
17819             Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
17820             Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
17821         }
17822 #endif
17823     }
17824
17825
17826     place = opnd;               /* Op node, where operand used to be. */
17827 #ifdef RE_TRACK_PATTERN_OFFSETS
17828     if (RExC_offsets) {         /* MJD */
17829         MJD_OFFSET_DEBUG(
17830               ("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
17831               "reginsert",
17832               __LINE__,
17833               PL_reg_name[op],
17834               (UV)(place - RExC_emit_start) > RExC_offsets[0]
17835               ? "Overwriting end of array!\n" : "OK",
17836               (UV)(place - RExC_emit_start),
17837               (UV)(RExC_parse - RExC_start),
17838               (UV)RExC_offsets[0]));
17839         Set_Node_Offset(place, RExC_parse);
17840         Set_Node_Length(place, 1);
17841     }
17842 #endif
17843     src = NEXTOPER(place);
17844     FILL_ADVANCE_NODE(place, op);
17845     Zero(src, offset, regnode);
17846 }
17847
17848 /*
17849 - regtail - set the next-pointer at the end of a node chain of p to val.
17850 - SEE ALSO: regtail_study
17851 */
17852 STATIC void
17853 S_regtail(pTHX_ RExC_state_t * pRExC_state,
17854                 const regnode * const p,
17855                 const regnode * const val,
17856                 const U32 depth)
17857 {
17858     regnode *scan;
17859     GET_RE_DEBUG_FLAGS_DECL;
17860
17861     PERL_ARGS_ASSERT_REGTAIL;
17862 #ifndef DEBUGGING
17863     PERL_UNUSED_ARG(depth);
17864 #endif
17865
17866     if (SIZE_ONLY)
17867         return;
17868
17869     /* Find last node. */
17870     scan = (regnode *) p;
17871     for (;;) {
17872         regnode * const temp = regnext(scan);
17873         DEBUG_PARSE_r({
17874             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
17875             regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
17876             PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
17877                 SvPV_nolen_const(RExC_mysv), REG_NODE_NUM(scan),
17878                     (temp == NULL ? "->" : ""),
17879                     (temp == NULL ? PL_reg_name[OP(val)] : "")
17880             );
17881         });
17882         if (temp == NULL)
17883             break;
17884         scan = temp;
17885     }
17886
17887     if (reg_off_by_arg[OP(scan)]) {
17888         ARG_SET(scan, val - scan);
17889     }
17890     else {
17891         NEXT_OFF(scan) = val - scan;
17892     }
17893 }
17894
17895 #ifdef DEBUGGING
17896 /*
17897 - regtail_study - set the next-pointer at the end of a node chain of p to val.
17898 - Look for optimizable sequences at the same time.
17899 - currently only looks for EXACT chains.
17900
17901 This is experimental code. The idea is to use this routine to perform
17902 in place optimizations on branches and groups as they are constructed,
17903 with the long term intention of removing optimization from study_chunk so
17904 that it is purely analytical.
17905
17906 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
17907 to control which is which.
17908
17909 */
17910 /* TODO: All four parms should be const */
17911
17912 STATIC U8
17913 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p,
17914                       const regnode *val,U32 depth)
17915 {
17916     regnode *scan;
17917     U8 exact = PSEUDO;
17918 #ifdef EXPERIMENTAL_INPLACESCAN
17919     I32 min = 0;
17920 #endif
17921     GET_RE_DEBUG_FLAGS_DECL;
17922
17923     PERL_ARGS_ASSERT_REGTAIL_STUDY;
17924
17925
17926     if (SIZE_ONLY)
17927         return exact;
17928
17929     /* Find last node. */
17930
17931     scan = p;
17932     for (;;) {
17933         regnode * const temp = regnext(scan);
17934 #ifdef EXPERIMENTAL_INPLACESCAN
17935         if (PL_regkind[OP(scan)] == EXACT) {
17936             bool unfolded_multi_char;   /* Unexamined in this routine */
17937             if (join_exact(pRExC_state, scan, &min,
17938                            &unfolded_multi_char, 1, val, depth+1))
17939                 return EXACT;
17940         }
17941 #endif
17942         if ( exact ) {
17943             switch (OP(scan)) {
17944                 case EXACT:
17945                 case EXACTL:
17946                 case EXACTF:
17947                 case EXACTFA_NO_TRIE:
17948                 case EXACTFA:
17949                 case EXACTFU:
17950                 case EXACTFLU8:
17951                 case EXACTFU_SS:
17952                 case EXACTFL:
17953                         if( exact == PSEUDO )
17954                             exact= OP(scan);
17955                         else if ( exact != OP(scan) )
17956                             exact= 0;
17957                 case NOTHING:
17958                     break;
17959                 default:
17960                     exact= 0;
17961             }
17962         }
17963         DEBUG_PARSE_r({
17964             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
17965             regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state);
17966             PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
17967                 SvPV_nolen_const(RExC_mysv),
17968                 REG_NODE_NUM(scan),
17969                 PL_reg_name[exact]);
17970         });
17971         if (temp == NULL)
17972             break;
17973         scan = temp;
17974     }
17975     DEBUG_PARSE_r({
17976         DEBUG_PARSE_MSG("");
17977         regprop(RExC_rx, RExC_mysv, val, NULL, pRExC_state);
17978         PerlIO_printf(Perl_debug_log,
17979                       "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
17980                       SvPV_nolen_const(RExC_mysv),
17981                       (IV)REG_NODE_NUM(val),
17982                       (IV)(val - scan)
17983         );
17984     });
17985     if (reg_off_by_arg[OP(scan)]) {
17986         ARG_SET(scan, val - scan);
17987     }
17988     else {
17989         NEXT_OFF(scan) = val - scan;
17990     }
17991
17992     return exact;
17993 }
17994 #endif
17995
17996 /*
17997  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
17998  */
17999 #ifdef DEBUGGING
18000
18001 static void
18002 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
18003 {
18004     int bit;
18005     int set=0;
18006
18007     ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8);
18008
18009     for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) {
18010         if (flags & (1<<bit)) {
18011             if (!set++ && lead)
18012                 PerlIO_printf(Perl_debug_log, "%s",lead);
18013             PerlIO_printf(Perl_debug_log, "%s ",PL_reg_intflags_name[bit]);
18014         }
18015     }
18016     if (lead)  {
18017         if (set)
18018             PerlIO_printf(Perl_debug_log, "\n");
18019         else
18020             PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
18021     }
18022 }
18023
18024 static void
18025 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
18026 {
18027     int bit;
18028     int set=0;
18029     regex_charset cs;
18030
18031     ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8);
18032
18033     for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) {
18034         if (flags & (1<<bit)) {
18035             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
18036                 continue;
18037             }
18038             if (!set++ && lead)
18039                 PerlIO_printf(Perl_debug_log, "%s",lead);
18040             PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
18041         }
18042     }
18043     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
18044             if (!set++ && lead) {
18045                 PerlIO_printf(Perl_debug_log, "%s",lead);
18046             }
18047             switch (cs) {
18048                 case REGEX_UNICODE_CHARSET:
18049                     PerlIO_printf(Perl_debug_log, "UNICODE");
18050                     break;
18051                 case REGEX_LOCALE_CHARSET:
18052                     PerlIO_printf(Perl_debug_log, "LOCALE");
18053                     break;
18054                 case REGEX_ASCII_RESTRICTED_CHARSET:
18055                     PerlIO_printf(Perl_debug_log, "ASCII-RESTRICTED");
18056                     break;
18057                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
18058                     PerlIO_printf(Perl_debug_log, "ASCII-MORE_RESTRICTED");
18059                     break;
18060                 default:
18061                     PerlIO_printf(Perl_debug_log, "UNKNOWN CHARACTER SET");
18062                     break;
18063             }
18064     }
18065     if (lead)  {
18066         if (set)
18067             PerlIO_printf(Perl_debug_log, "\n");
18068         else
18069             PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
18070     }
18071 }
18072 #endif
18073
18074 void
18075 Perl_regdump(pTHX_ const regexp *r)
18076 {
18077 #ifdef DEBUGGING
18078     SV * const sv = sv_newmortal();
18079     SV *dsv= sv_newmortal();
18080     RXi_GET_DECL(r,ri);
18081     GET_RE_DEBUG_FLAGS_DECL;
18082
18083     PERL_ARGS_ASSERT_REGDUMP;
18084
18085     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
18086
18087     /* Header fields of interest. */
18088     if (r->anchored_substr) {
18089         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
18090             RE_SV_DUMPLEN(r->anchored_substr), 30);
18091         PerlIO_printf(Perl_debug_log,
18092                       "anchored %s%s at %"IVdf" ",
18093                       s, RE_SV_TAIL(r->anchored_substr),
18094                       (IV)r->anchored_offset);
18095     } else if (r->anchored_utf8) {
18096         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
18097             RE_SV_DUMPLEN(r->anchored_utf8), 30);
18098         PerlIO_printf(Perl_debug_log,
18099                       "anchored utf8 %s%s at %"IVdf" ",
18100                       s, RE_SV_TAIL(r->anchored_utf8),
18101                       (IV)r->anchored_offset);
18102     }
18103     if (r->float_substr) {
18104         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
18105             RE_SV_DUMPLEN(r->float_substr), 30);
18106         PerlIO_printf(Perl_debug_log,
18107                       "floating %s%s at %"IVdf"..%"UVuf" ",
18108                       s, RE_SV_TAIL(r->float_substr),
18109                       (IV)r->float_min_offset, (UV)r->float_max_offset);
18110     } else if (r->float_utf8) {
18111         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
18112             RE_SV_DUMPLEN(r->float_utf8), 30);
18113         PerlIO_printf(Perl_debug_log,
18114                       "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
18115                       s, RE_SV_TAIL(r->float_utf8),
18116                       (IV)r->float_min_offset, (UV)r->float_max_offset);
18117     }
18118     if (r->check_substr || r->check_utf8)
18119         PerlIO_printf(Perl_debug_log,
18120                       (const char *)
18121                       (r->check_substr == r->float_substr
18122                        && r->check_utf8 == r->float_utf8
18123                        ? "(checking floating" : "(checking anchored"));
18124     if (r->intflags & PREGf_NOSCAN)
18125         PerlIO_printf(Perl_debug_log, " noscan");
18126     if (r->extflags & RXf_CHECK_ALL)
18127         PerlIO_printf(Perl_debug_log, " isall");
18128     if (r->check_substr || r->check_utf8)
18129         PerlIO_printf(Perl_debug_log, ") ");
18130
18131     if (ri->regstclass) {
18132         regprop(r, sv, ri->regstclass, NULL, NULL);
18133         PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
18134     }
18135     if (r->intflags & PREGf_ANCH) {
18136         PerlIO_printf(Perl_debug_log, "anchored");
18137         if (r->intflags & PREGf_ANCH_MBOL)
18138             PerlIO_printf(Perl_debug_log, "(MBOL)");
18139         if (r->intflags & PREGf_ANCH_SBOL)
18140             PerlIO_printf(Perl_debug_log, "(SBOL)");
18141         if (r->intflags & PREGf_ANCH_GPOS)
18142             PerlIO_printf(Perl_debug_log, "(GPOS)");
18143         (void)PerlIO_putc(Perl_debug_log, ' ');
18144     }
18145     if (r->intflags & PREGf_GPOS_SEEN)
18146         PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
18147     if (r->intflags & PREGf_SKIP)
18148         PerlIO_printf(Perl_debug_log, "plus ");
18149     if (r->intflags & PREGf_IMPLICIT)
18150         PerlIO_printf(Perl_debug_log, "implicit ");
18151     PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
18152     if (r->extflags & RXf_EVAL_SEEN)
18153         PerlIO_printf(Perl_debug_log, "with eval ");
18154     PerlIO_printf(Perl_debug_log, "\n");
18155     DEBUG_FLAGS_r({
18156         regdump_extflags("r->extflags: ",r->extflags);
18157         regdump_intflags("r->intflags: ",r->intflags);
18158     });
18159 #else
18160     PERL_ARGS_ASSERT_REGDUMP;
18161     PERL_UNUSED_CONTEXT;
18162     PERL_UNUSED_ARG(r);
18163 #endif  /* DEBUGGING */
18164 }
18165
18166 /*
18167 - regprop - printable representation of opcode, with run time support
18168 */
18169
18170 void
18171 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state)
18172 {
18173 #ifdef DEBUGGING
18174     int k;
18175
18176     /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
18177     static const char * const anyofs[] = {
18178 #if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 || _CC_LOWER != 3 \
18179     || _CC_UPPER != 4 || _CC_PUNCT != 5 || _CC_PRINT != 6                   \
18180     || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 || _CC_CASED != 9            \
18181     || _CC_SPACE != 10 || _CC_BLANK != 11 || _CC_XDIGIT != 12               \
18182     || _CC_CNTRL != 13 || _CC_ASCII != 14 || _CC_VERTSPACE != 15
18183   #error Need to adjust order of anyofs[]
18184 #endif
18185         "\\w",
18186         "\\W",
18187         "\\d",
18188         "\\D",
18189         "[:alpha:]",
18190         "[:^alpha:]",
18191         "[:lower:]",
18192         "[:^lower:]",
18193         "[:upper:]",
18194         "[:^upper:]",
18195         "[:punct:]",
18196         "[:^punct:]",
18197         "[:print:]",
18198         "[:^print:]",
18199         "[:alnum:]",
18200         "[:^alnum:]",
18201         "[:graph:]",
18202         "[:^graph:]",
18203         "[:cased:]",
18204         "[:^cased:]",
18205         "\\s",
18206         "\\S",
18207         "[:blank:]",
18208         "[:^blank:]",
18209         "[:xdigit:]",
18210         "[:^xdigit:]",
18211         "[:cntrl:]",
18212         "[:^cntrl:]",
18213         "[:ascii:]",
18214         "[:^ascii:]",
18215         "\\v",
18216         "\\V"
18217     };
18218     RXi_GET_DECL(prog,progi);
18219     GET_RE_DEBUG_FLAGS_DECL;
18220
18221     PERL_ARGS_ASSERT_REGPROP;
18222
18223     sv_setpvn(sv, "", 0);
18224
18225     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
18226         /* It would be nice to FAIL() here, but this may be called from
18227            regexec.c, and it would be hard to supply pRExC_state. */
18228         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
18229                                               (int)OP(o), (int)REGNODE_MAX);
18230     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
18231
18232     k = PL_regkind[OP(o)];
18233
18234     if (k == EXACT) {
18235         sv_catpvs(sv, " ");
18236         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
18237          * is a crude hack but it may be the best for now since
18238          * we have no flag "this EXACTish node was UTF-8"
18239          * --jhi */
18240         pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
18241                   PERL_PV_ESCAPE_UNI_DETECT |
18242                   PERL_PV_ESCAPE_NONASCII   |
18243                   PERL_PV_PRETTY_ELLIPSES   |
18244                   PERL_PV_PRETTY_LTGT       |
18245                   PERL_PV_PRETTY_NOCLEAR
18246                   );
18247     } else if (k == TRIE) {
18248         /* print the details of the trie in dumpuntil instead, as
18249          * progi->data isn't available here */
18250         const char op = OP(o);
18251         const U32 n = ARG(o);
18252         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
18253                (reg_ac_data *)progi->data->data[n] :
18254                NULL;
18255         const reg_trie_data * const trie
18256             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
18257
18258         Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
18259         DEBUG_TRIE_COMPILE_r(
18260           Perl_sv_catpvf(aTHX_ sv,
18261             "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
18262             (UV)trie->startstate,
18263             (IV)trie->statecount-1, /* -1 because of the unused 0 element */
18264             (UV)trie->wordcount,
18265             (UV)trie->minlen,
18266             (UV)trie->maxlen,
18267             (UV)TRIE_CHARCOUNT(trie),
18268             (UV)trie->uniquecharcount
18269           );
18270         );
18271         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
18272             sv_catpvs(sv, "[");
18273             (void) put_charclass_bitmap_innards(sv,
18274                                                 (IS_ANYOF_TRIE(op))
18275                                                  ? ANYOF_BITMAP(o)
18276                                                  : TRIE_BITMAP(trie),
18277                                                 NULL);
18278             sv_catpvs(sv, "]");
18279         }
18280
18281     } else if (k == CURLY) {
18282         U32 lo = ARG1(o), hi = ARG2(o);
18283         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
18284             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
18285         Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo);
18286         if (hi == REG_INFTY)
18287             sv_catpvs(sv, "INFTY");
18288         else
18289             Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi);
18290         sv_catpvs(sv, "}");
18291     }
18292     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
18293         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
18294     else if (k == REF || k == OPEN || k == CLOSE
18295              || k == GROUPP || OP(o)==ACCEPT)
18296     {
18297         AV *name_list= NULL;
18298         U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o);
18299         Perl_sv_catpvf(aTHX_ sv, "%"UVuf, (UV)parno);        /* Parenth number */
18300         if ( RXp_PAREN_NAMES(prog) ) {
18301             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
18302         } else if ( pRExC_state ) {
18303             name_list= RExC_paren_name_list;
18304         }
18305         if (name_list) {
18306             if ( k != REF || (OP(o) < NREF)) {
18307                 SV **name= av_fetch(name_list, parno, 0 );
18308                 if (name)
18309                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
18310             }
18311             else {
18312                 SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]);
18313                 I32 *nums=(I32*)SvPVX(sv_dat);
18314                 SV **name= av_fetch(name_list, nums[0], 0 );
18315                 I32 n;
18316                 if (name) {
18317                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
18318                         Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
18319                                     (n ? "," : ""), (IV)nums[n]);
18320                     }
18321                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
18322                 }
18323             }
18324         }
18325         if ( k == REF && reginfo) {
18326             U32 n = ARG(o);  /* which paren pair */
18327             I32 ln = prog->offs[n].start;
18328             if (prog->lastparen < n || ln == -1)
18329                 Perl_sv_catpvf(aTHX_ sv, ": FAIL");
18330             else if (ln == prog->offs[n].end)
18331                 Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING");
18332             else {
18333                 const char *s = reginfo->strbeg + ln;
18334                 Perl_sv_catpvf(aTHX_ sv, ": ");
18335                 Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0,
18336                     PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE );
18337             }
18338         }
18339     } else if (k == GOSUB) {
18340         AV *name_list= NULL;
18341         if ( RXp_PAREN_NAMES(prog) ) {
18342             name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
18343         } else if ( pRExC_state ) {
18344             name_list= RExC_paren_name_list;
18345         }
18346
18347         /* Paren and offset */
18348         Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o));
18349         if (name_list) {
18350             SV **name= av_fetch(name_list, ARG(o), 0 );
18351             if (name)
18352                 Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
18353         }
18354     }
18355     else if (k == LOGICAL)
18356         /* 2: embedded, otherwise 1 */
18357         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);
18358     else if (k == ANYOF) {
18359         const U8 flags = ANYOF_FLAGS(o);
18360         int do_sep = 0;
18361         SV* bitmap_invlist = NULL;  /* Will hold what the bit map contains */
18362
18363
18364         if (OP(o) == ANYOFL) {
18365             if (ANYOFL_UTF8_LOCALE_REQD(flags)) {
18366                 sv_catpvs(sv, "{utf8-loc}");
18367             }
18368             else {
18369                 sv_catpvs(sv, "{loc}");
18370             }
18371         }
18372         if (flags & ANYOFL_FOLD)
18373             sv_catpvs(sv, "{i}");
18374         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
18375         if (flags & ANYOF_INVERT)
18376             sv_catpvs(sv, "^");
18377
18378         /* output what the standard cp 0-NUM_ANYOF_CODE_POINTS-1 bitmap matches
18379          * */
18380         do_sep = put_charclass_bitmap_innards(sv, ANYOF_BITMAP(o),
18381                                                             &bitmap_invlist);
18382
18383         /* output any special charclass tests (used entirely under use
18384          * locale) * */
18385         if (ANYOF_POSIXL_TEST_ANY_SET(o)) {
18386             int i;
18387             for (i = 0; i < ANYOF_POSIXL_MAX; i++) {
18388                 if (ANYOF_POSIXL_TEST(o,i)) {
18389                     sv_catpv(sv, anyofs[i]);
18390                     do_sep = 1;
18391                 }
18392             }
18393         }
18394
18395         if (    ARG(o) != ANYOF_ONLY_HAS_BITMAP
18396             || (flags
18397                 & ( ANYOF_MATCHES_ALL_ABOVE_BITMAP
18398                    |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP
18399                    |ANYOFL_FOLD)))
18400         {
18401             if (do_sep) {
18402                 Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]);
18403                 if (flags & ANYOF_INVERT)
18404                     /*make sure the invert info is in each */
18405                     sv_catpvs(sv, "^");
18406             }
18407
18408             if (OP(o) == ANYOFD
18409                 && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))
18410             {
18411                 sv_catpvs(sv, "{non-utf8-latin1-all}");
18412             }
18413
18414             if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP)
18415                 sv_catpvs(sv, "{above_bitmap_all}");
18416
18417             if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) {
18418                 SV *lv; /* Set if there is something outside the bit map. */
18419                 bool byte_output = FALSE;   /* If something has been output */
18420                 SV *only_utf8_locale;
18421
18422                 /* Get the stuff that wasn't in the bitmap.  'bitmap_invlist'
18423                  * is used to guarantee that nothing in the bitmap gets
18424                  * returned */
18425                 (void) _get_regclass_nonbitmap_data(prog, o, FALSE,
18426                                                     &lv, &only_utf8_locale,
18427                                                     bitmap_invlist);
18428                 if (lv && lv != &PL_sv_undef) {
18429                     char *s = savesvpv(lv);
18430                     char * const origs = s;
18431
18432                     while (*s && *s != '\n')
18433                         s++;
18434
18435                     if (*s == '\n') {
18436                         const char * const t = ++s;
18437
18438                         if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP) {
18439                             if (OP(o) == ANYOFD) {
18440                                 sv_catpvs(sv, "{utf8}");
18441                             }
18442                             else {
18443                                 sv_catpvs(sv, "{outside bitmap}");
18444                             }
18445                         }
18446
18447                         if (byte_output) {
18448                             sv_catpvs(sv, " ");
18449                         }
18450
18451                         while (*s) {
18452                             if (*s == '\n') {
18453
18454                                 /* Truncate very long output */
18455                                 if (s - origs > 256) {
18456                                     Perl_sv_catpvf(aTHX_ sv,
18457                                                 "%.*s...",
18458                                                 (int) (s - origs - 1),
18459                                                 t);
18460                                     goto out_dump;
18461                                 }
18462                                 *s = ' ';
18463                             }
18464                             else if (*s == '\t') {
18465                                 *s = '-';
18466                             }
18467                             s++;
18468                         }
18469                         if (s[-1] == ' ')
18470                             s[-1] = 0;
18471
18472                         sv_catpv(sv, t);
18473                     }
18474
18475                   out_dump:
18476
18477                     Safefree(origs);
18478                     SvREFCNT_dec_NN(lv);
18479                 }
18480
18481                 if ((flags & ANYOFL_FOLD)
18482                      && only_utf8_locale
18483                      && only_utf8_locale != &PL_sv_undef)
18484                 {
18485                     UV start, end;
18486                     int max_entries = 256;
18487
18488                     sv_catpvs(sv, "{utf8 locale}");
18489                     invlist_iterinit(only_utf8_locale);
18490                     while (invlist_iternext(only_utf8_locale,
18491                                             &start, &end)) {
18492                         put_range(sv, start, end, FALSE);
18493                         max_entries --;
18494                         if (max_entries < 0) {
18495                             sv_catpvs(sv, "...");
18496                             break;
18497                         }
18498                     }
18499                     invlist_iterfinish(only_utf8_locale);
18500                 }
18501             }
18502         }
18503         SvREFCNT_dec(bitmap_invlist);
18504
18505
18506         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
18507     }
18508     else if (k == POSIXD || k == NPOSIXD) {
18509         U8 index = FLAGS(o) * 2;
18510         if (index < C_ARRAY_LENGTH(anyofs)) {
18511             if (*anyofs[index] != '[')  {
18512                 sv_catpv(sv, "[");
18513             }
18514             sv_catpv(sv, anyofs[index]);
18515             if (*anyofs[index] != '[')  {
18516                 sv_catpv(sv, "]");
18517             }
18518         }
18519         else {
18520             Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
18521         }
18522     }
18523     else if (k == BOUND || k == NBOUND) {
18524         /* Must be synced with order of 'bound_type' in regcomp.h */
18525         const char * const bounds[] = {
18526             "",      /* Traditional */
18527             "{gcb}",
18528             "{lb}",
18529             "{sb}",
18530             "{wb}"
18531         };
18532         assert(FLAGS(o) < C_ARRAY_LENGTH(bounds));
18533         sv_catpv(sv, bounds[FLAGS(o)]);
18534     }
18535     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
18536         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
18537     else if (OP(o) == SBOL)
18538         Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^");
18539
18540     /* add on the verb argument if there is one */
18541     if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) {
18542         Perl_sv_catpvf(aTHX_ sv, ":%"SVf,
18543                        SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
18544     }
18545 #else
18546     PERL_UNUSED_CONTEXT;
18547     PERL_UNUSED_ARG(sv);
18548     PERL_UNUSED_ARG(o);
18549     PERL_UNUSED_ARG(prog);
18550     PERL_UNUSED_ARG(reginfo);
18551     PERL_UNUSED_ARG(pRExC_state);
18552 #endif  /* DEBUGGING */
18553 }
18554
18555
18556
18557 SV *
18558 Perl_re_intuit_string(pTHX_ REGEXP * const r)
18559 {                               /* Assume that RE_INTUIT is set */
18560     struct regexp *const prog = ReANY(r);
18561     GET_RE_DEBUG_FLAGS_DECL;
18562
18563     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
18564     PERL_UNUSED_CONTEXT;
18565
18566     DEBUG_COMPILE_r(
18567         {
18568             const char * const s = SvPV_nolen_const(RX_UTF8(r)
18569                       ? prog->check_utf8 : prog->check_substr);
18570
18571             if (!PL_colorset) reginitcolors();
18572             PerlIO_printf(Perl_debug_log,
18573                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
18574                       PL_colors[4],
18575                       RX_UTF8(r) ? "utf8 " : "",
18576                       PL_colors[5],PL_colors[0],
18577                       s,
18578                       PL_colors[1],
18579                       (strlen(s) > 60 ? "..." : ""));
18580         } );
18581
18582     /* use UTF8 check substring if regexp pattern itself is in UTF8 */
18583     return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr;
18584 }
18585
18586 /*
18587    pregfree()
18588
18589    handles refcounting and freeing the perl core regexp structure. When
18590    it is necessary to actually free the structure the first thing it
18591    does is call the 'free' method of the regexp_engine associated to
18592    the regexp, allowing the handling of the void *pprivate; member
18593    first. (This routine is not overridable by extensions, which is why
18594    the extensions free is called first.)
18595
18596    See regdupe and regdupe_internal if you change anything here.
18597 */
18598 #ifndef PERL_IN_XSUB_RE
18599 void
18600 Perl_pregfree(pTHX_ REGEXP *r)
18601 {
18602     SvREFCNT_dec(r);
18603 }
18604
18605 void
18606 Perl_pregfree2(pTHX_ REGEXP *rx)
18607 {
18608     struct regexp *const r = ReANY(rx);
18609     GET_RE_DEBUG_FLAGS_DECL;
18610
18611     PERL_ARGS_ASSERT_PREGFREE2;
18612
18613     if (r->mother_re) {
18614         ReREFCNT_dec(r->mother_re);
18615     } else {
18616         CALLREGFREE_PVT(rx); /* free the private data */
18617         SvREFCNT_dec(RXp_PAREN_NAMES(r));
18618         Safefree(r->xpv_len_u.xpvlenu_pv);
18619     }
18620     if (r->substrs) {
18621         SvREFCNT_dec(r->anchored_substr);
18622         SvREFCNT_dec(r->anchored_utf8);
18623         SvREFCNT_dec(r->float_substr);
18624         SvREFCNT_dec(r->float_utf8);
18625         Safefree(r->substrs);
18626     }
18627     RX_MATCH_COPY_FREE(rx);
18628 #ifdef PERL_ANY_COW
18629     SvREFCNT_dec(r->saved_copy);
18630 #endif
18631     Safefree(r->offs);
18632     SvREFCNT_dec(r->qr_anoncv);
18633     rx->sv_u.svu_rx = 0;
18634 }
18635
18636 /*  reg_temp_copy()
18637
18638     This is a hacky workaround to the structural issue of match results
18639     being stored in the regexp structure which is in turn stored in
18640     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
18641     could be PL_curpm in multiple contexts, and could require multiple
18642     result sets being associated with the pattern simultaneously, such
18643     as when doing a recursive match with (??{$qr})
18644
18645     The solution is to make a lightweight copy of the regexp structure
18646     when a qr// is returned from the code executed by (??{$qr}) this
18647     lightweight copy doesn't actually own any of its data except for
18648     the starp/end and the actual regexp structure itself.
18649
18650 */
18651
18652
18653 REGEXP *
18654 Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
18655 {
18656     struct regexp *ret;
18657     struct regexp *const r = ReANY(rx);
18658     const bool islv = ret_x && SvTYPE(ret_x) == SVt_PVLV;
18659
18660     PERL_ARGS_ASSERT_REG_TEMP_COPY;
18661
18662     if (!ret_x)
18663         ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
18664     else {
18665         SvOK_off((SV *)ret_x);
18666         if (islv) {
18667             /* For PVLVs, SvANY points to the xpvlv body while sv_u points
18668                to the regexp.  (For SVt_REGEXPs, sv_upgrade has already
18669                made both spots point to the same regexp body.) */
18670             REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
18671             assert(!SvPVX(ret_x));
18672             ret_x->sv_u.svu_rx = temp->sv_any;
18673             temp->sv_any = NULL;
18674             SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
18675             SvREFCNT_dec_NN(temp);
18676             /* SvCUR still resides in the xpvlv struct, so the regexp copy-
18677                ing below will not set it. */
18678             SvCUR_set(ret_x, SvCUR(rx));
18679         }
18680     }
18681     /* This ensures that SvTHINKFIRST(sv) is true, and hence that
18682        sv_force_normal(sv) is called.  */
18683     SvFAKE_on(ret_x);
18684     ret = ReANY(ret_x);
18685
18686     SvFLAGS(ret_x) |= SvUTF8(rx);
18687     /* We share the same string buffer as the original regexp, on which we
18688        hold a reference count, incremented when mother_re is set below.
18689        The string pointer is copied here, being part of the regexp struct.
18690      */
18691     memcpy(&(ret->xpv_cur), &(r->xpv_cur),
18692            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
18693     if (r->offs) {
18694         const I32 npar = r->nparens+1;
18695         Newx(ret->offs, npar, regexp_paren_pair);
18696         Copy(r->offs, ret->offs, npar, regexp_paren_pair);
18697     }
18698     if (r->substrs) {
18699         Newx(ret->substrs, 1, struct reg_substr_data);
18700         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
18701
18702         SvREFCNT_inc_void(ret->anchored_substr);
18703         SvREFCNT_inc_void(ret->anchored_utf8);
18704         SvREFCNT_inc_void(ret->float_substr);
18705         SvREFCNT_inc_void(ret->float_utf8);
18706
18707         /* check_substr and check_utf8, if non-NULL, point to either their
18708            anchored or float namesakes, and don't hold a second reference.  */
18709     }
18710     RX_MATCH_COPIED_off(ret_x);
18711 #ifdef PERL_ANY_COW
18712     ret->saved_copy = NULL;
18713 #endif
18714     ret->mother_re = ReREFCNT_inc(r->mother_re ? r->mother_re : rx);
18715     SvREFCNT_inc_void(ret->qr_anoncv);
18716
18717     return ret_x;
18718 }
18719 #endif
18720
18721 /* regfree_internal()
18722
18723    Free the private data in a regexp. This is overloadable by
18724    extensions. Perl takes care of the regexp structure in pregfree(),
18725    this covers the *pprivate pointer which technically perl doesn't
18726    know about, however of course we have to handle the
18727    regexp_internal structure when no extension is in use.
18728
18729    Note this is called before freeing anything in the regexp
18730    structure.
18731  */
18732
18733 void
18734 Perl_regfree_internal(pTHX_ REGEXP * const rx)
18735 {
18736     struct regexp *const r = ReANY(rx);
18737     RXi_GET_DECL(r,ri);
18738     GET_RE_DEBUG_FLAGS_DECL;
18739
18740     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
18741
18742     DEBUG_COMPILE_r({
18743         if (!PL_colorset)
18744             reginitcolors();
18745         {
18746             SV *dsv= sv_newmortal();
18747             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
18748                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
18749             PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
18750                 PL_colors[4],PL_colors[5],s);
18751         }
18752     });
18753 #ifdef RE_TRACK_PATTERN_OFFSETS
18754     if (ri->u.offsets)
18755         Safefree(ri->u.offsets);             /* 20010421 MJD */
18756 #endif
18757     if (ri->code_blocks) {
18758         int n;
18759         for (n = 0; n < ri->num_code_blocks; n++)
18760             SvREFCNT_dec(ri->code_blocks[n].src_regex);
18761         Safefree(ri->code_blocks);
18762     }
18763
18764     if (ri->data) {
18765         int n = ri->data->count;
18766
18767         while (--n >= 0) {
18768           /* If you add a ->what type here, update the comment in regcomp.h */
18769             switch (ri->data->what[n]) {
18770             case 'a':
18771             case 'r':
18772             case 's':
18773             case 'S':
18774             case 'u':
18775                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
18776                 break;
18777             case 'f':
18778                 Safefree(ri->data->data[n]);
18779                 break;
18780             case 'l':
18781             case 'L':
18782                 break;
18783             case 'T':
18784                 { /* Aho Corasick add-on structure for a trie node.
18785                      Used in stclass optimization only */
18786                     U32 refcount;
18787                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
18788 #ifdef USE_ITHREADS
18789                     dVAR;
18790 #endif
18791                     OP_REFCNT_LOCK;
18792                     refcount = --aho->refcount;
18793                     OP_REFCNT_UNLOCK;
18794                     if ( !refcount ) {
18795                         PerlMemShared_free(aho->states);
18796                         PerlMemShared_free(aho->fail);
18797                          /* do this last!!!! */
18798                         PerlMemShared_free(ri->data->data[n]);
18799                         /* we should only ever get called once, so
18800                          * assert as much, and also guard the free
18801                          * which /might/ happen twice. At the least
18802                          * it will make code anlyzers happy and it
18803                          * doesn't cost much. - Yves */
18804                         assert(ri->regstclass);
18805                         if (ri->regstclass) {
18806                             PerlMemShared_free(ri->regstclass);
18807                             ri->regstclass = 0;
18808                         }
18809                     }
18810                 }
18811                 break;
18812             case 't':
18813                 {
18814                     /* trie structure. */
18815                     U32 refcount;
18816                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
18817 #ifdef USE_ITHREADS
18818                     dVAR;
18819 #endif
18820                     OP_REFCNT_LOCK;
18821                     refcount = --trie->refcount;
18822                     OP_REFCNT_UNLOCK;
18823                     if ( !refcount ) {
18824                         PerlMemShared_free(trie->charmap);
18825                         PerlMemShared_free(trie->states);
18826                         PerlMemShared_free(trie->trans);
18827                         if (trie->bitmap)
18828                             PerlMemShared_free(trie->bitmap);
18829                         if (trie->jump)
18830                             PerlMemShared_free(trie->jump);
18831                         PerlMemShared_free(trie->wordinfo);
18832                         /* do this last!!!! */
18833                         PerlMemShared_free(ri->data->data[n]);
18834                     }
18835                 }
18836                 break;
18837             default:
18838                 Perl_croak(aTHX_ "panic: regfree data code '%c'",
18839                                                     ri->data->what[n]);
18840             }
18841         }
18842         Safefree(ri->data->what);
18843         Safefree(ri->data);
18844     }
18845
18846     Safefree(ri);
18847 }
18848
18849 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
18850 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
18851 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
18852
18853 /*
18854    re_dup - duplicate a regexp.
18855
18856    This routine is expected to clone a given regexp structure. It is only
18857    compiled under USE_ITHREADS.
18858
18859    After all of the core data stored in struct regexp is duplicated
18860    the regexp_engine.dupe method is used to copy any private data
18861    stored in the *pprivate pointer. This allows extensions to handle
18862    any duplication it needs to do.
18863
18864    See pregfree() and regfree_internal() if you change anything here.
18865 */
18866 #if defined(USE_ITHREADS)
18867 #ifndef PERL_IN_XSUB_RE
18868 void
18869 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
18870 {
18871     dVAR;
18872     I32 npar;
18873     const struct regexp *r = ReANY(sstr);
18874     struct regexp *ret = ReANY(dstr);
18875
18876     PERL_ARGS_ASSERT_RE_DUP_GUTS;
18877
18878     npar = r->nparens+1;
18879     Newx(ret->offs, npar, regexp_paren_pair);
18880     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
18881
18882     if (ret->substrs) {
18883         /* Do it this way to avoid reading from *r after the StructCopy().
18884            That way, if any of the sv_dup_inc()s dislodge *r from the L1
18885            cache, it doesn't matter.  */
18886         const bool anchored = r->check_substr
18887             ? r->check_substr == r->anchored_substr
18888             : r->check_utf8 == r->anchored_utf8;
18889         Newx(ret->substrs, 1, struct reg_substr_data);
18890         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
18891
18892         ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
18893         ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
18894         ret->float_substr = sv_dup_inc(ret->float_substr, param);
18895         ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
18896
18897         /* check_substr and check_utf8, if non-NULL, point to either their
18898            anchored or float namesakes, and don't hold a second reference.  */
18899
18900         if (ret->check_substr) {
18901             if (anchored) {
18902                 assert(r->check_utf8 == r->anchored_utf8);
18903                 ret->check_substr = ret->anchored_substr;
18904                 ret->check_utf8 = ret->anchored_utf8;
18905             } else {
18906                 assert(r->check_substr == r->float_substr);
18907                 assert(r->check_utf8 == r->float_utf8);
18908                 ret->check_substr = ret->float_substr;
18909                 ret->check_utf8 = ret->float_utf8;
18910             }
18911         } else if (ret->check_utf8) {
18912             if (anchored) {
18913                 ret->check_utf8 = ret->anchored_utf8;
18914             } else {
18915                 ret->check_utf8 = ret->float_utf8;
18916             }
18917         }
18918     }
18919
18920     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
18921     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
18922
18923     if (ret->pprivate)
18924         RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
18925
18926     if (RX_MATCH_COPIED(dstr))
18927         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
18928     else
18929         ret->subbeg = NULL;
18930 #ifdef PERL_ANY_COW
18931     ret->saved_copy = NULL;
18932 #endif
18933
18934     /* Whether mother_re be set or no, we need to copy the string.  We
18935        cannot refrain from copying it when the storage points directly to
18936        our mother regexp, because that's
18937                1: a buffer in a different thread
18938                2: something we no longer hold a reference on
18939                so we need to copy it locally.  */
18940     RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED(sstr), SvCUR(sstr)+1);
18941     ret->mother_re   = NULL;
18942 }
18943 #endif /* PERL_IN_XSUB_RE */
18944
18945 /*
18946    regdupe_internal()
18947
18948    This is the internal complement to regdupe() which is used to copy
18949    the structure pointed to by the *pprivate pointer in the regexp.
18950    This is the core version of the extension overridable cloning hook.
18951    The regexp structure being duplicated will be copied by perl prior
18952    to this and will be provided as the regexp *r argument, however
18953    with the /old/ structures pprivate pointer value. Thus this routine
18954    may override any copying normally done by perl.
18955
18956    It returns a pointer to the new regexp_internal structure.
18957 */
18958
18959 void *
18960 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
18961 {
18962     dVAR;
18963     struct regexp *const r = ReANY(rx);
18964     regexp_internal *reti;
18965     int len;
18966     RXi_GET_DECL(r,ri);
18967
18968     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
18969
18970     len = ProgLen(ri);
18971
18972     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode),
18973           char, regexp_internal);
18974     Copy(ri->program, reti->program, len+1, regnode);
18975
18976     reti->num_code_blocks = ri->num_code_blocks;
18977     if (ri->code_blocks) {
18978         int n;
18979         Newxc(reti->code_blocks, ri->num_code_blocks, struct reg_code_block,
18980                 struct reg_code_block);
18981         Copy(ri->code_blocks, reti->code_blocks, ri->num_code_blocks,
18982                 struct reg_code_block);
18983         for (n = 0; n < ri->num_code_blocks; n++)
18984              reti->code_blocks[n].src_regex = (REGEXP*)
18985                     sv_dup_inc((SV*)(ri->code_blocks[n].src_regex), param);
18986     }
18987     else
18988         reti->code_blocks = NULL;
18989
18990     reti->regstclass = NULL;
18991
18992     if (ri->data) {
18993         struct reg_data *d;
18994         const int count = ri->data->count;
18995         int i;
18996
18997         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
18998                 char, struct reg_data);
18999         Newx(d->what, count, U8);
19000
19001         d->count = count;
19002         for (i = 0; i < count; i++) {
19003             d->what[i] = ri->data->what[i];
19004             switch (d->what[i]) {
19005                 /* see also regcomp.h and regfree_internal() */
19006             case 'a': /* actually an AV, but the dup function is identical.  */
19007             case 'r':
19008             case 's':
19009             case 'S':
19010             case 'u': /* actually an HV, but the dup function is identical.  */
19011                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
19012                 break;
19013             case 'f':
19014                 /* This is cheating. */
19015                 Newx(d->data[i], 1, regnode_ssc);
19016                 StructCopy(ri->data->data[i], d->data[i], regnode_ssc);
19017                 reti->regstclass = (regnode*)d->data[i];
19018                 break;
19019             case 'T':
19020                 /* Trie stclasses are readonly and can thus be shared
19021                  * without duplication. We free the stclass in pregfree
19022                  * when the corresponding reg_ac_data struct is freed.
19023                  */
19024                 reti->regstclass= ri->regstclass;
19025                 /* FALLTHROUGH */
19026             case 't':
19027                 OP_REFCNT_LOCK;
19028                 ((reg_trie_data*)ri->data->data[i])->refcount++;
19029                 OP_REFCNT_UNLOCK;
19030                 /* FALLTHROUGH */
19031             case 'l':
19032             case 'L':
19033                 d->data[i] = ri->data->data[i];
19034                 break;
19035             default:
19036                 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'",
19037                                                            ri->data->what[i]);
19038             }
19039         }
19040
19041         reti->data = d;
19042     }
19043     else
19044         reti->data = NULL;
19045
19046     reti->name_list_idx = ri->name_list_idx;
19047
19048 #ifdef RE_TRACK_PATTERN_OFFSETS
19049     if (ri->u.offsets) {
19050         Newx(reti->u.offsets, 2*len+1, U32);
19051         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
19052     }
19053 #else
19054     SetProgLen(reti,len);
19055 #endif
19056
19057     return (void*)reti;
19058 }
19059
19060 #endif    /* USE_ITHREADS */
19061
19062 #ifndef PERL_IN_XSUB_RE
19063
19064 /*
19065  - regnext - dig the "next" pointer out of a node
19066  */
19067 regnode *
19068 Perl_regnext(pTHX_ regnode *p)
19069 {
19070     I32 offset;
19071
19072     if (!p)
19073         return(NULL);
19074
19075     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
19076         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d",
19077                                                 (int)OP(p), (int)REGNODE_MAX);
19078     }
19079
19080     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
19081     if (offset == 0)
19082         return(NULL);
19083
19084     return(p+offset);
19085 }
19086 #endif
19087
19088 STATIC void
19089 S_re_croak2(pTHX_ bool utf8, const char* pat1,const char* pat2,...)
19090 {
19091     va_list args;
19092     STRLEN l1 = strlen(pat1);
19093     STRLEN l2 = strlen(pat2);
19094     char buf[512];
19095     SV *msv;
19096     const char *message;
19097
19098     PERL_ARGS_ASSERT_RE_CROAK2;
19099
19100     if (l1 > 510)
19101         l1 = 510;
19102     if (l1 + l2 > 510)
19103         l2 = 510 - l1;
19104     Copy(pat1, buf, l1 , char);
19105     Copy(pat2, buf + l1, l2 , char);
19106     buf[l1 + l2] = '\n';
19107     buf[l1 + l2 + 1] = '\0';
19108     va_start(args, pat2);
19109     msv = vmess(buf, &args);
19110     va_end(args);
19111     message = SvPV_const(msv,l1);
19112     if (l1 > 512)
19113         l1 = 512;
19114     Copy(message, buf, l1 , char);
19115     /* l1-1 to avoid \n */
19116     Perl_croak(aTHX_ "%"UTF8f, UTF8fARG(utf8, l1-1, buf));
19117 }
19118
19119 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
19120
19121 #ifndef PERL_IN_XSUB_RE
19122 void
19123 Perl_save_re_context(pTHX)
19124 {
19125     I32 nparens = -1;
19126     I32 i;
19127
19128     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
19129
19130     if (PL_curpm) {
19131         const REGEXP * const rx = PM_GETRE(PL_curpm);
19132         if (rx)
19133             nparens = RX_NPARENS(rx);
19134     }
19135
19136     /* RT #124109. This is a complete hack; in the SWASHNEW case we know
19137      * that PL_curpm will be null, but that utf8.pm and the modules it
19138      * loads will only use $1..$3.
19139      * The t/porting/re_context.t test file checks this assumption.
19140      */
19141     if (nparens == -1)
19142         nparens = 3;
19143
19144     for (i = 1; i <= nparens; i++) {
19145         char digits[TYPE_CHARS(long)];
19146         const STRLEN len = my_snprintf(digits, sizeof(digits),
19147                                        "%lu", (long)i);
19148         GV *const *const gvp
19149             = (GV**)hv_fetch(PL_defstash, digits, len, 0);
19150
19151         if (gvp) {
19152             GV * const gv = *gvp;
19153             if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
19154                 save_scalar(gv);
19155         }
19156     }
19157 }
19158 #endif
19159
19160 #ifdef DEBUGGING
19161
19162 STATIC void
19163 S_put_code_point(pTHX_ SV *sv, UV c)
19164 {
19165     PERL_ARGS_ASSERT_PUT_CODE_POINT;
19166
19167     if (c > 255) {
19168         Perl_sv_catpvf(aTHX_ sv, "\\x{%04"UVXf"}", c);
19169     }
19170     else if (isPRINT(c)) {
19171         const char string = (char) c;
19172         if (isBACKSLASHED_PUNCT(c))
19173             sv_catpvs(sv, "\\");
19174         sv_catpvn(sv, &string, 1);
19175     }
19176     else {
19177         const char * const mnemonic = cntrl_to_mnemonic((char) c);
19178         if (mnemonic) {
19179             Perl_sv_catpvf(aTHX_ sv, "%s", mnemonic);
19180         }
19181         else {
19182             Perl_sv_catpvf(aTHX_ sv, "\\x{%02X}", (U8) c);
19183         }
19184     }
19185 }
19186
19187 #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C
19188
19189 STATIC void
19190 S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals)
19191 {
19192     /* Appends to 'sv' a displayable version of the range of code points from
19193      * 'start' to 'end'.  It assumes that only ASCII printables are displayable
19194      * as-is (though some of these will be escaped by put_code_point()). */
19195
19196     const unsigned int min_range_count = 3;
19197
19198     assert(start <= end);
19199
19200     PERL_ARGS_ASSERT_PUT_RANGE;
19201
19202     while (start <= end) {
19203         UV this_end;
19204         const char * format;
19205
19206         if (end - start < min_range_count) {
19207
19208             /* Individual chars in short ranges */
19209             for (; start <= end; start++) {
19210                 put_code_point(sv, start);
19211             }
19212             break;
19213         }
19214
19215         /* If permitted by the input options, and there is a possibility that
19216          * this range contains a printable literal, look to see if there is
19217          * one.  */
19218         if (allow_literals && start <= MAX_PRINT_A) {
19219
19220             /* If the range begin isn't an ASCII printable, effectively split
19221              * the range into two parts:
19222              *  1) the portion before the first such printable,
19223              *  2) the rest
19224              * and output them separately. */
19225             if (! isPRINT_A(start)) {
19226                 UV temp_end = start + 1;
19227
19228                 /* There is no point looking beyond the final possible
19229                  * printable, in MAX_PRINT_A */
19230                 UV max = MIN(end, MAX_PRINT_A);
19231
19232                 while (temp_end <= max && ! isPRINT_A(temp_end)) {
19233                     temp_end++;
19234                 }
19235
19236                 /* Here, temp_end points to one beyond the first printable if
19237                  * found, or to one beyond 'max' if not.  If none found, make
19238                  * sure that we use the entire range */
19239                 if (temp_end > MAX_PRINT_A) {
19240                     temp_end = end + 1;
19241                 }
19242
19243                 /* Output the first part of the split range, the part that
19244                  * doesn't have printables, with no looking for literals
19245                  * (otherwise we would infinitely recurse) */
19246                 put_range(sv, start, temp_end - 1, FALSE);
19247
19248                 /* The 2nd part of the range (if any) starts here. */
19249                 start = temp_end;
19250
19251                 /* We continue instead of dropping down because even if the 2nd
19252                  * part is non-empty, it could be so short that we want to
19253                  * output it specially, as tested for at the top of this loop.
19254                  * */
19255                 continue;
19256             }
19257
19258             /* Here, 'start' is a printable ASCII.  If it is an alphanumeric,
19259              * output a sub-range of just the digits or letters, then process
19260              * the remaining portion as usual. */
19261             if (isALPHANUMERIC_A(start)) {
19262                 UV mask = (isDIGIT_A(start))
19263                            ? _CC_DIGIT
19264                              : isUPPER_A(start)
19265                                ? _CC_UPPER
19266                                : _CC_LOWER;
19267                 UV temp_end = start + 1;
19268
19269                 /* Find the end of the sub-range that includes just the
19270                  * characters in the same class as the first character in it */
19271                 while (temp_end <= end && _generic_isCC_A(temp_end, mask)) {
19272                     temp_end++;
19273                 }
19274                 temp_end--;
19275
19276                 /* For short ranges, don't duplicate the code above to output
19277                  * them; just call recursively */
19278                 if (temp_end - start < min_range_count) {
19279                     put_range(sv, start, temp_end, FALSE);
19280                 }
19281                 else {  /* Output as a range */
19282                     put_code_point(sv, start);
19283                     sv_catpvs(sv, "-");
19284                     put_code_point(sv, temp_end);
19285                 }
19286                 start = temp_end + 1;
19287                 continue;
19288             }
19289
19290             /* We output any other printables as individual characters */
19291             if (isPUNCT_A(start) || isSPACE_A(start)) {
19292                 while (start <= end && (isPUNCT_A(start)
19293                                         || isSPACE_A(start)))
19294                 {
19295                     put_code_point(sv, start);
19296                     start++;
19297                 }
19298                 continue;
19299             }
19300         } /* End of looking for literals */
19301
19302         /* Here is not to output as a literal.  Some control characters have
19303          * mnemonic names.  Split off any of those at the beginning and end of
19304          * the range to print mnemonically.  It isn't possible for many of
19305          * these to be in a row, so this won't overwhelm with output */
19306         while (isMNEMONIC_CNTRL(start) && start <= end) {
19307             put_code_point(sv, start);
19308             start++;
19309         }
19310         if (start < end && isMNEMONIC_CNTRL(end)) {
19311
19312             /* Here, the final character in the range has a mnemonic name.
19313              * Work backwards from the end to find the final non-mnemonic */
19314             UV temp_end = end - 1;
19315             while (isMNEMONIC_CNTRL(temp_end)) {
19316                 temp_end--;
19317             }
19318
19319             /* And separately output the range that doesn't have mnemonics */
19320             put_range(sv, start, temp_end, FALSE);
19321
19322             /* Then output the mnemonic trailing controls */
19323             start = temp_end + 1;
19324             while (start <= end) {
19325                 put_code_point(sv, start);
19326                 start++;
19327             }
19328             break;
19329         }
19330
19331         /* As a final resort, output the range or subrange as hex. */
19332
19333         this_end = (end < NUM_ANYOF_CODE_POINTS)
19334                     ? end
19335                     : NUM_ANYOF_CODE_POINTS - 1;
19336 #if NUM_ANYOF_CODE_POINTS > 256
19337         format = (this_end < 256)
19338                  ? "\\x{%02"UVXf"}-\\x{%02"UVXf"}"
19339                  : "\\x{%04"UVXf"}-\\x{%04"UVXf"}";
19340 #else
19341         format = "\\x{%02"UVXf"}-\\x{%02"UVXf"}";
19342 #endif
19343         GCC_DIAG_IGNORE(-Wformat-nonliteral);
19344         Perl_sv_catpvf(aTHX_ sv, format, start, this_end);
19345         GCC_DIAG_RESTORE;
19346         break;
19347     }
19348 }
19349
19350 STATIC bool
19351 S_put_charclass_bitmap_innards(pTHX_ SV *sv, char *bitmap, SV** bitmap_invlist)
19352 {
19353     /* Appends to 'sv' a displayable version of the innards of the bracketed
19354      * character class whose bitmap is 'bitmap';  Returns 'TRUE' if it actually
19355      * output anything, and bitmap_invlist, if not NULL, will point to an
19356      * inversion list of what is in the bit map */
19357
19358     int i;
19359     UV start, end;
19360     unsigned int punct_count = 0;
19361     SV* invlist;
19362     bool allow_literals = TRUE;
19363     bool inverted_for_output = FALSE;
19364
19365     PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS;
19366
19367     /* Worst case is exactly every-other code point is in the list */
19368     invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2);
19369
19370     /* Convert the bit map to an inversion list, keeping track of how many
19371      * ASCII puncts are set, including an extra amount for the backslashed
19372      * ones.  */
19373     for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) {
19374         if (BITMAP_TEST(bitmap, i)) {
19375             invlist = add_cp_to_invlist(invlist, i);
19376             if (isPUNCT_A(i)) {
19377                 punct_count++;
19378                 if isBACKSLASHED_PUNCT(i) {
19379                     punct_count++;
19380                 }
19381             }
19382         }
19383     }
19384
19385     /* Nothing to output */
19386     if (_invlist_len(invlist) == 0) {
19387         SvREFCNT_dec_NN(invlist);
19388         return FALSE;
19389     }
19390
19391     /* Generally, it is more readable if printable characters are output as
19392      * literals, but if a range (nearly) spans all of them, it's best to output
19393      * it as a single range.  This code will use a single range if all but 2
19394      * printables are in it */
19395     invlist_iterinit(invlist);
19396     while (invlist_iternext(invlist, &start, &end)) {
19397
19398         /* If range starts beyond final printable, it doesn't have any in it */
19399         if (start > MAX_PRINT_A) {
19400             break;
19401         }
19402
19403         /* In both ASCII and EBCDIC, a SPACE is the lowest printable.  To span
19404          * all but two, the range must start and end no later than 2 from
19405          * either end */
19406         if (start < ' ' + 2 && end > MAX_PRINT_A - 2) {
19407             if (end > MAX_PRINT_A) {
19408                 end = MAX_PRINT_A;
19409             }
19410             if (start < ' ') {
19411                 start = ' ';
19412             }
19413             if (end - start >= MAX_PRINT_A - ' ' - 2) {
19414                 allow_literals = FALSE;
19415             }
19416             break;
19417         }
19418     }
19419     invlist_iterfinish(invlist);
19420
19421     /* The legibility of the output depends mostly on how many punctuation
19422      * characters are output.  There are 32 possible ASCII ones, and some have
19423      * an additional backslash, bringing it to currently 36, so if any more
19424      * than 18 are to be output, we can instead output it as its complement,
19425      * yielding fewer puncts, and making it more legible.  But give some weight
19426      * to the fact that outputting it as a complement is less legible than a
19427      * straight output, so don't complement unless we are somewhat over the 18
19428      * mark */
19429     if (allow_literals && punct_count > 22) {
19430         sv_catpvs(sv, "^");
19431
19432         /* Add everything remaining to the list, so when we invert it just
19433          * below, it will be excluded */
19434         _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist);
19435         _invlist_invert(invlist);
19436         inverted_for_output = TRUE;
19437     }
19438
19439     /* Here we have figured things out.  Output each range */
19440     invlist_iterinit(invlist);
19441     while (invlist_iternext(invlist, &start, &end)) {
19442         if (start >= NUM_ANYOF_CODE_POINTS) {
19443             break;
19444         }
19445         put_range(sv, start, end, allow_literals);
19446     }
19447     invlist_iterfinish(invlist);
19448
19449     if (bitmap_invlist) {
19450
19451         /* Here, wants the inversion list returned.  If we inverted it, we have
19452          * to restore it to the original */
19453         if (inverted_for_output) {
19454             _invlist_invert(invlist);
19455             _invlist_intersection(invlist, PL_InBitmap, &invlist);
19456         }
19457
19458         *bitmap_invlist = invlist;
19459     }
19460     else {
19461         SvREFCNT_dec_NN(invlist);
19462     }
19463
19464     return TRUE;
19465 }
19466
19467 #define CLEAR_OPTSTART \
19468     if (optstart) STMT_START {                                               \
19469         DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,                       \
19470                               " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
19471         optstart=NULL;                                                       \
19472     } STMT_END
19473
19474 #define DUMPUNTIL(b,e)                                                       \
19475                     CLEAR_OPTSTART;                                          \
19476                     node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
19477
19478 STATIC const regnode *
19479 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
19480             const regnode *last, const regnode *plast,
19481             SV* sv, I32 indent, U32 depth)
19482 {
19483     U8 op = PSEUDO;     /* Arbitrary non-END op. */
19484     const regnode *next;
19485     const regnode *optstart= NULL;
19486
19487     RXi_GET_DECL(r,ri);
19488     GET_RE_DEBUG_FLAGS_DECL;
19489
19490     PERL_ARGS_ASSERT_DUMPUNTIL;
19491
19492 #ifdef DEBUG_DUMPUNTIL
19493     PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
19494         last ? last-start : 0,plast ? plast-start : 0);
19495 #endif
19496
19497     if (plast && plast < last)
19498         last= plast;
19499
19500     while (PL_regkind[op] != END && (!last || node < last)) {
19501         assert(node);
19502         /* While that wasn't END last time... */
19503         NODE_ALIGN(node);
19504         op = OP(node);
19505         if (op == CLOSE || op == WHILEM)
19506             indent--;
19507         next = regnext((regnode *)node);
19508
19509         /* Where, what. */
19510         if (OP(node) == OPTIMIZED) {
19511             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
19512                 optstart = node;
19513             else
19514                 goto after_print;
19515         } else
19516             CLEAR_OPTSTART;
19517
19518         regprop(r, sv, node, NULL, NULL);
19519         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
19520                       (int)(2*indent + 1), "", SvPVX_const(sv));
19521
19522         if (OP(node) != OPTIMIZED) {
19523             if (next == NULL)           /* Next ptr. */
19524                 PerlIO_printf(Perl_debug_log, " (0)");
19525             else if (PL_regkind[(U8)op] == BRANCH
19526                      && PL_regkind[OP(next)] != BRANCH )
19527                 PerlIO_printf(Perl_debug_log, " (FAIL)");
19528             else
19529                 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
19530             (void)PerlIO_putc(Perl_debug_log, '\n');
19531         }
19532
19533       after_print:
19534         if (PL_regkind[(U8)op] == BRANCHJ) {
19535             assert(next);
19536             {
19537                 const regnode *nnode = (OP(next) == LONGJMP
19538                                        ? regnext((regnode *)next)
19539                                        : next);
19540                 if (last && nnode > last)
19541                     nnode = last;
19542                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
19543             }
19544         }
19545         else if (PL_regkind[(U8)op] == BRANCH) {
19546             assert(next);
19547             DUMPUNTIL(NEXTOPER(node), next);
19548         }
19549         else if ( PL_regkind[(U8)op]  == TRIE ) {
19550             const regnode *this_trie = node;
19551             const char op = OP(node);
19552             const U32 n = ARG(node);
19553             const reg_ac_data * const ac = op>=AHOCORASICK ?
19554                (reg_ac_data *)ri->data->data[n] :
19555                NULL;
19556             const reg_trie_data * const trie =
19557                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
19558 #ifdef DEBUGGING
19559             AV *const trie_words
19560                            = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
19561 #endif
19562             const regnode *nextbranch= NULL;
19563             I32 word_idx;
19564             sv_setpvs(sv, "");
19565             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
19566                 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
19567
19568                 PerlIO_printf(Perl_debug_log, "%*s%s ",
19569                    (int)(2*(indent+3)), "",
19570                     elem_ptr
19571                     ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr),
19572                                 SvCUR(*elem_ptr), 60,
19573                                 PL_colors[0], PL_colors[1],
19574                                 (SvUTF8(*elem_ptr)
19575                                  ? PERL_PV_ESCAPE_UNI
19576                                  : 0)
19577                                 | PERL_PV_PRETTY_ELLIPSES
19578                                 | PERL_PV_PRETTY_LTGT
19579                             )
19580                     : "???"
19581                 );
19582                 if (trie->jump) {
19583                     U16 dist= trie->jump[word_idx+1];
19584                     PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
19585                                (UV)((dist ? this_trie + dist : next) - start));
19586                     if (dist) {
19587                         if (!nextbranch)
19588                             nextbranch= this_trie + trie->jump[0];
19589                         DUMPUNTIL(this_trie + dist, nextbranch);
19590                     }
19591                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
19592                         nextbranch= regnext((regnode *)nextbranch);
19593                 } else {
19594                     PerlIO_printf(Perl_debug_log, "\n");
19595                 }
19596             }
19597             if (last && next > last)
19598                 node= last;
19599             else
19600                 node= next;
19601         }
19602         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
19603             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
19604                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
19605         }
19606         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
19607             assert(next);
19608             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
19609         }
19610         else if ( op == PLUS || op == STAR) {
19611             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
19612         }
19613         else if (PL_regkind[(U8)op] == ANYOF) {
19614             /* arglen 1 + class block */
19615             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_MATCHES_POSIXL)
19616                           ? ANYOF_POSIXL_SKIP
19617                           : ANYOF_SKIP);
19618             node = NEXTOPER(node);
19619         }
19620         else if (PL_regkind[(U8)op] == EXACT) {
19621             /* Literal string, where present. */
19622             node += NODE_SZ_STR(node) - 1;
19623             node = NEXTOPER(node);
19624         }
19625         else {
19626             node = NEXTOPER(node);
19627             node += regarglen[(U8)op];
19628         }
19629         if (op == CURLYX || op == OPEN)
19630             indent++;
19631     }
19632     CLEAR_OPTSTART;
19633 #ifdef DEBUG_DUMPUNTIL
19634     PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
19635 #endif
19636     return node;
19637 }
19638
19639 #endif  /* DEBUGGING */
19640
19641 /*
19642  * ex: set ts=8 sts=4 sw=4 et:
19643  */