This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
In B.xs use I16 to avoid an "initializer will be sign-extended" warning.
[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 const struct regexp_engine my_reg_engine;
85 #else
86 #  include "regcomp.h"
87 #endif
88
89 #include "dquote_static.c"
90 #include "charclass_invlists.h"
91 #include "inline_invlist.c"
92 #include "unicode_constants.h"
93
94 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
95 #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
96 #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c)
97
98 #ifdef op
99 #undef op
100 #endif /* op */
101
102 #ifdef MSDOS
103 #  if defined(BUGGY_MSC6)
104  /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
105 #    pragma optimize("a",off)
106  /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
107 #    pragma optimize("w",on )
108 #  endif /* BUGGY_MSC6 */
109 #endif /* MSDOS */
110
111 #ifndef STATIC
112 #define STATIC  static
113 #endif
114
115
116 typedef struct RExC_state_t {
117     U32         flags;                  /* RXf_* are we folding, multilining? */
118     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
119     char        *precomp;               /* uncompiled string. */
120     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
121     regexp      *rx;                    /* perl core regexp structure */
122     regexp_internal     *rxi;           /* internal data for regexp object pprivate field */        
123     char        *start;                 /* Start of input for compile */
124     char        *end;                   /* End of input for compile */
125     char        *parse;                 /* Input-scan pointer. */
126     I32         whilem_seen;            /* number of WHILEM in this expr */
127     regnode     *emit_start;            /* Start of emitted-code area */
128     regnode     *emit_bound;            /* First regnode outside of the allocated space */
129     regnode     *emit;                  /* Code-emit pointer; if = &emit_dummy,
130                                            implies compiling, so don't emit */
131     regnode     emit_dummy;             /* placeholder for emit to point to */
132     I32         naughty;                /* How bad is this pattern? */
133     I32         sawback;                /* Did we see \1, ...? */
134     U32         seen;
135     I32         size;                   /* Code size. */
136     I32         npar;                   /* Capture buffer count, (OPEN). */
137     I32         cpar;                   /* Capture buffer count, (CLOSE). */
138     I32         nestroot;               /* root parens we are in - used by accept */
139     I32         extralen;
140     I32         seen_zerolen;
141     regnode     **open_parens;          /* pointers to open parens */
142     regnode     **close_parens;         /* pointers to close parens */
143     regnode     *opend;                 /* END node in program */
144     I32         utf8;           /* whether the pattern is utf8 or not */
145     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
146                                 /* XXX use this for future optimisation of case
147                                  * where pattern must be upgraded to utf8. */
148     I32         uni_semantics;  /* If a d charset modifier should use unicode
149                                    rules, even if the pattern is not in
150                                    utf8 */
151     HV          *paren_names;           /* Paren names */
152     
153     regnode     **recurse;              /* Recurse regops */
154     I32         recurse_count;          /* Number of recurse regops */
155     I32         in_lookbehind;
156     I32         contains_locale;
157     I32         override_recoding;
158     I32         in_multi_char_class;
159     struct reg_code_block *code_blocks; /* positions of literal (?{})
160                                             within pattern */
161     int         num_code_blocks;        /* size of code_blocks[] */
162     int         code_index;             /* next code_blocks[] slot */
163 #if ADD_TO_REGEXEC
164     char        *starttry;              /* -Dr: where regtry was called. */
165 #define RExC_starttry   (pRExC_state->starttry)
166 #endif
167     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
168 #ifdef DEBUGGING
169     const char  *lastparse;
170     I32         lastnum;
171     AV          *paren_name_list;       /* idx -> name */
172 #define RExC_lastparse  (pRExC_state->lastparse)
173 #define RExC_lastnum    (pRExC_state->lastnum)
174 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
175 #endif
176 } RExC_state_t;
177
178 #define RExC_flags      (pRExC_state->flags)
179 #define RExC_pm_flags   (pRExC_state->pm_flags)
180 #define RExC_precomp    (pRExC_state->precomp)
181 #define RExC_rx_sv      (pRExC_state->rx_sv)
182 #define RExC_rx         (pRExC_state->rx)
183 #define RExC_rxi        (pRExC_state->rxi)
184 #define RExC_start      (pRExC_state->start)
185 #define RExC_end        (pRExC_state->end)
186 #define RExC_parse      (pRExC_state->parse)
187 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
188 #ifdef RE_TRACK_PATTERN_OFFSETS
189 #define RExC_offsets    (pRExC_state->rxi->u.offsets) /* I am not like the others */
190 #endif
191 #define RExC_emit       (pRExC_state->emit)
192 #define RExC_emit_dummy (pRExC_state->emit_dummy)
193 #define RExC_emit_start (pRExC_state->emit_start)
194 #define RExC_emit_bound (pRExC_state->emit_bound)
195 #define RExC_naughty    (pRExC_state->naughty)
196 #define RExC_sawback    (pRExC_state->sawback)
197 #define RExC_seen       (pRExC_state->seen)
198 #define RExC_size       (pRExC_state->size)
199 #define RExC_npar       (pRExC_state->npar)
200 #define RExC_nestroot   (pRExC_state->nestroot)
201 #define RExC_extralen   (pRExC_state->extralen)
202 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
203 #define RExC_utf8       (pRExC_state->utf8)
204 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
205 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
206 #define RExC_open_parens        (pRExC_state->open_parens)
207 #define RExC_close_parens       (pRExC_state->close_parens)
208 #define RExC_opend      (pRExC_state->opend)
209 #define RExC_paren_names        (pRExC_state->paren_names)
210 #define RExC_recurse    (pRExC_state->recurse)
211 #define RExC_recurse_count      (pRExC_state->recurse_count)
212 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
213 #define RExC_contains_locale    (pRExC_state->contains_locale)
214 #define RExC_override_recoding (pRExC_state->override_recoding)
215 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
216
217
218 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
219 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
220         ((*s) == '{' && regcurly(s, FALSE)))
221
222 #ifdef SPSTART
223 #undef SPSTART          /* dratted cpp namespace... */
224 #endif
225 /*
226  * Flags to be passed up and down.
227  */
228 #define WORST           0       /* Worst case. */
229 #define HASWIDTH        0x01    /* Known to match non-null strings. */
230
231 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
232  * character.  (There needs to be a case: in the switch statement in regexec.c
233  * for any node marked SIMPLE.)  Note that this is not the same thing as
234  * REGNODE_SIMPLE */
235 #define SIMPLE          0x02
236 #define SPSTART         0x04    /* Starts with * or + */
237 #define POSTPONED       0x08    /* (?1),(?&name), (??{...}) or similar */
238 #define TRYAGAIN        0x10    /* Weeded out a declaration. */
239 #define RESTART_UTF8    0x20    /* Restart, need to calcuate sizes as UTF-8 */
240
241 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
242
243 /* whether trie related optimizations are enabled */
244 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
245 #define TRIE_STUDY_OPT
246 #define FULL_TRIE_STUDY
247 #define TRIE_STCLASS
248 #endif
249
250
251
252 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
253 #define PBITVAL(paren) (1 << ((paren) & 7))
254 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
255 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
256 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
257
258 #define REQUIRE_UTF8    STMT_START {                                       \
259                                      if (!UTF) {                           \
260                                          *flagp = RESTART_UTF8;            \
261                                          return NULL;                      \
262                                      }                                     \
263                         } STMT_END
264
265 /* This converts the named class defined in regcomp.h to its equivalent class
266  * number defined in handy.h. */
267 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
268 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
269
270 /* About scan_data_t.
271
272   During optimisation we recurse through the regexp program performing
273   various inplace (keyhole style) optimisations. In addition study_chunk
274   and scan_commit populate this data structure with information about
275   what strings MUST appear in the pattern. We look for the longest 
276   string that must appear at a fixed location, and we look for the
277   longest string that may appear at a floating location. So for instance
278   in the pattern:
279   
280     /FOO[xX]A.*B[xX]BAR/
281     
282   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
283   strings (because they follow a .* construct). study_chunk will identify
284   both FOO and BAR as being the longest fixed and floating strings respectively.
285   
286   The strings can be composites, for instance
287   
288      /(f)(o)(o)/
289      
290   will result in a composite fixed substring 'foo'.
291   
292   For each string some basic information is maintained:
293   
294   - offset or min_offset
295     This is the position the string must appear at, or not before.
296     It also implicitly (when combined with minlenp) tells us how many
297     characters must match before the string we are searching for.
298     Likewise when combined with minlenp and the length of the string it
299     tells us how many characters must appear after the string we have 
300     found.
301   
302   - max_offset
303     Only used for floating strings. This is the rightmost point that
304     the string can appear at. If set to I32 max it indicates that the
305     string can occur infinitely far to the right.
306   
307   - minlenp
308     A pointer to the minimum number of characters of the pattern that the
309     string was found inside. This is important as in the case of positive
310     lookahead or positive lookbehind we can have multiple patterns 
311     involved. Consider
312     
313     /(?=FOO).*F/
314     
315     The minimum length of the pattern overall is 3, the minimum length
316     of the lookahead part is 3, but the minimum length of the part that
317     will actually match is 1. So 'FOO's minimum length is 3, but the 
318     minimum length for the F is 1. This is important as the minimum length
319     is used to determine offsets in front of and behind the string being 
320     looked for.  Since strings can be composites this is the length of the
321     pattern at the time it was committed with a scan_commit. Note that
322     the length is calculated by study_chunk, so that the minimum lengths
323     are not known until the full pattern has been compiled, thus the 
324     pointer to the value.
325   
326   - lookbehind
327   
328     In the case of lookbehind the string being searched for can be
329     offset past the start point of the final matching string. 
330     If this value was just blithely removed from the min_offset it would
331     invalidate some of the calculations for how many chars must match
332     before or after (as they are derived from min_offset and minlen and
333     the length of the string being searched for). 
334     When the final pattern is compiled and the data is moved from the
335     scan_data_t structure into the regexp structure the information
336     about lookbehind is factored in, with the information that would 
337     have been lost precalculated in the end_shift field for the 
338     associated string.
339
340   The fields pos_min and pos_delta are used to store the minimum offset
341   and the delta to the maximum offset at the current point in the pattern.    
342
343 */
344
345 typedef struct scan_data_t {
346     /*I32 len_min;      unused */
347     /*I32 len_delta;    unused */
348     I32 pos_min;
349     I32 pos_delta;
350     SV *last_found;
351     I32 last_end;           /* min value, <0 unless valid. */
352     I32 last_start_min;
353     I32 last_start_max;
354     SV **longest;           /* Either &l_fixed, or &l_float. */
355     SV *longest_fixed;      /* longest fixed string found in pattern */
356     I32 offset_fixed;       /* offset where it starts */
357     I32 *minlen_fixed;      /* pointer to the minlen relevant to the string */
358     I32 lookbehind_fixed;   /* is the position of the string modfied by LB */
359     SV *longest_float;      /* longest floating string found in pattern */
360     I32 offset_float_min;   /* earliest point in string it can appear */
361     I32 offset_float_max;   /* latest point in string it can appear */
362     I32 *minlen_float;      /* pointer to the minlen relevant to the string */
363     I32 lookbehind_float;   /* is the position of the string modified by LB */
364     I32 flags;
365     I32 whilem_c;
366     I32 *last_closep;
367     struct regnode_charclass_class *start_class;
368 } scan_data_t;
369
370 /*
371  * Forward declarations for pregcomp()'s friends.
372  */
373
374 static const scan_data_t zero_scan_data =
375   { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
376
377 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
378 #define SF_BEFORE_SEOL          0x0001
379 #define SF_BEFORE_MEOL          0x0002
380 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
381 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
382
383 #ifdef NO_UNARY_PLUS
384 #  define SF_FIX_SHIFT_EOL      (0+2)
385 #  define SF_FL_SHIFT_EOL               (0+4)
386 #else
387 #  define SF_FIX_SHIFT_EOL      (+2)
388 #  define SF_FL_SHIFT_EOL               (+4)
389 #endif
390
391 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
392 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
393
394 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
395 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
396 #define SF_IS_INF               0x0040
397 #define SF_HAS_PAR              0x0080
398 #define SF_IN_PAR               0x0100
399 #define SF_HAS_EVAL             0x0200
400 #define SCF_DO_SUBSTR           0x0400
401 #define SCF_DO_STCLASS_AND      0x0800
402 #define SCF_DO_STCLASS_OR       0x1000
403 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
404 #define SCF_WHILEM_VISITED_POS  0x2000
405
406 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
407 #define SCF_SEEN_ACCEPT         0x8000 
408 #define SCF_TRIE_DOING_RESTUDY 0x10000
409
410 #define UTF cBOOL(RExC_utf8)
411
412 /* The enums for all these are ordered so things work out correctly */
413 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
414 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_DEPENDS_CHARSET)
415 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
416 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) >= REGEX_UNICODE_CHARSET)
417 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_RESTRICTED_CHARSET)
418 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) >= REGEX_ASCII_RESTRICTED_CHARSET)
419 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
420
421 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
422
423 #define OOB_NAMEDCLASS          -1
424
425 /* There is no code point that is out-of-bounds, so this is problematic.  But
426  * its only current use is to initialize a variable that is always set before
427  * looked at. */
428 #define OOB_UNICODE             0xDEADBEEF
429
430 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
431 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
432
433
434 /* length of regex to show in messages that don't mark a position within */
435 #define RegexLengthToShowInErrorMessages 127
436
437 /*
438  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
439  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
440  * op/pragma/warn/regcomp.
441  */
442 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
443 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
444
445 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
446
447 /*
448  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
449  * arg. Show regex, up to a maximum length. If it's too long, chop and add
450  * "...".
451  */
452 #define _FAIL(code) STMT_START {                                        \
453     const char *ellipses = "";                                          \
454     IV len = RExC_end - RExC_precomp;                                   \
455                                                                         \
456     if (!SIZE_ONLY)                                                     \
457         SAVEFREESV(RExC_rx_sv);                                         \
458     if (len > RegexLengthToShowInErrorMessages) {                       \
459         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
460         len = RegexLengthToShowInErrorMessages - 10;                    \
461         ellipses = "...";                                               \
462     }                                                                   \
463     code;                                                               \
464 } STMT_END
465
466 #define FAIL(msg) _FAIL(                            \
467     Perl_croak(aTHX_ "%s in regex m/%.*s%s/",       \
468             msg, (int)len, RExC_precomp, ellipses))
469
470 #define FAIL2(msg,arg) _FAIL(                       \
471     Perl_croak(aTHX_ msg " in regex m/%.*s%s/",     \
472             arg, (int)len, RExC_precomp, ellipses))
473
474 /*
475  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
476  */
477 #define Simple_vFAIL(m) STMT_START {                                    \
478     const IV offset = RExC_parse - RExC_precomp;                        \
479     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
480             m, (int)offset, RExC_precomp, RExC_precomp + offset);       \
481 } STMT_END
482
483 /*
484  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
485  */
486 #define vFAIL(m) STMT_START {                           \
487     if (!SIZE_ONLY)                                     \
488         SAVEFREESV(RExC_rx_sv);                         \
489     Simple_vFAIL(m);                                    \
490 } STMT_END
491
492 /*
493  * Like Simple_vFAIL(), but accepts two arguments.
494  */
495 #define Simple_vFAIL2(m,a1) STMT_START {                        \
496     const IV offset = RExC_parse - RExC_precomp;                        \
497     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1,                   \
498             (int)offset, RExC_precomp, RExC_precomp + offset);  \
499 } STMT_END
500
501 /*
502  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
503  */
504 #define vFAIL2(m,a1) STMT_START {                       \
505     if (!SIZE_ONLY)                                     \
506         SAVEFREESV(RExC_rx_sv);                         \
507     Simple_vFAIL2(m, a1);                               \
508 } STMT_END
509
510
511 /*
512  * Like Simple_vFAIL(), but accepts three arguments.
513  */
514 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
515     const IV offset = RExC_parse - RExC_precomp;                \
516     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2,               \
517             (int)offset, RExC_precomp, RExC_precomp + offset);  \
518 } STMT_END
519
520 /*
521  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
522  */
523 #define vFAIL3(m,a1,a2) STMT_START {                    \
524     if (!SIZE_ONLY)                                     \
525         SAVEFREESV(RExC_rx_sv);                         \
526     Simple_vFAIL3(m, a1, a2);                           \
527 } STMT_END
528
529 /*
530  * Like Simple_vFAIL(), but accepts four arguments.
531  */
532 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
533     const IV offset = RExC_parse - RExC_precomp;                \
534     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,           \
535             (int)offset, RExC_precomp, RExC_precomp + offset);  \
536 } STMT_END
537
538 #define vFAIL4(m,a1,a2,a3) STMT_START {                 \
539     if (!SIZE_ONLY)                                     \
540         SAVEFREESV(RExC_rx_sv);                         \
541     Simple_vFAIL4(m, a1, a2, a3);                       \
542 } STMT_END
543
544 /* m is not necessarily a "literal string", in this macro */
545 #define reg_warn_non_literal_string(loc, m) STMT_START {                \
546     const IV offset = loc - RExC_precomp;                               \
547     Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION,      \
548             m, (int)offset, RExC_precomp, RExC_precomp + offset);       \
549 } STMT_END
550
551 #define ckWARNreg(loc,m) STMT_START {                                   \
552     const IV offset = loc - RExC_precomp;                               \
553     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
554             (int)offset, RExC_precomp, RExC_precomp + offset);          \
555 } STMT_END
556
557 #define vWARN_dep(loc, m) STMT_START {                                  \
558     const IV offset = loc - RExC_precomp;                               \
559     Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), m REPORT_LOCATION,     \
560             (int)offset, RExC_precomp, RExC_precomp + offset);          \
561 } STMT_END
562
563 #define ckWARNdep(loc,m) STMT_START {                                   \
564     const IV offset = loc - RExC_precomp;                               \
565     Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),                   \
566             m REPORT_LOCATION,                                          \
567             (int)offset, RExC_precomp, RExC_precomp + offset);          \
568 } STMT_END
569
570 #define ckWARNregdep(loc,m) STMT_START {                                \
571     const IV offset = loc - RExC_precomp;                               \
572     Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP),     \
573             m REPORT_LOCATION,                                          \
574             (int)offset, RExC_precomp, RExC_precomp + offset);          \
575 } STMT_END
576
577 #define ckWARN2reg_d(loc,m, a1) STMT_START {                            \
578     const IV offset = loc - RExC_precomp;                               \
579     Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP),                       \
580             m REPORT_LOCATION,                                          \
581             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
582 } STMT_END
583
584 #define ckWARN2reg(loc, m, a1) STMT_START {                             \
585     const IV offset = loc - RExC_precomp;                               \
586     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
587             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
588 } STMT_END
589
590 #define vWARN3(loc, m, a1, a2) STMT_START {                             \
591     const IV offset = loc - RExC_precomp;                               \
592     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
593             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
594 } STMT_END
595
596 #define ckWARN3reg(loc, m, a1, a2) STMT_START {                         \
597     const IV offset = loc - RExC_precomp;                               \
598     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
599             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
600 } STMT_END
601
602 #define vWARN4(loc, m, a1, a2, a3) STMT_START {                         \
603     const IV offset = loc - RExC_precomp;                               \
604     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
605             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
606 } STMT_END
607
608 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START {                     \
609     const IV offset = loc - RExC_precomp;                               \
610     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
611             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
612 } STMT_END
613
614 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START {                     \
615     const IV offset = loc - RExC_precomp;                               \
616     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
617             a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
618 } STMT_END
619
620
621 /* Allow for side effects in s */
622 #define REGC(c,s) STMT_START {                  \
623     if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
624 } STMT_END
625
626 /* Macros for recording node offsets.   20001227 mjd@plover.com 
627  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
628  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
629  * Element 0 holds the number n.
630  * Position is 1 indexed.
631  */
632 #ifndef RE_TRACK_PATTERN_OFFSETS
633 #define Set_Node_Offset_To_R(node,byte)
634 #define Set_Node_Offset(node,byte)
635 #define Set_Cur_Node_Offset
636 #define Set_Node_Length_To_R(node,len)
637 #define Set_Node_Length(node,len)
638 #define Set_Node_Cur_Length(node,start)
639 #define Node_Offset(n) 
640 #define Node_Length(n) 
641 #define Set_Node_Offset_Length(node,offset,len)
642 #define ProgLen(ri) ri->u.proglen
643 #define SetProgLen(ri,x) ri->u.proglen = x
644 #else
645 #define ProgLen(ri) ri->u.offsets[0]
646 #define SetProgLen(ri,x) ri->u.offsets[0] = x
647 #define Set_Node_Offset_To_R(node,byte) STMT_START {                    \
648     if (! SIZE_ONLY) {                                                  \
649         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
650                     __LINE__, (int)(node), (int)(byte)));               \
651         if((node) < 0) {                                                \
652             Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
653         } else {                                                        \
654             RExC_offsets[2*(node)-1] = (byte);                          \
655         }                                                               \
656     }                                                                   \
657 } STMT_END
658
659 #define Set_Node_Offset(node,byte) \
660     Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
661 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
662
663 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
664     if (! SIZE_ONLY) {                                                  \
665         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
666                 __LINE__, (int)(node), (int)(len)));                    \
667         if((node) < 0) {                                                \
668             Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
669         } else {                                                        \
670             RExC_offsets[2*(node)] = (len);                             \
671         }                                                               \
672     }                                                                   \
673 } STMT_END
674
675 #define Set_Node_Length(node,len) \
676     Set_Node_Length_To_R((node)-RExC_emit_start, len)
677 #define Set_Node_Cur_Length(node, start)                \
678     Set_Node_Length(node, RExC_parse - start)
679
680 /* Get offsets and lengths */
681 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
682 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
683
684 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
685     Set_Node_Offset_To_R((node)-RExC_emit_start, (offset));     \
686     Set_Node_Length_To_R((node)-RExC_emit_start, (len));        \
687 } STMT_END
688 #endif
689
690 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
691 #define EXPERIMENTAL_INPLACESCAN
692 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
693
694 #define DEBUG_STUDYDATA(str,data,depth)                              \
695 DEBUG_OPTIMISE_MORE_r(if(data){                                      \
696     PerlIO_printf(Perl_debug_log,                                    \
697         "%*s" str "Pos:%"IVdf"/%"IVdf                                \
698         " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s",       \
699         (int)(depth)*2, "",                                          \
700         (IV)((data)->pos_min),                                       \
701         (IV)((data)->pos_delta),                                     \
702         (UV)((data)->flags),                                         \
703         (IV)((data)->whilem_c),                                      \
704         (IV)((data)->last_closep ? *((data)->last_closep) : -1),     \
705         is_inf ? "INF " : ""                                         \
706     );                                                               \
707     if ((data)->last_found)                                          \
708         PerlIO_printf(Perl_debug_log,                                \
709             "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
710             " %sFloat: '%s' @ %"IVdf"/%"IVdf"",                      \
711             SvPVX_const((data)->last_found),                         \
712             (IV)((data)->last_end),                                  \
713             (IV)((data)->last_start_min),                            \
714             (IV)((data)->last_start_max),                            \
715             ((data)->longest &&                                      \
716              (data)->longest==&((data)->longest_fixed)) ? "*" : "",  \
717             SvPVX_const((data)->longest_fixed),                      \
718             (IV)((data)->offset_fixed),                              \
719             ((data)->longest &&                                      \
720              (data)->longest==&((data)->longest_float)) ? "*" : "",  \
721             SvPVX_const((data)->longest_float),                      \
722             (IV)((data)->offset_float_min),                          \
723             (IV)((data)->offset_float_max)                           \
724         );                                                           \
725     PerlIO_printf(Perl_debug_log,"\n");                              \
726 });
727
728 /* Mark that we cannot extend a found fixed substring at this point.
729    Update the longest found anchored substring and the longest found
730    floating substrings if needed. */
731
732 STATIC void
733 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
734 {
735     const STRLEN l = CHR_SVLEN(data->last_found);
736     const STRLEN old_l = CHR_SVLEN(*data->longest);
737     GET_RE_DEBUG_FLAGS_DECL;
738
739     PERL_ARGS_ASSERT_SCAN_COMMIT;
740
741     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
742         SvSetMagicSV(*data->longest, data->last_found);
743         if (*data->longest == data->longest_fixed) {
744             data->offset_fixed = l ? data->last_start_min : data->pos_min;
745             if (data->flags & SF_BEFORE_EOL)
746                 data->flags
747                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
748             else
749                 data->flags &= ~SF_FIX_BEFORE_EOL;
750             data->minlen_fixed=minlenp;
751             data->lookbehind_fixed=0;
752         }
753         else { /* *data->longest == data->longest_float */
754             data->offset_float_min = l ? data->last_start_min : data->pos_min;
755             data->offset_float_max = (l
756                                       ? data->last_start_max
757                                       : (data->pos_delta == I32_MAX ? I32_MAX : data->pos_min + data->pos_delta));
758             if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
759                 data->offset_float_max = I32_MAX;
760             if (data->flags & SF_BEFORE_EOL)
761                 data->flags
762                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
763             else
764                 data->flags &= ~SF_FL_BEFORE_EOL;
765             data->minlen_float=minlenp;
766             data->lookbehind_float=0;
767         }
768     }
769     SvCUR_set(data->last_found, 0);
770     {
771         SV * const sv = data->last_found;
772         if (SvUTF8(sv) && SvMAGICAL(sv)) {
773             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
774             if (mg)
775                 mg->mg_len = 0;
776         }
777     }
778     data->last_end = -1;
779     data->flags &= ~SF_BEFORE_EOL;
780     DEBUG_STUDYDATA("commit: ",data,0);
781 }
782
783 /* These macros set, clear and test whether the synthetic start class ('ssc',
784  * given by the parameter) matches an empty string (EOS).  This uses the
785  * 'next_off' field in the node, to save a bit in the flags field.  The ssc
786  * stands alone, so there is never a next_off, so this field is otherwise
787  * unused.  The EOS information is used only for compilation, but theoretically
788  * it could be passed on to the execution code.  This could be used to store
789  * more than one bit of information, but only this one is currently used. */
790 #define SET_SSC_EOS(node)   STMT_START { (node)->next_off = TRUE; } STMT_END
791 #define CLEAR_SSC_EOS(node) STMT_START { (node)->next_off = FALSE; } STMT_END
792 #define TEST_SSC_EOS(node)  cBOOL((node)->next_off)
793
794 /* Can match anything (initialization) */
795 STATIC void
796 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
797 {
798     PERL_ARGS_ASSERT_CL_ANYTHING;
799
800     ANYOF_BITMAP_SETALL(cl);
801     cl->flags = ANYOF_UNICODE_ALL;
802     SET_SSC_EOS(cl);
803
804     /* If any portion of the regex is to operate under locale rules,
805      * initialization includes it.  The reason this isn't done for all regexes
806      * is that the optimizer was written under the assumption that locale was
807      * all-or-nothing.  Given the complexity and lack of documentation in the
808      * optimizer, and that there are inadequate test cases for locale, so many
809      * parts of it may not work properly, it is safest to avoid locale unless
810      * necessary. */
811     if (RExC_contains_locale) {
812         ANYOF_CLASS_SETALL(cl);     /* /l uses class */
813         cl->flags |= ANYOF_LOCALE|ANYOF_CLASS|ANYOF_LOC_FOLD;
814     }
815     else {
816         ANYOF_CLASS_ZERO(cl);       /* Only /l uses class now */
817     }
818 }
819
820 /* Can match anything (initialization) */
821 STATIC int
822 S_cl_is_anything(const struct regnode_charclass_class *cl)
823 {
824     int value;
825
826     PERL_ARGS_ASSERT_CL_IS_ANYTHING;
827
828     for (value = 0; value < ANYOF_MAX; value += 2)
829         if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
830             return 1;
831     if (!(cl->flags & ANYOF_UNICODE_ALL))
832         return 0;
833     if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
834         return 0;
835     return 1;
836 }
837
838 /* Can match anything (initialization) */
839 STATIC void
840 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
841 {
842     PERL_ARGS_ASSERT_CL_INIT;
843
844     Zero(cl, 1, struct regnode_charclass_class);
845     cl->type = ANYOF;
846     cl_anything(pRExC_state, cl);
847     ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
848 }
849
850 /* These two functions currently do the exact same thing */
851 #define cl_init_zero            cl_init
852
853 /* 'AND' a given class with another one.  Can create false positives.  'cl'
854  * should not be inverted.  'and_with->flags & ANYOF_CLASS' should be 0 if
855  * 'and_with' is a regnode_charclass instead of a regnode_charclass_class. */
856 STATIC void
857 S_cl_and(struct regnode_charclass_class *cl,
858         const struct regnode_charclass_class *and_with)
859 {
860     PERL_ARGS_ASSERT_CL_AND;
861
862     assert(PL_regkind[and_with->type] == ANYOF);
863
864     /* I (khw) am not sure all these restrictions are necessary XXX */
865     if (!(ANYOF_CLASS_TEST_ANY_SET(and_with))
866         && !(ANYOF_CLASS_TEST_ANY_SET(cl))
867         && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
868         && !(and_with->flags & ANYOF_LOC_FOLD)
869         && !(cl->flags & ANYOF_LOC_FOLD)) {
870         int i;
871
872         if (and_with->flags & ANYOF_INVERT)
873             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
874                 cl->bitmap[i] &= ~and_with->bitmap[i];
875         else
876             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
877                 cl->bitmap[i] &= and_with->bitmap[i];
878     } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
879
880     if (and_with->flags & ANYOF_INVERT) {
881
882         /* Here, the and'ed node is inverted.  Get the AND of the flags that
883          * aren't affected by the inversion.  Those that are affected are
884          * handled individually below */
885         U8 affected_flags = cl->flags & ~INVERSION_UNAFFECTED_FLAGS;
886         cl->flags &= (and_with->flags & INVERSION_UNAFFECTED_FLAGS);
887         cl->flags |= affected_flags;
888
889         /* We currently don't know how to deal with things that aren't in the
890          * bitmap, but we know that the intersection is no greater than what
891          * is already in cl, so let there be false positives that get sorted
892          * out after the synthetic start class succeeds, and the node is
893          * matched for real. */
894
895         /* The inversion of these two flags indicate that the resulting
896          * intersection doesn't have them */
897         if (and_with->flags & ANYOF_UNICODE_ALL) {
898             cl->flags &= ~ANYOF_UNICODE_ALL;
899         }
900         if (and_with->flags & ANYOF_NON_UTF8_LATIN1_ALL) {
901             cl->flags &= ~ANYOF_NON_UTF8_LATIN1_ALL;
902         }
903     }
904     else {   /* and'd node is not inverted */
905         U8 outside_bitmap_but_not_utf8; /* Temp variable */
906
907         if (! ANYOF_NONBITMAP(and_with)) {
908
909             /* Here 'and_with' doesn't match anything outside the bitmap
910              * (except possibly ANYOF_UNICODE_ALL), which means the
911              * intersection can't either, except for ANYOF_UNICODE_ALL, in
912              * which case we don't know what the intersection is, but it's no
913              * greater than what cl already has, so can just leave it alone,
914              * with possible false positives */
915             if (! (and_with->flags & ANYOF_UNICODE_ALL)) {
916                 ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
917                 cl->flags &= ~ANYOF_NONBITMAP_NON_UTF8;
918             }
919         }
920         else if (! ANYOF_NONBITMAP(cl)) {
921
922             /* Here, 'and_with' does match something outside the bitmap, and cl
923              * doesn't have a list of things to match outside the bitmap.  If
924              * cl can match all code points above 255, the intersection will
925              * be those above-255 code points that 'and_with' matches.  If cl
926              * can't match all Unicode code points, it means that it can't
927              * match anything outside the bitmap (since the 'if' that got us
928              * into this block tested for that), so we leave the bitmap empty.
929              */
930             if (cl->flags & ANYOF_UNICODE_ALL) {
931                 ARG_SET(cl, ARG(and_with));
932
933                 /* and_with's ARG may match things that don't require UTF8.
934                  * And now cl's will too, in spite of this being an 'and'.  See
935                  * the comments below about the kludge */
936                 cl->flags |= and_with->flags & ANYOF_NONBITMAP_NON_UTF8;
937             }
938         }
939         else {
940             /* Here, both 'and_with' and cl match something outside the
941              * bitmap.  Currently we do not do the intersection, so just match
942              * whatever cl had at the beginning.  */
943         }
944
945
946         /* Take the intersection of the two sets of flags.  However, the
947          * ANYOF_NONBITMAP_NON_UTF8 flag is treated as an 'or'.  This is a
948          * kludge around the fact that this flag is not treated like the others
949          * which are initialized in cl_anything().  The way the optimizer works
950          * is that the synthetic start class (SSC) is initialized to match
951          * anything, and then the first time a real node is encountered, its
952          * values are AND'd with the SSC's with the result being the values of
953          * the real node.  However, there are paths through the optimizer where
954          * the AND never gets called, so those initialized bits are set
955          * inappropriately, which is not usually a big deal, as they just cause
956          * false positives in the SSC, which will just mean a probably
957          * imperceptible slow down in execution.  However this bit has a
958          * higher false positive consequence in that it can cause utf8.pm,
959          * utf8_heavy.pl ... to be loaded when not necessary, which is a much
960          * bigger slowdown and also causes significant extra memory to be used.
961          * In order to prevent this, the code now takes a different tack.  The
962          * bit isn't set unless some part of the regular expression needs it,
963          * but once set it won't get cleared.  This means that these extra
964          * modules won't get loaded unless there was some path through the
965          * pattern that would have required them anyway, and  so any false
966          * positives that occur by not ANDing them out when they could be
967          * aren't as severe as they would be if we treated this bit like all
968          * the others */
969         outside_bitmap_but_not_utf8 = (cl->flags | and_with->flags)
970                                       & ANYOF_NONBITMAP_NON_UTF8;
971         cl->flags &= and_with->flags;
972         cl->flags |= outside_bitmap_but_not_utf8;
973     }
974 }
975
976 /* 'OR' a given class with another one.  Can create false positives.  'cl'
977  * should not be inverted.  'or_with->flags & ANYOF_CLASS' should be 0 if
978  * 'or_with' is a regnode_charclass instead of a regnode_charclass_class. */
979 STATIC void
980 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
981 {
982     PERL_ARGS_ASSERT_CL_OR;
983
984     if (or_with->flags & ANYOF_INVERT) {
985
986         /* Here, the or'd node is to be inverted.  This means we take the
987          * complement of everything not in the bitmap, but currently we don't
988          * know what that is, so give up and match anything */
989         if (ANYOF_NONBITMAP(or_with)) {
990             cl_anything(pRExC_state, cl);
991         }
992         /* We do not use
993          * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
994          *   <= (B1 | !B2) | (CL1 | !CL2)
995          * which is wasteful if CL2 is small, but we ignore CL2:
996          *   (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
997          * XXXX Can we handle case-fold?  Unclear:
998          *   (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
999          *   (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
1000          */
1001         else if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
1002              && !(or_with->flags & ANYOF_LOC_FOLD)
1003              && !(cl->flags & ANYOF_LOC_FOLD) ) {
1004             int i;
1005
1006             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
1007                 cl->bitmap[i] |= ~or_with->bitmap[i];
1008         } /* XXXX: logic is complicated otherwise */
1009         else {
1010             cl_anything(pRExC_state, cl);
1011         }
1012
1013         /* And, we can just take the union of the flags that aren't affected
1014          * by the inversion */
1015         cl->flags |= or_with->flags & INVERSION_UNAFFECTED_FLAGS;
1016
1017         /* For the remaining flags:
1018             ANYOF_UNICODE_ALL and inverted means to not match anything above
1019                     255, which means that the union with cl should just be
1020                     what cl has in it, so can ignore this flag
1021             ANYOF_NON_UTF8_LATIN1_ALL and inverted means if not utf8 and ord
1022                     is 127-255 to match them, but then invert that, so the
1023                     union with cl should just be what cl has in it, so can
1024                     ignore this flag
1025          */
1026     } else {    /* 'or_with' is not inverted */
1027         /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
1028         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
1029              && (!(or_with->flags & ANYOF_LOC_FOLD)
1030                  || (cl->flags & ANYOF_LOC_FOLD)) ) {
1031             int i;
1032
1033             /* OR char bitmap and class bitmap separately */
1034             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
1035                 cl->bitmap[i] |= or_with->bitmap[i];
1036             if (or_with->flags & ANYOF_CLASS) {
1037                 ANYOF_CLASS_OR(or_with, cl);
1038             }
1039         }
1040         else { /* XXXX: logic is complicated, leave it along for a moment. */
1041             cl_anything(pRExC_state, cl);
1042         }
1043
1044         if (ANYOF_NONBITMAP(or_with)) {
1045
1046             /* Use the added node's outside-the-bit-map match if there isn't a
1047              * conflict.  If there is a conflict (both nodes match something
1048              * outside the bitmap, but what they match outside is not the same
1049              * pointer, and hence not easily compared until XXX we extend
1050              * inversion lists this far), give up and allow the start class to
1051              * match everything outside the bitmap.  If that stuff is all above
1052              * 255, can just set UNICODE_ALL, otherwise caould be anything. */
1053             if (! ANYOF_NONBITMAP(cl)) {
1054                 ARG_SET(cl, ARG(or_with));
1055             }
1056             else if (ARG(cl) != ARG(or_with)) {
1057
1058                 if ((or_with->flags & ANYOF_NONBITMAP_NON_UTF8)) {
1059                     cl_anything(pRExC_state, cl);
1060                 }
1061                 else {
1062                     cl->flags |= ANYOF_UNICODE_ALL;
1063                 }
1064             }
1065         }
1066
1067         /* Take the union */
1068         cl->flags |= or_with->flags;
1069     }
1070 }
1071
1072 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1073 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
1074 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1075 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
1076
1077
1078 #ifdef DEBUGGING
1079 /*
1080    dump_trie(trie,widecharmap,revcharmap)
1081    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1082    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1083
1084    These routines dump out a trie in a somewhat readable format.
1085    The _interim_ variants are used for debugging the interim
1086    tables that are used to generate the final compressed
1087    representation which is what dump_trie expects.
1088
1089    Part of the reason for their existence is to provide a form
1090    of documentation as to how the different representations function.
1091
1092 */
1093
1094 /*
1095   Dumps the final compressed table form of the trie to Perl_debug_log.
1096   Used for debugging make_trie().
1097 */
1098
1099 STATIC void
1100 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1101             AV *revcharmap, U32 depth)
1102 {
1103     U32 state;
1104     SV *sv=sv_newmortal();
1105     int colwidth= widecharmap ? 6 : 4;
1106     U16 word;
1107     GET_RE_DEBUG_FLAGS_DECL;
1108
1109     PERL_ARGS_ASSERT_DUMP_TRIE;
1110
1111     PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1112         (int)depth * 2 + 2,"",
1113         "Match","Base","Ofs" );
1114
1115     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1116         SV ** const tmp = av_fetch( revcharmap, state, 0);
1117         if ( tmp ) {
1118             PerlIO_printf( Perl_debug_log, "%*s", 
1119                 colwidth,
1120                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1121                             PL_colors[0], PL_colors[1],
1122                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1123                             PERL_PV_ESCAPE_FIRSTCHAR 
1124                 ) 
1125             );
1126         }
1127     }
1128     PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1129         (int)depth * 2 + 2,"");
1130
1131     for( state = 0 ; state < trie->uniquecharcount ; state++ )
1132         PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1133     PerlIO_printf( Perl_debug_log, "\n");
1134
1135     for( state = 1 ; state < trie->statecount ; state++ ) {
1136         const U32 base = trie->states[ state ].trans.base;
1137
1138         PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
1139
1140         if ( trie->states[ state ].wordnum ) {
1141             PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
1142         } else {
1143             PerlIO_printf( Perl_debug_log, "%6s", "" );
1144         }
1145
1146         PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1147
1148         if ( base ) {
1149             U32 ofs = 0;
1150
1151             while( ( base + ofs  < trie->uniquecharcount ) ||
1152                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
1153                      && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
1154                     ofs++;
1155
1156             PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1157
1158             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1159                 if ( ( base + ofs >= trie->uniquecharcount ) &&
1160                      ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1161                      trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1162                 {
1163                    PerlIO_printf( Perl_debug_log, "%*"UVXf,
1164                     colwidth,
1165                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
1166                 } else {
1167                     PerlIO_printf( Perl_debug_log, "%*s",colwidth,"   ." );
1168                 }
1169             }
1170
1171             PerlIO_printf( Perl_debug_log, "]");
1172
1173         }
1174         PerlIO_printf( Perl_debug_log, "\n" );
1175     }
1176     PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=", (int)depth*2, "");
1177     for (word=1; word <= trie->wordcount; word++) {
1178         PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
1179             (int)word, (int)(trie->wordinfo[word].prev),
1180             (int)(trie->wordinfo[word].len));
1181     }
1182     PerlIO_printf(Perl_debug_log, "\n" );
1183 }    
1184 /*
1185   Dumps a fully constructed but uncompressed trie in list form.
1186   List tries normally only are used for construction when the number of 
1187   possible chars (trie->uniquecharcount) is very high.
1188   Used for debugging make_trie().
1189 */
1190 STATIC void
1191 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
1192                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
1193                          U32 depth)
1194 {
1195     U32 state;
1196     SV *sv=sv_newmortal();
1197     int colwidth= widecharmap ? 6 : 4;
1198     GET_RE_DEBUG_FLAGS_DECL;
1199
1200     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1201
1202     /* print out the table precompression.  */
1203     PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1204         (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1205         "------:-----+-----------------\n" );
1206     
1207     for( state=1 ; state < next_alloc ; state ++ ) {
1208         U16 charid;
1209     
1210         PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
1211             (int)depth * 2 + 2,"", (UV)state  );
1212         if ( ! trie->states[ state ].wordnum ) {
1213             PerlIO_printf( Perl_debug_log, "%5s| ","");
1214         } else {
1215             PerlIO_printf( Perl_debug_log, "W%4x| ",
1216                 trie->states[ state ].wordnum
1217             );
1218         }
1219         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
1220             SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
1221             if ( tmp ) {
1222                 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1223                     colwidth,
1224                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1225                             PL_colors[0], PL_colors[1],
1226                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1227                             PERL_PV_ESCAPE_FIRSTCHAR 
1228                     ) ,
1229                     TRIE_LIST_ITEM(state,charid).forid,
1230                     (UV)TRIE_LIST_ITEM(state,charid).newstate
1231                 );
1232                 if (!(charid % 10)) 
1233                     PerlIO_printf(Perl_debug_log, "\n%*s| ",
1234                         (int)((depth * 2) + 14), "");
1235             }
1236         }
1237         PerlIO_printf( Perl_debug_log, "\n");
1238     }
1239 }    
1240
1241 /*
1242   Dumps a fully constructed but uncompressed trie in table form.
1243   This is the normal DFA style state transition table, with a few 
1244   twists to facilitate compression later. 
1245   Used for debugging make_trie().
1246 */
1247 STATIC void
1248 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
1249                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
1250                           U32 depth)
1251 {
1252     U32 state;
1253     U16 charid;
1254     SV *sv=sv_newmortal();
1255     int colwidth= widecharmap ? 6 : 4;
1256     GET_RE_DEBUG_FLAGS_DECL;
1257
1258     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
1259     
1260     /*
1261        print out the table precompression so that we can do a visual check
1262        that they are identical.
1263      */
1264     
1265     PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1266
1267     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1268         SV ** const tmp = av_fetch( revcharmap, charid, 0);
1269         if ( tmp ) {
1270             PerlIO_printf( Perl_debug_log, "%*s", 
1271                 colwidth,
1272                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1273                             PL_colors[0], PL_colors[1],
1274                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1275                             PERL_PV_ESCAPE_FIRSTCHAR 
1276                 ) 
1277             );
1278         }
1279     }
1280
1281     PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1282
1283     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1284         PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1285     }
1286
1287     PerlIO_printf( Perl_debug_log, "\n" );
1288
1289     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1290
1291         PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ", 
1292             (int)depth * 2 + 2,"",
1293             (UV)TRIE_NODENUM( state ) );
1294
1295         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1296             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1297             if (v)
1298                 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1299             else
1300                 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1301         }
1302         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1303             PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1304         } else {
1305             PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1306             trie->states[ TRIE_NODENUM( state ) ].wordnum );
1307         }
1308     }
1309 }
1310
1311 #endif
1312
1313
1314 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1315   startbranch: the first branch in the whole branch sequence
1316   first      : start branch of sequence of branch-exact nodes.
1317                May be the same as startbranch
1318   last       : Thing following the last branch.
1319                May be the same as tail.
1320   tail       : item following the branch sequence
1321   count      : words in the sequence
1322   flags      : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1323   depth      : indent depth
1324
1325 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1326
1327 A trie is an N'ary tree where the branches are determined by digital
1328 decomposition of the key. IE, at the root node you look up the 1st character and
1329 follow that branch repeat until you find the end of the branches. Nodes can be
1330 marked as "accepting" meaning they represent a complete word. Eg:
1331
1332   /he|she|his|hers/
1333
1334 would convert into the following structure. Numbers represent states, letters
1335 following numbers represent valid transitions on the letter from that state, if
1336 the number is in square brackets it represents an accepting state, otherwise it
1337 will be in parenthesis.
1338
1339       +-h->+-e->[3]-+-r->(8)-+-s->[9]
1340       |    |
1341       |   (2)
1342       |    |
1343      (1)   +-i->(6)-+-s->[7]
1344       |
1345       +-s->(3)-+-h->(4)-+-e->[5]
1346
1347       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1348
1349 This shows that when matching against the string 'hers' we will begin at state 1
1350 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1351 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1352 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1353 single traverse. We store a mapping from accepting to state to which word was
1354 matched, and then when we have multiple possibilities we try to complete the
1355 rest of the regex in the order in which they occured in the alternation.
1356
1357 The only prior NFA like behaviour that would be changed by the TRIE support is
1358 the silent ignoring of duplicate alternations which are of the form:
1359
1360  / (DUPE|DUPE) X? (?{ ... }) Y /x
1361
1362 Thus EVAL blocks following a trie may be called a different number of times with
1363 and without the optimisation. With the optimisations dupes will be silently
1364 ignored. This inconsistent behaviour of EVAL type nodes is well established as
1365 the following demonstrates:
1366
1367  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1368
1369 which prints out 'word' three times, but
1370
1371  'words'=~/(word|word|word)(?{ print $1 })S/
1372
1373 which doesnt print it out at all. This is due to other optimisations kicking in.
1374
1375 Example of what happens on a structural level:
1376
1377 The regexp /(ac|ad|ab)+/ will produce the following debug output:
1378
1379    1: CURLYM[1] {1,32767}(18)
1380    5:   BRANCH(8)
1381    6:     EXACT <ac>(16)
1382    8:   BRANCH(11)
1383    9:     EXACT <ad>(16)
1384   11:   BRANCH(14)
1385   12:     EXACT <ab>(16)
1386   16:   SUCCEED(0)
1387   17:   NOTHING(18)
1388   18: END(0)
1389
1390 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1391 and should turn into:
1392
1393    1: CURLYM[1] {1,32767}(18)
1394    5:   TRIE(16)
1395         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1396           <ac>
1397           <ad>
1398           <ab>
1399   16:   SUCCEED(0)
1400   17:   NOTHING(18)
1401   18: END(0)
1402
1403 Cases where tail != last would be like /(?foo|bar)baz/:
1404
1405    1: BRANCH(4)
1406    2:   EXACT <foo>(8)
1407    4: BRANCH(7)
1408    5:   EXACT <bar>(8)
1409    7: TAIL(8)
1410    8: EXACT <baz>(10)
1411   10: END(0)
1412
1413 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1414 and would end up looking like:
1415
1416     1: TRIE(8)
1417       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1418         <foo>
1419         <bar>
1420    7: TAIL(8)
1421    8: EXACT <baz>(10)
1422   10: END(0)
1423
1424     d = uvuni_to_utf8_flags(d, uv, 0);
1425
1426 is the recommended Unicode-aware way of saying
1427
1428     *(d++) = uv;
1429 */
1430
1431 #define TRIE_STORE_REVCHAR(val)                                            \
1432     STMT_START {                                                           \
1433         if (UTF) {                                                         \
1434             SV *zlopp = newSV(7); /* XXX: optimize me */                   \
1435             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
1436             unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, val); \
1437             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
1438             SvPOK_on(zlopp);                                               \
1439             SvUTF8_on(zlopp);                                              \
1440             av_push(revcharmap, zlopp);                                    \
1441         } else {                                                           \
1442             char ooooff = (char)val;                                           \
1443             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
1444         }                                                                  \
1445         } STMT_END
1446
1447 #define TRIE_READ_CHAR STMT_START {                                                     \
1448     wordlen++;                                                                          \
1449     if ( UTF ) {                                                                        \
1450         /* if it is UTF then it is either already folded, or does not need folding */   \
1451         uvc = utf8n_to_uvuni( (const U8*) uc, UTF8_MAXLEN, &len, uniflags);             \
1452     }                                                                                   \
1453     else if (folder == PL_fold_latin1) {                                                \
1454         /* if we use this folder we have to obey unicode rules on latin-1 data */       \
1455         if ( foldlen > 0 ) {                                                            \
1456            uvc = utf8n_to_uvuni( (const U8*) scan, UTF8_MAXLEN, &len, uniflags );       \
1457            foldlen -= len;                                                              \
1458            scan += len;                                                                 \
1459            len = 0;                                                                     \
1460         } else {                                                                        \
1461             len = 1;                                                                    \
1462             uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, FOLD_FLAGS_FULL);       \
1463             skiplen = UNISKIP(uvc);                                                     \
1464             foldlen -= skiplen;                                                         \
1465             scan = foldbuf + skiplen;                                                   \
1466         }                                                                               \
1467     } else {                                                                            \
1468         /* raw data, will be folded later if needed */                                  \
1469         uvc = (U32)*uc;                                                                 \
1470         len = 1;                                                                        \
1471     }                                                                                   \
1472 } STMT_END
1473
1474
1475
1476 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
1477     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
1478         U32 ging = TRIE_LIST_LEN( state ) *= 2;                 \
1479         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1480     }                                                           \
1481     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
1482     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
1483     TRIE_LIST_CUR( state )++;                                   \
1484 } STMT_END
1485
1486 #define TRIE_LIST_NEW(state) STMT_START {                       \
1487     Newxz( trie->states[ state ].trans.list,               \
1488         4, reg_trie_trans_le );                                 \
1489      TRIE_LIST_CUR( state ) = 1;                                \
1490      TRIE_LIST_LEN( state ) = 4;                                \
1491 } STMT_END
1492
1493 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
1494     U16 dupe= trie->states[ state ].wordnum;                    \
1495     regnode * const noper_next = regnext( noper );              \
1496                                                                 \
1497     DEBUG_r({                                                   \
1498         /* store the word for dumping */                        \
1499         SV* tmp;                                                \
1500         if (OP(noper) != NOTHING)                               \
1501             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
1502         else                                                    \
1503             tmp = newSVpvn_utf8( "", 0, UTF );                  \
1504         av_push( trie_words, tmp );                             \
1505     });                                                         \
1506                                                                 \
1507     curword++;                                                  \
1508     trie->wordinfo[curword].prev   = 0;                         \
1509     trie->wordinfo[curword].len    = wordlen;                   \
1510     trie->wordinfo[curword].accept = state;                     \
1511                                                                 \
1512     if ( noper_next < tail ) {                                  \
1513         if (!trie->jump)                                        \
1514             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1515         trie->jump[curword] = (U16)(noper_next - convert);      \
1516         if (!jumper)                                            \
1517             jumper = noper_next;                                \
1518         if (!nextbranch)                                        \
1519             nextbranch= regnext(cur);                           \
1520     }                                                           \
1521                                                                 \
1522     if ( dupe ) {                                               \
1523         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
1524         /* chain, so that when the bits of chain are later    */\
1525         /* linked together, the dups appear in the chain      */\
1526         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1527         trie->wordinfo[dupe].prev = curword;                    \
1528     } else {                                                    \
1529         /* we haven't inserted this word yet.                */ \
1530         trie->states[ state ].wordnum = curword;                \
1531     }                                                           \
1532 } STMT_END
1533
1534
1535 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
1536      ( ( base + charid >=  ucharcount                                   \
1537          && base + charid < ubound                                      \
1538          && state == trie->trans[ base - ucharcount + charid ].check    \
1539          && trie->trans[ base - ucharcount + charid ].next )            \
1540            ? trie->trans[ base - ucharcount + charid ].next             \
1541            : ( state==1 ? special : 0 )                                 \
1542       )
1543
1544 #define MADE_TRIE       1
1545 #define MADE_JUMP_TRIE  2
1546 #define MADE_EXACT_TRIE 4
1547
1548 STATIC I32
1549 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1550 {
1551     dVAR;
1552     /* first pass, loop through and scan words */
1553     reg_trie_data *trie;
1554     HV *widecharmap = NULL;
1555     AV *revcharmap = newAV();
1556     regnode *cur;
1557     const U32 uniflags = UTF8_ALLOW_DEFAULT;
1558     STRLEN len = 0;
1559     UV uvc = 0;
1560     U16 curword = 0;
1561     U32 next_alloc = 0;
1562     regnode *jumper = NULL;
1563     regnode *nextbranch = NULL;
1564     regnode *convert = NULL;
1565     U32 *prev_states; /* temp array mapping each state to previous one */
1566     /* we just use folder as a flag in utf8 */
1567     const U8 * folder = NULL;
1568
1569 #ifdef DEBUGGING
1570     const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1571     AV *trie_words = NULL;
1572     /* along with revcharmap, this only used during construction but both are
1573      * useful during debugging so we store them in the struct when debugging.
1574      */
1575 #else
1576     const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1577     STRLEN trie_charcount=0;
1578 #endif
1579     SV *re_trie_maxbuff;
1580     GET_RE_DEBUG_FLAGS_DECL;
1581
1582     PERL_ARGS_ASSERT_MAKE_TRIE;
1583 #ifndef DEBUGGING
1584     PERL_UNUSED_ARG(depth);
1585 #endif
1586
1587     switch (flags) {
1588         case EXACT: break;
1589         case EXACTFA:
1590         case EXACTFU_SS:
1591         case EXACTFU_TRICKYFOLD:
1592         case EXACTFU: folder = PL_fold_latin1; break;
1593         case EXACTF:  folder = PL_fold; break;
1594         case EXACTFL: folder = PL_fold_locale; break;
1595         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
1596     }
1597
1598     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1599     trie->refcount = 1;
1600     trie->startstate = 1;
1601     trie->wordcount = word_count;
1602     RExC_rxi->data->data[ data_slot ] = (void*)trie;
1603     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1604     if (flags == EXACT)
1605         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1606     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
1607                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
1608
1609     DEBUG_r({
1610         trie_words = newAV();
1611     });
1612
1613     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1614     if (!SvIOK(re_trie_maxbuff)) {
1615         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1616     }
1617     DEBUG_TRIE_COMPILE_r({
1618                 PerlIO_printf( Perl_debug_log,
1619                   "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1620                   (int)depth * 2 + 2, "", 
1621                   REG_NODE_NUM(startbranch),REG_NODE_NUM(first), 
1622                   REG_NODE_NUM(last), REG_NODE_NUM(tail),
1623                   (int)depth);
1624     });
1625    
1626    /* Find the node we are going to overwrite */
1627     if ( first == startbranch && OP( last ) != BRANCH ) {
1628         /* whole branch chain */
1629         convert = first;
1630     } else {
1631         /* branch sub-chain */
1632         convert = NEXTOPER( first );
1633     }
1634         
1635     /*  -- First loop and Setup --
1636
1637        We first traverse the branches and scan each word to determine if it
1638        contains widechars, and how many unique chars there are, this is
1639        important as we have to build a table with at least as many columns as we
1640        have unique chars.
1641
1642        We use an array of integers to represent the character codes 0..255
1643        (trie->charmap) and we use a an HV* to store Unicode characters. We use the
1644        native representation of the character value as the key and IV's for the
1645        coded index.
1646
1647        *TODO* If we keep track of how many times each character is used we can
1648        remap the columns so that the table compression later on is more
1649        efficient in terms of memory by ensuring the most common value is in the
1650        middle and the least common are on the outside.  IMO this would be better
1651        than a most to least common mapping as theres a decent chance the most
1652        common letter will share a node with the least common, meaning the node
1653        will not be compressible. With a middle is most common approach the worst
1654        case is when we have the least common nodes twice.
1655
1656      */
1657
1658     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1659         regnode *noper = NEXTOPER( cur );
1660         const U8 *uc = (U8*)STRING( noper );
1661         const U8 *e  = uc + STR_LEN( noper );
1662         STRLEN foldlen = 0;
1663         U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1664         STRLEN skiplen = 0;
1665         const U8 *scan = (U8*)NULL;
1666         U32 wordlen      = 0;         /* required init */
1667         STRLEN chars = 0;
1668         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
1669
1670         if (OP(noper) == NOTHING) {
1671             regnode *noper_next= regnext(noper);
1672             if (noper_next != tail && OP(noper_next) == flags) {
1673                 noper = noper_next;
1674                 uc= (U8*)STRING(noper);
1675                 e= uc + STR_LEN(noper);
1676                 trie->minlen= STR_LEN(noper);
1677             } else {
1678                 trie->minlen= 0;
1679                 continue;
1680             }
1681         }
1682
1683         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
1684             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1685                                           regardless of encoding */
1686             if (OP( noper ) == EXACTFU_SS) {
1687                 /* false positives are ok, so just set this */
1688                 TRIE_BITMAP_SET(trie,0xDF);
1689             }
1690         }
1691         for ( ; uc < e ; uc += len ) {
1692             TRIE_CHARCOUNT(trie)++;
1693             TRIE_READ_CHAR;
1694             chars++;
1695             if ( uvc < 256 ) {
1696                 if ( folder ) {
1697                     U8 folded= folder[ (U8) uvc ];
1698                     if ( !trie->charmap[ folded ] ) {
1699                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
1700                         TRIE_STORE_REVCHAR( folded );
1701                     }
1702                 }
1703                 if ( !trie->charmap[ uvc ] ) {
1704                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1705                     TRIE_STORE_REVCHAR( uvc );
1706                 }
1707                 if ( set_bit ) {
1708                     /* store the codepoint in the bitmap, and its folded
1709                      * equivalent. */
1710                     TRIE_BITMAP_SET(trie, uvc);
1711
1712                     /* store the folded codepoint */
1713                     if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
1714
1715                     if ( !UTF ) {
1716                         /* store first byte of utf8 representation of
1717                            variant codepoints */
1718                         if (! UNI_IS_INVARIANT(uvc)) {
1719                             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
1720                         }
1721                     }
1722                     set_bit = 0; /* We've done our bit :-) */
1723                 }
1724             } else {
1725                 SV** svpp;
1726                 if ( !widecharmap )
1727                     widecharmap = newHV();
1728
1729                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1730
1731                 if ( !svpp )
1732                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1733
1734                 if ( !SvTRUE( *svpp ) ) {
1735                     sv_setiv( *svpp, ++trie->uniquecharcount );
1736                     TRIE_STORE_REVCHAR(uvc);
1737                 }
1738             }
1739         }
1740         if( cur == first ) {
1741             trie->minlen = chars;
1742             trie->maxlen = chars;
1743         } else if (chars < trie->minlen) {
1744             trie->minlen = chars;
1745         } else if (chars > trie->maxlen) {
1746             trie->maxlen = chars;
1747         }
1748         if (OP( noper ) == EXACTFU_SS) {
1749             /* XXX: workaround - 'ss' could match "\x{DF}" so minlen could be 1 and not 2*/
1750             if (trie->minlen > 1)
1751                 trie->minlen= 1;
1752         }
1753         if (OP( noper ) == EXACTFU_TRICKYFOLD) {
1754             /* XXX: workround - things like "\x{1FBE}\x{0308}\x{0301}" can match "\x{0390}" 
1755              *                - We assume that any such sequence might match a 2 byte string */
1756             if (trie->minlen > 2 )
1757                 trie->minlen= 2;
1758         }
1759
1760     } /* end first pass */
1761     DEBUG_TRIE_COMPILE_r(
1762         PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1763                 (int)depth * 2 + 2,"",
1764                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1765                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1766                 (int)trie->minlen, (int)trie->maxlen )
1767     );
1768
1769     /*
1770         We now know what we are dealing with in terms of unique chars and
1771         string sizes so we can calculate how much memory a naive
1772         representation using a flat table  will take. If it's over a reasonable
1773         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1774         conservative but potentially much slower representation using an array
1775         of lists.
1776
1777         At the end we convert both representations into the same compressed
1778         form that will be used in regexec.c for matching with. The latter
1779         is a form that cannot be used to construct with but has memory
1780         properties similar to the list form and access properties similar
1781         to the table form making it both suitable for fast searches and
1782         small enough that its feasable to store for the duration of a program.
1783
1784         See the comment in the code where the compressed table is produced
1785         inplace from the flat tabe representation for an explanation of how
1786         the compression works.
1787
1788     */
1789
1790
1791     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
1792     prev_states[1] = 0;
1793
1794     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1795         /*
1796             Second Pass -- Array Of Lists Representation
1797
1798             Each state will be represented by a list of charid:state records
1799             (reg_trie_trans_le) the first such element holds the CUR and LEN
1800             points of the allocated array. (See defines above).
1801
1802             We build the initial structure using the lists, and then convert
1803             it into the compressed table form which allows faster lookups
1804             (but cant be modified once converted).
1805         */
1806
1807         STRLEN transcount = 1;
1808
1809         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1810             "%*sCompiling trie using list compiler\n",
1811             (int)depth * 2 + 2, ""));
1812
1813         trie->states = (reg_trie_state *)
1814             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1815                                   sizeof(reg_trie_state) );
1816         TRIE_LIST_NEW(1);
1817         next_alloc = 2;
1818
1819         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1820
1821             regnode *noper   = NEXTOPER( cur );
1822             U8 *uc           = (U8*)STRING( noper );
1823             const U8 *e      = uc + STR_LEN( noper );
1824             U32 state        = 1;         /* required init */
1825             U16 charid       = 0;         /* sanity init */
1826             U8 *scan         = (U8*)NULL; /* sanity init */
1827             STRLEN foldlen   = 0;         /* required init */
1828             U32 wordlen      = 0;         /* required init */
1829             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1830             STRLEN skiplen   = 0;
1831
1832             if (OP(noper) == NOTHING) {
1833                 regnode *noper_next= regnext(noper);
1834                 if (noper_next != tail && OP(noper_next) == flags) {
1835                     noper = noper_next;
1836                     uc= (U8*)STRING(noper);
1837                     e= uc + STR_LEN(noper);
1838                 }
1839             }
1840
1841             if (OP(noper) != NOTHING) {
1842                 for ( ; uc < e ; uc += len ) {
1843
1844                     TRIE_READ_CHAR;
1845
1846                     if ( uvc < 256 ) {
1847                         charid = trie->charmap[ uvc ];
1848                     } else {
1849                         SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1850                         if ( !svpp ) {
1851                             charid = 0;
1852                         } else {
1853                             charid=(U16)SvIV( *svpp );
1854                         }
1855                     }
1856                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
1857                     if ( charid ) {
1858
1859                         U16 check;
1860                         U32 newstate = 0;
1861
1862                         charid--;
1863                         if ( !trie->states[ state ].trans.list ) {
1864                             TRIE_LIST_NEW( state );
1865                         }
1866                         for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1867                             if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1868                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1869                                 break;
1870                             }
1871                         }
1872                         if ( ! newstate ) {
1873                             newstate = next_alloc++;
1874                             prev_states[newstate] = state;
1875                             TRIE_LIST_PUSH( state, charid, newstate );
1876                             transcount++;
1877                         }
1878                         state = newstate;
1879                     } else {
1880                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1881                     }
1882                 }
1883             }
1884             TRIE_HANDLE_WORD(state);
1885
1886         } /* end second pass */
1887
1888         /* next alloc is the NEXT state to be allocated */
1889         trie->statecount = next_alloc; 
1890         trie->states = (reg_trie_state *)
1891             PerlMemShared_realloc( trie->states,
1892                                    next_alloc
1893                                    * sizeof(reg_trie_state) );
1894
1895         /* and now dump it out before we compress it */
1896         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1897                                                          revcharmap, next_alloc,
1898                                                          depth+1)
1899         );
1900
1901         trie->trans = (reg_trie_trans *)
1902             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1903         {
1904             U32 state;
1905             U32 tp = 0;
1906             U32 zp = 0;
1907
1908
1909             for( state=1 ; state < next_alloc ; state ++ ) {
1910                 U32 base=0;
1911
1912                 /*
1913                 DEBUG_TRIE_COMPILE_MORE_r(
1914                     PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1915                 );
1916                 */
1917
1918                 if (trie->states[state].trans.list) {
1919                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1920                     U16 maxid=minid;
1921                     U16 idx;
1922
1923                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1924                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1925                         if ( forid < minid ) {
1926                             minid=forid;
1927                         } else if ( forid > maxid ) {
1928                             maxid=forid;
1929                         }
1930                     }
1931                     if ( transcount < tp + maxid - minid + 1) {
1932                         transcount *= 2;
1933                         trie->trans = (reg_trie_trans *)
1934                             PerlMemShared_realloc( trie->trans,
1935                                                      transcount
1936                                                      * sizeof(reg_trie_trans) );
1937                         Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1938                     }
1939                     base = trie->uniquecharcount + tp - minid;
1940                     if ( maxid == minid ) {
1941                         U32 set = 0;
1942                         for ( ; zp < tp ; zp++ ) {
1943                             if ( ! trie->trans[ zp ].next ) {
1944                                 base = trie->uniquecharcount + zp - minid;
1945                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1946                                 trie->trans[ zp ].check = state;
1947                                 set = 1;
1948                                 break;
1949                             }
1950                         }
1951                         if ( !set ) {
1952                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1953                             trie->trans[ tp ].check = state;
1954                             tp++;
1955                             zp = tp;
1956                         }
1957                     } else {
1958                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1959                             const U32 tid = base -  trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1960                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1961                             trie->trans[ tid ].check = state;
1962                         }
1963                         tp += ( maxid - minid + 1 );
1964                     }
1965                     Safefree(trie->states[ state ].trans.list);
1966                 }
1967                 /*
1968                 DEBUG_TRIE_COMPILE_MORE_r(
1969                     PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1970                 );
1971                 */
1972                 trie->states[ state ].trans.base=base;
1973             }
1974             trie->lasttrans = tp + 1;
1975         }
1976     } else {
1977         /*
1978            Second Pass -- Flat Table Representation.
1979
1980            we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1981            We know that we will need Charcount+1 trans at most to store the data
1982            (one row per char at worst case) So we preallocate both structures
1983            assuming worst case.
1984
1985            We then construct the trie using only the .next slots of the entry
1986            structs.
1987
1988            We use the .check field of the first entry of the node temporarily to
1989            make compression both faster and easier by keeping track of how many non
1990            zero fields are in the node.
1991
1992            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1993            transition.
1994
1995            There are two terms at use here: state as a TRIE_NODEIDX() which is a
1996            number representing the first entry of the node, and state as a
1997            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1998            TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1999            are 2 entrys per node. eg:
2000
2001              A B       A B
2002           1. 2 4    1. 3 7
2003           2. 0 3    3. 0 5
2004           3. 0 0    5. 0 0
2005           4. 0 0    7. 0 0
2006
2007            The table is internally in the right hand, idx form. However as we also
2008            have to deal with the states array which is indexed by nodenum we have to
2009            use TRIE_NODENUM() to convert.
2010
2011         */
2012         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
2013             "%*sCompiling trie using table compiler\n",
2014             (int)depth * 2 + 2, ""));
2015
2016         trie->trans = (reg_trie_trans *)
2017             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
2018                                   * trie->uniquecharcount + 1,
2019                                   sizeof(reg_trie_trans) );
2020         trie->states = (reg_trie_state *)
2021             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
2022                                   sizeof(reg_trie_state) );
2023         next_alloc = trie->uniquecharcount + 1;
2024
2025
2026         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
2027
2028             regnode *noper   = NEXTOPER( cur );
2029             const U8 *uc     = (U8*)STRING( noper );
2030             const U8 *e      = uc + STR_LEN( noper );
2031
2032             U32 state        = 1;         /* required init */
2033
2034             U16 charid       = 0;         /* sanity init */
2035             U32 accept_state = 0;         /* sanity init */
2036             U8 *scan         = (U8*)NULL; /* sanity init */
2037
2038             STRLEN foldlen   = 0;         /* required init */
2039             U32 wordlen      = 0;         /* required init */
2040             STRLEN skiplen   = 0;
2041             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2042
2043             if (OP(noper) == NOTHING) {
2044                 regnode *noper_next= regnext(noper);
2045                 if (noper_next != tail && OP(noper_next) == flags) {
2046                     noper = noper_next;
2047                     uc= (U8*)STRING(noper);
2048                     e= uc + STR_LEN(noper);
2049                 }
2050             }
2051
2052             if ( OP(noper) != NOTHING ) {
2053                 for ( ; uc < e ; uc += len ) {
2054
2055                     TRIE_READ_CHAR;
2056
2057                     if ( uvc < 256 ) {
2058                         charid = trie->charmap[ uvc ];
2059                     } else {
2060                         SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
2061                         charid = svpp ? (U16)SvIV(*svpp) : 0;
2062                     }
2063                     if ( charid ) {
2064                         charid--;
2065                         if ( !trie->trans[ state + charid ].next ) {
2066                             trie->trans[ state + charid ].next = next_alloc;
2067                             trie->trans[ state ].check++;
2068                             prev_states[TRIE_NODENUM(next_alloc)]
2069                                     = TRIE_NODENUM(state);
2070                             next_alloc += trie->uniquecharcount;
2071                         }
2072                         state = trie->trans[ state + charid ].next;
2073                     } else {
2074                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2075                     }
2076                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
2077                 }
2078             }
2079             accept_state = TRIE_NODENUM( state );
2080             TRIE_HANDLE_WORD(accept_state);
2081
2082         } /* end second pass */
2083
2084         /* and now dump it out before we compress it */
2085         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
2086                                                           revcharmap,
2087                                                           next_alloc, depth+1));
2088
2089         {
2090         /*
2091            * Inplace compress the table.*
2092
2093            For sparse data sets the table constructed by the trie algorithm will
2094            be mostly 0/FAIL transitions or to put it another way mostly empty.
2095            (Note that leaf nodes will not contain any transitions.)
2096
2097            This algorithm compresses the tables by eliminating most such
2098            transitions, at the cost of a modest bit of extra work during lookup:
2099
2100            - Each states[] entry contains a .base field which indicates the
2101            index in the state[] array wheres its transition data is stored.
2102
2103            - If .base is 0 there are no valid transitions from that node.
2104
2105            - If .base is nonzero then charid is added to it to find an entry in
2106            the trans array.
2107
2108            -If trans[states[state].base+charid].check!=state then the
2109            transition is taken to be a 0/Fail transition. Thus if there are fail
2110            transitions at the front of the node then the .base offset will point
2111            somewhere inside the previous nodes data (or maybe even into a node
2112            even earlier), but the .check field determines if the transition is
2113            valid.
2114
2115            XXX - wrong maybe?
2116            The following process inplace converts the table to the compressed
2117            table: We first do not compress the root node 1,and mark all its
2118            .check pointers as 1 and set its .base pointer as 1 as well. This
2119            allows us to do a DFA construction from the compressed table later,
2120            and ensures that any .base pointers we calculate later are greater
2121            than 0.
2122
2123            - We set 'pos' to indicate the first entry of the second node.
2124
2125            - We then iterate over the columns of the node, finding the first and
2126            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
2127            and set the .check pointers accordingly, and advance pos
2128            appropriately and repreat for the next node. Note that when we copy
2129            the next pointers we have to convert them from the original
2130            NODEIDX form to NODENUM form as the former is not valid post
2131            compression.
2132
2133            - If a node has no transitions used we mark its base as 0 and do not
2134            advance the pos pointer.
2135
2136            - If a node only has one transition we use a second pointer into the
2137            structure to fill in allocated fail transitions from other states.
2138            This pointer is independent of the main pointer and scans forward
2139            looking for null transitions that are allocated to a state. When it
2140            finds one it writes the single transition into the "hole".  If the
2141            pointer doesnt find one the single transition is appended as normal.
2142
2143            - Once compressed we can Renew/realloc the structures to release the
2144            excess space.
2145
2146            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
2147            specifically Fig 3.47 and the associated pseudocode.
2148
2149            demq
2150         */
2151         const U32 laststate = TRIE_NODENUM( next_alloc );
2152         U32 state, charid;
2153         U32 pos = 0, zp=0;
2154         trie->statecount = laststate;
2155
2156         for ( state = 1 ; state < laststate ; state++ ) {
2157             U8 flag = 0;
2158             const U32 stateidx = TRIE_NODEIDX( state );
2159             const U32 o_used = trie->trans[ stateidx ].check;
2160             U32 used = trie->trans[ stateidx ].check;
2161             trie->trans[ stateidx ].check = 0;
2162
2163             for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
2164                 if ( flag || trie->trans[ stateidx + charid ].next ) {
2165                     if ( trie->trans[ stateidx + charid ].next ) {
2166                         if (o_used == 1) {
2167                             for ( ; zp < pos ; zp++ ) {
2168                                 if ( ! trie->trans[ zp ].next ) {
2169                                     break;
2170                                 }
2171                             }
2172                             trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
2173                             trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2174                             trie->trans[ zp ].check = state;
2175                             if ( ++zp > pos ) pos = zp;
2176                             break;
2177                         }
2178                         used--;
2179                     }
2180                     if ( !flag ) {
2181                         flag = 1;
2182                         trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
2183                     }
2184                     trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2185                     trie->trans[ pos ].check = state;
2186                     pos++;
2187                 }
2188             }
2189         }
2190         trie->lasttrans = pos + 1;
2191         trie->states = (reg_trie_state *)
2192             PerlMemShared_realloc( trie->states, laststate
2193                                    * sizeof(reg_trie_state) );
2194         DEBUG_TRIE_COMPILE_MORE_r(
2195                 PerlIO_printf( Perl_debug_log,
2196                     "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
2197                     (int)depth * 2 + 2,"",
2198                     (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
2199                     (IV)next_alloc,
2200                     (IV)pos,
2201                     ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
2202             );
2203
2204         } /* end table compress */
2205     }
2206     DEBUG_TRIE_COMPILE_MORE_r(
2207             PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
2208                 (int)depth * 2 + 2, "",
2209                 (UV)trie->statecount,
2210                 (UV)trie->lasttrans)
2211     );
2212     /* resize the trans array to remove unused space */
2213     trie->trans = (reg_trie_trans *)
2214         PerlMemShared_realloc( trie->trans, trie->lasttrans
2215                                * sizeof(reg_trie_trans) );
2216
2217     {   /* Modify the program and insert the new TRIE node */ 
2218         U8 nodetype =(U8)(flags & 0xFF);
2219         char *str=NULL;
2220         
2221 #ifdef DEBUGGING
2222         regnode *optimize = NULL;
2223 #ifdef RE_TRACK_PATTERN_OFFSETS
2224
2225         U32 mjd_offset = 0;
2226         U32 mjd_nodelen = 0;
2227 #endif /* RE_TRACK_PATTERN_OFFSETS */
2228 #endif /* DEBUGGING */
2229         /*
2230            This means we convert either the first branch or the first Exact,
2231            depending on whether the thing following (in 'last') is a branch
2232            or not and whther first is the startbranch (ie is it a sub part of
2233            the alternation or is it the whole thing.)
2234            Assuming its a sub part we convert the EXACT otherwise we convert
2235            the whole branch sequence, including the first.
2236          */
2237         /* Find the node we are going to overwrite */
2238         if ( first != startbranch || OP( last ) == BRANCH ) {
2239             /* branch sub-chain */
2240             NEXT_OFF( first ) = (U16)(last - first);
2241 #ifdef RE_TRACK_PATTERN_OFFSETS
2242             DEBUG_r({
2243                 mjd_offset= Node_Offset((convert));
2244                 mjd_nodelen= Node_Length((convert));
2245             });
2246 #endif
2247             /* whole branch chain */
2248         }
2249 #ifdef RE_TRACK_PATTERN_OFFSETS
2250         else {
2251             DEBUG_r({
2252                 const  regnode *nop = NEXTOPER( convert );
2253                 mjd_offset= Node_Offset((nop));
2254                 mjd_nodelen= Node_Length((nop));
2255             });
2256         }
2257         DEBUG_OPTIMISE_r(
2258             PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
2259                 (int)depth * 2 + 2, "",
2260                 (UV)mjd_offset, (UV)mjd_nodelen)
2261         );
2262 #endif
2263         /* But first we check to see if there is a common prefix we can 
2264            split out as an EXACT and put in front of the TRIE node.  */
2265         trie->startstate= 1;
2266         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
2267             U32 state;
2268             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
2269                 U32 ofs = 0;
2270                 I32 idx = -1;
2271                 U32 count = 0;
2272                 const U32 base = trie->states[ state ].trans.base;
2273
2274                 if ( trie->states[state].wordnum )
2275                         count = 1;
2276
2277                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2278                     if ( ( base + ofs >= trie->uniquecharcount ) &&
2279                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
2280                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2281                     {
2282                         if ( ++count > 1 ) {
2283                             SV **tmp = av_fetch( revcharmap, ofs, 0);
2284                             const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
2285                             if ( state == 1 ) break;
2286                             if ( count == 2 ) {
2287                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2288                                 DEBUG_OPTIMISE_r(
2289                                     PerlIO_printf(Perl_debug_log,
2290                                         "%*sNew Start State=%"UVuf" Class: [",
2291                                         (int)depth * 2 + 2, "",
2292                                         (UV)state));
2293                                 if (idx >= 0) {
2294                                     SV ** const tmp = av_fetch( revcharmap, idx, 0);
2295                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
2296
2297                                     TRIE_BITMAP_SET(trie,*ch);
2298                                     if ( folder )
2299                                         TRIE_BITMAP_SET(trie, folder[ *ch ]);
2300                                     DEBUG_OPTIMISE_r(
2301                                         PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
2302                                     );
2303                                 }
2304                             }
2305                             TRIE_BITMAP_SET(trie,*ch);
2306                             if ( folder )
2307                                 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2308                             DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2309                         }
2310                         idx = ofs;
2311                     }
2312                 }
2313                 if ( count == 1 ) {
2314                     SV **tmp = av_fetch( revcharmap, idx, 0);
2315                     STRLEN len;
2316                     char *ch = SvPV( *tmp, len );
2317                     DEBUG_OPTIMISE_r({
2318                         SV *sv=sv_newmortal();
2319                         PerlIO_printf( Perl_debug_log,
2320                             "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2321                             (int)depth * 2 + 2, "",
2322                             (UV)state, (UV)idx, 
2323                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6, 
2324                                 PL_colors[0], PL_colors[1],
2325                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2326                                 PERL_PV_ESCAPE_FIRSTCHAR 
2327                             )
2328                         );
2329                     });
2330                     if ( state==1 ) {
2331                         OP( convert ) = nodetype;
2332                         str=STRING(convert);
2333                         STR_LEN(convert)=0;
2334                     }
2335                     STR_LEN(convert) += len;
2336                     while (len--)
2337                         *str++ = *ch++;
2338                 } else {
2339 #ifdef DEBUGGING            
2340                     if (state>1)
2341                         DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
2342 #endif
2343                     break;
2344                 }
2345             }
2346             trie->prefixlen = (state-1);
2347             if (str) {
2348                 regnode *n = convert+NODE_SZ_STR(convert);
2349                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
2350                 trie->startstate = state;
2351                 trie->minlen -= (state - 1);
2352                 trie->maxlen -= (state - 1);
2353 #ifdef DEBUGGING
2354                /* At least the UNICOS C compiler choked on this
2355                 * being argument to DEBUG_r(), so let's just have
2356                 * it right here. */
2357                if (
2358 #ifdef PERL_EXT_RE_BUILD
2359                    1
2360 #else
2361                    DEBUG_r_TEST
2362 #endif
2363                    ) {
2364                    regnode *fix = convert;
2365                    U32 word = trie->wordcount;
2366                    mjd_nodelen++;
2367                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2368                    while( ++fix < n ) {
2369                        Set_Node_Offset_Length(fix, 0, 0);
2370                    }
2371                    while (word--) {
2372                        SV ** const tmp = av_fetch( trie_words, word, 0 );
2373                        if (tmp) {
2374                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
2375                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2376                            else
2377                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2378                        }
2379                    }
2380                }
2381 #endif
2382                 if (trie->maxlen) {
2383                     convert = n;
2384                 } else {
2385                     NEXT_OFF(convert) = (U16)(tail - convert);
2386                     DEBUG_r(optimize= n);
2387                 }
2388             }
2389         }
2390         if (!jumper) 
2391             jumper = last; 
2392         if ( trie->maxlen ) {
2393             NEXT_OFF( convert ) = (U16)(tail - convert);
2394             ARG_SET( convert, data_slot );
2395             /* Store the offset to the first unabsorbed branch in 
2396                jump[0], which is otherwise unused by the jump logic. 
2397                We use this when dumping a trie and during optimisation. */
2398             if (trie->jump) 
2399                 trie->jump[0] = (U16)(nextbranch - convert);
2400             
2401             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
2402              *   and there is a bitmap
2403              *   and the first "jump target" node we found leaves enough room
2404              * then convert the TRIE node into a TRIEC node, with the bitmap
2405              * embedded inline in the opcode - this is hypothetically faster.
2406              */
2407             if ( !trie->states[trie->startstate].wordnum
2408                  && trie->bitmap
2409                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2410             {
2411                 OP( convert ) = TRIEC;
2412                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2413                 PerlMemShared_free(trie->bitmap);
2414                 trie->bitmap= NULL;
2415             } else 
2416                 OP( convert ) = TRIE;
2417
2418             /* store the type in the flags */
2419             convert->flags = nodetype;
2420             DEBUG_r({
2421             optimize = convert 
2422                       + NODE_STEP_REGNODE 
2423                       + regarglen[ OP( convert ) ];
2424             });
2425             /* XXX We really should free up the resource in trie now, 
2426                    as we won't use them - (which resources?) dmq */
2427         }
2428         /* needed for dumping*/
2429         DEBUG_r(if (optimize) {
2430             regnode *opt = convert;
2431
2432             while ( ++opt < optimize) {
2433                 Set_Node_Offset_Length(opt,0,0);
2434             }
2435             /* 
2436                 Try to clean up some of the debris left after the 
2437                 optimisation.
2438              */
2439             while( optimize < jumper ) {
2440                 mjd_nodelen += Node_Length((optimize));
2441                 OP( optimize ) = OPTIMIZED;
2442                 Set_Node_Offset_Length(optimize,0,0);
2443                 optimize++;
2444             }
2445             Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2446         });
2447     } /* end node insert */
2448
2449     /*  Finish populating the prev field of the wordinfo array.  Walk back
2450      *  from each accept state until we find another accept state, and if
2451      *  so, point the first word's .prev field at the second word. If the
2452      *  second already has a .prev field set, stop now. This will be the
2453      *  case either if we've already processed that word's accept state,
2454      *  or that state had multiple words, and the overspill words were
2455      *  already linked up earlier.
2456      */
2457     {
2458         U16 word;
2459         U32 state;
2460         U16 prev;
2461
2462         for (word=1; word <= trie->wordcount; word++) {
2463             prev = 0;
2464             if (trie->wordinfo[word].prev)
2465                 continue;
2466             state = trie->wordinfo[word].accept;
2467             while (state) {
2468                 state = prev_states[state];
2469                 if (!state)
2470                     break;
2471                 prev = trie->states[state].wordnum;
2472                 if (prev)
2473                     break;
2474             }
2475             trie->wordinfo[word].prev = prev;
2476         }
2477         Safefree(prev_states);
2478     }
2479
2480
2481     /* and now dump out the compressed format */
2482     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2483
2484     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2485 #ifdef DEBUGGING
2486     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2487     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2488 #else
2489     SvREFCNT_dec_NN(revcharmap);
2490 #endif
2491     return trie->jump 
2492            ? MADE_JUMP_TRIE 
2493            : trie->startstate>1 
2494              ? MADE_EXACT_TRIE 
2495              : MADE_TRIE;
2496 }
2497
2498 STATIC void
2499 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source,  regnode *stclass, U32 depth)
2500 {
2501 /* The Trie is constructed and compressed now so we can build a fail array if it's needed
2502
2503    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2504    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2505    ISBN 0-201-10088-6
2506
2507    We find the fail state for each state in the trie, this state is the longest proper
2508    suffix of the current state's 'word' that is also a proper prefix of another word in our
2509    trie. State 1 represents the word '' and is thus the default fail state. This allows
2510    the DFA not to have to restart after its tried and failed a word at a given point, it
2511    simply continues as though it had been matching the other word in the first place.
2512    Consider
2513       'abcdgu'=~/abcdefg|cdgu/
2514    When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2515    fail, which would bring us to the state representing 'd' in the second word where we would
2516    try 'g' and succeed, proceeding to match 'cdgu'.
2517  */
2518  /* add a fail transition */
2519     const U32 trie_offset = ARG(source);
2520     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2521     U32 *q;
2522     const U32 ucharcount = trie->uniquecharcount;
2523     const U32 numstates = trie->statecount;
2524     const U32 ubound = trie->lasttrans + ucharcount;
2525     U32 q_read = 0;
2526     U32 q_write = 0;
2527     U32 charid;
2528     U32 base = trie->states[ 1 ].trans.base;
2529     U32 *fail;
2530     reg_ac_data *aho;
2531     const U32 data_slot = add_data( pRExC_state, 1, "T" );
2532     GET_RE_DEBUG_FLAGS_DECL;
2533
2534     PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
2535 #ifndef DEBUGGING
2536     PERL_UNUSED_ARG(depth);
2537 #endif
2538
2539
2540     ARG_SET( stclass, data_slot );
2541     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2542     RExC_rxi->data->data[ data_slot ] = (void*)aho;
2543     aho->trie=trie_offset;
2544     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2545     Copy( trie->states, aho->states, numstates, reg_trie_state );
2546     Newxz( q, numstates, U32);
2547     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2548     aho->refcount = 1;
2549     fail = aho->fail;
2550     /* initialize fail[0..1] to be 1 so that we always have
2551        a valid final fail state */
2552     fail[ 0 ] = fail[ 1 ] = 1;
2553
2554     for ( charid = 0; charid < ucharcount ; charid++ ) {
2555         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2556         if ( newstate ) {
2557             q[ q_write ] = newstate;
2558             /* set to point at the root */
2559             fail[ q[ q_write++ ] ]=1;
2560         }
2561     }
2562     while ( q_read < q_write) {
2563         const U32 cur = q[ q_read++ % numstates ];
2564         base = trie->states[ cur ].trans.base;
2565
2566         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2567             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2568             if (ch_state) {
2569                 U32 fail_state = cur;
2570                 U32 fail_base;
2571                 do {
2572                     fail_state = fail[ fail_state ];
2573                     fail_base = aho->states[ fail_state ].trans.base;
2574                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2575
2576                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2577                 fail[ ch_state ] = fail_state;
2578                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2579                 {
2580                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
2581                 }
2582                 q[ q_write++ % numstates] = ch_state;
2583             }
2584         }
2585     }
2586     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2587        when we fail in state 1, this allows us to use the
2588        charclass scan to find a valid start char. This is based on the principle
2589        that theres a good chance the string being searched contains lots of stuff
2590        that cant be a start char.
2591      */
2592     fail[ 0 ] = fail[ 1 ] = 0;
2593     DEBUG_TRIE_COMPILE_r({
2594         PerlIO_printf(Perl_debug_log,
2595                       "%*sStclass Failtable (%"UVuf" states): 0", 
2596                       (int)(depth * 2), "", (UV)numstates
2597         );
2598         for( q_read=1; q_read<numstates; q_read++ ) {
2599             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2600         }
2601         PerlIO_printf(Perl_debug_log, "\n");
2602     });
2603     Safefree(q);
2604     /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2605 }
2606
2607
2608 /*
2609  * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2610  * These need to be revisited when a newer toolchain becomes available.
2611  */
2612 #if defined(__sparc64__) && defined(__GNUC__)
2613 #   if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2614 #       undef  SPARC64_GCC_WORKAROUND
2615 #       define SPARC64_GCC_WORKAROUND 1
2616 #   endif
2617 #endif
2618
2619 #define DEBUG_PEEP(str,scan,depth) \
2620     DEBUG_OPTIMISE_r({if (scan){ \
2621        SV * const mysv=sv_newmortal(); \
2622        regnode *Next = regnext(scan); \
2623        regprop(RExC_rx, mysv, scan); \
2624        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2625        (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2626        Next ? (REG_NODE_NUM(Next)) : 0 ); \
2627    }});
2628
2629
2630 /* The below joins as many adjacent EXACTish nodes as possible into a single
2631  * one.  The regop may be changed if the node(s) contain certain sequences that
2632  * require special handling.  The joining is only done if:
2633  * 1) there is room in the current conglomerated node to entirely contain the
2634  *    next one.
2635  * 2) they are the exact same node type
2636  *
2637  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
2638  * these get optimized out
2639  *
2640  * If a node is to match under /i (folded), the number of characters it matches
2641  * can be different than its character length if it contains a multi-character
2642  * fold.  *min_subtract is set to the total delta of the input nodes.
2643  *
2644  * And *has_exactf_sharp_s is set to indicate whether or not the node is EXACTF
2645  * and contains LATIN SMALL LETTER SHARP S
2646  *
2647  * This is as good a place as any to discuss the design of handling these
2648  * multi-character fold sequences.  It's been wrong in Perl for a very long
2649  * time.  There are three code points in Unicode whose multi-character folds
2650  * were long ago discovered to mess things up.  The previous designs for
2651  * dealing with these involved assigning a special node for them.  This
2652  * approach doesn't work, as evidenced by this example:
2653  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
2654  * Both these fold to "sss", but if the pattern is parsed to create a node that
2655  * would match just the \xDF, it won't be able to handle the case where a
2656  * successful match would have to cross the node's boundary.  The new approach
2657  * that hopefully generally solves the problem generates an EXACTFU_SS node
2658  * that is "sss".
2659  *
2660  * It turns out that there are problems with all multi-character folds, and not
2661  * just these three.  Now the code is general, for all such cases, but the
2662  * three still have some special handling.  The approach taken is:
2663  * 1)   This routine examines each EXACTFish node that could contain multi-
2664  *      character fold sequences.  It returns in *min_subtract how much to
2665  *      subtract from the the actual length of the string to get a real minimum
2666  *      match length; it is 0 if there are no multi-char folds.  This delta is
2667  *      used by the caller to adjust the min length of the match, and the delta
2668  *      between min and max, so that the optimizer doesn't reject these
2669  *      possibilities based on size constraints.
2670  * 2)   Certain of these sequences require special handling by the trie code,
2671  *      so, if found, this code changes the joined node type to special ops:
2672  *      EXACTFU_TRICKYFOLD and EXACTFU_SS.
2673  * 3)   For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
2674  *      is used for an EXACTFU node that contains at least one "ss" sequence in
2675  *      it.  For non-UTF-8 patterns and strings, this is the only case where
2676  *      there is a possible fold length change.  That means that a regular
2677  *      EXACTFU node without UTF-8 involvement doesn't have to concern itself
2678  *      with length changes, and so can be processed faster.  regexec.c takes
2679  *      advantage of this.  Generally, an EXACTFish node that is in UTF-8 is
2680  *      pre-folded by regcomp.c.  This saves effort in regex matching.
2681  *      However, the pre-folding isn't done for non-UTF8 patterns because the
2682  *      fold of the MICRO SIGN requires UTF-8, and we don't want to slow things
2683  *      down by forcing the pattern into UTF8 unless necessary.  Also what
2684  *      EXACTF and EXACTFL nodes fold to isn't known until runtime.  The fold
2685  *      possibilities for the non-UTF8 patterns are quite simple, except for
2686  *      the sharp s.  All the ones that don't involve a UTF-8 target string are
2687  *      members of a fold-pair, and arrays are set up for all of them so that
2688  *      the other member of the pair can be found quickly.  Code elsewhere in
2689  *      this file makes sure that in EXACTFU nodes, the sharp s gets folded to
2690  *      'ss', even if the pattern isn't UTF-8.  This avoids the issues
2691  *      described in the next item.
2692  * 4)   A problem remains for the sharp s in EXACTF and EXACTFA nodes when the
2693  *      pattern isn't in UTF-8. (BTW, there cannot be an EXACTF node with a
2694  *      UTF-8 pattern.)  An assumption that the optimizer part of regexec.c
2695  *      (probably unwittingly, in Perl_regexec_flags()) makes is that a
2696  *      character in the pattern corresponds to at most a single character in
2697  *      the target string.  (And I do mean character, and not byte here, unlike
2698  *      other parts of the documentation that have never been updated to
2699  *      account for multibyte Unicode.)  sharp s in EXACTF nodes can match the
2700  *      two character string 'ss'; in EXACTFA nodes it can match
2701  *      "\x{17F}\x{17F}".  These violate the assumption, and they are the only
2702  *      instances where it is violated.  I'm reluctant to try to change the
2703  *      assumption, as the code involved is impenetrable to me (khw), so
2704  *      instead the code here punts.  This routine examines (when the pattern
2705  *      isn't UTF-8) EXACTF and EXACTFA nodes for the sharp s, and returns a
2706  *      boolean indicating whether or not the node contains a sharp s.  When it
2707  *      is true, the caller sets a flag that later causes the optimizer in this
2708  *      file to not set values for the floating and fixed string lengths, and
2709  *      thus avoids the optimizer code in regexec.c that makes the invalid
2710  *      assumption.  Thus, there is no optimization based on string lengths for
2711  *      non-UTF8-pattern EXACTF and EXACTFA nodes that contain the sharp s.
2712  *      (The reason the assumption is wrong only in these two cases is that all
2713  *      other non-UTF-8 folds are 1-1; and, for UTF-8 patterns, we pre-fold all
2714  *      other folds to their expanded versions.  We can't prefold sharp s to
2715  *      'ss' in EXACTF nodes because we don't know at compile time if it
2716  *      actually matches 'ss' or not.  It will match iff the target string is
2717  *      in UTF-8, unlike the EXACTFU nodes, where it always matches; and
2718  *      EXACTFA and EXACTFL where it never does.  In an EXACTFA node in a UTF-8
2719  *      pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the problem;
2720  *      but in a non-UTF8 pattern, folding it to that above-Latin1 string would
2721  *      require the pattern to be forced into UTF-8, the overhead of which we
2722  *      want to avoid.)
2723  */
2724
2725 #define JOIN_EXACT(scan,min_subtract,has_exactf_sharp_s, flags) \
2726     if (PL_regkind[OP(scan)] == EXACT) \
2727         join_exact(pRExC_state,(scan),(min_subtract),has_exactf_sharp_s, (flags),NULL,depth+1)
2728
2729 STATIC U32
2730 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, UV *min_subtract, bool *has_exactf_sharp_s, U32 flags,regnode *val, U32 depth) {
2731     /* Merge several consecutive EXACTish nodes into one. */
2732     regnode *n = regnext(scan);
2733     U32 stringok = 1;
2734     regnode *next = scan + NODE_SZ_STR(scan);
2735     U32 merged = 0;
2736     U32 stopnow = 0;
2737 #ifdef DEBUGGING
2738     regnode *stop = scan;
2739     GET_RE_DEBUG_FLAGS_DECL;
2740 #else
2741     PERL_UNUSED_ARG(depth);
2742 #endif
2743
2744     PERL_ARGS_ASSERT_JOIN_EXACT;
2745 #ifndef EXPERIMENTAL_INPLACESCAN
2746     PERL_UNUSED_ARG(flags);
2747     PERL_UNUSED_ARG(val);
2748 #endif
2749     DEBUG_PEEP("join",scan,depth);
2750
2751     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
2752      * EXACT ones that are mergeable to the current one. */
2753     while (n
2754            && (PL_regkind[OP(n)] == NOTHING
2755                || (stringok && OP(n) == OP(scan)))
2756            && NEXT_OFF(n)
2757            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
2758     {
2759         
2760         if (OP(n) == TAIL || n > next)
2761             stringok = 0;
2762         if (PL_regkind[OP(n)] == NOTHING) {
2763             DEBUG_PEEP("skip:",n,depth);
2764             NEXT_OFF(scan) += NEXT_OFF(n);
2765             next = n + NODE_STEP_REGNODE;
2766 #ifdef DEBUGGING
2767             if (stringok)
2768                 stop = n;
2769 #endif
2770             n = regnext(n);
2771         }
2772         else if (stringok) {
2773             const unsigned int oldl = STR_LEN(scan);
2774             regnode * const nnext = regnext(n);
2775
2776             /* XXX I (khw) kind of doubt that this works on platforms where
2777              * U8_MAX is above 255 because of lots of other assumptions */
2778             /* Don't join if the sum can't fit into a single node */
2779             if (oldl + STR_LEN(n) > U8_MAX)
2780                 break;
2781             
2782             DEBUG_PEEP("merg",n,depth);
2783             merged++;
2784
2785             NEXT_OFF(scan) += NEXT_OFF(n);
2786             STR_LEN(scan) += STR_LEN(n);
2787             next = n + NODE_SZ_STR(n);
2788             /* Now we can overwrite *n : */
2789             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2790 #ifdef DEBUGGING
2791             stop = next - 1;
2792 #endif
2793             n = nnext;
2794             if (stopnow) break;
2795         }
2796
2797 #ifdef EXPERIMENTAL_INPLACESCAN
2798         if (flags && !NEXT_OFF(n)) {
2799             DEBUG_PEEP("atch", val, depth);
2800             if (reg_off_by_arg[OP(n)]) {
2801                 ARG_SET(n, val - n);
2802             }
2803             else {
2804                 NEXT_OFF(n) = val - n;
2805             }
2806             stopnow = 1;
2807         }
2808 #endif
2809     }
2810
2811     *min_subtract = 0;
2812     *has_exactf_sharp_s = FALSE;
2813
2814     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
2815      * can now analyze for sequences of problematic code points.  (Prior to
2816      * this final joining, sequences could have been split over boundaries, and
2817      * hence missed).  The sequences only happen in folding, hence for any
2818      * non-EXACT EXACTish node */
2819     if (OP(scan) != EXACT) {
2820         const U8 * const s0 = (U8*) STRING(scan);
2821         const U8 * s = s0;
2822         const U8 * const s_end = s0 + STR_LEN(scan);
2823
2824         /* One pass is made over the node's string looking for all the
2825          * possibilities.  to avoid some tests in the loop, there are two main
2826          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
2827          * non-UTF-8 */
2828         if (UTF) {
2829
2830             /* Examine the string for a multi-character fold sequence.  UTF-8
2831              * patterns have all characters pre-folded by the time this code is
2832              * executed */
2833             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
2834                                      length sequence we are looking for is 2 */
2835             {
2836                 int count = 0;
2837                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
2838                 if (! len) {    /* Not a multi-char fold: get next char */
2839                     s += UTF8SKIP(s);
2840                     continue;
2841                 }
2842
2843                 /* Nodes with 'ss' require special handling, except for EXACTFL
2844                  * and EXACTFA for which there is no multi-char fold to this */
2845                 if (len == 2 && *s == 's' && *(s+1) == 's'
2846                     && OP(scan) != EXACTFL && OP(scan) != EXACTFA)
2847                 {
2848                     count = 2;
2849                     OP(scan) = EXACTFU_SS;
2850                     s += 2;
2851                 }
2852                 else if (len == 6   /* len is the same in both ASCII and EBCDIC
2853                                        for these */
2854                          && (memEQ(s, GREEK_SMALL_LETTER_IOTA_UTF8
2855                                       COMBINING_DIAERESIS_UTF8
2856                                       COMBINING_ACUTE_ACCENT_UTF8,
2857                                    6)
2858                              || memEQ(s, GREEK_SMALL_LETTER_UPSILON_UTF8
2859                                          COMBINING_DIAERESIS_UTF8
2860                                          COMBINING_ACUTE_ACCENT_UTF8,
2861                                      6)))
2862                 {
2863                     count = 3;
2864
2865                     /* These two folds require special handling by trie's, so
2866                      * change the node type to indicate this.  If EXACTFA and
2867                      * EXACTFL were ever to be handled by trie's, this would
2868                      * have to be changed.  If this node has already been
2869                      * changed to EXACTFU_SS in this loop, leave it as is.  (I
2870                      * (khw) think it doesn't matter in regexec.c for UTF
2871                      * patterns, but no need to change it */
2872                     if (OP(scan) == EXACTFU) {
2873                         OP(scan) = EXACTFU_TRICKYFOLD;
2874                     }
2875                     s += 6;
2876                 }
2877                 else { /* Here is a generic multi-char fold. */
2878                     const U8* multi_end  = s + len;
2879
2880                     /* Count how many characters in it.  In the case of /l and
2881                      * /aa, no folds which contain ASCII code points are
2882                      * allowed, so check for those, and skip if found.  (In
2883                      * EXACTFL, no folds are allowed to any Latin1 code point,
2884                      * not just ASCII.  But there aren't any of these
2885                      * currently, nor ever likely, so don't take the time to
2886                      * test for them.  The code that generates the
2887                      * is_MULTI_foo() macros croaks should one actually get put
2888                      * into Unicode .) */
2889                     if (OP(scan) != EXACTFL && OP(scan) != EXACTFA) {
2890                         count = utf8_length(s, multi_end);
2891                         s = multi_end;
2892                     }
2893                     else {
2894                         while (s < multi_end) {
2895                             if (isASCII(*s)) {
2896                                 s++;
2897                                 goto next_iteration;
2898                             }
2899                             else {
2900                                 s += UTF8SKIP(s);
2901                             }
2902                             count++;
2903                         }
2904                     }
2905                 }
2906
2907                 /* The delta is how long the sequence is minus 1 (1 is how long
2908                  * the character that folds to the sequence is) */
2909                 *min_subtract += count - 1;
2910             next_iteration: ;
2911             }
2912         }
2913         else if (OP(scan) == EXACTFA) {
2914
2915             /* Non-UTF-8 pattern, EXACTFA node.  There can't be a multi-char
2916              * fold to the ASCII range (and there are no existing ones in the
2917              * upper latin1 range).  But, as outlined in the comments preceding
2918              * this function, we need to flag any occurrences of the sharp s */
2919             while (s < s_end) {
2920                 if (*s == LATIN_SMALL_LETTER_SHARP_S) {
2921                     *has_exactf_sharp_s = TRUE;
2922                     break;
2923                 }
2924                 s++;
2925                 continue;
2926             }
2927         }
2928         else if (OP(scan) != EXACTFL) {
2929
2930             /* Non-UTF-8 pattern, not EXACTFA nor EXACTFL node.  Look for the
2931              * multi-char folds that are all Latin1.  (This code knows that
2932              * there are no current multi-char folds possible with EXACTFL,
2933              * relying on fold_grind.t to catch any errors if the very unlikely
2934              * event happens that some get added in future Unicode versions.)
2935              * As explained in the comments preceding this function, we look
2936              * also for the sharp s in EXACTF nodes; it can be in the final
2937              * position.  Otherwise we can stop looking 1 byte earlier because
2938              * have to find at least two characters for a multi-fold */
2939             const U8* upper = (OP(scan) == EXACTF) ? s_end : s_end -1;
2940
2941             /* The below is perhaps overboard, but this allows us to save a
2942              * test each time through the loop at the expense of a mask.  This
2943              * is because on both EBCDIC and ASCII machines, 'S' and 's' differ
2944              * by a single bit.  On ASCII they are 32 apart; on EBCDIC, they
2945              * are 64.  This uses an exclusive 'or' to find that bit and then
2946              * inverts it to form a mask, with just a single 0, in the bit
2947              * position where 'S' and 's' differ. */
2948             const U8 S_or_s_mask = (U8) ~ ('S' ^ 's');
2949             const U8 s_masked = 's' & S_or_s_mask;
2950
2951             while (s < upper) {
2952                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
2953                 if (! len) {    /* Not a multi-char fold. */
2954                     if (*s == LATIN_SMALL_LETTER_SHARP_S && OP(scan) == EXACTF)
2955                     {
2956                         *has_exactf_sharp_s = TRUE;
2957                     }
2958                     s++;
2959                     continue;
2960                 }
2961
2962                 if (len == 2
2963                     && ((*s & S_or_s_mask) == s_masked)
2964                     && ((*(s+1) & S_or_s_mask) == s_masked))
2965                 {
2966
2967                     /* EXACTF nodes need to know that the minimum length
2968                      * changed so that a sharp s in the string can match this
2969                      * ss in the pattern, but they remain EXACTF nodes, as they
2970                      * won't match this unless the target string is is UTF-8,
2971                      * which we don't know until runtime */
2972                     if (OP(scan) != EXACTF) {
2973                         OP(scan) = EXACTFU_SS;
2974                     }
2975                 }
2976
2977                 *min_subtract += len - 1;
2978                 s += len;
2979             }
2980         }
2981     }
2982
2983 #ifdef DEBUGGING
2984     /* Allow dumping but overwriting the collection of skipped
2985      * ops and/or strings with fake optimized ops */
2986     n = scan + NODE_SZ_STR(scan);
2987     while (n <= stop) {
2988         OP(n) = OPTIMIZED;
2989         FLAGS(n) = 0;
2990         NEXT_OFF(n) = 0;
2991         n++;
2992     }
2993 #endif
2994     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2995     return stopnow;
2996 }
2997
2998 /* REx optimizer.  Converts nodes into quicker variants "in place".
2999    Finds fixed substrings.  */
3000
3001 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
3002    to the position after last scanned or to NULL. */
3003
3004 #define INIT_AND_WITHP \
3005     assert(!and_withp); \
3006     Newx(and_withp,1,struct regnode_charclass_class); \
3007     SAVEFREEPV(and_withp)
3008
3009 /* this is a chain of data about sub patterns we are processing that
3010    need to be handled separately/specially in study_chunk. Its so
3011    we can simulate recursion without losing state.  */
3012 struct scan_frame;
3013 typedef struct scan_frame {
3014     regnode *last;  /* last node to process in this frame */
3015     regnode *next;  /* next node to process when last is reached */
3016     struct scan_frame *prev; /*previous frame*/
3017     I32 stop; /* what stopparen do we use */
3018 } scan_frame;
3019
3020
3021 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
3022
3023 STATIC I32
3024 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
3025                         I32 *minlenp, I32 *deltap,
3026                         regnode *last,
3027                         scan_data_t *data,
3028                         I32 stopparen,
3029                         U8* recursed,
3030                         struct regnode_charclass_class *and_withp,
3031                         U32 flags, U32 depth)
3032                         /* scanp: Start here (read-write). */
3033                         /* deltap: Write maxlen-minlen here. */
3034                         /* last: Stop before this one. */
3035                         /* data: string data about the pattern */
3036                         /* stopparen: treat close N as END */
3037                         /* recursed: which subroutines have we recursed into */
3038                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
3039 {
3040     dVAR;
3041     I32 min = 0;    /* There must be at least this number of characters to match */
3042     I32 pars = 0, code;
3043     regnode *scan = *scanp, *next;
3044     I32 delta = 0;
3045     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
3046     int is_inf_internal = 0;            /* The studied chunk is infinite */
3047     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
3048     scan_data_t data_fake;
3049     SV *re_trie_maxbuff = NULL;
3050     regnode *first_non_open = scan;
3051     I32 stopmin = I32_MAX;
3052     scan_frame *frame = NULL;
3053     GET_RE_DEBUG_FLAGS_DECL;
3054
3055     PERL_ARGS_ASSERT_STUDY_CHUNK;
3056
3057 #ifdef DEBUGGING
3058     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
3059 #endif
3060
3061     if ( depth == 0 ) {
3062         while (first_non_open && OP(first_non_open) == OPEN)
3063             first_non_open=regnext(first_non_open);
3064     }
3065
3066
3067   fake_study_recurse:
3068     while ( scan && OP(scan) != END && scan < last ){
3069         UV min_subtract = 0;    /* How mmany chars to subtract from the minimum
3070                                    node length to get a real minimum (because
3071                                    the folded version may be shorter) */
3072         bool has_exactf_sharp_s = FALSE;
3073         /* Peephole optimizer: */
3074         DEBUG_STUDYDATA("Peep:", data,depth);
3075         DEBUG_PEEP("Peep",scan,depth);
3076
3077         /* Its not clear to khw or hv why this is done here, and not in the
3078          * clauses that deal with EXACT nodes.  khw's guess is that it's
3079          * because of a previous design */
3080         JOIN_EXACT(scan,&min_subtract, &has_exactf_sharp_s, 0);
3081
3082         /* Follow the next-chain of the current node and optimize
3083            away all the NOTHINGs from it.  */
3084         if (OP(scan) != CURLYX) {
3085             const int max = (reg_off_by_arg[OP(scan)]
3086                        ? I32_MAX
3087                        /* I32 may be smaller than U16 on CRAYs! */
3088                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
3089             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
3090             int noff;
3091             regnode *n = scan;
3092
3093             /* Skip NOTHING and LONGJMP. */
3094             while ((n = regnext(n))
3095                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
3096                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
3097                    && off + noff < max)
3098                 off += noff;
3099             if (reg_off_by_arg[OP(scan)])
3100                 ARG(scan) = off;
3101             else
3102                 NEXT_OFF(scan) = off;
3103         }
3104
3105
3106
3107         /* The principal pseudo-switch.  Cannot be a switch, since we
3108            look into several different things.  */
3109         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
3110                    || OP(scan) == IFTHEN) {
3111             next = regnext(scan);
3112             code = OP(scan);
3113             /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
3114
3115             if (OP(next) == code || code == IFTHEN) {
3116                 /* NOTE - There is similar code to this block below for handling
3117                    TRIE nodes on a re-study.  If you change stuff here check there
3118                    too. */
3119                 I32 max1 = 0, min1 = I32_MAX, num = 0;
3120                 struct regnode_charclass_class accum;
3121                 regnode * const startbranch=scan;
3122
3123                 if (flags & SCF_DO_SUBSTR)
3124                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
3125                 if (flags & SCF_DO_STCLASS)
3126                     cl_init_zero(pRExC_state, &accum);
3127
3128                 while (OP(scan) == code) {
3129                     I32 deltanext, minnext, f = 0, fake;
3130                     struct regnode_charclass_class this_class;
3131
3132                     num++;
3133                     data_fake.flags = 0;
3134                     if (data) {
3135                         data_fake.whilem_c = data->whilem_c;
3136                         data_fake.last_closep = data->last_closep;
3137                     }
3138                     else
3139                         data_fake.last_closep = &fake;
3140
3141                     data_fake.pos_delta = delta;
3142                     next = regnext(scan);
3143                     scan = NEXTOPER(scan);
3144                     if (code != BRANCH)
3145                         scan = NEXTOPER(scan);
3146                     if (flags & SCF_DO_STCLASS) {
3147                         cl_init(pRExC_state, &this_class);
3148                         data_fake.start_class = &this_class;
3149                         f = SCF_DO_STCLASS_AND;
3150                     }
3151                     if (flags & SCF_WHILEM_VISITED_POS)
3152                         f |= SCF_WHILEM_VISITED_POS;
3153
3154                     /* we suppose the run is continuous, last=next...*/
3155                     minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3156                                           next, &data_fake,
3157                                           stopparen, recursed, NULL, f,depth+1);
3158                     if (min1 > minnext)
3159                         min1 = minnext;
3160                     if (deltanext == I32_MAX) {
3161                         is_inf = is_inf_internal = 1;
3162                         max1 = I32_MAX;
3163                     } else if (max1 < minnext + deltanext)
3164                         max1 = minnext + deltanext;
3165                     scan = next;
3166                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3167                         pars++;
3168                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
3169                         if ( stopmin > minnext) 
3170                             stopmin = min + min1;
3171                         flags &= ~SCF_DO_SUBSTR;
3172                         if (data)
3173                             data->flags |= SCF_SEEN_ACCEPT;
3174                     }
3175                     if (data) {
3176                         if (data_fake.flags & SF_HAS_EVAL)
3177                             data->flags |= SF_HAS_EVAL;
3178                         data->whilem_c = data_fake.whilem_c;
3179                     }
3180                     if (flags & SCF_DO_STCLASS)
3181                         cl_or(pRExC_state, &accum, &this_class);
3182                 }
3183                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
3184                     min1 = 0;
3185                 if (flags & SCF_DO_SUBSTR) {
3186                     data->pos_min += min1;
3187                     if (data->pos_delta >= I32_MAX - (max1 - min1))
3188                         data->pos_delta = I32_MAX;
3189                     else
3190                         data->pos_delta += max1 - min1;
3191                     if (max1 != min1 || is_inf)
3192                         data->longest = &(data->longest_float);
3193                 }
3194                 min += min1;
3195                 if (delta == I32_MAX || I32_MAX - delta - (max1 - min1) < 0)
3196                     delta = I32_MAX;
3197                 else
3198                     delta += max1 - min1;
3199                 if (flags & SCF_DO_STCLASS_OR) {
3200                     cl_or(pRExC_state, data->start_class, &accum);
3201                     if (min1) {
3202                         cl_and(data->start_class, and_withp);
3203                         flags &= ~SCF_DO_STCLASS;
3204                     }
3205                 }
3206                 else if (flags & SCF_DO_STCLASS_AND) {
3207                     if (min1) {
3208                         cl_and(data->start_class, &accum);
3209                         flags &= ~SCF_DO_STCLASS;
3210                     }
3211                     else {
3212                         /* Switch to OR mode: cache the old value of
3213                          * data->start_class */
3214                         INIT_AND_WITHP;
3215                         StructCopy(data->start_class, and_withp,
3216                                    struct regnode_charclass_class);
3217                         flags &= ~SCF_DO_STCLASS_AND;
3218                         StructCopy(&accum, data->start_class,
3219                                    struct regnode_charclass_class);
3220                         flags |= SCF_DO_STCLASS_OR;
3221                         SET_SSC_EOS(data->start_class);
3222                     }
3223                 }
3224
3225                 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
3226                 /* demq.
3227
3228                    Assuming this was/is a branch we are dealing with: 'scan' now
3229                    points at the item that follows the branch sequence, whatever
3230                    it is. We now start at the beginning of the sequence and look
3231                    for subsequences of
3232
3233                    BRANCH->EXACT=>x1
3234                    BRANCH->EXACT=>x2
3235                    tail
3236
3237                    which would be constructed from a pattern like /A|LIST|OF|WORDS/
3238
3239                    If we can find such a subsequence we need to turn the first
3240                    element into a trie and then add the subsequent branch exact
3241                    strings to the trie.
3242
3243                    We have two cases
3244
3245                      1. patterns where the whole set of branches can be converted. 
3246
3247                      2. patterns where only a subset can be converted.
3248
3249                    In case 1 we can replace the whole set with a single regop
3250                    for the trie. In case 2 we need to keep the start and end
3251                    branches so
3252
3253                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
3254                      becomes BRANCH TRIE; BRANCH X;
3255
3256                   There is an additional case, that being where there is a 
3257                   common prefix, which gets split out into an EXACT like node
3258                   preceding the TRIE node.
3259
3260                   If x(1..n)==tail then we can do a simple trie, if not we make
3261                   a "jump" trie, such that when we match the appropriate word
3262                   we "jump" to the appropriate tail node. Essentially we turn
3263                   a nested if into a case structure of sorts.
3264
3265                 */
3266
3267                     int made=0;
3268                     if (!re_trie_maxbuff) {
3269                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
3270                         if (!SvIOK(re_trie_maxbuff))
3271                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
3272                     }
3273                     if ( SvIV(re_trie_maxbuff)>=0  ) {
3274                         regnode *cur;
3275                         regnode *first = (regnode *)NULL;
3276                         regnode *last = (regnode *)NULL;
3277                         regnode *tail = scan;
3278                         U8 trietype = 0;
3279                         U32 count=0;
3280
3281 #ifdef DEBUGGING
3282                         SV * const mysv = sv_newmortal();       /* for dumping */
3283 #endif
3284                         /* var tail is used because there may be a TAIL
3285                            regop in the way. Ie, the exacts will point to the
3286                            thing following the TAIL, but the last branch will
3287                            point at the TAIL. So we advance tail. If we
3288                            have nested (?:) we may have to move through several
3289                            tails.
3290                          */
3291
3292                         while ( OP( tail ) == TAIL ) {
3293                             /* this is the TAIL generated by (?:) */
3294                             tail = regnext( tail );
3295                         }
3296
3297                         
3298                         DEBUG_TRIE_COMPILE_r({
3299                             regprop(RExC_rx, mysv, tail );
3300                             PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
3301                                 (int)depth * 2 + 2, "", 
3302                                 "Looking for TRIE'able sequences. Tail node is: ", 
3303                                 SvPV_nolen_const( mysv )
3304                             );
3305                         });
3306                         
3307                         /*
3308
3309                             Step through the branches
3310                                 cur represents each branch,
3311                                 noper is the first thing to be matched as part of that branch
3312                                 noper_next is the regnext() of that node.
3313
3314                             We normally handle a case like this /FOO[xyz]|BAR[pqr]/
3315                             via a "jump trie" but we also support building with NOJUMPTRIE,
3316                             which restricts the trie logic to structures like /FOO|BAR/.
3317
3318                             If noper is a trieable nodetype then the branch is a possible optimization
3319                             target. If we are building under NOJUMPTRIE then we require that noper_next
3320                             is the same as scan (our current position in the regex program).
3321
3322                             Once we have two or more consecutive such branches we can create a
3323                             trie of the EXACT's contents and stitch it in place into the program.
3324
3325                             If the sequence represents all of the branches in the alternation we
3326                             replace the entire thing with a single TRIE node.
3327
3328                             Otherwise when it is a subsequence we need to stitch it in place and
3329                             replace only the relevant branches. This means the first branch has
3330                             to remain as it is used by the alternation logic, and its next pointer,
3331                             and needs to be repointed at the item on the branch chain following
3332                             the last branch we have optimized away.
3333
3334                             This could be either a BRANCH, in which case the subsequence is internal,
3335                             or it could be the item following the branch sequence in which case the
3336                             subsequence is at the end (which does not necessarily mean the first node
3337                             is the start of the alternation).
3338
3339                             TRIE_TYPE(X) is a define which maps the optype to a trietype.
3340
3341                                 optype          |  trietype
3342                                 ----------------+-----------
3343                                 NOTHING         | NOTHING
3344                                 EXACT           | EXACT
3345                                 EXACTFU         | EXACTFU
3346                                 EXACTFU_SS      | EXACTFU
3347                                 EXACTFU_TRICKYFOLD | EXACTFU
3348                                 EXACTFA         | 0
3349
3350
3351                         */
3352 #define TRIE_TYPE(X) ( ( NOTHING == (X) ) ? NOTHING :   \
3353                        ( EXACT == (X) )   ? EXACT :        \
3354                        ( EXACTFU == (X) || EXACTFU_SS == (X) || EXACTFU_TRICKYFOLD == (X) ) ? EXACTFU :        \
3355                        0 )
3356
3357                         /* dont use tail as the end marker for this traverse */
3358                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
3359                             regnode * const noper = NEXTOPER( cur );
3360                             U8 noper_type = OP( noper );
3361                             U8 noper_trietype = TRIE_TYPE( noper_type );
3362 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
3363                             regnode * const noper_next = regnext( noper );
3364                             U8 noper_next_type = (noper_next && noper_next != tail) ? OP(noper_next) : 0;
3365                             U8 noper_next_trietype = (noper_next && noper_next != tail) ? TRIE_TYPE( noper_next_type ) :0;
3366 #endif
3367
3368                             DEBUG_TRIE_COMPILE_r({
3369                                 regprop(RExC_rx, mysv, cur);
3370                                 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
3371                                    (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
3372
3373                                 regprop(RExC_rx, mysv, noper);
3374                                 PerlIO_printf( Perl_debug_log, " -> %s",
3375                                     SvPV_nolen_const(mysv));
3376
3377                                 if ( noper_next ) {
3378                                   regprop(RExC_rx, mysv, noper_next );
3379                                   PerlIO_printf( Perl_debug_log,"\t=> %s\t",
3380                                     SvPV_nolen_const(mysv));
3381                                 }
3382                                 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d,tt==%s,nt==%s,nnt==%s)\n",
3383                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
3384                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] 
3385                                 );
3386                             });
3387
3388                             /* Is noper a trieable nodetype that can be merged with the
3389                              * current trie (if there is one)? */
3390                             if ( noper_trietype
3391                                   &&
3392                                   (
3393                                         ( noper_trietype == NOTHING)
3394                                         || ( trietype == NOTHING )
3395                                         || ( trietype == noper_trietype )
3396                                   )
3397 #ifdef NOJUMPTRIE
3398                                   && noper_next == tail
3399 #endif
3400                                   && count < U16_MAX)
3401                             {
3402                                 /* Handle mergable triable node
3403                                  * Either we are the first node in a new trieable sequence,
3404                                  * in which case we do some bookkeeping, otherwise we update
3405                                  * the end pointer. */
3406                                 if ( !first ) {
3407                                     first = cur;
3408                                     if ( noper_trietype == NOTHING ) {
3409 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
3410                                         regnode * const noper_next = regnext( noper );
3411                                         U8 noper_next_type = (noper_next && noper_next!=tail) ? OP(noper_next) : 0;
3412                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
3413 #endif
3414
3415                                         if ( noper_next_trietype ) {
3416                                             trietype = noper_next_trietype;
3417                                         } else if (noper_next_type)  {
3418                                             /* a NOTHING regop is 1 regop wide. We need at least two
3419                                              * for a trie so we can't merge this in */
3420                                             first = NULL;
3421                                         }
3422                                     } else {
3423                                         trietype = noper_trietype;
3424                                     }
3425                                 } else {
3426                                     if ( trietype == NOTHING )
3427                                         trietype = noper_trietype;
3428                                     last = cur;
3429                                 }
3430                                 if (first)
3431                                     count++;
3432                             } /* end handle mergable triable node */
3433                             else {
3434                                 /* handle unmergable node -
3435                                  * noper may either be a triable node which can not be tried
3436                                  * together with the current trie, or a non triable node */
3437                                 if ( last ) {
3438                                     /* If last is set and trietype is not NOTHING then we have found
3439                                      * at least two triable branch sequences in a row of a similar
3440                                      * trietype so we can turn them into a trie. If/when we
3441                                      * allow NOTHING to start a trie sequence this condition will be
3442                                      * required, and it isn't expensive so we leave it in for now. */
3443                                     if ( trietype && trietype != NOTHING )
3444                                         make_trie( pRExC_state,
3445                                                 startbranch, first, cur, tail, count,
3446                                                 trietype, depth+1 );
3447                                     last = NULL; /* note: we clear/update first, trietype etc below, so we dont do it here */
3448                                 }
3449                                 if ( noper_trietype
3450 #ifdef NOJUMPTRIE
3451                                      && noper_next == tail
3452 #endif
3453                                 ){
3454                                     /* noper is triable, so we can start a new trie sequence */
3455                                     count = 1;
3456                                     first = cur;
3457                                     trietype = noper_trietype;
3458                                 } else if (first) {
3459                                     /* if we already saw a first but the current node is not triable then we have
3460                                      * to reset the first information. */
3461                                     count = 0;
3462                                     first = NULL;
3463                                     trietype = 0;
3464                                 }
3465                             } /* end handle unmergable node */
3466                         } /* loop over branches */
3467                         DEBUG_TRIE_COMPILE_r({
3468                             regprop(RExC_rx, mysv, cur);
3469                             PerlIO_printf( Perl_debug_log,
3470                               "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
3471                               "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
3472
3473                         });
3474                         if ( last && trietype ) {
3475                             if ( trietype != NOTHING ) {
3476                                 /* the last branch of the sequence was part of a trie,
3477                                  * so we have to construct it here outside of the loop
3478                                  */
3479                                 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, trietype, depth+1 );
3480 #ifdef TRIE_STUDY_OPT
3481                                 if ( ((made == MADE_EXACT_TRIE &&
3482                                      startbranch == first)
3483                                      || ( first_non_open == first )) &&
3484                                      depth==0 ) {
3485                                     flags |= SCF_TRIE_RESTUDY;
3486                                     if ( startbranch == first
3487                                          && scan == tail )
3488                                     {
3489                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
3490                                     }
3491                                 }
3492 #endif
3493                             } else {
3494                                 /* at this point we know whatever we have is a NOTHING sequence/branch
3495                                  * AND if 'startbranch' is 'first' then we can turn the whole thing into a NOTHING
3496                                  */
3497                                 if ( startbranch == first ) {
3498                                     regnode *opt;
3499                                     /* the entire thing is a NOTHING sequence, something like this:
3500                                      * (?:|) So we can turn it into a plain NOTHING op. */
3501                                     DEBUG_TRIE_COMPILE_r({
3502                                         regprop(RExC_rx, mysv, cur);
3503                                         PerlIO_printf( Perl_debug_log,
3504                                           "%*s- %s (%d) <NOTHING BRANCH SEQUENCE>\n", (int)depth * 2 + 2,
3505                                           "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
3506
3507                                     });
3508                                     OP(startbranch)= NOTHING;
3509                                     NEXT_OFF(startbranch)= tail - startbranch;
3510                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
3511                                         OP(opt)= OPTIMIZED;
3512                                 }
3513                             }
3514                         } /* end if ( last) */
3515                     } /* TRIE_MAXBUF is non zero */
3516                     
3517                 } /* do trie */
3518                 
3519             }
3520             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
3521                 scan = NEXTOPER(NEXTOPER(scan));
3522             } else                      /* single branch is optimized. */
3523                 scan = NEXTOPER(scan);
3524             continue;
3525         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
3526             scan_frame *newframe = NULL;
3527             I32 paren;
3528             regnode *start;
3529             regnode *end;
3530
3531             if (OP(scan) != SUSPEND) {
3532             /* set the pointer */
3533                 if (OP(scan) == GOSUB) {
3534                     paren = ARG(scan);
3535                     RExC_recurse[ARG2L(scan)] = scan;
3536                     start = RExC_open_parens[paren-1];
3537                     end   = RExC_close_parens[paren-1];
3538                 } else {
3539                     paren = 0;
3540                     start = RExC_rxi->program + 1;
3541                     end   = RExC_opend;
3542                 }
3543                 if (!recursed) {
3544                     Newxz(recursed, (((RExC_npar)>>3) +1), U8);
3545                     SAVEFREEPV(recursed);
3546                 }
3547                 if (!PAREN_TEST(recursed,paren+1)) {
3548                     PAREN_SET(recursed,paren+1);
3549                     Newx(newframe,1,scan_frame);
3550                 } else {
3551                     if (flags & SCF_DO_SUBSTR) {
3552                         SCAN_COMMIT(pRExC_state,data,minlenp);
3553                         data->longest = &(data->longest_float);
3554                     }
3555                     is_inf = is_inf_internal = 1;
3556                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3557                         cl_anything(pRExC_state, data->start_class);
3558                     flags &= ~SCF_DO_STCLASS;
3559                 }
3560             } else {
3561                 Newx(newframe,1,scan_frame);
3562                 paren = stopparen;
3563                 start = scan+2;
3564                 end = regnext(scan);
3565             }
3566             if (newframe) {
3567                 assert(start);
3568                 assert(end);
3569                 SAVEFREEPV(newframe);
3570                 newframe->next = regnext(scan);
3571                 newframe->last = last;
3572                 newframe->stop = stopparen;
3573                 newframe->prev = frame;
3574
3575                 frame = newframe;
3576                 scan =  start;
3577                 stopparen = paren;
3578                 last = end;
3579
3580                 continue;
3581             }
3582         }
3583         else if (OP(scan) == EXACT) {
3584             I32 l = STR_LEN(scan);
3585             UV uc;
3586             if (UTF) {
3587                 const U8 * const s = (U8*)STRING(scan);
3588                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
3589                 l = utf8_length(s, s + l);
3590             } else {
3591                 uc = *((U8*)STRING(scan));
3592             }
3593             min += l;
3594             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3595                 /* The code below prefers earlier match for fixed
3596                    offset, later match for variable offset.  */
3597                 if (data->last_end == -1) { /* Update the start info. */
3598                     data->last_start_min = data->pos_min;
3599                     data->last_start_max = is_inf
3600                         ? I32_MAX : data->pos_min + data->pos_delta;
3601                 }
3602                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3603                 if (UTF)
3604                     SvUTF8_on(data->last_found);
3605                 {
3606                     SV * const sv = data->last_found;
3607                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3608                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
3609                     if (mg && mg->mg_len >= 0)
3610                         mg->mg_len += utf8_length((U8*)STRING(scan),
3611                                                   (U8*)STRING(scan)+STR_LEN(scan));
3612                 }
3613                 data->last_end = data->pos_min + l;
3614                 data->pos_min += l; /* As in the first entry. */
3615                 data->flags &= ~SF_BEFORE_EOL;
3616             }
3617             if (flags & SCF_DO_STCLASS_AND) {
3618                 /* Check whether it is compatible with what we know already! */
3619                 int compat = 1;
3620
3621
3622                 /* If compatible, we or it in below.  It is compatible if is
3623                  * in the bitmp and either 1) its bit or its fold is set, or 2)
3624                  * it's for a locale.  Even if there isn't unicode semantics
3625                  * here, at runtime there may be because of matching against a
3626                  * utf8 string, so accept a possible false positive for
3627                  * latin1-range folds */
3628                 if (uc >= 0x100 ||
3629                     (!(data->start_class->flags & ANYOF_LOCALE)
3630                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
3631                     && (!(data->start_class->flags & ANYOF_LOC_FOLD)
3632                         || !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3633                     )
3634                 {
3635                     compat = 0;
3636                 }
3637                 ANYOF_CLASS_ZERO(data->start_class);
3638                 ANYOF_BITMAP_ZERO(data->start_class);
3639                 if (compat)
3640                     ANYOF_BITMAP_SET(data->start_class, uc);
3641                 else if (uc >= 0x100) {
3642                     int i;
3643
3644                     /* Some Unicode code points fold to the Latin1 range; as
3645                      * XXX temporary code, instead of figuring out if this is
3646                      * one, just assume it is and set all the start class bits
3647                      * that could be some such above 255 code point's fold
3648                      * which will generate fals positives.  As the code
3649                      * elsewhere that does compute the fold settles down, it
3650                      * can be extracted out and re-used here */
3651                     for (i = 0; i < 256; i++){
3652                         if (HAS_NONLATIN1_FOLD_CLOSURE(i)) {
3653                             ANYOF_BITMAP_SET(data->start_class, i);
3654                         }
3655                     }
3656                 }
3657                 CLEAR_SSC_EOS(data->start_class);
3658                 if (uc < 0x100)
3659                   data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3660             }
3661             else if (flags & SCF_DO_STCLASS_OR) {
3662                 /* false positive possible if the class is case-folded */
3663                 if (uc < 0x100)
3664                     ANYOF_BITMAP_SET(data->start_class, uc);
3665                 else
3666                     data->start_class->flags |= ANYOF_UNICODE_ALL;
3667                 CLEAR_SSC_EOS(data->start_class);
3668                 cl_and(data->start_class, and_withp);
3669             }
3670             flags &= ~SCF_DO_STCLASS;
3671         }
3672         else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3673             I32 l = STR_LEN(scan);
3674             UV uc = *((U8*)STRING(scan));
3675
3676             /* Search for fixed substrings supports EXACT only. */
3677             if (flags & SCF_DO_SUBSTR) {
3678                 assert(data);
3679                 SCAN_COMMIT(pRExC_state, data, minlenp);
3680             }
3681             if (UTF) {
3682                 const U8 * const s = (U8 *)STRING(scan);
3683                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
3684                 l = utf8_length(s, s + l);
3685             }
3686             if (has_exactf_sharp_s) {
3687                 RExC_seen |= REG_SEEN_EXACTF_SHARP_S;
3688             }
3689             min += l - min_subtract;
3690             assert (min >= 0);
3691             delta += min_subtract;
3692             if (flags & SCF_DO_SUBSTR) {
3693                 data->pos_min += l - min_subtract;
3694                 if (data->pos_min < 0) {
3695                     data->pos_min = 0;
3696                 }
3697                 data->pos_delta += min_subtract;
3698                 if (min_subtract) {
3699                     data->longest = &(data->longest_float);
3700                 }
3701             }
3702             if (flags & SCF_DO_STCLASS_AND) {
3703                 /* Check whether it is compatible with what we know already! */
3704                 int compat = 1;
3705                 if (uc >= 0x100 ||
3706                  (!(data->start_class->flags & ANYOF_LOCALE)
3707                   && !ANYOF_BITMAP_TEST(data->start_class, uc)
3708                   && !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3709                 {
3710                     compat = 0;
3711                 }
3712                 ANYOF_CLASS_ZERO(data->start_class);
3713                 ANYOF_BITMAP_ZERO(data->start_class);
3714                 if (compat) {
3715                     ANYOF_BITMAP_SET(data->start_class, uc);
3716                     CLEAR_SSC_EOS(data->start_class);
3717                     if (OP(scan) == EXACTFL) {
3718                         /* XXX This set is probably no longer necessary, and
3719                          * probably wrong as LOCALE now is on in the initial
3720                          * state */
3721                         data->start_class->flags |= ANYOF_LOCALE|ANYOF_LOC_FOLD;
3722                     }
3723                     else {
3724
3725                         /* Also set the other member of the fold pair.  In case
3726                          * that unicode semantics is called for at runtime, use
3727                          * the full latin1 fold.  (Can't do this for locale,
3728                          * because not known until runtime) */
3729                         ANYOF_BITMAP_SET(data->start_class, PL_fold_latin1[uc]);
3730
3731                         /* All other (EXACTFL handled above) folds except under
3732                          * /iaa that include s, S, and sharp_s also may include
3733                          * the others */
3734                         if (OP(scan) != EXACTFA) {
3735                             if (uc == 's' || uc == 'S') {
3736                                 ANYOF_BITMAP_SET(data->start_class,
3737                                                  LATIN_SMALL_LETTER_SHARP_S);
3738                             }
3739                             else if (uc == LATIN_SMALL_LETTER_SHARP_S) {
3740                                 ANYOF_BITMAP_SET(data->start_class, 's');
3741                                 ANYOF_BITMAP_SET(data->start_class, 'S');
3742                             }
3743                         }
3744                     }
3745                 }
3746                 else if (uc >= 0x100) {
3747                     int i;
3748                     for (i = 0; i < 256; i++){
3749                         if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)) {
3750                             ANYOF_BITMAP_SET(data->start_class, i);
3751                         }
3752                     }
3753                 }
3754             }
3755             else if (flags & SCF_DO_STCLASS_OR) {
3756                 if (data->start_class->flags & ANYOF_LOC_FOLD) {
3757                     /* false positive possible if the class is case-folded.
3758                        Assume that the locale settings are the same... */
3759                     if (uc < 0x100) {
3760                         ANYOF_BITMAP_SET(data->start_class, uc);
3761                         if (OP(scan) != EXACTFL) {
3762
3763                             /* And set the other member of the fold pair, but
3764                              * can't do that in locale because not known until
3765                              * run-time */
3766                             ANYOF_BITMAP_SET(data->start_class,
3767                                              PL_fold_latin1[uc]);
3768
3769                             /* All folds except under /iaa that include s, S,
3770                              * and sharp_s also may include the others */
3771                             if (OP(scan) != EXACTFA) {
3772                                 if (uc == 's' || uc == 'S') {
3773                                     ANYOF_BITMAP_SET(data->start_class,
3774                                                    LATIN_SMALL_LETTER_SHARP_S);
3775                                 }
3776                                 else if (uc == LATIN_SMALL_LETTER_SHARP_S) {
3777                                     ANYOF_BITMAP_SET(data->start_class, 's');
3778                                     ANYOF_BITMAP_SET(data->start_class, 'S');
3779                                 }
3780                             }
3781                         }
3782                     }
3783                     CLEAR_SSC_EOS(data->start_class);
3784                 }
3785                 cl_and(data->start_class, and_withp);
3786             }
3787             flags &= ~SCF_DO_STCLASS;
3788         }
3789         else if (REGNODE_VARIES(OP(scan))) {
3790             I32 mincount, maxcount, minnext, deltanext, fl = 0;
3791             I32 f = flags, pos_before = 0;
3792             regnode * const oscan = scan;
3793             struct regnode_charclass_class this_class;
3794             struct regnode_charclass_class *oclass = NULL;
3795             I32 next_is_eval = 0;
3796
3797             switch (PL_regkind[OP(scan)]) {
3798             case WHILEM:                /* End of (?:...)* . */
3799                 scan = NEXTOPER(scan);
3800                 goto finish;
3801             case PLUS:
3802                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3803                     next = NEXTOPER(scan);
3804                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3805                         mincount = 1;
3806                         maxcount = REG_INFTY;
3807                         next = regnext(scan);
3808                         scan = NEXTOPER(scan);
3809                         goto do_curly;
3810                     }
3811                 }
3812                 if (flags & SCF_DO_SUBSTR)
3813                     data->pos_min++;
3814                 min++;
3815                 /* Fall through. */
3816             case STAR:
3817                 if (flags & SCF_DO_STCLASS) {
3818                     mincount = 0;
3819                     maxcount = REG_INFTY;
3820                     next = regnext(scan);
3821                     scan = NEXTOPER(scan);
3822                     goto do_curly;
3823                 }
3824                 is_inf = is_inf_internal = 1;
3825                 scan = regnext(scan);
3826                 if (flags & SCF_DO_SUBSTR) {
3827                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
3828                     data->longest = &(data->longest_float);
3829                 }
3830                 goto optimize_curly_tail;
3831             case CURLY:
3832                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3833                     && (scan->flags == stopparen))
3834                 {
3835                     mincount = 1;
3836                     maxcount = 1;
3837                 } else {
3838                     mincount = ARG1(scan);
3839                     maxcount = ARG2(scan);
3840                 }
3841                 next = regnext(scan);
3842                 if (OP(scan) == CURLYX) {
3843                     I32 lp = (data ? *(data->last_closep) : 0);
3844                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3845                 }
3846                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3847                 next_is_eval = (OP(scan) == EVAL);
3848               do_curly:
3849                 if (flags & SCF_DO_SUBSTR) {
3850                     if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3851                     pos_before = data->pos_min;
3852                 }
3853                 if (data) {
3854                     fl = data->flags;
3855                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3856                     if (is_inf)
3857                         data->flags |= SF_IS_INF;
3858                 }
3859                 if (flags & SCF_DO_STCLASS) {
3860                     cl_init(pRExC_state, &this_class);
3861                     oclass = data->start_class;
3862                     data->start_class = &this_class;
3863                     f |= SCF_DO_STCLASS_AND;
3864                     f &= ~SCF_DO_STCLASS_OR;
3865                 }
3866                 /* Exclude from super-linear cache processing any {n,m}
3867                    regops for which the combination of input pos and regex
3868                    pos is not enough information to determine if a match
3869                    will be possible.
3870
3871                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
3872                    regex pos at the \s*, the prospects for a match depend not
3873                    only on the input position but also on how many (bar\s*)
3874                    repeats into the {4,8} we are. */
3875                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
3876                     f &= ~SCF_WHILEM_VISITED_POS;
3877
3878                 /* This will finish on WHILEM, setting scan, or on NULL: */
3879                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, 
3880                                       last, data, stopparen, recursed, NULL,
3881                                       (mincount == 0
3882                                         ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3883
3884                 if (flags & SCF_DO_STCLASS)
3885                     data->start_class = oclass;
3886                 if (mincount == 0 || minnext == 0) {
3887                     if (flags & SCF_DO_STCLASS_OR) {
3888                         cl_or(pRExC_state, data->start_class, &this_class);
3889                     }
3890                     else if (flags & SCF_DO_STCLASS_AND) {
3891                         /* Switch to OR mode: cache the old value of
3892                          * data->start_class */
3893                         INIT_AND_WITHP;
3894                         StructCopy(data->start_class, and_withp,
3895                                    struct regnode_charclass_class);
3896                         flags &= ~SCF_DO_STCLASS_AND;
3897                         StructCopy(&this_class, data->start_class,
3898                                    struct regnode_charclass_class);
3899                         flags |= SCF_DO_STCLASS_OR;
3900                         SET_SSC_EOS(data->start_class);
3901                     }
3902                 } else {                /* Non-zero len */
3903                     if (flags & SCF_DO_STCLASS_OR) {
3904                         cl_or(pRExC_state, data->start_class, &this_class);
3905                         cl_and(data->start_class, and_withp);
3906                     }
3907                     else if (flags & SCF_DO_STCLASS_AND)
3908                         cl_and(data->start_class, &this_class);
3909                     flags &= ~SCF_DO_STCLASS;
3910                 }
3911                 if (!scan)              /* It was not CURLYX, but CURLY. */
3912                     scan = next;
3913                 if (!(flags & SCF_TRIE_DOING_RESTUDY)
3914                     /* ? quantifier ok, except for (?{ ... }) */
3915                     && (next_is_eval || !(mincount == 0 && maxcount == 1))
3916                     && (minnext == 0) && (deltanext == 0)
3917                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3918                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
3919                 {
3920                     /* Fatal warnings may leak the regexp without this: */
3921                     SAVEFREESV(RExC_rx_sv);
3922                     ckWARNreg(RExC_parse,
3923                               "Quantifier unexpected on zero-length expression");
3924                     (void)ReREFCNT_inc(RExC_rx_sv);
3925                 }
3926
3927                 min += minnext * mincount;
3928                 is_inf_internal |= deltanext == I32_MAX
3929                                      || (maxcount == REG_INFTY && minnext + deltanext > 0);
3930                 is_inf |= is_inf_internal;
3931                 if (is_inf)
3932                     delta = I32_MAX;
3933                 else
3934                     delta += (minnext + deltanext) * maxcount - minnext * mincount;
3935
3936                 /* Try powerful optimization CURLYX => CURLYN. */
3937                 if (  OP(oscan) == CURLYX && data
3938                       && data->flags & SF_IN_PAR
3939                       && !(data->flags & SF_HAS_EVAL)
3940                       && !deltanext && minnext == 1 ) {
3941                     /* Try to optimize to CURLYN.  */
3942                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3943                     regnode * const nxt1 = nxt;
3944 #ifdef DEBUGGING
3945                     regnode *nxt2;
3946 #endif
3947
3948                     /* Skip open. */
3949                     nxt = regnext(nxt);
3950                     if (!REGNODE_SIMPLE(OP(nxt))
3951                         && !(PL_regkind[OP(nxt)] == EXACT
3952                              && STR_LEN(nxt) == 1))
3953                         goto nogo;
3954 #ifdef DEBUGGING
3955                     nxt2 = nxt;
3956 #endif
3957                     nxt = regnext(nxt);
3958                     if (OP(nxt) != CLOSE)
3959                         goto nogo;
3960                     if (RExC_open_parens) {
3961                         RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3962                         RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3963                     }
3964                     /* Now we know that nxt2 is the only contents: */
3965                     oscan->flags = (U8)ARG(nxt);
3966                     OP(oscan) = CURLYN;
3967                     OP(nxt1) = NOTHING; /* was OPEN. */
3968
3969 #ifdef DEBUGGING
3970                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3971                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
3972                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
3973                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
3974                     OP(nxt + 1) = OPTIMIZED; /* was count. */
3975                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
3976 #endif
3977                 }
3978               nogo:
3979
3980                 /* Try optimization CURLYX => CURLYM. */
3981                 if (  OP(oscan) == CURLYX && data
3982                       && !(data->flags & SF_HAS_PAR)
3983                       && !(data->flags & SF_HAS_EVAL)
3984                       && !deltanext     /* atom is fixed width */
3985                       && minnext != 0   /* CURLYM can't handle zero width */
3986                       && ! (RExC_seen & REG_SEEN_EXACTF_SHARP_S) /* Nor \xDF */
3987                 ) {
3988                     /* XXXX How to optimize if data == 0? */
3989                     /* Optimize to a simpler form.  */
3990                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3991                     regnode *nxt2;
3992
3993                     OP(oscan) = CURLYM;
3994                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3995                             && (OP(nxt2) != WHILEM))
3996                         nxt = nxt2;
3997                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
3998                     /* Need to optimize away parenths. */
3999                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
4000                         /* Set the parenth number.  */
4001                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
4002
4003                         oscan->flags = (U8)ARG(nxt);
4004                         if (RExC_open_parens) {
4005                             RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
4006                             RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
4007                         }
4008                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
4009                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
4010
4011 #ifdef DEBUGGING
4012                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
4013                         OP(nxt + 1) = OPTIMIZED; /* was count. */
4014                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
4015                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
4016 #endif
4017 #if 0
4018                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
4019                             regnode *nnxt = regnext(nxt1);
4020                             if (nnxt == nxt) {
4021                                 if (reg_off_by_arg[OP(nxt1)])
4022                                     ARG_SET(nxt1, nxt2 - nxt1);
4023                                 else if (nxt2 - nxt1 < U16_MAX)
4024                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
4025                                 else
4026                                     OP(nxt) = NOTHING;  /* Cannot beautify */
4027                             }
4028                             nxt1 = nnxt;
4029                         }
4030 #endif
4031                         /* Optimize again: */
4032                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
4033                                     NULL, stopparen, recursed, NULL, 0,depth+1);
4034                     }
4035                     else
4036                         oscan->flags = 0;
4037                 }
4038                 else if ((OP(oscan) == CURLYX)
4039                          && (flags & SCF_WHILEM_VISITED_POS)
4040                          /* See the comment on a similar expression above.
4041                             However, this time it's not a subexpression
4042                             we care about, but the expression itself. */
4043                          && (maxcount == REG_INFTY)
4044                          && data && ++data->whilem_c < 16) {
4045                     /* This stays as CURLYX, we can put the count/of pair. */
4046                     /* Find WHILEM (as in regexec.c) */
4047                     regnode *nxt = oscan + NEXT_OFF(oscan);
4048
4049                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
4050                         nxt += ARG(nxt);
4051                     PREVOPER(nxt)->flags = (U8)(data->whilem_c
4052                         | (RExC_whilem_seen << 4)); /* On WHILEM */
4053                 }
4054                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
4055                     pars++;
4056                 if (flags & SCF_DO_SUBSTR) {
4057                     SV *last_str = NULL;
4058                     int counted = mincount != 0;
4059
4060                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
4061 #if defined(SPARC64_GCC_WORKAROUND)
4062                         I32 b = 0;
4063                         STRLEN l = 0;
4064                         const char *s = NULL;
4065                         I32 old = 0;
4066
4067                         if (pos_before >= data->last_start_min)
4068                             b = pos_before;
4069                         else
4070                             b = data->last_start_min;
4071
4072                         l = 0;
4073                         s = SvPV_const(data->last_found, l);
4074                         old = b - data->last_start_min;
4075
4076 #else
4077                         I32 b = pos_before >= data->last_start_min
4078                             ? pos_before : data->last_start_min;
4079                         STRLEN l;
4080                         const char * const s = SvPV_const(data->last_found, l);
4081                         I32 old = b - data->last_start_min;
4082 #endif
4083
4084                         if (UTF)
4085                             old = utf8_hop((U8*)s, old) - (U8*)s;
4086                         l -= old;
4087                         /* Get the added string: */
4088                         last_str = newSVpvn_utf8(s  + old, l, UTF);
4089                         if (deltanext == 0 && pos_before == b) {
4090                             /* What was added is a constant string */
4091                             if (mincount > 1) {
4092                                 SvGROW(last_str, (mincount * l) + 1);
4093                                 repeatcpy(SvPVX(last_str) + l,
4094                                           SvPVX_const(last_str), l, mincount - 1);
4095                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
4096                                 /* Add additional parts. */
4097                                 SvCUR_set(data->last_found,
4098                                           SvCUR(data->last_found) - l);
4099                                 sv_catsv(data->last_found, last_str);
4100                                 {
4101                                     SV * sv = data->last_found;
4102                                     MAGIC *mg =
4103                                         SvUTF8(sv) && SvMAGICAL(sv) ?
4104                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
4105                                     if (mg && mg->mg_len >= 0)
4106                                         mg->mg_len += CHR_SVLEN(last_str) - l;
4107                                 }
4108                                 data->last_end += l * (mincount - 1);
4109                             }
4110                         } else {
4111                             /* start offset must point into the last copy */
4112                             data->last_start_min += minnext * (mincount - 1);
4113                             data->last_start_max += is_inf ? I32_MAX
4114                                 : (maxcount - 1) * (minnext + data->pos_delta);
4115                         }
4116                     }
4117                     /* It is counted once already... */
4118                     data->pos_min += minnext * (mincount - counted);
4119 #if 0
4120 PerlIO_printf(Perl_debug_log, "counted=%d deltanext=%d I32_MAX=%d minnext=%d maxcount=%d mincount=%d\n",
4121     counted, deltanext, I32_MAX, minnext, maxcount, mincount);
4122 if (deltanext != I32_MAX)
4123 PerlIO_printf(Perl_debug_log, "LHS=%d RHS=%d\n", -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount, I32_MAX - data->pos_delta);
4124 #endif
4125                     if (deltanext == I32_MAX || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= I32_MAX - data->pos_delta)
4126                         data->pos_delta = I32_MAX;
4127                     else
4128                         data->pos_delta += - counted * deltanext +
4129                         (minnext + deltanext) * maxcount - minnext * mincount;
4130                     if (mincount != maxcount) {
4131                          /* Cannot extend fixed substrings found inside
4132                             the group.  */
4133                         SCAN_COMMIT(pRExC_state,data,minlenp);
4134                         if (mincount && last_str) {
4135                             SV * const sv = data->last_found;
4136                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
4137                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
4138
4139                             if (mg)
4140                                 mg->mg_len = -1;
4141                             sv_setsv(sv, last_str);
4142                             data->last_end = data->pos_min;
4143                             data->last_start_min =
4144                                 data->pos_min - CHR_SVLEN(last_str);
4145                             data->last_start_max = is_inf
4146                                 ? I32_MAX
4147                                 : data->pos_min + data->pos_delta
4148                                 - CHR_SVLEN(last_str);
4149                         }
4150                         data->longest = &(data->longest_float);
4151                     }
4152                     SvREFCNT_dec(last_str);
4153                 }
4154                 if (data && (fl & SF_HAS_EVAL))
4155                     data->flags |= SF_HAS_EVAL;
4156               optimize_curly_tail:
4157                 if (OP(oscan) != CURLYX) {
4158                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
4159                            && NEXT_OFF(next))
4160                         NEXT_OFF(oscan) += NEXT_OFF(next);
4161                 }
4162                 continue;
4163             default:                    /* REF, and CLUMP only? */
4164                 if (flags & SCF_DO_SUBSTR) {
4165                     SCAN_COMMIT(pRExC_state,data,minlenp);      /* Cannot expect anything... */
4166                     data->longest = &(data->longest_float);
4167                 }
4168                 is_inf = is_inf_internal = 1;
4169                 if (flags & SCF_DO_STCLASS_OR)
4170                     cl_anything(pRExC_state, data->start_class);
4171                 flags &= ~SCF_DO_STCLASS;
4172                 break;
4173             }
4174         }
4175         else if (OP(scan) == LNBREAK) {
4176             if (flags & SCF_DO_STCLASS) {
4177                 int value = 0;
4178                 CLEAR_SSC_EOS(data->start_class); /* No match on empty */
4179                 if (flags & SCF_DO_STCLASS_AND) {
4180                     for (value = 0; value < 256; value++)
4181                         if (!is_VERTWS_cp(value))
4182                             ANYOF_BITMAP_CLEAR(data->start_class, value);
4183                 }
4184                 else {
4185                     for (value = 0; value < 256; value++)
4186                         if (is_VERTWS_cp(value))
4187                             ANYOF_BITMAP_SET(data->start_class, value);
4188                 }
4189                 if (flags & SCF_DO_STCLASS_OR)
4190                     cl_and(data->start_class, and_withp);
4191                 flags &= ~SCF_DO_STCLASS;
4192             }
4193             min++;
4194             delta++;    /* Because of the 2 char string cr-lf */
4195             if (flags & SCF_DO_SUBSTR) {
4196                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4197                 data->pos_min += 1;
4198                 data->pos_delta += 1;
4199                 data->longest = &(data->longest_float);
4200             }
4201         }
4202         else if (REGNODE_SIMPLE(OP(scan))) {
4203             int value = 0;
4204
4205             if (flags & SCF_DO_SUBSTR) {
4206                 SCAN_COMMIT(pRExC_state,data,minlenp);
4207                 data->pos_min++;
4208             }
4209             min++;
4210             if (flags & SCF_DO_STCLASS) {
4211                 int loop_max = 256;
4212                 CLEAR_SSC_EOS(data->start_class); /* No match on empty */
4213
4214                 /* Some of the logic below assumes that switching
4215                    locale on will only add false positives. */
4216                 switch (PL_regkind[OP(scan)]) {
4217                     U8 classnum;
4218
4219                 case SANY:
4220                 default:
4221 #ifdef DEBUGGING
4222                    Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan));
4223 #endif
4224                  do_default:
4225                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4226                         cl_anything(pRExC_state, data->start_class);
4227                     break;
4228                 case REG_ANY:
4229                     if (OP(scan) == SANY)
4230                         goto do_default;
4231                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
4232                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
4233                                 || ANYOF_CLASS_TEST_ANY_SET(data->start_class));
4234                         cl_anything(pRExC_state, data->start_class);
4235                     }
4236                     if (flags & SCF_DO_STCLASS_AND || !value)
4237                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
4238                     break;
4239                 case ANYOF:
4240                     if (flags & SCF_DO_STCLASS_AND)
4241                         cl_and(data->start_class,
4242                                (struct regnode_charclass_class*)scan);
4243                     else
4244                         cl_or(pRExC_state, data->start_class,
4245                               (struct regnode_charclass_class*)scan);
4246                     break;
4247                 case POSIXA:
4248                     loop_max = 128;
4249                     /* FALL THROUGH */
4250                 case POSIXL:
4251                 case POSIXD:
4252                 case POSIXU:
4253                     classnum = FLAGS(scan);
4254                     if (flags & SCF_DO_STCLASS_AND) {
4255                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4256                             ANYOF_CLASS_CLEAR(data->start_class, classnum_to_namedclass(classnum) + 1);
4257                             for (value = 0; value < loop_max; value++) {
4258                                 if (! _generic_isCC(UNI_TO_NATIVE(value), classnum)) {
4259                                     ANYOF_BITMAP_CLEAR(data->start_class, UNI_TO_NATIVE(value));
4260                                 }
4261                             }
4262                         }
4263                     }
4264                     else {
4265                         if (data->start_class->flags & ANYOF_LOCALE) {
4266                             ANYOF_CLASS_SET(data->start_class, classnum_to_namedclass(classnum));
4267                         }
4268                         else {
4269
4270                         /* Even if under locale, set the bits for non-locale
4271                          * in case it isn't a true locale-node.  This will
4272                          * create false positives if it truly is locale */
4273                         for (value = 0; value < loop_max; value++) {
4274                             if (_generic_isCC(UNI_TO_NATIVE(value), classnum)) {
4275                                 ANYOF_BITMAP_SET(data->start_class, UNI_TO_NATIVE(value));
4276                             }
4277                         }
4278                         }
4279                     }
4280                     break;
4281                 case NPOSIXA:
4282                     loop_max = 128;
4283                     /* FALL THROUGH */
4284                 case NPOSIXL:
4285                 case NPOSIXU:
4286                 case NPOSIXD:
4287                     classnum = FLAGS(scan);
4288                     if (flags & SCF_DO_STCLASS_AND) {
4289                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4290                             ANYOF_CLASS_CLEAR(data->start_class, classnum_to_namedclass(classnum));
4291                             for (value = 0; value < loop_max; value++) {
4292                                 if (_generic_isCC(UNI_TO_NATIVE(value), classnum)) {
4293                                     ANYOF_BITMAP_CLEAR(data->start_class, UNI_TO_NATIVE(value));
4294                                 }
4295                             }
4296                         }
4297                     }
4298                     else {
4299                         if (data->start_class->flags & ANYOF_LOCALE) {
4300                             ANYOF_CLASS_SET(data->start_class, classnum_to_namedclass(classnum) + 1);
4301                         }
4302                         else {
4303
4304                         /* Even if under locale, set the bits for non-locale in
4305                          * case it isn't a true locale-node.  This will create
4306                          * false positives if it truly is locale */
4307                         for (value = 0; value < loop_max; value++) {
4308                             if (! _generic_isCC(UNI_TO_NATIVE(value), classnum)) {
4309                                 ANYOF_BITMAP_SET(data->start_class, UNI_TO_NATIVE(value));
4310                             }
4311                         }
4312                         if (PL_regkind[OP(scan)] == NPOSIXD) {
4313                             data->start_class->flags |= ANYOF_NON_UTF8_LATIN1_ALL;
4314                         }
4315                         }
4316                     }
4317                     break;
4318                 }
4319                 if (flags & SCF_DO_STCLASS_OR)
4320                     cl_and(data->start_class, and_withp);
4321                 flags &= ~SCF_DO_STCLASS;
4322             }
4323         }
4324         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
4325             data->flags |= (OP(scan) == MEOL
4326                             ? SF_BEFORE_MEOL
4327                             : SF_BEFORE_SEOL);
4328             SCAN_COMMIT(pRExC_state, data, minlenp);
4329
4330         }
4331         else if (  PL_regkind[OP(scan)] == BRANCHJ
4332                  /* Lookbehind, or need to calculate parens/evals/stclass: */
4333                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
4334                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
4335             if ( OP(scan) == UNLESSM &&
4336                  scan->flags == 0 &&
4337                  OP(NEXTOPER(NEXTOPER(scan))) == NOTHING &&
4338                  OP(regnext(NEXTOPER(NEXTOPER(scan)))) == SUCCEED
4339             ) {
4340                 regnode *opt;
4341                 regnode *upto= regnext(scan);
4342                 DEBUG_PARSE_r({
4343                     SV * const mysv_val=sv_newmortal();
4344                     DEBUG_STUDYDATA("OPFAIL",data,depth);
4345
4346                     /*DEBUG_PARSE_MSG("opfail");*/
4347                     regprop(RExC_rx, mysv_val, upto);
4348                     PerlIO_printf(Perl_debug_log, "~ replace with OPFAIL pointed at %s (%"IVdf") offset %"IVdf"\n",
4349                                   SvPV_nolen_const(mysv_val),
4350                                   (IV)REG_NODE_NUM(upto),
4351                                   (IV)(upto - scan)
4352                     );
4353                 });
4354                 OP(scan) = OPFAIL;
4355                 NEXT_OFF(scan) = upto - scan;
4356                 for (opt= scan + 1; opt < upto ; opt++)
4357                     OP(opt) = OPTIMIZED;
4358                 scan= upto;
4359                 continue;
4360             }
4361             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY 
4362                 || OP(scan) == UNLESSM )
4363             {
4364                 /* Negative Lookahead/lookbehind
4365                    In this case we can't do fixed string optimisation.
4366                 */
4367
4368                 I32 deltanext, minnext, fake = 0;
4369                 regnode *nscan;
4370                 struct regnode_charclass_class intrnl;
4371                 int f = 0;
4372
4373                 data_fake.flags = 0;
4374                 if (data) {
4375                     data_fake.whilem_c = data->whilem_c;
4376                     data_fake.last_closep = data->last_closep;
4377                 }
4378                 else
4379                     data_fake.last_closep = &fake;
4380                 data_fake.pos_delta = delta;
4381                 if ( flags & SCF_DO_STCLASS && !scan->flags
4382                      && OP(scan) == IFMATCH ) { /* Lookahead */
4383                     cl_init(pRExC_state, &intrnl);
4384                     data_fake.start_class = &intrnl;
4385                     f |= SCF_DO_STCLASS_AND;
4386                 }
4387                 if (flags & SCF_WHILEM_VISITED_POS)
4388                     f |= SCF_WHILEM_VISITED_POS;
4389                 next = regnext(scan);
4390                 nscan = NEXTOPER(NEXTOPER(scan));
4391                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, 
4392                     last, &data_fake, stopparen, recursed, NULL, f, depth+1);
4393                 if (scan->flags) {
4394                     if (deltanext) {
4395                         FAIL("Variable length lookbehind not implemented");
4396                     }
4397                     else if (minnext > (I32)U8_MAX) {
4398                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
4399                     }
4400                     scan->flags = (U8)minnext;
4401                 }
4402                 if (data) {
4403                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4404                         pars++;
4405                     if (data_fake.flags & SF_HAS_EVAL)
4406                         data->flags |= SF_HAS_EVAL;
4407                     data->whilem_c = data_fake.whilem_c;
4408                 }
4409                 if (f & SCF_DO_STCLASS_AND) {
4410                     if (flags & SCF_DO_STCLASS_OR) {
4411                         /* OR before, AND after: ideally we would recurse with
4412                          * data_fake to get the AND applied by study of the
4413                          * remainder of the pattern, and then derecurse;
4414                          * *** HACK *** for now just treat as "no information".
4415                          * See [perl #56690].
4416                          */
4417                         cl_init(pRExC_state, data->start_class);
4418                     }  else {
4419                         /* AND before and after: combine and continue */
4420                         const int was = TEST_SSC_EOS(data->start_class);
4421
4422                         cl_and(data->start_class, &intrnl);
4423                         if (was)
4424                             SET_SSC_EOS(data->start_class);
4425                     }
4426                 }
4427             }
4428 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
4429             else {
4430                 /* Positive Lookahead/lookbehind
4431                    In this case we can do fixed string optimisation,
4432                    but we must be careful about it. Note in the case of
4433                    lookbehind the positions will be offset by the minimum
4434                    length of the pattern, something we won't know about
4435                    until after the recurse.
4436                 */
4437                 I32 deltanext, fake = 0;
4438                 regnode *nscan;
4439                 struct regnode_charclass_class intrnl;
4440                 int f = 0;
4441                 /* We use SAVEFREEPV so that when the full compile 
4442                     is finished perl will clean up the allocated 
4443                     minlens when it's all done. This way we don't
4444                     have to worry about freeing them when we know
4445                     they wont be used, which would be a pain.
4446                  */
4447                 I32 *minnextp;
4448                 Newx( minnextp, 1, I32 );
4449                 SAVEFREEPV(minnextp);
4450
4451                 if (data) {
4452                     StructCopy(data, &data_fake, scan_data_t);
4453                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
4454                         f |= SCF_DO_SUBSTR;
4455                         if (scan->flags) 
4456                             SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
4457                         data_fake.last_found=newSVsv(data->last_found);
4458                     }
4459                 }
4460                 else
4461                     data_fake.last_closep = &fake;
4462                 data_fake.flags = 0;
4463                 data_fake.pos_delta = delta;
4464                 if (is_inf)
4465                     data_fake.flags |= SF_IS_INF;
4466                 if ( flags & SCF_DO_STCLASS && !scan->flags
4467                      && OP(scan) == IFMATCH ) { /* Lookahead */
4468                     cl_init(pRExC_state, &intrnl);
4469                     data_fake.start_class = &intrnl;
4470                     f |= SCF_DO_STCLASS_AND;
4471                 }
4472                 if (flags & SCF_WHILEM_VISITED_POS)
4473                     f |= SCF_WHILEM_VISITED_POS;
4474                 next = regnext(scan);
4475                 nscan = NEXTOPER(NEXTOPER(scan));
4476
4477                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, 
4478                     last, &data_fake, stopparen, recursed, NULL, f,depth+1);
4479                 if (scan->flags) {
4480                     if (deltanext) {
4481                         FAIL("Variable length lookbehind not implemented");
4482                     }
4483                     else if (*minnextp > (I32)U8_MAX) {
4484                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
4485                     }
4486                     scan->flags = (U8)*minnextp;
4487                 }
4488
4489                 *minnextp += min;
4490
4491                 if (f & SCF_DO_STCLASS_AND) {
4492                     const int was = TEST_SSC_EOS(data.start_class);
4493
4494                     cl_and(data->start_class, &intrnl);
4495                     if (was)
4496                         SET_SSC_EOS(data->start_class);
4497                 }
4498                 if (data) {
4499                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4500                         pars++;
4501                     if (data_fake.flags & SF_HAS_EVAL)
4502                         data->flags |= SF_HAS_EVAL;
4503                     data->whilem_c = data_fake.whilem_c;
4504                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
4505                         if (RExC_rx->minlen<*minnextp)
4506                             RExC_rx->minlen=*minnextp;
4507                         SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
4508                         SvREFCNT_dec_NN(data_fake.last_found);
4509                         
4510                         if ( data_fake.minlen_fixed != minlenp ) 
4511                         {
4512                             data->offset_fixed= data_fake.offset_fixed;
4513                             data->minlen_fixed= data_fake.minlen_fixed;
4514                             data->lookbehind_fixed+= scan->flags;
4515                         }
4516                         if ( data_fake.minlen_float != minlenp )
4517                         {
4518                             data->minlen_float= data_fake.minlen_float;
4519                             data->offset_float_min=data_fake.offset_float_min;
4520                             data->offset_float_max=data_fake.offset_float_max;
4521                             data->lookbehind_float+= scan->flags;
4522                         }
4523                     }
4524                 }
4525             }
4526 #endif
4527         }
4528         else if (OP(scan) == OPEN) {
4529             if (stopparen != (I32)ARG(scan))
4530                 pars++;
4531         }
4532         else if (OP(scan) == CLOSE) {
4533             if (stopparen == (I32)ARG(scan)) {
4534                 break;
4535             }
4536             if ((I32)ARG(scan) == is_par) {
4537                 next = regnext(scan);
4538
4539                 if ( next && (OP(next) != WHILEM) && next < last)
4540                     is_par = 0;         /* Disable optimization */
4541             }
4542             if (data)
4543                 *(data->last_closep) = ARG(scan);
4544         }
4545         else if (OP(scan) == EVAL) {
4546                 if (data)
4547                     data->flags |= SF_HAS_EVAL;
4548         }
4549         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
4550             if (flags & SCF_DO_SUBSTR) {
4551                 SCAN_COMMIT(pRExC_state,data,minlenp);
4552                 flags &= ~SCF_DO_SUBSTR;
4553             }
4554             if (data && OP(scan)==ACCEPT) {
4555                 data->flags |= SCF_SEEN_ACCEPT;
4556                 if (stopmin > min)
4557                     stopmin = min;
4558             }
4559         }
4560         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
4561         {
4562                 if (flags & SCF_DO_SUBSTR) {
4563                     SCAN_COMMIT(pRExC_state,data,minlenp);
4564                     data->longest = &(data->longest_float);
4565                 }
4566                 is_inf = is_inf_internal = 1;
4567                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4568                     cl_anything(pRExC_state, data->start_class);
4569                 flags &= ~SCF_DO_STCLASS;
4570         }
4571         else if (OP(scan) == GPOS) {
4572             if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
4573                 !(delta || is_inf || (data && data->pos_delta))) 
4574             {
4575                 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
4576                     RExC_rx->extflags |= RXf_ANCH_GPOS;
4577                 if (RExC_rx->gofs < (U32)min)
4578                     RExC_rx->gofs = min;
4579             } else {
4580                 RExC_rx->extflags |= RXf_GPOS_FLOAT;
4581                 RExC_rx->gofs = 0;
4582             }       
4583         }
4584 #ifdef TRIE_STUDY_OPT
4585 #ifdef FULL_TRIE_STUDY
4586         else if (PL_regkind[OP(scan)] == TRIE) {
4587             /* NOTE - There is similar code to this block above for handling
4588                BRANCH nodes on the initial study.  If you change stuff here
4589                check there too. */
4590             regnode *trie_node= scan;
4591             regnode *tail= regnext(scan);
4592             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4593             I32 max1 = 0, min1 = I32_MAX;
4594             struct regnode_charclass_class accum;
4595
4596             if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
4597                 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
4598             if (flags & SCF_DO_STCLASS)
4599                 cl_init_zero(pRExC_state, &accum);
4600                 
4601             if (!trie->jump) {
4602                 min1= trie->minlen;
4603                 max1= trie->maxlen;
4604             } else {
4605                 const regnode *nextbranch= NULL;
4606                 U32 word;
4607                 
4608                 for ( word=1 ; word <= trie->wordcount ; word++) 
4609                 {
4610                     I32 deltanext=0, minnext=0, f = 0, fake;
4611                     struct regnode_charclass_class this_class;
4612                     
4613                     data_fake.flags = 0;
4614                     if (data) {
4615                         data_fake.whilem_c = data->whilem_c;
4616                         data_fake.last_closep = data->last_closep;
4617                     }
4618                     else
4619                         data_fake.last_closep = &fake;
4620                     data_fake.pos_delta = delta;
4621                     if (flags & SCF_DO_STCLASS) {
4622                         cl_init(pRExC_state, &this_class);
4623                         data_fake.start_class = &this_class;
4624                         f = SCF_DO_STCLASS_AND;
4625                     }
4626                     if (flags & SCF_WHILEM_VISITED_POS)
4627                         f |= SCF_WHILEM_VISITED_POS;
4628     
4629                     if (trie->jump[word]) {
4630                         if (!nextbranch)
4631                             nextbranch = trie_node + trie->jump[0];
4632                         scan= trie_node + trie->jump[word];
4633                         /* We go from the jump point to the branch that follows
4634                            it. Note this means we need the vestigal unused branches
4635                            even though they arent otherwise used.
4636                          */
4637                         minnext = study_chunk(pRExC_state, &scan, minlenp, 
4638                             &deltanext, (regnode *)nextbranch, &data_fake, 
4639                             stopparen, recursed, NULL, f,depth+1);
4640                     }
4641                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
4642                         nextbranch= regnext((regnode*)nextbranch);
4643                     
4644                     if (min1 > (I32)(minnext + trie->minlen))
4645                         min1 = minnext + trie->minlen;
4646                     if (deltanext == I32_MAX) {
4647                         is_inf = is_inf_internal = 1;
4648                         max1 = I32_MAX;
4649                     } else if (max1 < (I32)(minnext + deltanext + trie->maxlen))
4650                         max1 = minnext + deltanext + trie->maxlen;
4651                     
4652                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4653                         pars++;
4654                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4655                         if ( stopmin > min + min1) 
4656                             stopmin = min + min1;
4657                         flags &= ~SCF_DO_SUBSTR;
4658                         if (data)
4659                             data->flags |= SCF_SEEN_ACCEPT;
4660                     }
4661                     if (data) {
4662                         if (data_fake.flags & SF_HAS_EVAL)
4663                             data->flags |= SF_HAS_EVAL;
4664                         data->whilem_c = data_fake.whilem_c;
4665                     }
4666                     if (flags & SCF_DO_STCLASS)
4667                         cl_or(pRExC_state, &accum, &this_class);
4668                 }
4669             }
4670             if (flags & SCF_DO_SUBSTR) {
4671                 data->pos_min += min1;
4672                 data->pos_delta += max1 - min1;
4673                 if (max1 != min1 || is_inf)
4674                     data->longest = &(data->longest_float);
4675             }
4676             min += min1;
4677             delta += max1 - min1;
4678             if (flags & SCF_DO_STCLASS_OR) {
4679                 cl_or(pRExC_state, data->start_class, &accum);
4680                 if (min1) {
4681                     cl_and(data->start_class, and_withp);
4682                     flags &= ~SCF_DO_STCLASS;
4683                 }
4684             }
4685             else if (flags & SCF_DO_STCLASS_AND) {
4686                 if (min1) {
4687                     cl_and(data->start_class, &accum);
4688                     flags &= ~SCF_DO_STCLASS;
4689                 }
4690                 else {
4691                     /* Switch to OR mode: cache the old value of
4692                      * data->start_class */
4693                     INIT_AND_WITHP;
4694                     StructCopy(data->start_class, and_withp,
4695                                struct regnode_charclass_class);
4696                     flags &= ~SCF_DO_STCLASS_AND;
4697                     StructCopy(&accum, data->start_class,
4698                                struct regnode_charclass_class);
4699                     flags |= SCF_DO_STCLASS_OR;
4700                     SET_SSC_EOS(data->start_class);
4701                 }
4702             }
4703             scan= tail;
4704             continue;
4705         }
4706 #else
4707         else if (PL_regkind[OP(scan)] == TRIE) {
4708             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4709             U8*bang=NULL;
4710             
4711             min += trie->minlen;
4712             delta += (trie->maxlen - trie->minlen);
4713             flags &= ~SCF_DO_STCLASS; /* xxx */
4714             if (flags & SCF_DO_SUBSTR) {
4715                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4716                 data->pos_min += trie->minlen;
4717                 data->pos_delta += (trie->maxlen - trie->minlen);
4718                 if (trie->maxlen != trie->minlen)
4719                     data->longest = &(data->longest_float);
4720             }
4721             if (trie->jump) /* no more substrings -- for now /grr*/
4722                 flags &= ~SCF_DO_SUBSTR; 
4723         }
4724 #endif /* old or new */
4725 #endif /* TRIE_STUDY_OPT */
4726
4727         /* Else: zero-length, ignore. */
4728         scan = regnext(scan);
4729     }
4730     if (frame) {
4731         last = frame->last;
4732         scan = frame->next;
4733         stopparen = frame->stop;
4734         frame = frame->prev;
4735         goto fake_study_recurse;
4736     }
4737
4738   finish:
4739     assert(!frame);
4740     DEBUG_STUDYDATA("pre-fin:",data,depth);
4741
4742     *scanp = scan;
4743     *deltap = is_inf_internal ? I32_MAX : delta;
4744     if (flags & SCF_DO_SUBSTR && is_inf)
4745         data->pos_delta = I32_MAX - data->pos_min;
4746     if (is_par > (I32)U8_MAX)
4747         is_par = 0;
4748     if (is_par && pars==1 && data) {
4749         data->flags |= SF_IN_PAR;
4750         data->flags &= ~SF_HAS_PAR;
4751     }
4752     else if (pars && data) {
4753         data->flags |= SF_HAS_PAR;
4754         data->flags &= ~SF_IN_PAR;
4755     }
4756     if (flags & SCF_DO_STCLASS_OR)
4757         cl_and(data->start_class, and_withp);
4758     if (flags & SCF_TRIE_RESTUDY)
4759         data->flags |=  SCF_TRIE_RESTUDY;
4760     
4761     DEBUG_STUDYDATA("post-fin:",data,depth);
4762     
4763     return min < stopmin ? min : stopmin;
4764 }
4765
4766 STATIC U32
4767 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
4768 {
4769     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
4770
4771     PERL_ARGS_ASSERT_ADD_DATA;
4772
4773     Renewc(RExC_rxi->data,
4774            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
4775            char, struct reg_data);
4776     if(count)
4777         Renew(RExC_rxi->data->what, count + n, U8);
4778     else
4779         Newx(RExC_rxi->data->what, n, U8);
4780     RExC_rxi->data->count = count + n;
4781     Copy(s, RExC_rxi->data->what + count, n, U8);
4782     return count;
4783 }
4784
4785 /*XXX: todo make this not included in a non debugging perl */
4786 #ifndef PERL_IN_XSUB_RE
4787 void
4788 Perl_reginitcolors(pTHX)
4789 {
4790     dVAR;
4791     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
4792     if (s) {
4793         char *t = savepv(s);
4794         int i = 0;
4795         PL_colors[0] = t;
4796         while (++i < 6) {
4797             t = strchr(t, '\t');
4798             if (t) {
4799                 *t = '\0';
4800                 PL_colors[i] = ++t;
4801             }
4802             else
4803                 PL_colors[i] = t = (char *)"";
4804         }
4805     } else {
4806         int i = 0;
4807         while (i < 6)
4808             PL_colors[i++] = (char *)"";
4809     }
4810     PL_colorset = 1;
4811 }
4812 #endif
4813
4814
4815 #ifdef TRIE_STUDY_OPT
4816 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething)            \
4817     STMT_START {                                            \
4818         if (                                                \
4819               (data.flags & SCF_TRIE_RESTUDY)               \
4820               && ! restudied++                              \
4821         ) {                                                 \
4822             dOsomething;                                    \
4823             goto reStudy;                                   \
4824         }                                                   \
4825     } STMT_END
4826 #else
4827 #define CHECK_RESTUDY_GOTO_butfirst
4828 #endif        
4829
4830 /*
4831  * pregcomp - compile a regular expression into internal code
4832  *
4833  * Decides which engine's compiler to call based on the hint currently in
4834  * scope
4835  */
4836
4837 #ifndef PERL_IN_XSUB_RE 
4838
4839 /* return the currently in-scope regex engine (or the default if none)  */
4840
4841 regexp_engine const *
4842 Perl_current_re_engine(pTHX)
4843 {
4844     dVAR;
4845
4846     if (IN_PERL_COMPILETIME) {
4847         HV * const table = GvHV(PL_hintgv);
4848         SV **ptr;
4849
4850         if (!table)
4851             return &PL_core_reg_engine;
4852         ptr = hv_fetchs(table, "regcomp", FALSE);
4853         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
4854             return &PL_core_reg_engine;
4855         return INT2PTR(regexp_engine*,SvIV(*ptr));
4856     }
4857     else {
4858         SV *ptr;
4859         if (!PL_curcop->cop_hints_hash)
4860             return &PL_core_reg_engine;
4861         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
4862         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
4863             return &PL_core_reg_engine;
4864         return INT2PTR(regexp_engine*,SvIV(ptr));
4865     }
4866 }
4867
4868
4869 REGEXP *
4870 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
4871 {
4872     dVAR;
4873     regexp_engine const *eng = current_re_engine();
4874     GET_RE_DEBUG_FLAGS_DECL;
4875
4876     PERL_ARGS_ASSERT_PREGCOMP;
4877
4878     /* Dispatch a request to compile a regexp to correct regexp engine. */
4879     DEBUG_COMPILE_r({
4880         PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4881                         PTR2UV(eng));
4882     });
4883     return CALLREGCOMP_ENG(eng, pattern, flags);
4884 }
4885 #endif
4886
4887 /* public(ish) entry point for the perl core's own regex compiling code.
4888  * It's actually a wrapper for Perl_re_op_compile that only takes an SV
4889  * pattern rather than a list of OPs, and uses the internal engine rather
4890  * than the current one */
4891
4892 REGEXP *
4893 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
4894 {
4895     SV *pat = pattern; /* defeat constness! */
4896     PERL_ARGS_ASSERT_RE_COMPILE;
4897     return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
4898 #ifdef PERL_IN_XSUB_RE
4899                                 &my_reg_engine,
4900 #else
4901                                 &PL_core_reg_engine,
4902 #endif
4903                                 NULL, NULL, rx_flags, 0);
4904 }
4905
4906
4907 /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code
4908  * blocks, recalculate the indices. Update pat_p and plen_p in-place to
4909  * point to the realloced string and length.
4910  *
4911  * This is essentially a copy of Perl_bytes_to_utf8() with the code index
4912  * stuff added */
4913
4914 static void
4915 S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state,
4916                     char **pat_p, STRLEN *plen_p, int num_code_blocks)
4917 {
4918     U8 *const src = (U8*)*pat_p;
4919     U8 *dst;
4920     int n=0;
4921     STRLEN s = 0, d = 0;
4922     bool do_end = 0;
4923     GET_RE_DEBUG_FLAGS_DECL;
4924
4925     DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
4926         "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
4927
4928     Newx(dst, *plen_p * 2 + 1, U8);
4929
4930     while (s < *plen_p) {
4931         const UV uv = NATIVE_TO_ASCII(src[s]);
4932         if (UNI_IS_INVARIANT(uv))
4933             dst[d]   = (U8)UTF_TO_NATIVE(uv);
4934         else {
4935             dst[d++] = (U8)UTF8_EIGHT_BIT_HI(uv);
4936             dst[d]   = (U8)UTF8_EIGHT_BIT_LO(uv);
4937         }
4938         if (n < num_code_blocks) {
4939             if (!do_end && pRExC_state->code_blocks[n].start == s) {
4940                 pRExC_state->code_blocks[n].start = d;
4941                 assert(dst[d] == '(');
4942                 do_end = 1;
4943             }
4944             else if (do_end && pRExC_state->code_blocks[n].end == s) {
4945                 pRExC_state->code_blocks[n].end = d;
4946                 assert(dst[d] == ')');
4947                 do_end = 0;
4948                 n++;
4949             }
4950         }
4951         s++;
4952         d++;
4953     }
4954     dst[d] = '\0';
4955     *plen_p = d;
4956     *pat_p = (char*) dst;
4957     SAVEFREEPV(*pat_p);
4958     RExC_orig_utf8 = RExC_utf8 = 1;
4959 }
4960
4961
4962
4963 /* S_concat_pat(): concatenate a list of args to the pattern string pat,
4964  * while recording any code block indices, and handling overloading,
4965  * nested qr// objects etc.  If pat is null, it will allocate a new
4966  * string, or just return the first arg, if there's only one.
4967  *
4968  * Returns the malloced/updated pat.
4969  * patternp and pat_count is the array of SVs to be concatted;
4970  * oplist is the optional list of ops that generated the SVs;
4971  * recompile_p is a pointer to a boolean that will be set if
4972  *   the regex will need to be recompiled.
4973  * delim, if non-null is an SV that will be inserted between each element
4974  */
4975
4976 static SV*
4977 S_concat_pat(pTHX_ RExC_state_t * const pRExC_state,
4978                 SV *pat, SV ** const patternp, int pat_count,
4979                 OP *oplist, bool *recompile_p, SV *delim)
4980 {
4981     SV **svp;
4982     int n = 0;
4983     bool use_delim = FALSE;
4984     bool alloced = FALSE;
4985
4986     /* if we know we have at least two args, create an empty string,
4987      * then concatenate args to that. For no args, return an empty string */
4988     if (!pat && pat_count != 1) {
4989         pat = newSVpvn("", 0);
4990         SAVEFREESV(pat);
4991         alloced = TRUE;
4992     }
4993
4994     for (svp = patternp; svp < patternp + pat_count; svp++) {
4995         SV *sv;
4996         SV *rx  = NULL;
4997         STRLEN orig_patlen = 0;
4998         bool code = 0;
4999         SV *msv = use_delim ? delim : *svp;
5000
5001         /* if we've got a delimiter, we go round the loop twice for each
5002          * svp slot (except the last), using the delimiter the second
5003          * time round */
5004         if (use_delim) {
5005             svp--;
5006             use_delim = FALSE;
5007         }
5008         else if (delim)
5009             use_delim = TRUE;
5010
5011         if (SvTYPE(msv) == SVt_PVAV) {
5012             /* we've encountered an interpolated array within
5013              * the pattern, e.g. /...@a..../. Expand the list of elements,
5014              * then recursively append elements.
5015              * The code in this block is based on S_pushav() */
5016
5017             AV *const av = (AV*)msv;
5018             const I32 maxarg = AvFILL(av) + 1;
5019             SV **array;
5020
5021             if (oplist) {
5022                 assert(oplist->op_type == OP_PADAV
5023                     || oplist->op_type == OP_RV2AV); 
5024                 oplist = oplist->op_sibling;;
5025             }
5026
5027             if (SvRMAGICAL(av)) {
5028                 U32 i;
5029
5030                 Newx(array, maxarg, SV*);
5031                 SAVEFREEPV(array);
5032                 for (i=0; i < (U32)maxarg; i++) {
5033                     SV ** const svp = av_fetch(av, i, FALSE);
5034                     array[i] = svp ? *svp : &PL_sv_undef;
5035                 }
5036             }
5037             else
5038                 array = AvARRAY(av);
5039
5040             pat = S_concat_pat(aTHX_ pRExC_state, pat,
5041                                 array, maxarg, NULL, recompile_p,
5042                                 /* $" */
5043                                 GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV))));
5044
5045             continue;
5046         }
5047
5048
5049         /* we make the assumption here that each op in the list of
5050          * op_siblings maps to one SV pushed onto the stack,
5051          * except for code blocks, with have both an OP_NULL and
5052          * and OP_CONST.
5053          * This allows us to match up the list of SVs against the
5054          * list of OPs to find the next code block.
5055          *
5056          * Note that       PUSHMARK PADSV PADSV ..
5057          * is optimised to
5058          *                 PADRANGE PADSV  PADSV  ..
5059          * so the alignment still works. */
5060
5061         if (oplist) {
5062             if (oplist->op_type == OP_NULL
5063                 && (oplist->op_flags & OPf_SPECIAL))
5064             {
5065                 assert(n < pRExC_state->num_code_blocks);
5066                 pRExC_state->code_blocks[n].start = pat ? SvCUR(pat) : 0;
5067                 pRExC_state->code_blocks[n].block = oplist;
5068                 pRExC_state->code_blocks[n].src_regex = NULL;
5069                 n++;
5070                 code = 1;
5071                 oplist = oplist->op_sibling; /* skip CONST */
5072                 assert(oplist);
5073             }
5074             oplist = oplist->op_sibling;;
5075         }
5076
5077         /* apply magic and QR overloading to arg */
5078
5079         SvGETMAGIC(msv);
5080         if (SvROK(msv) && SvAMAGIC(msv)) {
5081             SV *sv = AMG_CALLunary(msv, regexp_amg);
5082             if (sv) {
5083                 if (SvROK(sv))
5084                     sv = SvRV(sv);
5085                 if (SvTYPE(sv) != SVt_REGEXP)
5086                     Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
5087                 msv = sv;
5088             }
5089         }
5090
5091         /* try concatenation overload ... */
5092         if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) &&
5093                 (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
5094         {
5095             sv_setsv(pat, sv);
5096             /* overloading involved: all bets are off over literal
5097              * code. Pretend we haven't seen it */
5098             pRExC_state->num_code_blocks -= n;
5099             n = 0;
5100         }
5101         else  {
5102             /* ... or failing that, try "" overload */
5103             while (SvAMAGIC(msv)
5104                     && (sv = AMG_CALLunary(msv, string_amg))
5105                     && sv != msv
5106                     &&  !(   SvROK(msv)
5107                           && SvROK(sv)
5108                           && SvRV(msv) == SvRV(sv))
5109             ) {
5110                 msv = sv;
5111                 SvGETMAGIC(msv);
5112             }
5113             if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
5114                 msv = SvRV(msv);
5115
5116             if (pat) {
5117                 /* this is a partially unrolled
5118                  *     sv_catsv_nomg(pat, msv);
5119                  * that allows us to adjust code block indices if
5120                  * needed */
5121                 STRLEN dlen;
5122                 char *dst = SvPV_force_nomg(pat, dlen);
5123                 orig_patlen = dlen;
5124                 if (SvUTF8(msv) && !SvUTF8(pat)) {
5125                     S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n);
5126                     sv_setpvn(pat, dst, dlen);
5127                     SvUTF8_on(pat);
5128                 }
5129                 sv_catsv_nomg(pat, msv);
5130                 rx = msv;
5131             }
5132             else
5133                 pat = msv;
5134
5135             if (code)
5136                 pRExC_state->code_blocks[n-1].end = SvCUR(pat)-1;
5137         }
5138
5139         /* extract any code blocks within any embedded qr//'s */
5140         if (rx && SvTYPE(rx) == SVt_REGEXP
5141             && RX_ENGINE((REGEXP*)rx)->op_comp)
5142         {
5143
5144             RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
5145             if (ri->num_code_blocks) {
5146                 int i;
5147                 /* the presence of an embedded qr// with code means
5148                  * we should always recompile: the text of the
5149                  * qr// may not have changed, but it may be a
5150                  * different closure than last time */
5151                 *recompile_p = 1;
5152                 Renew(pRExC_state->code_blocks,
5153                     pRExC_state->num_code_blocks + ri->num_code_blocks,
5154                     struct reg_code_block);
5155                 pRExC_state->num_code_blocks += ri->num_code_blocks;
5156
5157                 for (i=0; i < ri->num_code_blocks; i++) {
5158                     struct reg_code_block *src, *dst;
5159                     STRLEN offset =  orig_patlen
5160                         + ReANY((REGEXP *)rx)->pre_prefix;
5161                     assert(n < pRExC_state->num_code_blocks);
5162                     src = &ri->code_blocks[i];
5163                     dst = &pRExC_state->code_blocks[n];
5164                     dst->start      = src->start + offset;
5165                     dst->end        = src->end   + offset;
5166                     dst->block      = src->block;
5167                     dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
5168                                             src->src_regex
5169                                                 ? src->src_regex
5170                                                 : (REGEXP*)rx);
5171                     n++;
5172                 }
5173             }
5174         }
5175     }
5176     /* avoid calling magic multiple times on a single element e.g. =~ $qr */
5177     if (alloced)
5178         SvSETMAGIC(pat);
5179
5180     return pat;
5181 }
5182
5183
5184
5185 /* see if there are any run-time code blocks in the pattern.
5186  * False positives are allowed */
5187
5188 static bool
5189 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
5190                     char *pat, STRLEN plen)
5191 {
5192     int n = 0;
5193     STRLEN s;
5194
5195     for (s = 0; s < plen; s++) {
5196         if (n < pRExC_state->num_code_blocks
5197             && s == pRExC_state->code_blocks[n].start)
5198         {
5199             s = pRExC_state->code_blocks[n].end;
5200             n++;
5201             continue;
5202         }
5203         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
5204          * positives here */
5205         if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' &&
5206             (pat[s+2] == '{'
5207                 || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{'))
5208         )
5209             return 1;
5210     }
5211     return 0;
5212 }
5213
5214 /* Handle run-time code blocks. We will already have compiled any direct
5215  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
5216  * copy of it, but with any literal code blocks blanked out and
5217  * appropriate chars escaped; then feed it into
5218  *
5219  *    eval "qr'modified_pattern'"
5220  *
5221  * For example,
5222  *
5223  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
5224  *
5225  * becomes
5226  *
5227  *    qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
5228  *
5229  * After eval_sv()-ing that, grab any new code blocks from the returned qr
5230  * and merge them with any code blocks of the original regexp.
5231  *
5232  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
5233  * instead, just save the qr and return FALSE; this tells our caller that
5234  * the original pattern needs upgrading to utf8.
5235  */
5236
5237 static bool
5238 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
5239     char *pat, STRLEN plen)
5240 {
5241     SV *qr;
5242
5243     GET_RE_DEBUG_FLAGS_DECL;
5244
5245     if (pRExC_state->runtime_code_qr) {
5246         /* this is the second time we've been called; this should
5247          * only happen if the main pattern got upgraded to utf8
5248          * during compilation; re-use the qr we compiled first time
5249          * round (which should be utf8 too)
5250          */
5251         qr = pRExC_state->runtime_code_qr;
5252         pRExC_state->runtime_code_qr = NULL;
5253         assert(RExC_utf8 && SvUTF8(qr));
5254     }
5255     else {
5256         int n = 0;
5257         STRLEN s;
5258         char *p, *newpat;
5259         int newlen = plen + 6; /* allow for "qr''x\0" extra chars */
5260         SV *sv, *qr_ref;
5261         dSP;
5262
5263         /* determine how many extra chars we need for ' and \ escaping */
5264         for (s = 0; s < plen; s++) {
5265             if (pat[s] == '\'' || pat[s] == '\\')
5266                 newlen++;
5267         }
5268
5269         Newx(newpat, newlen, char);
5270         p = newpat;
5271         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
5272
5273         for (s = 0; s < plen; s++) {
5274             if (n < pRExC_state->num_code_blocks
5275                 && s == pRExC_state->code_blocks[n].start)
5276             {
5277                 /* blank out literal code block */
5278                 assert(pat[s] == '(');
5279                 while (s <= pRExC_state->code_blocks[n].end) {
5280                     *p++ = '_';
5281                     s++;
5282                 }
5283                 s--;
5284                 n++;
5285                 continue;
5286             }
5287             if (pat[s] == '\'' || pat[s] == '\\')
5288                 *p++ = '\\';
5289             *p++ = pat[s];
5290         }
5291         *p++ = '\'';
5292         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED)
5293             *p++ = 'x';
5294         *p++ = '\0';
5295         DEBUG_COMPILE_r({
5296             PerlIO_printf(Perl_debug_log,
5297                 "%sre-parsing pattern for runtime code:%s %s\n",
5298                 PL_colors[4],PL_colors[5],newpat);
5299         });
5300
5301         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
5302         Safefree(newpat);
5303
5304         ENTER;
5305         SAVETMPS;
5306         save_re_context();
5307         PUSHSTACKi(PERLSI_REQUIRE);
5308         /* G_RE_REPARSING causes the toker to collapse \\ into \ when
5309          * parsing qr''; normally only q'' does this. It also alters
5310          * hints handling */
5311         eval_sv(sv, G_SCALAR|G_RE_REPARSING);
5312         SvREFCNT_dec_NN(sv);
5313         SPAGAIN;
5314         qr_ref = POPs;
5315         PUTBACK;
5316         {
5317             SV * const errsv = ERRSV;
5318             if (SvTRUE_NN(errsv))
5319             {
5320                 Safefree(pRExC_state->code_blocks);
5321                 /* use croak_sv ? */
5322                 Perl_croak_nocontext("%s", SvPV_nolen_const(errsv));
5323             }
5324         }
5325         assert(SvROK(qr_ref));
5326         qr = SvRV(qr_ref);
5327         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
5328         /* the leaving below frees the tmp qr_ref.
5329          * Give qr a life of its own */
5330         SvREFCNT_inc(qr);
5331         POPSTACK;
5332         FREETMPS;
5333         LEAVE;
5334
5335     }
5336
5337     if (!RExC_utf8 && SvUTF8(qr)) {
5338         /* first time through; the pattern got upgraded; save the
5339          * qr for the next time through */
5340         assert(!pRExC_state->runtime_code_qr);
5341         pRExC_state->runtime_code_qr = qr;
5342         return 0;
5343     }
5344
5345
5346     /* extract any code blocks within the returned qr//  */
5347
5348
5349     /* merge the main (r1) and run-time (r2) code blocks into one */
5350     {
5351         RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
5352         struct reg_code_block *new_block, *dst;
5353         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
5354         int i1 = 0, i2 = 0;
5355
5356         if (!r2->num_code_blocks) /* we guessed wrong */
5357         {
5358             SvREFCNT_dec_NN(qr);
5359             return 1;
5360         }
5361
5362         Newx(new_block,
5363             r1->num_code_blocks + r2->num_code_blocks,
5364             struct reg_code_block);
5365         dst = new_block;
5366
5367         while (    i1 < r1->num_code_blocks
5368                 || i2 < r2->num_code_blocks)
5369         {
5370             struct reg_code_block *src;
5371             bool is_qr = 0;
5372
5373             if (i1 == r1->num_code_blocks) {
5374                 src = &r2->code_blocks[i2++];
5375                 is_qr = 1;
5376             }
5377             else if (i2 == r2->num_code_blocks)
5378                 src = &r1->code_blocks[i1++];
5379             else if (  r1->code_blocks[i1].start
5380                      < r2->code_blocks[i2].start)
5381             {
5382                 src = &r1->code_blocks[i1++];
5383                 assert(src->end < r2->code_blocks[i2].start);
5384             }
5385             else {
5386                 assert(  r1->code_blocks[i1].start
5387                        > r2->code_blocks[i2].start);
5388                 src = &r2->code_blocks[i2++];
5389                 is_qr = 1;
5390                 assert(src->end < r1->code_blocks[i1].start);
5391             }
5392
5393             assert(pat[src->start] == '(');
5394             assert(pat[src->end]   == ')');
5395             dst->start      = src->start;
5396             dst->end        = src->end;
5397             dst->block      = src->block;
5398             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
5399                                     : src->src_regex;
5400             dst++;
5401         }
5402         r1->num_code_blocks += r2->num_code_blocks;
5403         Safefree(r1->code_blocks);
5404         r1->code_blocks = new_block;
5405     }
5406
5407     SvREFCNT_dec_NN(qr);
5408     return 1;
5409 }
5410
5411
5412 STATIC bool
5413 S_setup_longest(pTHX_ RExC_state_t *pRExC_state, SV* sv_longest, SV** rx_utf8, SV** rx_substr, I32* rx_end_shift, I32 lookbehind, I32 offset, I32 *minlen, STRLEN longest_length, bool eol, bool meol)
5414 {
5415     /* This is the common code for setting up the floating and fixed length
5416      * string data extracted from Perl_re_op_compile() below.  Returns a boolean
5417      * as to whether succeeded or not */
5418
5419     I32 t,ml;
5420
5421     if (! (longest_length
5422            || (eol /* Can't have SEOL and MULTI */
5423                && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
5424           )
5425             /* See comments for join_exact for why REG_SEEN_EXACTF_SHARP_S */
5426         || (RExC_seen & REG_SEEN_EXACTF_SHARP_S))
5427     {
5428         return FALSE;
5429     }
5430
5431     /* copy the information about the longest from the reg_scan_data
5432         over to the program. */
5433     if (SvUTF8(sv_longest)) {
5434         *rx_utf8 = sv_longest;
5435         *rx_substr = NULL;
5436     } else {
5437         *rx_substr = sv_longest;
5438         *rx_utf8 = NULL;
5439     }
5440     /* end_shift is how many chars that must be matched that
5441         follow this item. We calculate it ahead of time as once the
5442         lookbehind offset is added in we lose the ability to correctly
5443         calculate it.*/
5444     ml = minlen ? *(minlen) : (I32)longest_length;
5445     *rx_end_shift = ml - offset
5446         - longest_length + (SvTAIL(sv_longest) != 0)
5447         + lookbehind;
5448
5449     t = (eol/* Can't have SEOL and MULTI */
5450          && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
5451     fbm_compile(sv_longest, t ? FBMcf_TAIL : 0);
5452
5453     return TRUE;
5454 }
5455
5456 /*
5457  * Perl_re_op_compile - the perl internal RE engine's function to compile a
5458  * regular expression into internal code.
5459  * The pattern may be passed either as:
5460  *    a list of SVs (patternp plus pat_count)
5461  *    a list of OPs (expr)
5462  * If both are passed, the SV list is used, but the OP list indicates
5463  * which SVs are actually pre-compiled code blocks
5464  *
5465  * The SVs in the list have magic and qr overloading applied to them (and
5466  * the list may be modified in-place with replacement SVs in the latter
5467  * case).
5468  *
5469  * If the pattern hasn't changed from old_re, then old_re will be
5470  * returned.
5471  *
5472  * eng is the current engine. If that engine has an op_comp method, then
5473  * handle directly (i.e. we assume that op_comp was us); otherwise, just
5474  * do the initial concatenation of arguments and pass on to the external
5475  * engine.
5476  *
5477  * If is_bare_re is not null, set it to a boolean indicating whether the
5478  * arg list reduced (after overloading) to a single bare regex which has
5479  * been returned (i.e. /$qr/).
5480  *
5481  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
5482  *
5483  * pm_flags contains the PMf_* flags, typically based on those from the
5484  * pm_flags field of the related PMOP. Currently we're only interested in
5485  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
5486  *
5487  * We can't allocate space until we know how big the compiled form will be,
5488  * but we can't compile it (and thus know how big it is) until we've got a
5489  * place to put the code.  So we cheat:  we compile it twice, once with code
5490  * generation turned off and size counting turned on, and once "for real".
5491  * This also means that we don't allocate space until we are sure that the
5492  * thing really will compile successfully, and we never have to move the
5493  * code and thus invalidate pointers into it.  (Note that it has to be in
5494  * one piece because free() must be able to free it all.) [NB: not true in perl]
5495  *
5496  * Beware that the optimization-preparation code in here knows about some
5497  * of the structure of the compiled regexp.  [I'll say.]
5498  */
5499
5500 REGEXP *
5501 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
5502                     OP *expr, const regexp_engine* eng, REGEXP *old_re,
5503                      bool *is_bare_re, U32 orig_rx_flags, U32 pm_flags)
5504 {
5505     dVAR;
5506     REGEXP *rx;
5507     struct regexp *r;
5508     regexp_internal *ri;
5509     STRLEN plen;
5510     char *exp;
5511     regnode *scan;
5512     I32 flags;
5513     I32 minlen = 0;
5514     U32 rx_flags;
5515     SV *pat;
5516     SV *code_blocksv = NULL;
5517     SV** new_patternp = patternp;
5518
5519     /* these are all flags - maybe they should be turned
5520      * into a single int with different bit masks */
5521     I32 sawlookahead = 0;
5522     I32 sawplus = 0;
5523     I32 sawopen = 0;
5524     I32 sawminmod = 0;
5525
5526     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
5527     bool recompile = 0;
5528     bool runtime_code = 0;
5529     scan_data_t data;
5530     RExC_state_t RExC_state;
5531     RExC_state_t * const pRExC_state = &RExC_state;
5532 #ifdef TRIE_STUDY_OPT    
5533     int restudied = 0;
5534     RExC_state_t copyRExC_state;
5535 #endif    
5536     GET_RE_DEBUG_FLAGS_DECL;
5537
5538     PERL_ARGS_ASSERT_RE_OP_COMPILE;
5539
5540     DEBUG_r(if (!PL_colorset) reginitcolors());
5541
5542 #ifndef PERL_IN_XSUB_RE
5543     /* Initialize these here instead of as-needed, as is quick and avoids
5544      * having to test them each time otherwise */
5545     if (! PL_AboveLatin1) {
5546         PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
5547         PL_ASCII = _new_invlist_C_array(ASCII_invlist);
5548         PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
5549
5550         PL_L1Posix_ptrs[_CC_ALPHANUMERIC]
5551                                 = _new_invlist_C_array(L1PosixAlnum_invlist);
5552         PL_Posix_ptrs[_CC_ALPHANUMERIC]
5553                                 = _new_invlist_C_array(PosixAlnum_invlist);
5554
5555         PL_L1Posix_ptrs[_CC_ALPHA]
5556                                 = _new_invlist_C_array(L1PosixAlpha_invlist);
5557         PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(PosixAlpha_invlist);
5558
5559         PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(PosixBlank_invlist);
5560         PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(XPosixBlank_invlist);
5561
5562         /* Cased is the same as Alpha in the ASCII range */
5563         PL_L1Posix_ptrs[_CC_CASED] =  _new_invlist_C_array(L1Cased_invlist);
5564         PL_Posix_ptrs[_CC_CASED] =  _new_invlist_C_array(PosixAlpha_invlist);
5565
5566         PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(PosixCntrl_invlist);
5567         PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(XPosixCntrl_invlist);
5568
5569         PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(PosixDigit_invlist);
5570         PL_L1Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(PosixDigit_invlist);
5571
5572         PL_L1Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(L1PosixGraph_invlist);
5573         PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(PosixGraph_invlist);
5574
5575         PL_L1Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(L1PosixLower_invlist);
5576         PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(PosixLower_invlist);
5577
5578         PL_L1Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(L1PosixPrint_invlist);
5579         PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(PosixPrint_invlist);
5580
5581         PL_L1Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(L1PosixPunct_invlist);
5582         PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(PosixPunct_invlist);
5583
5584         PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(PerlSpace_invlist);
5585         PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(XPerlSpace_invlist);
5586         PL_Posix_ptrs[_CC_PSXSPC] = _new_invlist_C_array(PosixSpace_invlist);
5587         PL_XPosix_ptrs[_CC_PSXSPC] = _new_invlist_C_array(XPosixSpace_invlist);
5588
5589         PL_L1Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(L1PosixUpper_invlist);
5590         PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(PosixUpper_invlist);
5591
5592         PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(VertSpace_invlist);
5593
5594         PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(PosixWord_invlist);
5595         PL_L1Posix_ptrs[_CC_WORDCHAR]
5596                                 = _new_invlist_C_array(L1PosixWord_invlist);
5597
5598         PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(PosixXDigit_invlist);
5599         PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(XPosixXDigit_invlist);
5600
5601         PL_HasMultiCharFold = _new_invlist_C_array(_Perl_Multi_Char_Folds_invlist);
5602     }
5603 #endif
5604
5605     pRExC_state->code_blocks = NULL;
5606     pRExC_state->num_code_blocks = 0;
5607
5608     if (is_bare_re)
5609         *is_bare_re = FALSE;
5610
5611     if (expr && (expr->op_type == OP_LIST ||
5612                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
5613         /* allocate code_blocks if needed */
5614         OP *o;
5615         int ncode = 0;
5616
5617         for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling)
5618             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
5619                 ncode++; /* count of DO blocks */
5620         if (ncode) {
5621             pRExC_state->num_code_blocks = ncode;
5622             Newx(pRExC_state->code_blocks, ncode, struct reg_code_block);
5623         }
5624     }
5625
5626     if (!pat_count) {
5627         /* compile-time pattern with just OP_CONSTs and DO blocks */
5628
5629         int n;
5630         OP *o;
5631
5632         /* find how many CONSTs there are */
5633         assert(expr);
5634         n = 0;
5635         if (expr->op_type == OP_CONST)
5636             n = 1;
5637         else
5638             for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
5639                 if (o->op_type == OP_CONST)
5640                     n++;
5641             }
5642
5643         /* fake up an SV array */
5644
5645         assert(!new_patternp);
5646         Newx(new_patternp, n, SV*);
5647         SAVEFREEPV(new_patternp);
5648         pat_count = n;
5649
5650         n = 0;
5651         if (expr->op_type == OP_CONST)
5652             new_patternp[n] = cSVOPx_sv(expr);
5653         else
5654             for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
5655                 if (o->op_type == OP_CONST)
5656                     new_patternp[n++] = cSVOPo_sv;
5657             }
5658
5659     }
5660
5661     DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
5662         "Assembling pattern from %d elements%s\n", pat_count,
5663             orig_rx_flags & RXf_SPLIT ? " for split" : ""));
5664
5665     /* set expr to the first arg op */
5666
5667     if (pRExC_state->num_code_blocks
5668          && expr->op_type != OP_CONST)
5669     {
5670             expr = cLISTOPx(expr)->op_first;
5671             assert(   expr->op_type == OP_PUSHMARK
5672                    || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK)
5673                    || expr->op_type == OP_PADRANGE);
5674             expr = expr->op_sibling;
5675     }
5676
5677     pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count,
5678                         expr, &recompile, NULL);
5679
5680     /* handle bare (possibly after overloading) regex: foo =~ $re */
5681     {
5682         SV *re = pat;
5683         if (SvROK(re))
5684             re = SvRV(re);
5685         if (SvTYPE(re) == SVt_REGEXP) {
5686             if (is_bare_re)
5687                 *is_bare_re = TRUE;
5688             SvREFCNT_inc(re);
5689             Safefree(pRExC_state->code_blocks);
5690             DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
5691                 "Precompiled pattern%s\n",
5692                     orig_rx_flags & RXf_SPLIT ? " for split" : ""));
5693
5694             return (REGEXP*)re;
5695         }
5696     }
5697
5698     exp = SvPV_nomg(pat, plen);
5699
5700     if (!eng->op_comp) {
5701         if ((SvUTF8(pat) && IN_BYTES)
5702                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
5703         {
5704             /* make a temporary copy; either to convert to bytes,
5705              * or to avoid repeating get-magic / overloaded stringify */
5706             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
5707                                         (IN_BYTES ? 0 : SvUTF8(pat)));
5708         }
5709         Safefree(pRExC_state->code_blocks);
5710         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
5711     }
5712
5713     /* ignore the utf8ness if the pattern is 0 length */
5714     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
5715     RExC_uni_semantics = 0;
5716     RExC_contains_locale = 0;
5717     pRExC_state->runtime_code_qr = NULL;
5718
5719     DEBUG_COMPILE_r({
5720             SV *dsv= sv_newmortal();
5721             RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, 60);
5722             PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
5723                           PL_colors[4],PL_colors[5],s);
5724         });
5725
5726   redo_first_pass:
5727     /* we jump here if we upgrade the pattern to utf8 and have to
5728      * recompile */
5729
5730     if ((pm_flags & PMf_USE_RE_EVAL)
5731                 /* this second condition covers the non-regex literal case,
5732                  * i.e.  $foo =~ '(?{})'. */
5733                 || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL))
5734     )
5735         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen);
5736
5737     /* return old regex if pattern hasn't changed */
5738     /* XXX: note in the below we have to check the flags as well as the pattern.
5739      *
5740      * Things get a touch tricky as we have to compare the utf8 flag independently
5741      * from the compile flags.
5742      */
5743
5744     if (   old_re
5745         && !recompile
5746         && !!RX_UTF8(old_re) == !!RExC_utf8
5747         && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) )
5748         && RX_PRECOMP(old_re)
5749         && RX_PRELEN(old_re) == plen
5750         && memEQ(RX_PRECOMP(old_re), exp, plen)
5751         && !runtime_code /* with runtime code, always recompile */ )
5752     {
5753         Safefree(pRExC_state->code_blocks);
5754         return old_re;
5755     }
5756
5757     rx_flags = orig_rx_flags;
5758
5759     if (initial_charset == REGEX_LOCALE_CHARSET) {
5760         RExC_contains_locale = 1;
5761     }
5762     else if (RExC_utf8 && initial_charset == REGEX_DEPENDS_CHARSET) {
5763
5764         /* Set to use unicode semantics if the pattern is in utf8 and has the
5765          * 'depends' charset specified, as it means unicode when utf8  */
5766         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
5767     }
5768
5769     RExC_precomp = exp;
5770     RExC_flags = rx_flags;
5771     RExC_pm_flags = pm_flags;
5772
5773     if (runtime_code) {
5774         if (TAINTING_get && TAINT_get)
5775             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
5776
5777         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
5778             /* whoops, we have a non-utf8 pattern, whilst run-time code
5779              * got compiled as utf8. Try again with a utf8 pattern */
5780             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
5781                                     pRExC_state->num_code_blocks);
5782             goto redo_first_pass;
5783         }
5784     }
5785     assert(!pRExC_state->runtime_code_qr);
5786
5787     RExC_sawback = 0;
5788
5789     RExC_seen = 0;
5790     RExC_in_lookbehind = 0;
5791     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
5792     RExC_extralen = 0;
5793     RExC_override_recoding = 0;
5794     RExC_in_multi_char_class = 0;
5795
5796     /* First pass: determine size, legality. */
5797     RExC_parse = exp;
5798     RExC_start = exp;
5799     RExC_end = exp + plen;
5800     RExC_naughty = 0;
5801     RExC_npar = 1;
5802     RExC_nestroot = 0;
5803     RExC_size = 0L;
5804     RExC_emit = &RExC_emit_dummy;
5805     RExC_whilem_seen = 0;
5806     RExC_open_parens = NULL;
5807     RExC_close_parens = NULL;
5808     RExC_opend = NULL;
5809     RExC_paren_names = NULL;
5810 #ifdef DEBUGGING
5811     RExC_paren_name_list = NULL;
5812 #endif
5813     RExC_recurse = NULL;
5814     RExC_recurse_count = 0;
5815     pRExC_state->code_index = 0;
5816
5817 #if 0 /* REGC() is (currently) a NOP at the first pass.
5818        * Clever compilers notice this and complain. --jhi */
5819     REGC((U8)REG_MAGIC, (char*)RExC_emit);
5820 #endif
5821     DEBUG_PARSE_r(
5822         PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n");
5823         RExC_lastnum=0;
5824         RExC_lastparse=NULL;
5825     );
5826     /* reg may croak on us, not giving us a chance to free
5827        pRExC_state->code_blocks.  We cannot SAVEFREEPV it now, as we may
5828        need it to survive as long as the regexp (qr/(?{})/).
5829        We must check that code_blocksv is not already set, because we may
5830        have jumped back to restart the sizing pass. */
5831     if (pRExC_state->code_blocks && !code_blocksv) {
5832         code_blocksv = newSV_type(SVt_PV);
5833         SAVEFREESV(code_blocksv);
5834         SvPV_set(code_blocksv, (char *)pRExC_state->code_blocks);
5835         SvLEN_set(code_blocksv, 1); /*sufficient to make sv_clear free it*/
5836     }
5837     if (reg(pRExC_state, 0, &flags,1) == NULL) {
5838         /* It's possible to write a regexp in ascii that represents Unicode
5839         codepoints outside of the byte range, such as via \x{100}. If we
5840         detect such a sequence we have to convert the entire pattern to utf8
5841         and then recompile, as our sizing calculation will have been based
5842         on 1 byte == 1 character, but we will need to use utf8 to encode
5843         at least some part of the pattern, and therefore must convert the whole
5844         thing.
5845         -- dmq */
5846         if (flags & RESTART_UTF8) {
5847             S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen,
5848                                     pRExC_state->num_code_blocks);
5849             goto redo_first_pass;
5850         }
5851         Perl_croak(aTHX_ "panic: reg returned NULL to re_op_compile for sizing pass, flags=%#"UVxf"", (UV) flags);
5852     }
5853     if (code_blocksv)
5854         SvLEN_set(code_blocksv,0); /* no you can't have it, sv_clear */
5855
5856     DEBUG_PARSE_r({
5857         PerlIO_printf(Perl_debug_log, 
5858             "Required size %"IVdf" nodes\n"
5859             "Starting second pass (creation)\n", 
5860             (IV)RExC_size);
5861         RExC_lastnum=0; 
5862         RExC_lastparse=NULL; 
5863     });
5864
5865     /* The first pass could have found things that force Unicode semantics */
5866     if ((RExC_utf8 || RExC_uni_semantics)
5867          && get_regex_charset(rx_flags) == REGEX_DEPENDS_CHARSET)
5868     {
5869         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
5870     }
5871
5872     /* Small enough for pointer-storage convention?
5873        If extralen==0, this means that we will not need long jumps. */
5874     if (RExC_size >= 0x10000L && RExC_extralen)
5875         RExC_size += RExC_extralen;
5876     else
5877         RExC_extralen = 0;
5878     if (RExC_whilem_seen > 15)
5879         RExC_whilem_seen = 15;
5880
5881     /* Allocate space and zero-initialize. Note, the two step process 
5882        of zeroing when in debug mode, thus anything assigned has to 
5883        happen after that */
5884     rx = (REGEXP*) newSV_type(SVt_REGEXP);
5885     r = ReANY(rx);
5886     Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
5887          char, regexp_internal);
5888     if ( r == NULL || ri == NULL )
5889         FAIL("Regexp out of space");
5890 #ifdef DEBUGGING
5891     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
5892     Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
5893 #else 
5894     /* bulk initialize base fields with 0. */
5895     Zero(ri, sizeof(regexp_internal), char);        
5896 #endif
5897
5898     /* non-zero initialization begins here */
5899     RXi_SET( r, ri );
5900     r->engine= eng;
5901     r->extflags = rx_flags;
5902     RXp_COMPFLAGS(r) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK;
5903
5904     if (pm_flags & PMf_IS_QR) {
5905         ri->code_blocks = pRExC_state->code_blocks;
5906         ri->num_code_blocks = pRExC_state->num_code_blocks;
5907     }
5908     else
5909     {
5910         int n;
5911         for (n = 0; n < pRExC_state->num_code_blocks; n++)
5912             if (pRExC_state->code_blocks[n].src_regex)
5913                 SAVEFREESV(pRExC_state->code_blocks[n].src_regex);
5914         SAVEFREEPV(pRExC_state->code_blocks);
5915     }
5916
5917     {
5918         bool has_p     = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
5919         bool has_charset = (get_regex_charset(r->extflags) != REGEX_DEPENDS_CHARSET);
5920
5921         /* The caret is output if there are any defaults: if not all the STD
5922          * flags are set, or if no character set specifier is needed */
5923         bool has_default =
5924                     (((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
5925                     || ! has_charset);
5926         bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
5927         U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD)
5928                             >> RXf_PMf_STD_PMMOD_SHIFT);
5929         const char *fptr = STD_PAT_MODS;        /*"msix"*/
5930         char *p;
5931         /* Allocate for the worst case, which is all the std flags are turned
5932          * on.  If more precision is desired, we could do a population count of
5933          * the flags set.  This could be done with a small lookup table, or by
5934          * shifting, masking and adding, or even, when available, assembly
5935          * language for a machine-language population count.
5936          * We never output a minus, as all those are defaults, so are
5937          * covered by the caret */
5938         const STRLEN wraplen = plen + has_p + has_runon
5939             + has_default       /* If needs a caret */
5940
5941                 /* If needs a character set specifier */
5942             + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
5943             + (sizeof(STD_PAT_MODS) - 1)
5944             + (sizeof("(?:)") - 1);
5945
5946         Newx(p, wraplen + 1, char); /* +1 for the ending NUL */
5947         r->xpv_len_u.xpvlenu_pv = p;
5948         if (RExC_utf8)
5949             SvFLAGS(rx) |= SVf_UTF8;
5950         *p++='('; *p++='?';
5951
5952         /* If a default, cover it using the caret */
5953         if (has_default) {
5954             *p++= DEFAULT_PAT_MOD;
5955         }
5956         if (has_charset) {
5957             STRLEN len;
5958             const char* const name = get_regex_charset_name(r->extflags, &len);
5959             Copy(name, p, len, char);
5960             p += len;
5961         }
5962         if (has_p)
5963             *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
5964         {
5965             char ch;
5966             while((ch = *fptr++)) {
5967                 if(reganch & 1)
5968                     *p++ = ch;
5969                 reganch >>= 1;
5970             }
5971         }
5972
5973         *p++ = ':';
5974         Copy(RExC_precomp, p, plen, char);
5975         assert ((RX_WRAPPED(rx) - p) < 16);
5976         r->pre_prefix = p - RX_WRAPPED(rx);
5977         p += plen;
5978         if (has_runon)
5979             *p++ = '\n';
5980         *p++ = ')';
5981         *p = 0;
5982         SvCUR_set(rx, p - RX_WRAPPED(rx));
5983     }
5984
5985     r->intflags = 0;
5986     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
5987     
5988     if (RExC_seen & REG_SEEN_RECURSE) {
5989         Newxz(RExC_open_parens, RExC_npar,regnode *);
5990         SAVEFREEPV(RExC_open_parens);
5991         Newxz(RExC_close_parens,RExC_npar,regnode *);
5992         SAVEFREEPV(RExC_close_parens);
5993     }
5994
5995     /* Useful during FAIL. */
5996 #ifdef RE_TRACK_PATTERN_OFFSETS
5997     Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
5998     DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
5999                           "%s %"UVuf" bytes for offset annotations.\n",
6000                           ri->u.offsets ? "Got" : "Couldn't get",
6001                           (UV)((2*RExC_size+1) * sizeof(U32))));
6002 #endif
6003     SetProgLen(ri,RExC_size);
6004     RExC_rx_sv = rx;
6005     RExC_rx = r;
6006     RExC_rxi = ri;
6007
6008     /* Second pass: emit code. */
6009     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
6010     RExC_pm_flags = pm_flags;
6011     RExC_parse = exp;
6012     RExC_end = exp + plen;
6013     RExC_naughty = 0;
6014     RExC_npar = 1;
6015     RExC_emit_start = ri->program;
6016     RExC_emit = ri->program;
6017     RExC_emit_bound = ri->program + RExC_size + 1;
6018     pRExC_state->code_index = 0;
6019
6020     REGC((U8)REG_MAGIC, (char*) RExC_emit++);
6021     if (reg(pRExC_state, 0, &flags,1) == NULL) {
6022         ReREFCNT_dec(rx);   
6023         Perl_croak(aTHX_ "panic: reg returned NULL to re_op_compile for generation pass, flags=%#"UVxf"", (UV) flags);
6024     }
6025     /* XXXX To minimize changes to RE engine we always allocate
6026        3-units-long substrs field. */
6027     Newx(r->substrs, 1, struct reg_substr_data);
6028     if (RExC_recurse_count) {
6029         Newxz(RExC_recurse,RExC_recurse_count,regnode *);
6030         SAVEFREEPV(RExC_recurse);
6031     }
6032
6033 reStudy:
6034     r->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0;
6035     Zero(r->substrs, 1, struct reg_substr_data);
6036
6037 #ifdef TRIE_STUDY_OPT
6038     if (!restudied) {
6039         StructCopy(&zero_scan_data, &data, scan_data_t);
6040         copyRExC_state = RExC_state;
6041     } else {
6042         U32 seen=RExC_seen;
6043         DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
6044         
6045         RExC_state = copyRExC_state;
6046         if (seen & REG_TOP_LEVEL_BRANCHES) 
6047             RExC_seen |= REG_TOP_LEVEL_BRANCHES;
6048         else
6049             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
6050         StructCopy(&zero_scan_data, &data, scan_data_t);
6051     }
6052 #else
6053     StructCopy(&zero_scan_data, &data, scan_data_t);
6054 #endif    
6055
6056     /* Dig out information for optimizations. */
6057     r->extflags = RExC_flags; /* was pm_op */
6058     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
6059  
6060     if (UTF)
6061         SvUTF8_on(rx);  /* Unicode in it? */
6062     ri->regstclass = NULL;
6063     if (RExC_naughty >= 10)     /* Probably an expensive pattern. */
6064         r->intflags |= PREGf_NAUGHTY;
6065     scan = ri->program + 1;             /* First BRANCH. */
6066
6067     /* testing for BRANCH here tells us whether there is "must appear"
6068        data in the pattern. If there is then we can use it for optimisations */
6069     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /*  Only one top-level choice. */
6070         I32 fake;
6071         STRLEN longest_float_length, longest_fixed_length;
6072         struct regnode_charclass_class ch_class; /* pointed to by data */
6073         int stclass_flag;
6074         I32 last_close = 0; /* pointed to by data */
6075         regnode *first= scan;
6076         regnode *first_next= regnext(first);
6077         /*
6078          * Skip introductions and multiplicators >= 1
6079          * so that we can extract the 'meat' of the pattern that must 
6080          * match in the large if() sequence following.
6081          * NOTE that EXACT is NOT covered here, as it is normally
6082          * picked up by the optimiser separately. 
6083          *
6084          * This is unfortunate as the optimiser isnt handling lookahead
6085          * properly currently.
6086          *
6087          */
6088         while ((OP(first) == OPEN && (sawopen = 1)) ||
6089                /* An OR of *one* alternative - should not happen now. */
6090             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
6091             /* for now we can't handle lookbehind IFMATCH*/
6092             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
6093             (OP(first) == PLUS) ||
6094             (OP(first) == MINMOD) ||
6095                /* An {n,m} with n>0 */
6096             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
6097             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
6098         {
6099                 /* 
6100                  * the only op that could be a regnode is PLUS, all the rest
6101                  * will be regnode_1 or regnode_2.
6102                  *
6103                  * (yves doesn't think this is true)
6104                  */
6105                 if (OP(first) == PLUS)
6106                     sawplus = 1;
6107                 else {
6108                     if (OP(first) == MINMOD)
6109                         sawminmod = 1;
6110                     first += regarglen[OP(first)];
6111                 }
6112                 first = NEXTOPER(first);
6113                 first_next= regnext(first);
6114         }
6115
6116         /* Starting-point info. */
6117       again:
6118         DEBUG_PEEP("first:",first,0);
6119         /* Ignore EXACT as we deal with it later. */
6120         if (PL_regkind[OP(first)] == EXACT) {
6121             if (OP(first) == EXACT)
6122                 NOOP;   /* Empty, get anchored substr later. */
6123             else
6124                 ri->regstclass = first;
6125         }
6126 #ifdef TRIE_STCLASS
6127         else if (PL_regkind[OP(first)] == TRIE &&
6128                 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0) 
6129         {
6130             regnode *trie_op;
6131             /* this can happen only on restudy */
6132             if ( OP(first) == TRIE ) {
6133                 struct regnode_1 *trieop = (struct regnode_1 *)
6134                     PerlMemShared_calloc(1, sizeof(struct regnode_1));
6135                 StructCopy(first,trieop,struct regnode_1);
6136                 trie_op=(regnode *)trieop;
6137             } else {
6138                 struct regnode_charclass *trieop = (struct regnode_charclass *)
6139                     PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
6140                 StructCopy(first,trieop,struct regnode_charclass);
6141                 trie_op=(regnode *)trieop;
6142             }
6143             OP(trie_op)+=2;
6144             make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
6145             ri->regstclass = trie_op;
6146         }
6147 #endif
6148         else if (REGNODE_SIMPLE(OP(first)))
6149             ri->regstclass = first;
6150         else if (PL_regkind[OP(first)] == BOUND ||
6151                  PL_regkind[OP(first)] == NBOUND)
6152             ri->regstclass = first;
6153         else if (PL_regkind[OP(first)] == BOL) {
6154             r->extflags |= (OP(first) == MBOL
6155                            ? RXf_ANCH_MBOL
6156                            : (OP(first) == SBOL
6157                               ? RXf_ANCH_SBOL
6158                               : RXf_ANCH_BOL));
6159             first = NEXTOPER(first);
6160             goto again;
6161         }
6162         else if (OP(first) == GPOS) {
6163             r->extflags |= RXf_ANCH_GPOS;
6164             first = NEXTOPER(first);
6165             goto again;
6166         }
6167         else if ((!sawopen || !RExC_sawback) &&
6168             (OP(first) == STAR &&
6169             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
6170             !(r->extflags & RXf_ANCH) && !pRExC_state->num_code_blocks)
6171         {
6172             /* turn .* into ^.* with an implied $*=1 */
6173             const int type =
6174                 (OP(NEXTOPER(first)) == REG_ANY)
6175                     ? RXf_ANCH_MBOL
6176                     : RXf_ANCH_SBOL;
6177             r->extflags |= type;
6178             r->intflags |= PREGf_IMPLICIT;
6179             first = NEXTOPER(first);
6180             goto again;
6181         }
6182         if (sawplus && !sawminmod && !sawlookahead && (!sawopen || !RExC_sawback)
6183             && !pRExC_state->num_code_blocks) /* May examine pos and $& */
6184             /* x+ must match at the 1st pos of run of x's */
6185             r->intflags |= PREGf_SKIP;
6186
6187         /* Scan is after the zeroth branch, first is atomic matcher. */
6188 #ifdef TRIE_STUDY_OPT
6189         DEBUG_PARSE_r(
6190             if (!restudied)
6191                 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
6192                               (IV)(first - scan + 1))
6193         );
6194 #else
6195         DEBUG_PARSE_r(
6196             PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
6197                 (IV)(first - scan + 1))
6198         );
6199 #endif
6200
6201
6202         /*
6203         * If there's something expensive in the r.e., find the
6204         * longest literal string that must appear and make it the
6205         * regmust.  Resolve ties in favor of later strings, since
6206         * the regstart check works with the beginning of the r.e.
6207         * and avoiding duplication strengthens checking.  Not a
6208         * strong reason, but sufficient in the absence of others.
6209         * [Now we resolve ties in favor of the earlier string if
6210         * it happens that c_offset_min has been invalidated, since the
6211         * earlier string may buy us something the later one won't.]
6212         */
6213
6214         data.longest_fixed = newSVpvs("");
6215         data.longest_float = newSVpvs("");
6216         data.last_found = newSVpvs("");
6217         data.longest = &(data.longest_fixed);
6218         ENTER_with_name("study_chunk");
6219         SAVEFREESV(data.longest_fixed);
6220         SAVEFREESV(data.longest_float);
6221         SAVEFREESV(data.last_found);
6222         first = scan;
6223         if (!ri->regstclass) {
6224             cl_init(pRExC_state, &ch_class);
6225             data.start_class = &ch_class;
6226             stclass_flag = SCF_DO_STCLASS_AND;
6227         } else                          /* XXXX Check for BOUND? */
6228             stclass_flag = 0;
6229         data.last_closep = &last_close;
6230         
6231         minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
6232             &data, -1, NULL, NULL,
6233             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
6234                           | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
6235             0);
6236
6237
6238         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
6239
6240
6241         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
6242              && data.last_start_min == 0 && data.last_end > 0
6243              && !RExC_seen_zerolen
6244              && !(RExC_seen & REG_SEEN_VERBARG)
6245              && !((RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
6246             r->extflags |= RXf_CHECK_ALL;
6247         scan_commit(pRExC_state, &data,&minlen,0);
6248
6249         longest_float_length = CHR_SVLEN(data.longest_float);
6250
6251         if (! ((SvCUR(data.longest_fixed)  /* ok to leave SvCUR */
6252                    && data.offset_fixed == data.offset_float_min
6253                    && SvCUR(data.longest_fixed) == SvCUR(data.longest_float)))
6254             && S_setup_longest (aTHX_ pRExC_state,
6255                                     data.longest_float,
6256                                     &(r->float_utf8),
6257                                     &(r->float_substr),
6258                                     &(r->float_end_shift),
6259                                     data.lookbehind_float,
6260                                     data.offset_float_min,
6261                                     data.minlen_float,
6262                                     longest_float_length,
6263                                     cBOOL(data.flags & SF_FL_BEFORE_EOL),
6264                                     cBOOL(data.flags & SF_FL_BEFORE_MEOL)))
6265         {
6266             r->float_min_offset = data.offset_float_min - data.lookbehind_float;
6267             r->float_max_offset = data.offset_float_max;
6268             if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
6269                 r->float_max_offset -= data.lookbehind_float;
6270             SvREFCNT_inc_simple_void_NN(data.longest_float);
6271         }
6272         else {
6273             r->float_substr = r->float_utf8 = NULL;
6274             longest_float_length = 0;
6275         }
6276
6277         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
6278
6279         if (S_setup_longest (aTHX_ pRExC_state,
6280                                 data.longest_fixed,
6281                                 &(r->anchored_utf8),
6282                                 &(r->anchored_substr),
6283                                 &(r->anchored_end_shift),
6284                                 data.lookbehind_fixed,
6285                                 data.offset_fixed,
6286                                 data.minlen_fixed,
6287                                 longest_fixed_length,
6288                                 cBOOL(data.flags & SF_FIX_BEFORE_EOL),
6289                                 cBOOL(data.flags & SF_FIX_BEFORE_MEOL)))
6290         {
6291             r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
6292             SvREFCNT_inc_simple_void_NN(data.longest_fixed);
6293         }
6294         else {
6295             r->anchored_substr = r->anchored_utf8 = NULL;
6296             longest_fixed_length = 0;
6297         }
6298         LEAVE_with_name("study_chunk");
6299
6300         if (ri->regstclass
6301             && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
6302             ri->regstclass = NULL;
6303
6304         if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
6305             && stclass_flag
6306             && ! TEST_SSC_EOS(data.start_class)
6307             && !cl_is_anything(data.start_class))
6308         {
6309             const U32 n = add_data(pRExC_state, 1, "f");
6310             OP(data.start_class) = ANYOF_SYNTHETIC;
6311
6312             Newx(RExC_rxi->data->data[n], 1,
6313                 struct regnode_charclass_class);
6314             StructCopy(data.start_class,
6315                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
6316                        struct regnode_charclass_class);
6317             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
6318             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
6319             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
6320                       regprop(r, sv, (regnode*)data.start_class);
6321                       PerlIO_printf(Perl_debug_log,
6322                                     "synthetic stclass \"%s\".\n",
6323                                     SvPVX_const(sv));});
6324         }
6325
6326         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
6327         if (longest_fixed_length > longest_float_length) {
6328             r->check_end_shift = r->anchored_end_shift;
6329             r->check_substr = r->anchored_substr;
6330             r->check_utf8 = r->anchored_utf8;
6331             r->check_offset_min = r->check_offset_max = r->anchored_offset;
6332             if (r->extflags & RXf_ANCH_SINGLE)
6333                 r->extflags |= RXf_NOSCAN;
6334         }
6335         else {
6336             r->check_end_shift = r->float_end_shift;
6337             r->check_substr = r->float_substr;
6338             r->check_utf8 = r->float_utf8;
6339             r->check_offset_min = r->float_min_offset;
6340             r->check_offset_max = r->float_max_offset;
6341         }
6342         if ((r->check_substr || r->check_utf8) ) {
6343             r->extflags |= RXf_USE_INTUIT;
6344             if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
6345                 r->extflags |= RXf_INTUIT_TAIL;
6346         }
6347         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
6348         if ( (STRLEN)minlen < longest_float_length )
6349             minlen= longest_float_length;
6350         if ( (STRLEN)minlen < longest_fixed_length )
6351             minlen= longest_fixed_length;     
6352         */
6353     }
6354     else {
6355         /* Several toplevels. Best we can is to set minlen. */
6356         I32 fake;
6357         struct regnode_charclass_class ch_class;
6358         I32 last_close = 0;
6359
6360         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
6361
6362         scan = ri->program + 1;
6363         cl_init(pRExC_state, &ch_class);
6364         data.start_class = &ch_class;
6365         data.last_closep = &last_close;
6366
6367         
6368         minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
6369             &data, -1, NULL, NULL,
6370             SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS
6371                               |(restudied ? SCF_TRIE_DOING_RESTUDY : 0),
6372             0);
6373         
6374         CHECK_RESTUDY_GOTO_butfirst(NOOP);
6375
6376         r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
6377                 = r->float_substr = r->float_utf8 = NULL;
6378
6379         if (! TEST_SSC_EOS(data.start_class)
6380             && !cl_is_anything(data.start_class))
6381         {
6382             const U32 n = add_data(pRExC_state, 1, "f");
6383             OP(data.start_class) = ANYOF_SYNTHETIC;
6384
6385             Newx(RExC_rxi->data->data[n], 1,
6386                 struct regnode_charclass_class);
6387             StructCopy(data.start_class,
6388                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
6389                        struct regnode_charclass_class);
6390             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
6391             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
6392             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
6393                       regprop(r, sv, (regnode*)data.start_class);
6394                       PerlIO_printf(Perl_debug_log,
6395                                     "synthetic stclass \"%s\".\n",
6396                                     SvPVX_const(sv));});
6397         }
6398     }
6399
6400     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
6401        the "real" pattern. */
6402     DEBUG_OPTIMISE_r({
6403         PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
6404                       (IV)minlen, (IV)r->minlen);
6405     });
6406     r->minlenret = minlen;
6407     if (r->minlen < minlen) 
6408         r->minlen = minlen;
6409     
6410     if (RExC_seen & REG_SEEN_GPOS)
6411         r->extflags |= RXf_GPOS_SEEN;
6412     if (RExC_seen & REG_SEEN_LOOKBEHIND)
6413         r->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the lookbehind */
6414     if (pRExC_state->num_code_blocks)
6415         r->extflags |= RXf_EVAL_SEEN;
6416     if (RExC_seen & REG_SEEN_CANY)
6417         r->extflags |= RXf_CANY_SEEN;
6418     if (RExC_seen & REG_SEEN_VERBARG)
6419     {
6420         r->intflags |= PREGf_VERBARG_SEEN;
6421         r->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */
6422     }
6423     if (RExC_seen & REG_SEEN_CUTGROUP)
6424         r->intflags |= PREGf_CUTGROUP_SEEN;
6425     if (pm_flags & PMf_USE_RE_EVAL)
6426         r->intflags |= PREGf_USE_RE_EVAL;
6427     if (RExC_paren_names)
6428         RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
6429     else
6430         RXp_PAREN_NAMES(r) = NULL;
6431
6432     {
6433         regnode *first = ri->program + 1;
6434         U8 fop = OP(first);
6435         regnode *next = NEXTOPER(first);
6436         U8 nop = OP(next);
6437
6438         if (PL_regkind[fop] == NOTHING && nop == END)
6439             r->extflags |= RXf_NULL;
6440         else if (PL_regkind[fop] == BOL && nop == END)
6441             r->extflags |= RXf_START_ONLY;
6442         else if (fop == PLUS && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE && OP(regnext(first)) == END)
6443             r->extflags |= RXf_WHITE;
6444         else if ( r->extflags & RXf_SPLIT && fop == EXACT && STR_LEN(first) == 1 && *(STRING(first)) == ' ' && OP(regnext(first)) == END )
6445             r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
6446
6447     }
6448 #ifdef DEBUGGING
6449     if (RExC_paren_names) {
6450         ri->name_list_idx = add_data( pRExC_state, 1, "a" );
6451         ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
6452     } else
6453 #endif
6454         ri->name_list_idx = 0;
6455
6456     if (RExC_recurse_count) {
6457         for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
6458             const regnode *scan = RExC_recurse[RExC_recurse_count-1];
6459             ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
6460         }
6461     }
6462     Newxz(r->offs, RExC_npar, regexp_paren_pair);
6463     /* assume we don't need to swap parens around before we match */
6464
6465     DEBUG_DUMP_r({
6466         PerlIO_printf(Perl_debug_log,"Final program:\n");
6467         regdump(r);
6468     });
6469 #ifdef RE_TRACK_PATTERN_OFFSETS
6470     DEBUG_OFFSETS_r(if (ri->u.offsets) {
6471         const U32 len = ri->u.offsets[0];
6472         U32 i;
6473         GET_RE_DEBUG_FLAGS_DECL;
6474         PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
6475         for (i = 1; i <= len; i++) {
6476             if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
6477                 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
6478                 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
6479             }
6480         PerlIO_printf(Perl_debug_log, "\n");
6481     });
6482 #endif
6483
6484 #ifdef USE_ITHREADS
6485     /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated
6486      * by setting the regexp SV to readonly-only instead. If the
6487      * pattern's been recompiled, the USEDness should remain. */
6488     if (old_re && SvREADONLY(old_re))
6489         SvREADONLY_on(rx);
6490 #endif
6491     return rx;
6492 }
6493
6494
6495 SV*
6496 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
6497                     const U32 flags)
6498 {
6499     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
6500
6501     PERL_UNUSED_ARG(value);
6502
6503     if (flags & RXapif_FETCH) {
6504         return reg_named_buff_fetch(rx, key, flags);
6505     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
6506         Perl_croak_no_modify();
6507         return NULL;
6508     } else if (flags & RXapif_EXISTS) {
6509         return reg_named_buff_exists(rx, key, flags)
6510             ? &PL_sv_yes
6511             : &PL_sv_no;
6512     } else if (flags & RXapif_REGNAMES) {
6513         return reg_named_buff_all(rx, flags);
6514     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
6515         return reg_named_buff_scalar(rx, flags);
6516     } else {
6517         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
6518         return NULL;
6519     }
6520 }
6521
6522 SV*
6523 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
6524                          const U32 flags)
6525 {
6526     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
6527     PERL_UNUSED_ARG(lastkey);
6528
6529     if (flags & RXapif_FIRSTKEY)
6530         return reg_named_buff_firstkey(rx, flags);
6531     else if (flags & RXapif_NEXTKEY)
6532         return reg_named_buff_nextkey(rx, flags);
6533     else {
6534         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags);
6535         return NULL;
6536     }
6537 }
6538
6539 SV*
6540 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
6541                           const U32 flags)
6542 {
6543     AV *retarray = NULL;
6544     SV *ret;
6545     struct regexp *const rx = ReANY(r);
6546
6547     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
6548
6549     if (flags & RXapif_ALL)
6550         retarray=newAV();
6551
6552     if (rx && RXp_PAREN_NAMES(rx)) {
6553         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
6554         if (he_str) {
6555             IV i;
6556             SV* sv_dat=HeVAL(he_str);
6557             I32 *nums=(I32*)SvPVX(sv_dat);
6558             for ( i=0; i<SvIVX(sv_dat); i++ ) {
6559                 if ((I32)(rx->nparens) >= nums[i]
6560                     && rx->offs[nums[i]].start != -1
6561                     && rx->offs[nums[i]].end != -1)
6562                 {
6563                     ret = newSVpvs("");
6564                     CALLREG_NUMBUF_FETCH(r,nums[i],ret);
6565                     if (!retarray)
6566                         return ret;
6567                 } else {
6568                     if (retarray)
6569                         ret = newSVsv(&PL_sv_undef);
6570                 }
6571                 if (retarray)
6572                     av_push(retarray, ret);
6573             }
6574             if (retarray)
6575                 return newRV_noinc(MUTABLE_SV(retarray));
6576         }
6577     }
6578     return NULL;
6579 }
6580
6581 bool
6582 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
6583                            const U32 flags)
6584 {
6585     struct regexp *const rx = ReANY(r);
6586
6587     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
6588
6589     if (rx && RXp_PAREN_NAMES(rx)) {
6590         if (flags & RXapif_ALL) {
6591             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
6592         } else {
6593             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
6594             if (sv) {
6595                 SvREFCNT_dec_NN(sv);
6596                 return TRUE;
6597             } else {
6598                 return FALSE;
6599             }
6600         }
6601     } else {
6602         return FALSE;
6603     }
6604 }
6605
6606 SV*
6607 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
6608 {
6609     struct regexp *const rx = ReANY(r);
6610
6611     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
6612
6613     if ( rx && RXp_PAREN_NAMES(rx) ) {
6614         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
6615
6616         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
6617     } else {
6618         return FALSE;
6619     }
6620 }
6621
6622 SV*
6623 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
6624 {
6625     struct regexp *const rx = ReANY(r);
6626     GET_RE_DEBUG_FLAGS_DECL;
6627
6628     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
6629
6630     if (rx && RXp_PAREN_NAMES(rx)) {
6631         HV *hv = RXp_PAREN_NAMES(rx);
6632         HE *temphe;
6633         while ( (temphe = hv_iternext_flags(hv,0)) ) {
6634             IV i;
6635             IV parno = 0;
6636             SV* sv_dat = HeVAL(temphe);
6637             I32 *nums = (I32*)SvPVX(sv_dat);
6638             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
6639                 if ((I32)(rx->lastparen) >= nums[i] &&
6640                     rx->offs[nums[i]].start != -1 &&
6641                     rx->offs[nums[i]].end != -1)
6642                 {
6643                     parno = nums[i];
6644                     break;
6645                 }
6646             }
6647             if (parno || flags & RXapif_ALL) {
6648                 return newSVhek(HeKEY_hek(temphe));
6649             }
6650         }
6651     }
6652     return NULL;
6653 }
6654
6655 SV*
6656 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
6657 {
6658     SV *ret;
6659     AV *av;
6660     I32 length;
6661     struct regexp *const rx = ReANY(r);
6662
6663     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
6664
6665     if (rx && RXp_PAREN_NAMES(rx)) {
6666         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
6667             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
6668         } else if (flags & RXapif_ONE) {
6669             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
6670             av = MUTABLE_AV(SvRV(ret));
6671             length = av_len(av);
6672             SvREFCNT_dec_NN(ret);
6673             return newSViv(length + 1);
6674         } else {
6675             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags);
6676             return NULL;
6677         }
6678     }
6679     return &PL_sv_undef;
6680 }
6681
6682 SV*
6683 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
6684 {
6685     struct regexp *const rx = ReANY(r);
6686     AV *av = newAV();
6687
6688     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
6689
6690     if (rx && RXp_PAREN_NAMES(rx)) {
6691         HV *hv= RXp_PAREN_NAMES(rx);
6692         HE *temphe;
6693         (void)hv_iterinit(hv);
6694         while ( (temphe = hv_iternext_flags(hv,0)) ) {
6695             IV i;
6696             IV parno = 0;
6697             SV* sv_dat = HeVAL(temphe);
6698             I32 *nums = (I32*)SvPVX(sv_dat);
6699             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
6700                 if ((I32)(rx->lastparen) >= nums[i] &&
6701                     rx->offs[nums[i]].start != -1 &&
6702                     rx->offs[nums[i]].end != -1)
6703                 {
6704                     parno = nums[i];
6705                     break;
6706                 }
6707             }
6708             if (parno || flags & RXapif_ALL) {
6709                 av_push(av, newSVhek(HeKEY_hek(temphe)));
6710             }
6711         }
6712     }
6713
6714     return newRV_noinc(MUTABLE_SV(av));
6715 }
6716
6717 void
6718 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
6719                              SV * const sv)
6720 {
6721     struct regexp *const rx = ReANY(r);
6722     char *s = NULL;
6723     I32 i = 0;
6724     I32 s1, t1;
6725     I32 n = paren;
6726
6727     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
6728         
6729     if (      n == RX_BUFF_IDX_CARET_PREMATCH
6730            || n == RX_BUFF_IDX_CARET_FULLMATCH
6731            || n == RX_BUFF_IDX_CARET_POSTMATCH
6732        )
6733     {
6734         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
6735         if (!keepcopy) {
6736             /* on something like
6737              *    $r = qr/.../;
6738              *    /$qr/p;
6739              * the KEEPCOPY is set on the PMOP rather than the regex */
6740             if (PL_curpm && r == PM_GETRE(PL_curpm))
6741                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
6742         }
6743         if (!keepcopy)
6744             goto ret_undef;
6745     }
6746
6747     if (!rx->subbeg)
6748         goto ret_undef;
6749
6750     if (n == RX_BUFF_IDX_CARET_FULLMATCH)
6751         /* no need to distinguish between them any more */
6752         n = RX_BUFF_IDX_FULLMATCH;
6753
6754     if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
6755         && rx->offs[0].start != -1)
6756     {
6757         /* $`, ${^PREMATCH} */
6758         i = rx->offs[0].start;
6759         s = rx->subbeg;
6760     }
6761     else 
6762     if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
6763         && rx->offs[0].end != -1)
6764     {
6765         /* $', ${^POSTMATCH} */
6766         s = rx->subbeg - rx->suboffset + rx->offs[0].end;
6767         i = rx->sublen + rx->suboffset - rx->offs[0].end;
6768     } 
6769     else
6770     if ( 0 <= n && n <= (I32)rx->nparens &&
6771         (s1 = rx->offs[n].start) != -1 &&
6772         (t1 = rx->offs[n].end) != -1)
6773     {
6774         /* $&, ${^MATCH},  $1 ... */
6775         i = t1 - s1;
6776         s = rx->subbeg + s1 - rx->suboffset;
6777     } else {
6778         goto ret_undef;
6779     }          
6780
6781     assert(s >= rx->subbeg);
6782     assert(rx->sublen >= (s - rx->subbeg) + i );
6783     if (i >= 0) {
6784 #if NO_TAINT_SUPPORT
6785         sv_setpvn(sv, s, i);
6786 #else
6787         const int oldtainted = TAINT_get;
6788         TAINT_NOT;
6789         sv_setpvn(sv, s, i);
6790         TAINT_set(oldtainted);
6791 #endif
6792         if ( (rx->extflags & RXf_CANY_SEEN)
6793             ? (RXp_MATCH_UTF8(rx)
6794                         && (!i || is_utf8_string((U8*)s, i)))
6795             : (RXp_MATCH_UTF8(rx)) )
6796         {
6797             SvUTF8_on(sv);
6798         }
6799         else
6800             SvUTF8_off(sv);
6801         if (TAINTING_get) {
6802             if (RXp_MATCH_TAINTED(rx)) {
6803                 if (SvTYPE(sv) >= SVt_PVMG) {
6804                     MAGIC* const mg = SvMAGIC(sv);
6805                     MAGIC* mgt;
6806                     TAINT;
6807                     SvMAGIC_set(sv, mg->mg_moremagic);
6808                     SvTAINT(sv);
6809                     if ((mgt = SvMAGIC(sv))) {
6810                         mg->mg_moremagic = mgt;
6811                         SvMAGIC_set(sv, mg);
6812                     }
6813                 } else {
6814                     TAINT;
6815                     SvTAINT(sv);
6816                 }
6817             } else 
6818                 SvTAINTED_off(sv);
6819         }
6820     } else {
6821       ret_undef:
6822         sv_setsv(sv,&PL_sv_undef);
6823         return;
6824     }
6825 }
6826
6827 void
6828 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
6829                                                          SV const * const value)
6830 {
6831     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
6832
6833     PERL_UNUSED_ARG(rx);
6834     PERL_UNUSED_ARG(paren);
6835     PERL_UNUSED_ARG(value);
6836
6837     if (!PL_localizing)
6838         Perl_croak_no_modify();
6839 }
6840
6841 I32
6842 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
6843                               const I32 paren)
6844 {
6845     struct regexp *const rx = ReANY(r);
6846     I32 i;
6847     I32 s1, t1;
6848
6849     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
6850
6851     if (   paren == RX_BUFF_IDX_CARET_PREMATCH
6852         || paren == RX_BUFF_IDX_CARET_FULLMATCH
6853         || paren == RX_BUFF_IDX_CARET_POSTMATCH
6854     )
6855     {
6856         bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY);
6857         if (!keepcopy) {
6858             /* on something like
6859              *    $r = qr/.../;
6860              *    /$qr/p;
6861              * the KEEPCOPY is set on the PMOP rather than the regex */
6862             if (PL_curpm && r == PM_GETRE(PL_curpm))
6863                  keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY);
6864         }
6865         if (!keepcopy)
6866             goto warn_undef;
6867     }
6868
6869     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
6870     switch (paren) {
6871       case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
6872       case RX_BUFF_IDX_PREMATCH:       /* $` */
6873         if (rx->offs[0].start != -1) {
6874                         i = rx->offs[0].start;
6875                         if (i > 0) {
6876                                 s1 = 0;
6877                                 t1 = i;
6878                                 goto getlen;
6879                         }
6880             }
6881         return 0;
6882
6883       case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
6884       case RX_BUFF_IDX_POSTMATCH:       /* $' */
6885             if (rx->offs[0].end != -1) {
6886                         i = rx->sublen - rx->offs[0].end;
6887                         if (i > 0) {
6888                                 s1 = rx->offs[0].end;
6889                                 t1 = rx->sublen;
6890                                 goto getlen;
6891                         }
6892             }
6893         return 0;
6894
6895       default: /* $& / ${^MATCH}, $1, $2, ... */
6896             if (paren <= (I32)rx->nparens &&
6897             (s1 = rx->offs[paren].start) != -1 &&
6898             (t1 = rx->offs[paren].end) != -1)
6899             {
6900             i = t1 - s1;
6901             goto getlen;
6902         } else {
6903           warn_undef:
6904             if (ckWARN(WARN_UNINITIALIZED))
6905                 report_uninit((const SV *)sv);
6906             return 0;
6907         }
6908     }
6909   getlen:
6910     if (i > 0 && RXp_MATCH_UTF8(rx)) {
6911         const char * const s = rx->subbeg - rx->suboffset + s1;
6912         const U8 *ep;
6913         STRLEN el;
6914
6915         i = t1 - s1;
6916         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
6917                         i = el;
6918     }
6919     return i;
6920 }
6921
6922 SV*
6923 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
6924 {
6925     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
6926         PERL_UNUSED_ARG(rx);
6927         if (0)
6928             return NULL;
6929         else
6930             return newSVpvs("Regexp");
6931 }
6932
6933 /* Scans the name of a named buffer from the pattern.
6934  * If flags is REG_RSN_RETURN_NULL returns null.
6935  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
6936  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
6937  * to the parsed name as looked up in the RExC_paren_names hash.
6938  * If there is an error throws a vFAIL().. type exception.
6939  */
6940
6941 #define REG_RSN_RETURN_NULL    0
6942 #define REG_RSN_RETURN_NAME    1
6943 #define REG_RSN_RETURN_DATA    2
6944
6945 STATIC SV*
6946 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
6947 {
6948     char *name_start = RExC_parse;
6949
6950     PERL_ARGS_ASSERT_REG_SCAN_NAME;
6951
6952     if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
6953          /* skip IDFIRST by using do...while */
6954         if (UTF)
6955             do {
6956                 RExC_parse += UTF8SKIP(RExC_parse);
6957             } while (isWORDCHAR_utf8((U8*)RExC_parse));
6958         else
6959             do {
6960                 RExC_parse++;
6961             } while (isWORDCHAR(*RExC_parse));
6962     } else {
6963         RExC_parse++; /* so the <- from the vFAIL is after the offending character */
6964         vFAIL("Group name must start with a non-digit word character");
6965     }
6966     if ( flags ) {
6967         SV* sv_name
6968             = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
6969                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
6970         if ( flags == REG_RSN_RETURN_NAME)
6971             return sv_name;
6972         else if (flags==REG_RSN_RETURN_DATA) {
6973             HE *he_str = NULL;
6974             SV *sv_dat = NULL;
6975             if ( ! sv_name )      /* should not happen*/
6976                 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
6977             if (RExC_paren_names)
6978                 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
6979             if ( he_str )
6980                 sv_dat = HeVAL(he_str);
6981             if ( ! sv_dat )
6982                 vFAIL("Reference to nonexistent named group");
6983             return sv_dat;
6984         }
6985         else {
6986             Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
6987                        (unsigned long) flags);
6988         }
6989         assert(0); /* NOT REACHED */
6990     }
6991     return NULL;
6992 }
6993
6994 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
6995     int rem=(int)(RExC_end - RExC_parse);                       \
6996     int cut;                                                    \
6997     int num;                                                    \
6998     int iscut=0;                                                \
6999     if (rem>10) {                                               \
7000         rem=10;                                                 \
7001         iscut=1;                                                \
7002     }                                                           \
7003     cut=10-rem;                                                 \
7004     if (RExC_lastparse!=RExC_parse)                             \
7005         PerlIO_printf(Perl_debug_log," >%.*s%-*s",              \
7006             rem, RExC_parse,                                    \
7007             cut + 4,                                            \
7008             iscut ? "..." : "<"                                 \
7009         );                                                      \
7010     else                                                        \
7011         PerlIO_printf(Perl_debug_log,"%16s","");                \
7012                                                                 \
7013     if (SIZE_ONLY)                                              \
7014        num = RExC_size + 1;                                     \
7015     else                                                        \
7016        num=REG_NODE_NUM(RExC_emit);                             \
7017     if (RExC_lastnum!=num)                                      \
7018        PerlIO_printf(Perl_debug_log,"|%4d",num);                \
7019     else                                                        \
7020        PerlIO_printf(Perl_debug_log,"|%4s","");                 \
7021     PerlIO_printf(Perl_debug_log,"|%*s%-4s",                    \
7022         (int)((depth*2)), "",                                   \
7023         (funcname)                                              \
7024     );                                                          \
7025     RExC_lastnum=num;                                           \
7026     RExC_lastparse=RExC_parse;                                  \
7027 })
7028
7029
7030
7031 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
7032     DEBUG_PARSE_MSG((funcname));                            \
7033     PerlIO_printf(Perl_debug_log,"%4s","\n");               \
7034 })
7035 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({           \
7036     DEBUG_PARSE_MSG((funcname));                            \
7037     PerlIO_printf(Perl_debug_log,fmt "\n",args);               \
7038 })
7039
7040 /* This section of code defines the inversion list object and its methods.  The
7041  * interfaces are highly subject to change, so as much as possible is static to
7042  * this file.  An inversion list is here implemented as a malloc'd C UV array
7043  * as an SVt_INVLIST scalar.
7044  *
7045  * An inversion list for Unicode is an array of code points, sorted by ordinal
7046  * number.  The zeroth element is the first code point in the list.  The 1th
7047  * element is the first element beyond that not in the list.  In other words,
7048  * the first range is
7049  *  invlist[0]..(invlist[1]-1)
7050  * The other ranges follow.  Thus every element whose index is divisible by two
7051  * marks the beginning of a range that is in the list, and every element not
7052  * divisible by two marks the beginning of a range not in the list.  A single
7053  * element inversion list that contains the single code point N generally
7054  * consists of two elements
7055  *  invlist[0] == N
7056  *  invlist[1] == N+1
7057  * (The exception is when N is the highest representable value on the
7058  * machine, in which case the list containing just it would be a single
7059  * element, itself.  By extension, if the last range in the list extends to
7060  * infinity, then the first element of that range will be in the inversion list
7061  * at a position that is divisible by two, and is the final element in the
7062  * list.)
7063  * Taking the complement (inverting) an inversion list is quite simple, if the
7064  * first element is 0, remove it; otherwise add a 0 element at the beginning.
7065  * This implementation reserves an element at the beginning of each inversion
7066  * list to always contain 0; there is an additional flag in the header which
7067  * indicates if the list begins at the 0, or is offset to begin at the next
7068  * element.
7069  *
7070  * More about inversion lists can be found in "Unicode Demystified"
7071  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
7072  * More will be coming when functionality is added later.
7073  *
7074  * The inversion list data structure is currently implemented as an SV pointing
7075  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
7076  * array of UV whose memory management is automatically handled by the existing
7077  * facilities for SV's.
7078  *
7079  * Some of the methods should always be private to the implementation, and some
7080  * should eventually be made public */
7081
7082 /* The header definitions are in F<inline_invlist.c> */
7083
7084 PERL_STATIC_INLINE UV*
7085 S__invlist_array_init(pTHX_ SV* const invlist, const bool will_have_0)
7086 {
7087     /* Returns a pointer to the first element in the inversion list's array.
7088      * This is called upon initialization of an inversion list.  Where the
7089      * array begins depends on whether the list has the code point U+0000 in it
7090      * or not.  The other parameter tells it whether the code that follows this
7091      * call is about to put a 0 in the inversion list or not.  The first
7092      * element is either the element reserved for 0, if TRUE, or the element
7093      * after it, if FALSE */
7094
7095     bool* offset = get_invlist_offset_addr(invlist);
7096     UV* zero_addr = (UV *) SvPVX(invlist);
7097
7098     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
7099
7100     /* Must be empty */
7101     assert(! _invlist_len(invlist));
7102
7103     *zero_addr = 0;
7104
7105     /* 1^1 = 0; 1^0 = 1 */
7106     *offset = 1 ^ will_have_0;
7107     return zero_addr + *offset;
7108 }
7109
7110 PERL_STATIC_INLINE UV*
7111 S_invlist_array(pTHX_ SV* const invlist)
7112 {
7113     /* Returns the pointer to the inversion list's array.  Every time the
7114      * length changes, this needs to be called in case malloc or realloc moved
7115      * it */
7116
7117     PERL_ARGS_ASSERT_INVLIST_ARRAY;
7118
7119     /* Must not be empty.  If these fail, you probably didn't check for <len>
7120      * being non-zero before trying to get the array */
7121     assert(_invlist_len(invlist));
7122
7123     /* The very first element always contains zero, The array begins either
7124      * there, or if the inversion list is offset, at the element after it.
7125      * The offset header field determines which; it contains 0 or 1 to indicate
7126      * how much additionally to add */
7127     assert(0 == *(SvPVX(invlist)));
7128     return ((UV *) SvPVX(invlist) + *get_invlist_offset_addr(invlist));
7129 }
7130
7131 PERL_STATIC_INLINE void
7132 S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset)
7133 {
7134     /* Sets the current number of elements stored in the inversion list.
7135      * Updates SvCUR correspondingly */
7136
7137     PERL_ARGS_ASSERT_INVLIST_SET_LEN;
7138
7139     assert(SvTYPE(invlist) == SVt_INVLIST);
7140
7141     SvCUR_set(invlist,
7142               (len == 0)
7143                ? 0
7144                : TO_INTERNAL_SIZE(len + offset));
7145     assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist));
7146 }
7147
7148 PERL_STATIC_INLINE IV*
7149 S_get_invlist_previous_index_addr(pTHX_ SV* invlist)
7150 {
7151     /* Return the address of the IV that is reserved to hold the cached index
7152      * */
7153
7154     PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
7155
7156     assert(SvTYPE(invlist) == SVt_INVLIST);
7157
7158     return &(((XINVLIST*) SvANY(invlist))->prev_index);
7159 }
7160
7161 PERL_STATIC_INLINE IV
7162 S_invlist_previous_index(pTHX_ SV* const invlist)
7163 {
7164     /* Returns cached index of previous search */
7165
7166     PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
7167
7168     return *get_invlist_previous_index_addr(invlist);
7169 }
7170
7171 PERL_STATIC_INLINE void
7172 S_invlist_set_previous_index(pTHX_ SV* const invlist, const IV index)
7173 {
7174     /* Caches <index> for later retrieval */
7175
7176     PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
7177
7178     assert(index == 0 || index < (int) _invlist_len(invlist));
7179
7180     *get_invlist_previous_index_addr(invlist) = index;
7181 }
7182
7183 PERL_STATIC_INLINE UV
7184 S_invlist_max(pTHX_ SV* const invlist)
7185 {
7186     /* Returns the maximum number of elements storable in the inversion list's
7187      * array, without having to realloc() */
7188
7189     PERL_ARGS_ASSERT_INVLIST_MAX;
7190
7191     assert(SvTYPE(invlist) == SVt_INVLIST);
7192
7193     /* Assumes worst case, in which the 0 element is not counted in the
7194      * inversion list, so subtracts 1 for that */
7195     return SvLEN(invlist) == 0  /* This happens under _new_invlist_C_array */
7196            ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1
7197            : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1;
7198 }
7199
7200 #ifndef PERL_IN_XSUB_RE
7201 SV*
7202 Perl__new_invlist(pTHX_ IV initial_size)
7203 {
7204
7205     /* Return a pointer to a newly constructed inversion list, with enough
7206      * space to store 'initial_size' elements.  If that number is negative, a
7207      * system default is used instead */
7208
7209     SV* new_list;
7210
7211     if (initial_size < 0) {
7212         initial_size = 10;
7213     }
7214
7215     /* Allocate the initial space */
7216     new_list = newSV_type(SVt_INVLIST);
7217
7218     /* First 1 is in case the zero element isn't in the list; second 1 is for
7219      * trailing NUL */
7220     SvGROW(new_list, TO_INTERNAL_SIZE(initial_size + 1) + 1);
7221     invlist_set_len(new_list, 0, 0);
7222
7223     /* Force iterinit() to be used to get iteration to work */
7224     *get_invlist_iter_addr(new_list) = (STRLEN) UV_MAX;
7225
7226     *get_invlist_previous_index_addr(new_list) = 0;
7227
7228     return new_list;
7229 }
7230 #endif
7231
7232 STATIC SV*
7233 S__new_invlist_C_array(pTHX_ const UV* const list)
7234 {
7235     /* Return a pointer to a newly constructed inversion list, initialized to
7236      * point to <list>, which has to be in the exact correct inversion list
7237      * form, including internal fields.  Thus this is a dangerous routine that
7238      * should not be used in the wrong hands.  The passed in 'list' contains
7239      * several header fields at the beginning that are not part of the
7240      * inversion list body proper */
7241
7242     const STRLEN length = (STRLEN) list[0];
7243     const UV version_id =          list[1];
7244     const bool offset   =    cBOOL(list[2]);
7245 #define HEADER_LENGTH 3
7246     /* If any of the above changes in any way, you must change HEADER_LENGTH
7247      * (if appropriate) and regenerate INVLIST_VERSION_ID by running
7248      *      perl -E 'say int(rand 2**31-1)'
7249      */
7250 #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and
7251                                         data structure type, so that one being
7252                                         passed in can be validated to be an
7253                                         inversion list of the correct vintage.
7254                                        */
7255
7256     SV* invlist = newSV_type(SVt_INVLIST);
7257
7258     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
7259
7260     if (version_id != INVLIST_VERSION_ID) {
7261         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
7262     }
7263
7264     /* The generated array passed in includes header elements that aren't part
7265      * of the list proper, so start it just after them */
7266     SvPV_set(invlist, (char *) (list + HEADER_LENGTH));
7267
7268     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
7269                                shouldn't touch it */
7270
7271     *(get_invlist_offset_addr(invlist)) = offset;
7272
7273     /* The 'length' passed to us is the physical number of elements in the
7274      * inversion list.  But if there is an offset the logical number is one
7275      * less than that */
7276     invlist_set_len(invlist, length  - offset, offset);
7277
7278     invlist_set_previous_index(invlist, 0);
7279
7280     /* Initialize the iteration pointer. */
7281     invlist_iterfinish(invlist);
7282
7283     return invlist;
7284 }
7285
7286 STATIC void
7287 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
7288 {
7289     /* Grow the maximum size of an inversion list */
7290
7291     PERL_ARGS_ASSERT_INVLIST_EXTEND;
7292
7293     assert(SvTYPE(invlist) == SVt_INVLIST);
7294
7295     /* Add one to account for the zero element at the beginning which may not
7296      * be counted by the calling parameters */
7297     SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1));
7298 }
7299
7300 PERL_STATIC_INLINE void
7301 S_invlist_trim(pTHX_ SV* const invlist)
7302 {
7303     PERL_ARGS_ASSERT_INVLIST_TRIM;
7304
7305     assert(SvTYPE(invlist) == SVt_INVLIST);
7306
7307     /* Change the length of the inversion list to how many entries it currently
7308      * has */
7309     SvPV_shrink_to_cur((SV *) invlist);
7310 }
7311
7312 #define _invlist_union_complement_2nd(a, b, output) _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
7313
7314 STATIC void
7315 S__append_range_to_invlist(pTHX_ SV* const invlist, const UV start, const UV end)
7316 {
7317    /* Subject to change or removal.  Append the range from 'start' to 'end' at
7318     * the end of the inversion list.  The range must be above any existing
7319     * ones. */
7320
7321     UV* array;
7322     UV max = invlist_max(invlist);
7323     UV len = _invlist_len(invlist);
7324     bool offset;
7325
7326     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
7327
7328     if (len == 0) { /* Empty lists must be initialized */
7329         offset = start != 0;
7330         array = _invlist_array_init(invlist, ! offset);
7331     }
7332     else {
7333         /* Here, the existing list is non-empty. The current max entry in the
7334          * list is generally the first value not in the set, except when the
7335          * set extends to the end of permissible values, in which case it is
7336          * the first entry in that final set, and so this call is an attempt to
7337          * append out-of-order */
7338
7339         UV final_element = len - 1;
7340         array = invlist_array(invlist);
7341         if (array[final_element] > start
7342             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
7343         {
7344             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",
7345                        array[final_element], start,
7346                        ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
7347         }
7348
7349         /* Here, it is a legal append.  If the new range begins with the first
7350          * value not in the set, it is extending the set, so the new first
7351          * value not in the set is one greater than the newly extended range.
7352          * */
7353         offset = *get_invlist_offset_addr(invlist);
7354         if (array[final_element] == start) {
7355             if (end != UV_MAX) {
7356                 array[final_element] = end + 1;
7357             }
7358             else {
7359                 /* But if the end is the maximum representable on the machine,
7360                  * just let the range that this would extend to have no end */
7361                 invlist_set_len(invlist, len - 1, offset);
7362             }
7363             return;
7364         }
7365     }
7366
7367     /* Here the new range doesn't extend any existing set.  Add it */
7368
7369     len += 2;   /* Includes an element each for the start and end of range */
7370
7371     /* If wll overflow the existing space, extend, which may cause the array to
7372      * be moved */
7373     if (max < len) {
7374         invlist_extend(invlist, len);
7375
7376         /* Have to set len here to avoid assert failure in invlist_array() */
7377         invlist_set_len(invlist, len, offset);
7378
7379         array = invlist_array(invlist);
7380     }
7381     else {
7382         invlist_set_len(invlist, len, offset);
7383     }
7384
7385     /* The next item on the list starts the range, the one after that is
7386      * one past the new range.  */
7387     array[len - 2] = start;
7388     if (end != UV_MAX) {
7389         array[len - 1] = end + 1;
7390     }
7391     else {
7392         /* But if the end is the maximum representable on the machine, just let
7393          * the range have no end */
7394         invlist_set_len(invlist, len - 1, offset);
7395     }
7396 }
7397
7398 #ifndef PERL_IN_XSUB_RE
7399
7400 IV
7401 Perl__invlist_search(pTHX_ SV* const invlist, const UV cp)
7402 {
7403     /* Searches the inversion list for the entry that contains the input code
7404      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
7405      * return value is the index into the list's array of the range that
7406      * contains <cp> */
7407
7408     IV low = 0;
7409     IV mid;
7410     IV high = _invlist_len(invlist);
7411     const IV highest_element = high - 1;
7412     const UV* array;
7413
7414     PERL_ARGS_ASSERT__INVLIST_SEARCH;
7415
7416     /* If list is empty, return failure. */
7417     if (high == 0) {
7418         return -1;
7419     }
7420
7421     /* (We can't get the array unless we know the list is non-empty) */
7422     array = invlist_array(invlist);
7423
7424     mid = invlist_previous_index(invlist);
7425     assert(mid >=0 && mid <= highest_element);
7426
7427     /* <mid> contains the cache of the result of the previous call to this
7428      * function (0 the first time).  See if this call is for the same result,
7429      * or if it is for mid-1.  This is under the theory that calls to this
7430      * function will often be for related code points that are near each other.
7431      * And benchmarks show that caching gives better results.  We also test
7432      * here if the code point is within the bounds of the list.  These tests
7433      * replace others that would have had to be made anyway to make sure that
7434      * the array bounds were not exceeded, and these give us extra information
7435      * at the same time */
7436     if (cp >= array[mid]) {
7437         if (cp >= array[highest_element]) {
7438             return highest_element;
7439         }
7440
7441         /* Here, array[mid] <= cp < array[highest_element].  This means that
7442          * the final element is not the answer, so can exclude it; it also
7443          * means that <mid> is not the final element, so can refer to 'mid + 1'
7444          * safely */
7445         if (cp < array[mid + 1]) {
7446             return mid;
7447         }
7448         high--;
7449         low = mid + 1;
7450     }
7451     else { /* cp < aray[mid] */
7452         if (cp < array[0]) { /* Fail if outside the array */
7453             return -1;
7454         }
7455         high = mid;
7456         if (cp >= array[mid - 1]) {
7457             goto found_entry;
7458         }
7459     }
7460
7461     /* Binary search.  What we are looking for is <i> such that
7462      *  array[i] <= cp < array[i+1]
7463      * The loop below converges on the i+1.  Note that there may not be an
7464      * (i+1)th element in the array, and things work nonetheless */
7465     while (low < high) {
7466         mid = (low + high) / 2;
7467         assert(mid <= highest_element);
7468         if (array[mid] <= cp) { /* cp >= array[mid] */
7469             low = mid + 1;
7470
7471             /* We could do this extra test to exit the loop early.
7472             if (cp < array[low]) {
7473                 return mid;
7474             }
7475             */
7476         }
7477         else { /* cp < array[mid] */
7478             high = mid;
7479         }
7480     }
7481
7482   found_entry:
7483     high--;
7484     invlist_set_previous_index(invlist, high);
7485     return high;
7486 }
7487
7488 void
7489 Perl__invlist_populate_swatch(pTHX_ SV* const invlist, const UV start, const UV end, U8* swatch)
7490 {
7491     /* populates a swatch of a swash the same way swatch_get() does in utf8.c,
7492      * but is used when the swash has an inversion list.  This makes this much
7493      * faster, as it uses a binary search instead of a linear one.  This is
7494      * intimately tied to that function, and perhaps should be in utf8.c,
7495      * except it is intimately tied to inversion lists as well.  It assumes
7496      * that <swatch> is all 0's on input */
7497
7498     UV current = start;
7499     const IV len = _invlist_len(invlist);
7500     IV i;
7501     const UV * array;
7502
7503     PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
7504
7505     if (len == 0) { /* Empty inversion list */
7506         return;
7507     }
7508
7509     array = invlist_array(invlist);
7510
7511     /* Find which element it is */
7512     i = _invlist_search(invlist, start);
7513
7514     /* We populate from <start> to <end> */
7515     while (current < end) {
7516         UV upper;
7517
7518         /* The inversion list gives the results for every possible code point
7519          * after the first one in the list.  Only those ranges whose index is
7520          * even are ones that the inversion list matches.  For the odd ones,
7521          * and if the initial code point is not in the list, we have to skip
7522          * forward to the next element */
7523         if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
7524             i++;
7525             if (i >= len) { /* Finished if beyond the end of the array */
7526                 return;
7527             }
7528             current = array[i];
7529             if (current >= end) {   /* Finished if beyond the end of what we
7530                                        are populating */
7531                 if (LIKELY(end < UV_MAX)) {
7532                     return;
7533                 }
7534
7535                 /* We get here when the upper bound is the maximum
7536                  * representable on the machine, and we are looking for just
7537                  * that code point.  Have to special case it */
7538                 i = len;
7539                 goto join_end_of_list;
7540             }
7541         }
7542         assert(current >= start);
7543
7544         /* The current range ends one below the next one, except don't go past
7545          * <end> */
7546         i++;
7547         upper = (i < len && array[i] < end) ? array[i] : end;
7548
7549         /* Here we are in a range that matches.  Populate a bit in the 3-bit U8
7550          * for each code point in it */
7551         for (; current < upper; current++) {
7552             const STRLEN offset = (STRLEN)(current - start);
7553             swatch[offset >> 3] |= 1 << (offset & 7);
7554         }
7555
7556     join_end_of_list:
7557
7558         /* Quit if at the end of the list */
7559         if (i >= len) {
7560
7561             /* But first, have to deal with the highest possible code point on
7562              * the platform.  The previous code assumes that <end> is one
7563              * beyond where we want to populate, but that is impossible at the
7564              * platform's infinity, so have to handle it specially */
7565             if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
7566             {
7567                 const STRLEN offset = (STRLEN)(end - start);
7568                 swatch[offset >> 3] |= 1 << (offset & 7);
7569             }
7570             return;
7571         }
7572
7573         /* Advance to the next range, which will be for code points not in the
7574          * inversion list */
7575         current = array[i];
7576     }
7577
7578     return;
7579 }
7580
7581 void
7582 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, const bool complement_b, SV** output)
7583 {
7584     /* Take the union of two inversion lists and point <output> to it.  *output
7585      * SHOULD BE DEFINED upon input, and if it points to one of the two lists,
7586      * the reference count to that list will be decremented.  The first list,
7587      * <a>, may be NULL, in which case a copy of the second list is returned.
7588      * If <complement_b> is TRUE, the union is taken of the complement
7589      * (inversion) of <b> instead of b itself.
7590      *
7591      * The basis for this comes from "Unicode Demystified" Chapter 13 by
7592      * Richard Gillam, published by Addison-Wesley, and explained at some
7593      * length there.  The preface says to incorporate its examples into your
7594      * code at your own risk.
7595      *
7596      * The algorithm is like a merge sort.
7597      *
7598      * XXX A potential performance improvement is to keep track as we go along
7599      * if only one of the inputs contributes to the result, meaning the other
7600      * is a subset of that one.  In that case, we can skip the final copy and
7601      * return the larger of the input lists, but then outside code might need
7602      * to keep track of whether to free the input list or not */
7603
7604     const UV* array_a;    /* a's array */
7605     const UV* array_b;
7606     UV len_a;       /* length of a's array */
7607     UV len_b;
7608
7609     SV* u;                      /* the resulting union */
7610     UV* array_u;
7611     UV len_u;
7612
7613     UV i_a = 0;             /* current index into a's array */
7614     UV i_b = 0;
7615     UV i_u = 0;
7616
7617     /* running count, as explained in the algorithm source book; items are
7618      * stopped accumulating and are output when the count changes to/from 0.
7619      * The count is incremented when we start a range that's in the set, and
7620      * decremented when we start a range that's not in the set.  So its range
7621      * is 0 to 2.  Only when the count is zero is something not in the set.
7622      */
7623     UV count = 0;
7624
7625     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
7626     assert(a != b);
7627
7628     /* If either one is empty, the union is the other one */
7629     if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
7630         if (*output == a) {
7631             if (a != NULL) {
7632                 SvREFCNT_dec_NN(a);
7633             }
7634         }
7635         if (*output != b) {
7636             *output = invlist_clone(b);
7637             if (complement_b) {
7638                 _invlist_invert(*output);
7639             }
7640         } /* else *output already = b; */
7641         return;
7642     }
7643     else if ((len_b = _invlist_len(b)) == 0) {
7644         if (*output == b) {
7645             SvREFCNT_dec_NN(b);
7646         }
7647
7648         /* The complement of an empty list is a list that has everything in it,
7649          * so the union with <a> includes everything too */
7650         if (complement_b) {
7651             if (a == *output) {
7652                 SvREFCNT_dec_NN(a);
7653             }
7654             *output = _new_invlist(1);
7655             _append_range_to_invlist(*output, 0, UV_MAX);
7656         }
7657         else if (*output != a) {
7658             *output = invlist_clone(a);
7659         }
7660         /* else *output already = a; */
7661         return;
7662     }
7663
7664     /* Here both lists exist and are non-empty */
7665     array_a = invlist_array(a);
7666     array_b = invlist_array(b);
7667
7668     /* If are to take the union of 'a' with the complement of b, set it
7669      * up so are looking at b's complement. */
7670     if (complement_b) {
7671
7672         /* To complement, we invert: if the first element is 0, remove it.  To
7673          * do this, we just pretend the array starts one later */
7674         if (array_b[0] == 0) {
7675             array_b++;
7676             len_b--;
7677         }
7678         else {
7679
7680             /* But if the first element is not zero, we pretend the list starts
7681              * at the 0 that is always stored immediately before the array. */
7682             array_b--;
7683             len_b++;
7684         }
7685     }
7686
7687     /* Size the union for the worst case: that the sets are completely
7688      * disjoint */
7689     u = _new_invlist(len_a + len_b);
7690
7691     /* Will contain U+0000 if either component does */
7692     array_u = _invlist_array_init(u, (len_a > 0 && array_a[0] == 0)
7693                                       || (len_b > 0 && array_b[0] == 0));
7694
7695     /* Go through each list item by item, stopping when exhausted one of
7696      * them */
7697     while (i_a < len_a && i_b < len_b) {
7698         UV cp;      /* The element to potentially add to the union's array */
7699         bool cp_in_set;   /* is it in the the input list's set or not */
7700
7701         /* We need to take one or the other of the two inputs for the union.
7702          * Since we are merging two sorted lists, we take the smaller of the
7703          * next items.  In case of a tie, we take the one that is in its set
7704          * first.  If we took one not in the set first, it would decrement the
7705          * count, possibly to 0 which would cause it to be output as ending the
7706          * range, and the next time through we would take the same number, and
7707          * output it again as beginning the next range.  By doing it the
7708          * opposite way, there is no possibility that the count will be
7709          * momentarily decremented to 0, and thus the two adjoining ranges will
7710          * be seamlessly merged.  (In a tie and both are in the set or both not
7711          * in the set, it doesn't matter which we take first.) */
7712         if (array_a[i_a] < array_b[i_b]
7713             || (array_a[i_a] == array_b[i_b]
7714                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
7715         {
7716             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
7717             cp= array_a[i_a++];
7718         }
7719         else {
7720             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
7721             cp = array_b[i_b++];
7722         }
7723
7724         /* Here, have chosen which of the two inputs to look at.  Only output
7725          * if the running count changes to/from 0, which marks the
7726          * beginning/end of a range in that's in the set */
7727         if (cp_in_set) {
7728             if (count == 0) {
7729                 array_u[i_u++] = cp;
7730             }
7731             count++;
7732         }
7733         else {
7734             count--;
7735             if (count == 0) {
7736                 array_u[i_u++] = cp;
7737             }
7738         }
7739     }
7740
7741     /* Here, we are finished going through at least one of the lists, which
7742      * means there is something remaining in at most one.  We check if the list
7743      * that hasn't been exhausted is positioned such that we are in the middle
7744      * of a range in its set or not.  (i_a and i_b point to the element beyond
7745      * the one we care about.) If in the set, we decrement 'count'; if 0, there
7746      * is potentially more to output.
7747      * There are four cases:
7748      *  1) Both weren't in their sets, count is 0, and remains 0.  What's left
7749      *     in the union is entirely from the non-exhausted set.
7750      *  2) Both were in their sets, count is 2.  Nothing further should
7751      *     be output, as everything that remains will be in the exhausted
7752      *     list's set, hence in the union; decrementing to 1 but not 0 insures
7753      *     that
7754      *  3) the exhausted was in its set, non-exhausted isn't, count is 1.
7755      *     Nothing further should be output because the union includes
7756      *     everything from the exhausted set.  Not decrementing ensures that.
7757      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1;
7758      *     decrementing to 0 insures that we look at the remainder of the
7759      *     non-exhausted set */
7760     if ((i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
7761         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
7762     {
7763         count--;
7764     }
7765
7766     /* The final length is what we've output so far, plus what else is about to
7767      * be output.  (If 'count' is non-zero, then the input list we exhausted
7768      * has everything remaining up to the machine's limit in its set, and hence
7769      * in the union, so there will be no further output. */
7770     len_u = i_u;
7771     if (count == 0) {
7772         /* At most one of the subexpressions will be non-zero */
7773         len_u += (len_a - i_a) + (len_b - i_b);
7774     }
7775
7776     /* Set result to final length, which can change the pointer to array_u, so
7777      * re-find it */
7778     if (len_u != _invlist_len(u)) {
7779         invlist_set_len(u, len_u, *get_invlist_offset_addr(u));
7780         invlist_trim(u);
7781         array_u = invlist_array(u);
7782     }
7783
7784     /* When 'count' is 0, the list that was exhausted (if one was shorter than
7785      * the other) ended with everything above it not in its set.  That means
7786      * that the remaining part of the union is precisely the same as the
7787      * non-exhausted list, so can just copy it unchanged.  (If both list were
7788      * exhausted at the same time, then the operations below will be both 0.)
7789      */
7790     if (count == 0) {
7791         IV copy_count; /* At most one will have a non-zero copy count */
7792         if ((copy_count = len_a - i_a) > 0) {
7793             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
7794         }
7795         else if ((copy_count = len_b - i_b) > 0) {
7796             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
7797         }
7798     }
7799
7800     /*  We may be removing a reference to one of the inputs */
7801     if (a == *output || b == *output) {
7802         assert(! invlist_is_iterating(*output));
7803         SvREFCNT_dec_NN(*output);
7804     }
7805
7806     *output = u;
7807     return;
7808 }
7809
7810 void
7811 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, const bool complement_b, SV** i)
7812 {
7813     /* Take the intersection of two inversion lists and point <i> to it.  *i
7814      * SHOULD BE DEFINED upon input, and if it points to one of the two lists,
7815      * the reference count to that list will be decremented.
7816      * If <complement_b> is TRUE, the result will be the intersection of <a>
7817      * and the complement (or inversion) of <b> instead of <b> directly.
7818      *
7819      * The basis for this comes from "Unicode Demystified" Chapter 13 by
7820      * Richard Gillam, published by Addison-Wesley, and explained at some
7821      * length there.  The preface says to incorporate its examples into your
7822      * code at your own risk.  In fact, it had bugs
7823      *
7824      * The algorithm is like a merge sort, and is essentially the same as the
7825      * union above
7826      */
7827
7828     const UV* array_a;          /* a's array */
7829     const UV* array_b;
7830     UV len_a;   /* length of a's array */
7831     UV len_b;
7832
7833     SV* r;                   /* the resulting intersection */
7834     UV* array_r;
7835     UV len_r;
7836
7837     UV i_a = 0;             /* current index into a's array */
7838     UV i_b = 0;
7839     UV i_r = 0;
7840
7841     /* running count, as explained in the algorithm source book; items are
7842      * stopped accumulating and are output when the count changes to/from 2.
7843      * The count is incremented when we start a range that's in the set, and
7844      * decremented when we start a range that's not in the set.  So its range
7845      * is 0 to 2.  Only when the count is 2 is something in the intersection.
7846      */
7847     UV count = 0;
7848
7849     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
7850     assert(a != b);
7851
7852     /* Special case if either one is empty */
7853     len_a = (a == NULL) ? 0 : _invlist_len(a);
7854     if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
7855
7856         if (len_a != 0 && complement_b) {
7857
7858             /* Here, 'a' is not empty, therefore from the above 'if', 'b' must
7859              * be empty.  Here, also we are using 'b's complement, which hence
7860              * must be every possible code point.  Thus the intersection is
7861              * simply 'a'. */
7862             if (*i != a) {
7863                 if (*i == b) {
7864                     SvREFCNT_dec_NN(b);
7865                 }
7866
7867                 *i = invlist_clone(a);
7868             }
7869             /* else *i is already 'a' */
7870             return;
7871         }
7872
7873         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
7874          * intersection must be empty */
7875         if (*i == a) {
7876             SvREFCNT_dec_NN(a);
7877         }
7878         else if (*i == b) {
7879             SvREFCNT_dec_NN(b);
7880         }
7881         *i = _new_invlist(0);
7882         return;
7883     }
7884
7885     /* Here both lists exist and are non-empty */
7886     array_a = invlist_array(a);
7887     array_b = invlist_array(b);
7888
7889     /* If are to take the intersection of 'a' with the complement of b, set it
7890      * up so are looking at b's complement. */
7891     if (complement_b) {
7892
7893         /* To complement, we invert: if the first element is 0, remove it.  To
7894          * do this, we just pretend the array starts one later */
7895         if (array_b[0] == 0) {
7896             array_b++;
7897             len_b--;
7898         }
7899         else {
7900
7901             /* But if the first element is not zero, we pretend the list starts
7902              * at the 0 that is always stored immediately before the array. */
7903             array_b--;
7904             len_b++;
7905         }
7906     }
7907
7908     /* Size the intersection for the worst case: that the intersection ends up
7909      * fragmenting everything to be completely disjoint */
7910     r= _new_invlist(len_a + len_b);
7911
7912     /* Will contain U+0000 iff both components do */
7913     array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
7914                                      && len_b > 0 && array_b[0] == 0);
7915
7916     /* Go through each list item by item, stopping when exhausted one of
7917      * them */
7918     while (i_a < len_a && i_b < len_b) {
7919         UV cp;      /* The element to potentially add to the intersection's
7920                        array */
7921         bool cp_in_set; /* Is it in the input list's set or not */
7922
7923         /* We need to take one or the other of the two inputs for the
7924          * intersection.  Since we are merging two sorted lists, we take the
7925          * smaller of the next items.  In case of a tie, we take the one that
7926          * is not in its set first (a difference from the union algorithm).  If
7927          * we took one in the set first, it would increment the count, possibly
7928          * to 2 which would cause it to be output as starting a range in the
7929          * intersection, and the next time through we would take that same
7930          * number, and output it again as ending the set.  By doing it the
7931          * opposite of this, there is no possibility that the count will be
7932          * momentarily incremented to 2.  (In a tie and both are in the set or
7933          * both not in the set, it doesn't matter which we take first.) */
7934         if (array_a[i_a] < array_b[i_b]
7935             || (array_a[i_a] == array_b[i_b]
7936                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
7937         {
7938             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
7939             cp= array_a[i_a++];
7940         }
7941         else {
7942             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
7943             cp= array_b[i_b++];
7944         }
7945
7946         /* Here, have chosen which of the two inputs to look at.  Only output
7947          * if the running count changes to/from 2, which marks the
7948          * beginning/end of a range that's in the intersection */
7949         if (cp_in_set) {
7950             count++;
7951             if (count == 2) {
7952                 array_r[i_r++] = cp;
7953             }
7954         }
7955         else {
7956             if (count == 2) {
7957                 array_r[i_r++] = cp;
7958             }
7959             count--;
7960         }
7961     }
7962
7963     /* Here, we are finished going through at least one of the lists, which
7964      * means there is something remaining in at most one.  We check if the list
7965      * that has been exhausted is positioned such that we are in the middle
7966      * of a range in its set or not.  (i_a and i_b point to elements 1 beyond
7967      * the ones we care about.)  There are four cases:
7968      *  1) Both weren't in their sets, count is 0, and remains 0.  There's
7969      *     nothing left in the intersection.
7970      *  2) Both were in their sets, count is 2 and perhaps is incremented to
7971      *     above 2.  What should be output is exactly that which is in the
7972      *     non-exhausted set, as everything it has is also in the intersection
7973      *     set, and everything it doesn't have can't be in the intersection
7974      *  3) The exhausted was in its set, non-exhausted isn't, count is 1, and
7975      *     gets incremented to 2.  Like the previous case, the intersection is
7976      *     everything that remains in the non-exhausted set.
7977      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1, and
7978      *     remains 1.  And the intersection has nothing more. */
7979     if ((i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
7980         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
7981     {
7982         count++;
7983     }
7984
7985     /* The final length is what we've output so far plus what else is in the
7986      * intersection.  At most one of the subexpressions below will be non-zero */
7987     len_r = i_r;
7988     if (count >= 2) {
7989         len_r += (len_a - i_a) + (len_b - i_b);
7990     }
7991
7992     /* Set result to final length, which can change the pointer to array_r, so
7993      * re-find it */
7994     if (len_r != _invlist_len(r)) {
7995         invlist_set_len(r, len_r, *get_invlist_offset_addr(r));
7996         invlist_trim(r);
7997         array_r = invlist_array(r);
7998     }
7999
8000     /* Finish outputting any remaining */
8001     if (count >= 2) { /* At most one will have a non-zero copy count */
8002         IV copy_count;
8003         if ((copy_count = len_a - i_a) > 0) {
8004             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
8005         }
8006         else if ((copy_count = len_b - i_b) > 0) {
8007             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
8008         }
8009     }
8010
8011     /*  We may be removing a reference to one of the inputs */
8012     if (a == *i || b == *i) {
8013         assert(! invlist_is_iterating(*i));
8014         SvREFCNT_dec_NN(*i);
8015     }
8016
8017     *i = r;
8018     return;
8019 }
8020
8021 SV*
8022 Perl__add_range_to_invlist(pTHX_ SV* invlist, const UV start, const UV end)
8023 {
8024     /* Add the range from 'start' to 'end' inclusive to the inversion list's
8025      * set.  A pointer to the inversion list is returned.  This may actually be
8026      * a new list, in which case the passed in one has been destroyed.  The
8027      * passed in inversion list can be NULL, in which case a new one is created
8028      * with just the one range in it */
8029
8030     SV* range_invlist;
8031     UV len;
8032
8033     if (invlist == NULL) {
8034         invlist = _new_invlist(2);
8035         len = 0;
8036     }
8037     else {
8038         len = _invlist_len(invlist);
8039     }
8040
8041     /* If comes after the final entry actually in the list, can just append it
8042      * to the end, */
8043     if (len == 0
8044         || (! ELEMENT_RANGE_MATCHES_INVLIST(len - 1)
8045             && start >= invlist_array(invlist)[len - 1]))
8046     {
8047         _append_range_to_invlist(invlist, start, end);
8048         return invlist;
8049     }
8050
8051     /* Here, can't just append things, create and return a new inversion list
8052      * which is the union of this range and the existing inversion list */
8053     range_invlist = _new_invlist(2);
8054     _append_range_to_invlist(range_invlist, start, end);
8055
8056     _invlist_union(invlist, range_invlist, &invlist);
8057
8058     /* The temporary can be freed */
8059     SvREFCNT_dec_NN(range_invlist);
8060
8061     return invlist;
8062 }
8063
8064 #endif
8065
8066 PERL_STATIC_INLINE SV*
8067 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
8068     return _add_range_to_invlist(invlist, cp, cp);
8069 }
8070
8071 #ifndef PERL_IN_XSUB_RE
8072 void
8073 Perl__invlist_invert(pTHX_ SV* const invlist)
8074 {
8075     /* Complement the input inversion list.  This adds a 0 if the list didn't
8076      * have a zero; removes it otherwise.  As described above, the data
8077      * structure is set up so that this is very efficient */
8078
8079     PERL_ARGS_ASSERT__INVLIST_INVERT;
8080
8081     assert(! invlist_is_iterating(invlist));
8082
8083     /* The inverse of matching nothing is matching everything */
8084     if (_invlist_len(invlist) == 0) {
8085         _append_range_to_invlist(invlist, 0, UV_MAX);
8086         return;
8087     }
8088
8089     *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist);
8090 }
8091
8092 void
8093 Perl__invlist_invert_prop(pTHX_ SV* const invlist)
8094 {
8095     /* Complement the input inversion list (which must be a Unicode property,
8096      * all of which don't match above the Unicode maximum code point.)  And
8097      * Perl has chosen to not have the inversion match above that either.  This
8098      * adds a 0x110000 if the list didn't end with it, and removes it if it did
8099      */
8100
8101     UV len;
8102     UV* array;
8103
8104     PERL_ARGS_ASSERT__INVLIST_INVERT_PROP;
8105
8106     _invlist_invert(invlist);
8107
8108     len = _invlist_len(invlist);
8109
8110     if (len != 0) { /* If empty do nothing */
8111         array = invlist_array(invlist);
8112         if (array[len - 1] != PERL_UNICODE_MAX + 1) {
8113             /* Add 0x110000.  First, grow if necessary */
8114             len++;
8115             if (invlist_max(invlist) < len) {
8116                 invlist_extend(invlist, len);
8117                 array = invlist_array(invlist);
8118             }
8119             invlist_set_len(invlist, len, *get_invlist_offset_addr(invlist));
8120             array[len - 1] = PERL_UNICODE_MAX + 1;
8121         }
8122         else {  /* Remove the 0x110000 */
8123             invlist_set_len(invlist, len - 1, *get_invlist_offset_addr(invlist));
8124         }
8125     }
8126
8127     return;
8128 }
8129 #endif
8130
8131 PERL_STATIC_INLINE SV*
8132 S_invlist_clone(pTHX_ SV* const invlist)
8133 {
8134
8135     /* Return a new inversion list that is a copy of the input one, which is
8136      * unchanged */
8137
8138     /* Need to allocate extra space to accommodate Perl's addition of a
8139      * trailing NUL to SvPV's, since it thinks they are always strings */
8140     SV* new_invlist = _new_invlist(_invlist_len(invlist) + 1);
8141     STRLEN physical_length = SvCUR(invlist);
8142     bool offset = *(get_invlist_offset_addr(invlist));
8143
8144     PERL_ARGS_ASSERT_INVLIST_CLONE;
8145
8146     *(get_invlist_offset_addr(new_invlist)) = offset;
8147     invlist_set_len(new_invlist, _invlist_len(invlist), offset);
8148     Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char);
8149
8150     return new_invlist;
8151 }
8152
8153 PERL_STATIC_INLINE STRLEN*
8154 S_get_invlist_iter_addr(pTHX_ SV* invlist)
8155 {
8156     /* Return the address of the UV that contains the current iteration
8157      * position */
8158
8159     PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
8160
8161     assert(SvTYPE(invlist) == SVt_INVLIST);
8162
8163     return &(((XINVLIST*) SvANY(invlist))->iterator);
8164 }
8165
8166 PERL_STATIC_INLINE void
8167 S_invlist_iterinit(pTHX_ SV* invlist)   /* Initialize iterator for invlist */
8168 {
8169     PERL_ARGS_ASSERT_INVLIST_ITERINIT;
8170
8171     *get_invlist_iter_addr(invlist) = 0;
8172 }
8173
8174 PERL_STATIC_INLINE void
8175 S_invlist_iterfinish(pTHX_ SV* invlist)
8176 {
8177     /* Terminate iterator for invlist.  This is to catch development errors.
8178      * Any iteration that is interrupted before completed should call this
8179      * function.  Functions that add code points anywhere else but to the end
8180      * of an inversion list assert that they are not in the middle of an
8181      * iteration.  If they were, the addition would make the iteration
8182      * problematical: if the iteration hadn't reached the place where things
8183      * were being added, it would be ok */
8184
8185     PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
8186
8187     *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX;
8188 }
8189
8190 STATIC bool
8191 S_invlist_iternext(pTHX_ SV* invlist, UV* start, UV* end)
8192 {
8193     /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
8194      * This call sets in <*start> and <*end>, the next range in <invlist>.
8195      * Returns <TRUE> if successful and the next call will return the next
8196      * range; <FALSE> if was already at the end of the list.  If the latter,
8197      * <*start> and <*end> are unchanged, and the next call to this function
8198      * will start over at the beginning of the list */
8199
8200     STRLEN* pos = get_invlist_iter_addr(invlist);
8201     UV len = _invlist_len(invlist);
8202     UV *array;
8203
8204     PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
8205
8206     if (*pos >= len) {
8207         *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */
8208         return FALSE;
8209     }
8210
8211     array = invlist_array(invlist);
8212
8213     *start = array[(*pos)++];
8214
8215     if (*pos >= len) {
8216         *end = UV_MAX;
8217     }
8218     else {
8219         *end = array[(*pos)++] - 1;
8220     }
8221
8222     return TRUE;
8223 }
8224
8225 PERL_STATIC_INLINE bool
8226 S_invlist_is_iterating(pTHX_ SV* const invlist)
8227 {
8228     PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
8229
8230     return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX;
8231 }
8232
8233 PERL_STATIC_INLINE UV
8234 S_invlist_highest(pTHX_ SV* const invlist)
8235 {
8236     /* Returns the highest code point that matches an inversion list.  This API
8237      * has an ambiguity, as it returns 0 under either the highest is actually
8238      * 0, or if the list is empty.  If this distinction matters to you, check
8239      * for emptiness before calling this function */
8240
8241     UV len = _invlist_len(invlist);
8242     UV *array;
8243
8244     PERL_ARGS_ASSERT_INVLIST_HIGHEST;
8245
8246     if (len == 0) {
8247         return 0;
8248     }
8249
8250     array = invlist_array(invlist);
8251
8252     /* The last element in the array in the inversion list always starts a
8253      * range that goes to infinity.  That range may be for code points that are
8254      * matched in the inversion list, or it may be for ones that aren't
8255      * matched.  In the latter case, the highest code point in the set is one
8256      * less than the beginning of this range; otherwise it is the final element
8257      * of this range: infinity */
8258     return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
8259            ? UV_MAX
8260            : array[len - 1] - 1;
8261 }
8262
8263 #ifndef PERL_IN_XSUB_RE
8264 SV *
8265 Perl__invlist_contents(pTHX_ SV* const invlist)
8266 {
8267     /* Get the contents of an inversion list into a string SV so that they can
8268      * be printed out.  It uses the format traditionally done for debug tracing
8269      */
8270
8271     UV start, end;
8272     SV* output = newSVpvs("\n");
8273
8274     PERL_ARGS_ASSERT__INVLIST_CONTENTS;
8275
8276     assert(! invlist_is_iterating(invlist));
8277
8278     invlist_iterinit(invlist);
8279     while (invlist_iternext(invlist, &start, &end)) {
8280         if (end == UV_MAX) {
8281             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\tINFINITY\n", start);
8282         }
8283         else if (end != start) {
8284             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\t%04"UVXf"\n",
8285                     start,       end);
8286         }
8287         else {
8288             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\n", start);
8289         }
8290     }
8291
8292     return output;
8293 }
8294 #endif
8295
8296 #ifndef PERL_IN_XSUB_RE
8297 void
8298 Perl__invlist_dump(pTHX_ PerlIO *file, I32 level, const char * const indent, SV* const invlist)
8299 {
8300     /* Designed to be called only by do_sv_dump().  Dumps out the ranges of the
8301      * inversion list 'invlist' to 'file' at 'level'  Each line is prefixed by
8302      * the string 'indent'.  The output looks like this:
8303          [0] 0x000A .. 0x000D
8304          [2] 0x0085
8305          [4] 0x2028 .. 0x2029
8306          [6] 0x3104 .. INFINITY
8307      * This means that the first range of code points matched by the list are
8308      * 0xA through 0xD; the second range contains only the single code point
8309      * 0x85, etc.  An inversion list is an array of UVs.  Two array elements
8310      * are used to define each range (except if the final range extends to
8311      * infinity, only a single element is needed).  The array index of the
8312      * first element for the corresponding range is given in brackets. */
8313
8314     UV start, end;
8315     STRLEN count = 0;
8316
8317     PERL_ARGS_ASSERT__INVLIST_DUMP;
8318
8319     if (invlist_is_iterating(invlist)) {
8320         Perl_dump_indent(aTHX_ level, file,
8321              "%sCan't dump inversion list because is in middle of iterating\n",
8322              indent);
8323         return;
8324     }
8325
8326     invlist_iterinit(invlist);
8327     while (invlist_iternext(invlist, &start, &end)) {
8328         if (end == UV_MAX) {
8329             Perl_dump_indent(aTHX_ level, file,
8330                                        "%s[%"UVuf"] 0x%04"UVXf" .. INFINITY\n",
8331                                    indent, (UV)count, start);
8332         }
8333         else if (end != start) {
8334             Perl_dump_indent(aTHX_ level, file,
8335                                     "%s[%"UVuf"] 0x%04"UVXf" .. 0x%04"UVXf"\n",
8336                                 indent, (UV)count, start,         end);
8337         }
8338         else {
8339             Perl_dump_indent(aTHX_ level, file, "%s[%"UVuf"] 0x%04"UVXf"\n",
8340                                             indent, (UV)count, start);
8341         }
8342         count += 2;
8343     }
8344 }
8345 #endif
8346
8347 #ifdef PERL_ARGS_ASSERT__INVLISTEQ
8348 bool
8349 S__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b)
8350 {
8351     /* Return a boolean as to if the two passed in inversion lists are
8352      * identical.  The final argument, if TRUE, says to take the complement of
8353      * the second inversion list before doing the comparison */
8354
8355     const UV* array_a = invlist_array(a);
8356     const UV* array_b = invlist_array(b);
8357     UV len_a = _invlist_len(a);
8358     UV len_b = _invlist_len(b);
8359
8360     UV i = 0;               /* current index into the arrays */
8361     bool retval = TRUE;     /* Assume are identical until proven otherwise */
8362
8363     PERL_ARGS_ASSERT__INVLISTEQ;
8364
8365     /* If are to compare 'a' with the complement of b, set it
8366      * up so are looking at b's complement. */
8367     if (complement_b) {
8368
8369         /* The complement of nothing is everything, so <a> would have to have
8370          * just one element, starting at zero (ending at infinity) */
8371         if (len_b == 0) {
8372             return (len_a == 1 && array_a[0] == 0);
8373         }
8374         else if (array_b[0] == 0) {
8375
8376             /* Otherwise, to complement, we invert.  Here, the first element is
8377              * 0, just remove it.  To do this, we just pretend the array starts
8378              * one later */
8379
8380             array_b++;
8381             len_b--;
8382         }
8383         else {
8384
8385             /* But if the first element is not zero, we pretend the list starts
8386              * at the 0 that is always stored immediately before the array. */
8387             array_b--;
8388             len_b++;
8389         }
8390     }
8391
8392     /* Make sure that the lengths are the same, as well as the final element
8393      * before looping through the remainder.  (Thus we test the length, final,
8394      * and first elements right off the bat) */
8395     if (len_a != len_b || array_a[len_a-1] != array_b[len_a-1]) {
8396         retval = FALSE;
8397     }
8398     else for (i = 0; i < len_a - 1; i++) {
8399         if (array_a[i] != array_b[i]) {
8400             retval = FALSE;
8401             break;
8402         }
8403     }
8404
8405     return retval;
8406 }
8407 #endif
8408
8409 #undef HEADER_LENGTH
8410 #undef TO_INTERNAL_SIZE
8411 #undef FROM_INTERNAL_SIZE
8412 #undef INVLIST_VERSION_ID
8413
8414 /* End of inversion list object */
8415
8416 STATIC void
8417 S_parse_lparen_question_flags(pTHX_ struct RExC_state_t *pRExC_state)
8418 {
8419     /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)'
8420      * constructs, and updates RExC_flags with them.  On input, RExC_parse
8421      * should point to the first flag; it is updated on output to point to the
8422      * final ')' or ':'.  There needs to be at least one flag, or this will
8423      * abort */
8424
8425     /* for (?g), (?gc), and (?o) warnings; warning
8426        about (?c) will warn about (?g) -- japhy    */
8427
8428 #define WASTED_O  0x01
8429 #define WASTED_G  0x02
8430 #define WASTED_C  0x04
8431 #define WASTED_GC (WASTED_G|WASTED_C)
8432     I32 wastedflags = 0x00;
8433     U32 posflags = 0, negflags = 0;
8434     U32 *flagsp = &posflags;
8435     char has_charset_modifier = '\0';
8436     regex_charset cs;
8437     bool has_use_defaults = FALSE;
8438     const char* const seqstart = RExC_parse - 1; /* Point to the '?' */
8439
8440     PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS;
8441
8442     /* '^' as an initial flag sets certain defaults */
8443     if (UCHARAT(RExC_parse) == '^') {
8444         RExC_parse++;
8445         has_use_defaults = TRUE;
8446         STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
8447         set_regex_charset(&RExC_flags, (RExC_utf8 || RExC_uni_semantics)
8448                                         ? REGEX_UNICODE_CHARSET
8449                                         : REGEX_DEPENDS_CHARSET);
8450     }
8451
8452     cs = get_regex_charset(RExC_flags);
8453     if (cs == REGEX_DEPENDS_CHARSET
8454         && (RExC_utf8 || RExC_uni_semantics))
8455     {
8456         cs = REGEX_UNICODE_CHARSET;
8457     }
8458
8459     while (*RExC_parse) {
8460         /* && strchr("iogcmsx", *RExC_parse) */
8461         /* (?g), (?gc) and (?o) are useless here
8462            and must be globally applied -- japhy */
8463         switch (*RExC_parse) {
8464
8465             /* Code for the imsx flags */
8466             CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
8467
8468             case LOCALE_PAT_MOD:
8469                 if (has_charset_modifier) {
8470                     goto excess_modifier;
8471                 }
8472                 else if (flagsp == &negflags) {
8473                     goto neg_modifier;
8474                 }
8475                 cs = REGEX_LOCALE_CHARSET;
8476                 has_charset_modifier = LOCALE_PAT_MOD;
8477                 RExC_contains_locale = 1;
8478                 break;
8479             case UNICODE_PAT_MOD:
8480                 if (has_charset_modifier) {
8481                     goto excess_modifier;
8482                 }
8483                 else if (flagsp == &negflags) {
8484                     goto neg_modifier;
8485                 }
8486                 cs = REGEX_UNICODE_CHARSET;
8487                 has_charset_modifier = UNICODE_PAT_MOD;
8488                 break;
8489             case ASCII_RESTRICT_PAT_MOD:
8490                 if (flagsp == &negflags) {
8491                     goto neg_modifier;
8492                 }
8493                 if (has_charset_modifier) {
8494                     if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
8495                         goto excess_modifier;
8496                     }
8497                     /* Doubled modifier implies more restricted */
8498                     cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
8499                 }
8500                 else {
8501                     cs = REGEX_ASCII_RESTRICTED_CHARSET;
8502                 }
8503                 has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
8504                 break;
8505             case DEPENDS_PAT_MOD:
8506                 if (has_use_defaults) {
8507                     goto fail_modifiers;
8508                 }
8509                 else if (flagsp == &negflags) {
8510                     goto neg_modifier;
8511                 }
8512                 else if (has_charset_modifier) {
8513                     goto excess_modifier;
8514                 }
8515
8516                 /* The dual charset means unicode semantics if the
8517                  * pattern (or target, not known until runtime) are
8518                  * utf8, or something in the pattern indicates unicode
8519                  * semantics */
8520                 cs = (RExC_utf8 || RExC_uni_semantics)
8521                      ? REGEX_UNICODE_CHARSET
8522                      : REGEX_DEPENDS_CHARSET;
8523                 has_charset_modifier = DEPENDS_PAT_MOD;
8524                 break;
8525             excess_modifier:
8526                 RExC_parse++;
8527                 if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
8528                     vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
8529                 }
8530                 else if (has_charset_modifier == *(RExC_parse - 1)) {
8531                     vFAIL2("Regexp modifier \"%c\" may not appear twice", *(RExC_parse - 1));
8532                 }
8533                 else {
8534                     vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
8535                 }
8536                 /*NOTREACHED*/
8537             neg_modifier:
8538                 RExC_parse++;
8539                 vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"", *(RExC_parse - 1));
8540                 /*NOTREACHED*/
8541             case ONCE_PAT_MOD: /* 'o' */
8542             case GLOBAL_PAT_MOD: /* 'g' */
8543                 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
8544                     const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
8545                     if (! (wastedflags & wflagbit) ) {
8546                         wastedflags |= wflagbit;
8547                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
8548                         vWARN5(
8549                             RExC_parse + 1,
8550                             "Useless (%s%c) - %suse /%c modifier",
8551                             flagsp == &negflags ? "?-" : "?",
8552                             *RExC_parse,
8553                             flagsp == &negflags ? "don't " : "",
8554                             *RExC_parse
8555                         );
8556                     }
8557                 }
8558                 break;
8559
8560             case CONTINUE_PAT_MOD: /* 'c' */
8561                 if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
8562                     if (! (wastedflags & WASTED_C) ) {
8563                         wastedflags |= WASTED_GC;
8564                         /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */
8565                         vWARN3(
8566                             RExC_parse + 1,
8567                             "Useless (%sc) - %suse /gc modifier",
8568                             flagsp == &negflags ? "?-" : "?",
8569                             flagsp == &negflags ? "don't " : ""
8570                         );
8571                     }
8572                 }
8573                 break;
8574             case KEEPCOPY_PAT_MOD: /* 'p' */
8575                 if (flagsp == &negflags) {
8576                     if (SIZE_ONLY)
8577                         ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
8578                 } else {
8579                     *flagsp |= RXf_PMf_KEEPCOPY;
8580                 }
8581                 break;
8582             case '-':
8583                 /* A flag is a default iff it is following a minus, so
8584                  * if there is a minus, it means will be trying to
8585                  * re-specify a default which is an error */
8586                 if (has_use_defaults || flagsp == &negflags) {
8587                     goto fail_modifiers;
8588                 }
8589                 flagsp = &negflags;
8590                 wastedflags = 0;  /* reset so (?g-c) warns twice */
8591                 break;
8592             case ':':
8593             case ')':
8594                 RExC_flags |= posflags;
8595                 RExC_flags &= ~negflags;
8596                 set_regex_charset(&RExC_flags, cs);
8597                 return;
8598                 /*NOTREACHED*/
8599             default:
8600             fail_modifiers:
8601                 RExC_parse++;
8602                 vFAIL3("Sequence (%.*s...) not recognized",
8603                        RExC_parse-seqstart, seqstart);
8604                 /*NOTREACHED*/
8605         }
8606
8607         ++RExC_parse;
8608     }
8609 }
8610
8611 /*
8612  - reg - regular expression, i.e. main body or parenthesized thing
8613  *
8614  * Caller must absorb opening parenthesis.
8615  *
8616  * Combining parenthesis handling with the base level of regular expression
8617  * is a trifle forced, but the need to tie the tails of the branches to what
8618  * follows makes it hard to avoid.
8619  */
8620 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
8621 #ifdef DEBUGGING
8622 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
8623 #else
8624 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
8625 #endif
8626
8627 /* Returns NULL, setting *flagp to TRYAGAIN at the end of (?) that only sets
8628    flags. Returns NULL, setting *flagp to RESTART_UTF8 if the sizing scan
8629    needs to be restarted.
8630    Otherwise would only return NULL if regbranch() returns NULL, which
8631    cannot happen.  */
8632 STATIC regnode *
8633 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
8634     /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter.
8635      * 2 is like 1, but indicates that nextchar() has been called to advance
8636      * RExC_parse beyond the '('.  Things like '(?' are indivisible tokens, and
8637      * this flag alerts us to the need to check for that */
8638 {
8639     dVAR;
8640     regnode *ret;               /* Will be the head of the group. */
8641     regnode *br;
8642     regnode *lastbr;
8643     regnode *ender = NULL;
8644     I32 parno = 0;
8645     I32 flags;
8646     U32 oregflags = RExC_flags;
8647     bool have_branch = 0;
8648     bool is_open = 0;
8649     I32 freeze_paren = 0;
8650     I32 after_freeze = 0;
8651
8652     char * parse_start = RExC_parse; /* MJD */
8653     char * const oregcomp_parse = RExC_parse;
8654
8655     GET_RE_DEBUG_FLAGS_DECL;
8656
8657     PERL_ARGS_ASSERT_REG;
8658     DEBUG_PARSE("reg ");
8659
8660     *flagp = 0;                         /* Tentatively. */
8661
8662
8663     /* Make an OPEN node, if parenthesized. */
8664     if (paren) {
8665
8666         /* Under /x, space and comments can be gobbled up between the '(' and
8667          * here (if paren ==2).  The forms '(*VERB' and '(?...' disallow such
8668          * intervening space, as the sequence is a token, and a token should be
8669          * indivisible */
8670         bool has_intervening_patws = paren == 2 && *(RExC_parse - 1) != '(';
8671
8672         if ( *RExC_parse == '*') { /* (*VERB:ARG) */
8673             char *start_verb = RExC_parse;
8674             STRLEN verb_len = 0;
8675             char *start_arg = NULL;
8676             unsigned char op = 0;
8677             int argok = 1;
8678             int internal_argval = 0; /* internal_argval is only useful if !argok */
8679
8680             if (has_intervening_patws && SIZE_ONLY) {
8681                 ckWARNregdep(RExC_parse + 1, "In '(*VERB...)', splitting the initial '(*' is deprecated");
8682             }
8683             while ( *RExC_parse && *RExC_parse != ')' ) {
8684                 if ( *RExC_parse == ':' ) {
8685                     start_arg = RExC_parse + 1;
8686                     break;
8687                 }
8688                 RExC_parse++;
8689             }
8690             ++start_verb;
8691             verb_len = RExC_parse - start_verb;
8692             if ( start_arg ) {
8693                 RExC_parse++;
8694                 while ( *RExC_parse && *RExC_parse != ')' ) 
8695                     RExC_parse++;
8696                 if ( *RExC_parse != ')' ) 
8697                     vFAIL("Unterminated verb pattern argument");
8698                 if ( RExC_parse == start_arg )
8699                     start_arg = NULL;
8700             } else {
8701                 if ( *RExC_parse != ')' )
8702                     vFAIL("Unterminated verb pattern");
8703             }
8704             
8705             switch ( *start_verb ) {
8706             case 'A':  /* (*ACCEPT) */
8707                 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
8708                     op = ACCEPT;
8709                     internal_argval = RExC_nestroot;
8710                 }
8711                 break;
8712             case 'C':  /* (*COMMIT) */
8713                 if ( memEQs(start_verb,verb_len,"COMMIT") )
8714                     op = COMMIT;
8715                 break;
8716             case 'F':  /* (*FAIL) */
8717                 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
8718                     op = OPFAIL;
8719                     argok = 0;
8720                 }
8721                 break;
8722             case ':':  /* (*:NAME) */
8723             case 'M':  /* (*MARK:NAME) */
8724                 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
8725                     op = MARKPOINT;
8726                     argok = -1;
8727                 }
8728                 break;
8729             case 'P':  /* (*PRUNE) */
8730                 if ( memEQs(start_verb,verb_len,"PRUNE") )
8731                     op = PRUNE;
8732                 break;
8733             case 'S':   /* (*SKIP) */  
8734                 if ( memEQs(start_verb,verb_len,"SKIP") ) 
8735                     op = SKIP;
8736                 break;
8737             case 'T':  /* (*THEN) */
8738                 /* [19:06] <TimToady> :: is then */
8739                 if ( memEQs(start_verb,verb_len,"THEN") ) {
8740                     op = CUTGROUP;
8741                     RExC_seen |= REG_SEEN_CUTGROUP;
8742                 }
8743                 break;
8744             }
8745             if ( ! op ) {
8746                 RExC_parse++;
8747                 vFAIL3("Unknown verb pattern '%.*s'",
8748                     verb_len, start_verb);
8749             }
8750             if ( argok ) {
8751                 if ( start_arg && internal_argval ) {
8752                     vFAIL3("Verb pattern '%.*s' may not have an argument",
8753                         verb_len, start_verb); 
8754                 } else if ( argok < 0 && !start_arg ) {
8755                     vFAIL3("Verb pattern '%.*s' has a mandatory argument",
8756                         verb_len, start_verb);    
8757                 } else {
8758                     ret = reganode(pRExC_state, op, internal_argval);
8759                     if ( ! internal_argval && ! SIZE_ONLY ) {
8760                         if (start_arg) {
8761                             SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
8762                             ARG(ret) = add_data( pRExC_state, 1, "S" );
8763                             RExC_rxi->data->data[ARG(ret)]=(void*)sv;
8764                             ret->flags = 0;
8765                         } else {
8766                             ret->flags = 1; 
8767                         }
8768                     }               
8769                 }
8770                 if (!internal_argval)
8771                     RExC_seen |= REG_SEEN_VERBARG;
8772             } else if ( start_arg ) {
8773                 vFAIL3("Verb pattern '%.*s' may not have an argument",
8774                         verb_len, start_verb);    
8775             } else {
8776                 ret = reg_node(pRExC_state, op);
8777             }
8778             nextchar(pRExC_state);
8779             return ret;
8780         }
8781         else if (*RExC_parse == '?') { /* (?...) */
8782             bool is_logical = 0;
8783             const char * const seqstart = RExC_parse;
8784             if (has_intervening_patws && SIZE_ONLY) {
8785                 ckWARNregdep(RExC_parse + 1, "In '(?...)', splitting the initial '(?' is deprecated");
8786             }
8787
8788             RExC_parse++;
8789             paren = *RExC_parse++;
8790             ret = NULL;                 /* For look-ahead/behind. */
8791             switch (paren) {
8792
8793             case 'P':   /* (?P...) variants for those used to PCRE/Python */
8794                 paren = *RExC_parse++;
8795                 if ( paren == '<')         /* (?P<...>) named capture */
8796                     goto named_capture;
8797                 else if (paren == '>') {   /* (?P>name) named recursion */
8798                     goto named_recursion;
8799                 }
8800                 else if (paren == '=') {   /* (?P=...)  named backref */
8801                     /* this pretty much dupes the code for \k<NAME> in regatom(), if
8802                        you change this make sure you change that */
8803                     char* name_start = RExC_parse;
8804                     U32 num = 0;
8805                     SV *sv_dat = reg_scan_name(pRExC_state,
8806                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8807                     if (RExC_parse == name_start || *RExC_parse != ')')
8808                         vFAIL2("Sequence %.3s... not terminated",parse_start);
8809
8810                     if (!SIZE_ONLY) {
8811                         num = add_data( pRExC_state, 1, "S" );
8812                         RExC_rxi->data->data[num]=(void*)sv_dat;
8813                         SvREFCNT_inc_simple_void(sv_dat);
8814                     }
8815                     RExC_sawback = 1;
8816                     ret = reganode(pRExC_state,
8817                                    ((! FOLD)
8818                                      ? NREF
8819                                      : (ASCII_FOLD_RESTRICTED)
8820                                        ? NREFFA
8821                                        : (AT_LEAST_UNI_SEMANTICS)
8822                                          ? NREFFU
8823                                          : (LOC)
8824                                            ? NREFFL
8825                                            : NREFF),
8826                                     num);
8827                     *flagp |= HASWIDTH;
8828
8829                     Set_Node_Offset(ret, parse_start+1);
8830                     Set_Node_Cur_Length(ret, parse_start);
8831
8832                     nextchar(pRExC_state);
8833                     return ret;
8834                 }
8835                 RExC_parse++;
8836                 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8837                 /*NOTREACHED*/
8838             case '<':           /* (?<...) */
8839                 if (*RExC_parse == '!')
8840                     paren = ',';
8841                 else if (*RExC_parse != '=') 
8842               named_capture:
8843                 {               /* (?<...>) */
8844                     char *name_start;
8845                     SV *svname;
8846                     paren= '>';
8847             case '\'':          /* (?'...') */
8848                     name_start= RExC_parse;
8849                     svname = reg_scan_name(pRExC_state,
8850                         SIZE_ONLY ?  /* reverse test from the others */
8851                         REG_RSN_RETURN_NAME : 
8852                         REG_RSN_RETURN_NULL);
8853                     if (RExC_parse == name_start) {
8854                         RExC_parse++;
8855                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8856                         /*NOTREACHED*/
8857                     }
8858                     if (*RExC_parse != paren)
8859                         vFAIL2("Sequence (?%c... not terminated",
8860                             paren=='>' ? '<' : paren);
8861                     if (SIZE_ONLY) {
8862                         HE *he_str;
8863                         SV *sv_dat = NULL;
8864                         if (!svname) /* shouldn't happen */
8865                             Perl_croak(aTHX_
8866                                 "panic: reg_scan_name returned NULL");
8867                         if (!RExC_paren_names) {
8868                             RExC_paren_names= newHV();
8869                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
8870 #ifdef DEBUGGING
8871                             RExC_paren_name_list= newAV();
8872                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
8873 #endif
8874                         }
8875                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
8876                         if ( he_str )
8877                             sv_dat = HeVAL(he_str);
8878                         if ( ! sv_dat ) {
8879                             /* croak baby croak */
8880                             Perl_croak(aTHX_
8881                                 "panic: paren_name hash element allocation failed");
8882                         } else if ( SvPOK(sv_dat) ) {
8883                             /* (?|...) can mean we have dupes so scan to check
8884                                its already been stored. Maybe a flag indicating
8885                                we are inside such a construct would be useful,
8886                                but the arrays are likely to be quite small, so
8887                                for now we punt -- dmq */
8888                             IV count = SvIV(sv_dat);
8889                             I32 *pv = (I32*)SvPVX(sv_dat);
8890                             IV i;
8891                             for ( i = 0 ; i < count ; i++ ) {
8892                                 if ( pv[i] == RExC_npar ) {
8893                                     count = 0;
8894                                     break;
8895                                 }
8896                             }
8897                             if ( count ) {
8898                                 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
8899                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
8900                                 pv[count] = RExC_npar;
8901                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
8902                             }
8903                         } else {
8904                             (void)SvUPGRADE(sv_dat,SVt_PVNV);
8905                             sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
8906                             SvIOK_on(sv_dat);
8907                             SvIV_set(sv_dat, 1);
8908                         }
8909 #ifdef DEBUGGING
8910                         /* Yes this does cause a memory leak in debugging Perls */
8911                         if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
8912                             SvREFCNT_dec_NN(svname);
8913 #endif
8914
8915                         /*sv_dump(sv_dat);*/
8916                     }
8917                     nextchar(pRExC_state);
8918                     paren = 1;
8919                     goto capturing_parens;
8920                 }
8921                 RExC_seen |= REG_SEEN_LOOKBEHIND;
8922                 RExC_in_lookbehind++;
8923                 RExC_parse++;
8924             case '=':           /* (?=...) */
8925                 RExC_seen_zerolen++;
8926                 break;
8927             case '!':           /* (?!...) */
8928                 RExC_seen_zerolen++;
8929                 if (*RExC_parse == ')') {
8930                     ret=reg_node(pRExC_state, OPFAIL);
8931                     nextchar(pRExC_state);
8932                     return ret;
8933                 }
8934                 break;
8935             case '|':           /* (?|...) */
8936                 /* branch reset, behave like a (?:...) except that
8937                    buffers in alternations share the same numbers */
8938                 paren = ':'; 
8939                 after_freeze = freeze_paren = RExC_npar;
8940                 break;
8941             case ':':           /* (?:...) */
8942             case '>':           /* (?>...) */
8943                 break;
8944             case '$':           /* (?$...) */
8945             case '@':           /* (?@...) */
8946                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
8947                 break;
8948             case '#':           /* (?#...) */
8949                 /* XXX As soon as we disallow separating the '?' and '*' (by
8950                  * spaces or (?#...) comment), it is believed that this case
8951                  * will be unreachable and can be removed.  See
8952                  * [perl #117327] */
8953                 while (*RExC_parse && *RExC_parse != ')')
8954                     RExC_parse++;
8955                 if (*RExC_parse != ')')
8956                     FAIL("Sequence (?#... not terminated");
8957                 nextchar(pRExC_state);
8958                 *flagp = TRYAGAIN;
8959                 return NULL;
8960             case '0' :           /* (?0) */
8961             case 'R' :           /* (?R) */
8962                 if (*RExC_parse != ')')
8963                     FAIL("Sequence (?R) not terminated");
8964                 ret = reg_node(pRExC_state, GOSTART);
8965                 *flagp |= POSTPONED;
8966                 nextchar(pRExC_state);
8967                 return ret;
8968                 /*notreached*/
8969             { /* named and numeric backreferences */
8970                 I32 num;
8971             case '&':            /* (?&NAME) */
8972                 parse_start = RExC_parse - 1;
8973               named_recursion:
8974                 {
8975                     SV *sv_dat = reg_scan_name(pRExC_state,
8976                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8977                      num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
8978                 }
8979                 goto gen_recurse_regop;
8980                 assert(0); /* NOT REACHED */
8981             case '+':
8982                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
8983                     RExC_parse++;
8984                     vFAIL("Illegal pattern");
8985                 }
8986                 goto parse_recursion;
8987                 /* NOT REACHED*/
8988             case '-': /* (?-1) */
8989                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
8990                     RExC_parse--; /* rewind to let it be handled later */
8991                     goto parse_flags;
8992                 } 
8993                 /*FALLTHROUGH */
8994             case '1': case '2': case '3': case '4': /* (?1) */
8995             case '5': case '6': case '7': case '8': case '9':
8996                 RExC_parse--;
8997               parse_recursion:
8998                 num = atoi(RExC_parse);
8999                 parse_start = RExC_parse - 1; /* MJD */
9000                 if (*RExC_parse == '-')
9001                     RExC_parse++;
9002                 while (isDIGIT(*RExC_parse))
9003                         RExC_parse++;
9004                 if (*RExC_parse!=')') 
9005                     vFAIL("Expecting close bracket");
9006
9007               gen_recurse_regop:
9008                 if ( paren == '-' ) {
9009                     /*
9010                     Diagram of capture buffer numbering.
9011                     Top line is the normal capture buffer numbers
9012                     Bottom line is the negative indexing as from
9013                     the X (the (?-2))
9014
9015                     +   1 2    3 4 5 X          6 7
9016                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
9017                     -   5 4    3 2 1 X          x x
9018
9019                     */
9020                     num = RExC_npar + num;
9021                     if (num < 1)  {
9022                         RExC_parse++;
9023                         vFAIL("Reference to nonexistent group");
9024                     }
9025                 } else if ( paren == '+' ) {
9026                     num = RExC_npar + num - 1;
9027                 }
9028
9029                 ret = reganode(pRExC_state, GOSUB, num);
9030                 if (!SIZE_ONLY) {
9031                     if (num > (I32)RExC_rx->nparens) {
9032                         RExC_parse++;
9033                         vFAIL("Reference to nonexistent group");
9034                     }
9035                     ARG2L_SET( ret, RExC_recurse_count++);
9036                     RExC_emit++;
9037                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
9038                         "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
9039                 } else {
9040                     RExC_size++;
9041                 }
9042                 RExC_seen |= REG_SEEN_RECURSE;
9043                 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
9044                 Set_Node_Offset(ret, parse_start); /* MJD */
9045
9046                 *flagp |= POSTPONED;
9047                 nextchar(pRExC_state);
9048                 return ret;
9049             } /* named and numeric backreferences */
9050             assert(0); /* NOT REACHED */
9051
9052             case '?':           /* (??...) */
9053                 is_logical = 1;
9054                 if (*RExC_parse != '{') {
9055                     RExC_parse++;
9056                     vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
9057                     /*NOTREACHED*/
9058                 }
9059                 *flagp |= POSTPONED;
9060                 paren = *RExC_parse++;
9061                 /* FALL THROUGH */
9062             case '{':           /* (?{...}) */
9063             {
9064                 U32 n = 0;
9065                 struct reg_code_block *cb;
9066
9067                 RExC_seen_zerolen++;
9068
9069                 if (   !pRExC_state->num_code_blocks
9070                     || pRExC_state->code_index >= pRExC_state->num_code_blocks
9071                     || pRExC_state->code_blocks[pRExC_state->code_index].start
9072                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
9073                             - RExC_start)
9074                 ) {
9075                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
9076                         FAIL("panic: Sequence (?{...}): no code block found\n");
9077                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
9078                 }
9079                 /* this is a pre-compiled code block (?{...}) */
9080                 cb = &pRExC_state->code_blocks[pRExC_state->code_index];
9081                 RExC_parse = RExC_start + cb->end;
9082                 if (!SIZE_ONLY) {
9083                     OP *o = cb->block;
9084                     if (cb->src_regex) {
9085                         n = add_data(pRExC_state, 2, "rl");
9086                         RExC_rxi->data->data[n] =
9087                             (void*)SvREFCNT_inc((SV*)cb->src_regex);
9088                         RExC_rxi->data->data[n+1] = (void*)o;
9089                     }
9090                     else {
9091                         n = add_data(pRExC_state, 1,
9092                                (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l");
9093                         RExC_rxi->data->data[n] = (void*)o;
9094                     }
9095                 }
9096                 pRExC_state->code_index++;
9097                 nextchar(pRExC_state);
9098
9099                 if (is_logical) {
9100                     regnode *eval;
9101                     ret = reg_node(pRExC_state, LOGICAL);
9102                     eval = reganode(pRExC_state, EVAL, n);
9103                     if (!SIZE_ONLY) {
9104                         ret->flags = 2;
9105                         /* for later propagation into (??{}) return value */
9106                         eval->flags = (U8) (RExC_flags & RXf_PMf_COMPILETIME);
9107                     }
9108                     REGTAIL(pRExC_state, ret, eval);
9109                     /* deal with the length of this later - MJD */
9110                     return ret;
9111                 }
9112                 ret = reganode(pRExC_state, EVAL, n);
9113                 Set_Node_Length(ret, RExC_parse - parse_start + 1);
9114                 Set_Node_Offset(ret, parse_start);
9115                 return ret;
9116             }
9117             case '(':           /* (?(?{...})...) and (?(?=...)...) */
9118             {
9119                 int is_define= 0;
9120                 if (RExC_parse[0] == '?') {        /* (?(?...)) */
9121                     if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
9122                         || RExC_parse[1] == '<'
9123                         || RExC_parse[1] == '{') { /* Lookahead or eval. */
9124                         I32 flag;
9125                         regnode *tail;
9126
9127                         ret = reg_node(pRExC_state, LOGICAL);
9128                         if (!SIZE_ONLY)
9129                             ret->flags = 1;
9130                         
9131                         tail = reg(pRExC_state, 1, &flag, depth+1);
9132                         if (flag & RESTART_UTF8) {
9133                             *flagp = RESTART_UTF8;
9134                             return NULL;
9135                         }
9136                         REGTAIL(pRExC_state, ret, tail);
9137                         goto insert_if;
9138                     }
9139                 }
9140                 else if ( RExC_parse[0] == '<'     /* (?(<NAME>)...) */
9141                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
9142                 {
9143                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
9144                     char *name_start= RExC_parse++;
9145                     U32 num = 0;
9146                     SV *sv_dat=reg_scan_name(pRExC_state,
9147                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
9148                     if (RExC_parse == name_start || *RExC_parse != ch)
9149                         vFAIL2("Sequence (?(%c... not terminated",
9150                             (ch == '>' ? '<' : ch));
9151                     RExC_parse++;
9152                     if (!SIZE_ONLY) {
9153                         num = add_data( pRExC_state, 1, "S" );
9154                         RExC_rxi->data->data[num]=(void*)sv_dat;
9155                         SvREFCNT_inc_simple_void(sv_dat);
9156                     }
9157                     ret = reganode(pRExC_state,NGROUPP,num);
9158                     goto insert_if_check_paren;
9159                 }
9160                 else if (RExC_parse[0] == 'D' &&
9161                          RExC_parse[1] == 'E' &&
9162                          RExC_parse[2] == 'F' &&
9163                          RExC_parse[3] == 'I' &&
9164                          RExC_parse[4] == 'N' &&
9165                          RExC_parse[5] == 'E')
9166                 {
9167                     ret = reganode(pRExC_state,DEFINEP,0);
9168                     RExC_parse +=6 ;
9169                     is_define = 1;
9170                     goto insert_if_check_paren;
9171                 }
9172                 else if (RExC_parse[0] == 'R') {
9173                     RExC_parse++;
9174                     parno = 0;
9175                     if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
9176                         parno = atoi(RExC_parse++);
9177                         while (isDIGIT(*RExC_parse))
9178                             RExC_parse++;
9179                     } else if (RExC_parse[0] == '&') {
9180                         SV *sv_dat;
9181                         RExC_parse++;
9182                         sv_dat = reg_scan_name(pRExC_state,
9183                             SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
9184                         parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
9185                     }
9186                     ret = reganode(pRExC_state,INSUBP,parno); 
9187                     goto insert_if_check_paren;
9188                 }
9189                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
9190                     /* (?(1)...) */
9191                     char c;
9192                     parno = atoi(RExC_parse++);
9193
9194                     while (isDIGIT(*RExC_parse))
9195                         RExC_parse++;
9196                     ret = reganode(pRExC_state, GROUPP, parno);
9197
9198                  insert_if_check_paren:
9199                     if ((c = *nextchar(pRExC_state)) != ')')
9200                         vFAIL("Switch condition not recognized");
9201                   insert_if:
9202                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
9203                     br = regbranch(pRExC_state, &flags, 1,depth+1);
9204                     if (br == NULL) {
9205                         if (flags & RESTART_UTF8) {
9206                             *flagp = RESTART_UTF8;
9207                             return NULL;
9208                         }
9209                         FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"",
9210                               (UV) flags);
9211                     } else
9212                         REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
9213                     c = *nextchar(pRExC_state);
9214                     if (flags&HASWIDTH)
9215                         *flagp |= HASWIDTH;
9216                     if (c == '|') {
9217                         if (is_define) 
9218                             vFAIL("(?(DEFINE)....) does not allow branches");
9219                         lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
9220                         if (!regbranch(pRExC_state, &flags, 1,depth+1)) {
9221                             if (flags & RESTART_UTF8) {
9222                                 *flagp = RESTART_UTF8;
9223                                 return NULL;
9224                             }
9225                             FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"",
9226                                   (UV) flags);
9227                         }
9228                         REGTAIL(pRExC_state, ret, lastbr);
9229                         if (flags&HASWIDTH)
9230                             *flagp |= HASWIDTH;
9231                         c = *nextchar(pRExC_state);
9232                     }
9233                     else
9234                         lastbr = NULL;
9235                     if (c != ')')
9236                         vFAIL("Switch (?(condition)... contains too many branches");
9237                     ender = reg_node(pRExC_state, TAIL);
9238                     REGTAIL(pRExC_state, br, ender);
9239                     if (lastbr) {
9240                         REGTAIL(pRExC_state, lastbr, ender);
9241                         REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
9242                     }
9243                     else
9244                         REGTAIL(pRExC_state, ret, ender);
9245                     RExC_size++; /* XXX WHY do we need this?!!
9246                                     For large programs it seems to be required
9247                                     but I can't figure out why. -- dmq*/
9248                     return ret;
9249                 }
9250                 else {
9251                     vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
9252                 }
9253             }
9254             case '[':           /* (?[ ... ]) */
9255                 return handle_regex_sets(pRExC_state, NULL, flagp, depth,
9256                                          oregcomp_parse);
9257             case 0:
9258                 RExC_parse--; /* for vFAIL to print correctly */
9259                 vFAIL("Sequence (? incomplete");
9260                 break;
9261             default: /* e.g., (?i) */
9262                 --RExC_parse;
9263               parse_flags:
9264                 parse_lparen_question_flags(pRExC_state);
9265                 if (UCHARAT(RExC_parse) != ':') {
9266                     nextchar(pRExC_state);
9267                     *flagp = TRYAGAIN;
9268                     return NULL;
9269                 }
9270                 paren = ':';
9271                 nextchar(pRExC_state);
9272                 ret = NULL;
9273                 goto parse_rest;
9274             } /* end switch */
9275         }
9276         else {                  /* (...) */
9277           capturing_parens:
9278             parno = RExC_npar;
9279             RExC_npar++;
9280             
9281             ret = reganode(pRExC_state, OPEN, parno);
9282             if (!SIZE_ONLY ){
9283                 if (!RExC_nestroot) 
9284                     RExC_nestroot = parno;
9285                 if (RExC_seen & REG_SEEN_RECURSE
9286                     && !RExC_open_parens[parno-1])
9287                 {
9288                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
9289                         "Setting open paren #%"IVdf" to %d\n", 
9290                         (IV)parno, REG_NODE_NUM(ret)));
9291                     RExC_open_parens[parno-1]= ret;
9292                 }
9293             }
9294             Set_Node_Length(ret, 1); /* MJD */
9295             Set_Node_Offset(ret, RExC_parse); /* MJD */
9296             is_open = 1;
9297         }
9298     }
9299     else                        /* ! paren */
9300         ret = NULL;
9301    
9302    parse_rest:
9303     /* Pick up the branches, linking them together. */
9304     parse_start = RExC_parse;   /* MJD */
9305     br = regbranch(pRExC_state, &flags, 1,depth+1);
9306
9307     /*     branch_len = (paren != 0); */
9308
9309     if (br == NULL) {
9310         if (flags & RESTART_UTF8) {
9311             *flagp = RESTART_UTF8;
9312             return NULL;
9313         }
9314         FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"", (UV) flags);
9315     }
9316     if (*RExC_parse == '|') {
9317         if (!SIZE_ONLY && RExC_extralen) {
9318             reginsert(pRExC_state, BRANCHJ, br, depth+1);
9319         }
9320         else {                  /* MJD */
9321             reginsert(pRExC_state, BRANCH, br, depth+1);
9322             Set_Node_Length(br, paren != 0);
9323             Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
9324         }
9325         have_branch = 1;
9326         if (SIZE_ONLY)
9327             RExC_extralen += 1;         /* For BRANCHJ-BRANCH. */
9328     }
9329     else if (paren == ':') {
9330         *flagp |= flags&SIMPLE;
9331     }
9332     if (is_open) {                              /* Starts with OPEN. */
9333         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
9334     }
9335     else if (paren != '?')              /* Not Conditional */
9336         ret = br;
9337     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
9338     lastbr = br;
9339     while (*RExC_parse == '|') {
9340         if (!SIZE_ONLY && RExC_extralen) {
9341             ender = reganode(pRExC_state, LONGJMP,0);
9342             REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
9343         }
9344         if (SIZE_ONLY)
9345             RExC_extralen += 2;         /* Account for LONGJMP. */
9346         nextchar(pRExC_state);
9347         if (freeze_paren) {
9348             if (RExC_npar > after_freeze)
9349                 after_freeze = RExC_npar;
9350             RExC_npar = freeze_paren;       
9351         }
9352         br = regbranch(pRExC_state, &flags, 0, depth+1);
9353
9354         if (br == NULL) {
9355             if (flags & RESTART_UTF8) {
9356                 *flagp = RESTART_UTF8;
9357                 return NULL;
9358             }
9359             FAIL2("panic: regbranch returned NULL, flags=%#"UVxf"", (UV) flags);
9360         }
9361         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
9362         lastbr = br;
9363         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
9364     }
9365
9366     if (have_branch || paren != ':') {
9367         /* Make a closing node, and hook it on the end. */
9368         switch (paren) {
9369         case ':':
9370             ender = reg_node(pRExC_state, TAIL);
9371             break;
9372         case 1: case 2:
9373             ender = reganode(pRExC_state, CLOSE, parno);
9374             if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
9375                 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
9376                         "Setting close paren #%"IVdf" to %d\n", 
9377                         (IV)parno, REG_NODE_NUM(ender)));
9378                 RExC_close_parens[parno-1]= ender;
9379                 if (RExC_nestroot == parno) 
9380                     RExC_nestroot = 0;
9381             }       
9382             Set_Node_Offset(ender,RExC_parse+1); /* MJD */
9383             Set_Node_Length(ender,1); /* MJD */
9384             break;
9385         case '<':
9386         case ',':
9387         case '=':
9388         case '!':
9389             *flagp &= ~HASWIDTH;
9390             /* FALL THROUGH */
9391         case '>':
9392             ender = reg_node(pRExC_state, SUCCEED);
9393             break;
9394         case 0:
9395             ender = reg_node(pRExC_state, END);
9396             if (!SIZE_ONLY) {
9397                 assert(!RExC_opend); /* there can only be one! */
9398                 RExC_opend = ender;
9399             }
9400             break;
9401         }
9402         DEBUG_PARSE_r(if (!SIZE_ONLY) {
9403             SV * const mysv_val1=sv_newmortal();
9404             SV * const mysv_val2=sv_newmortal();
9405             DEBUG_PARSE_MSG("lsbr");
9406             regprop(RExC_rx, mysv_val1, lastbr);
9407             regprop(RExC_rx, mysv_val2, ender);
9408             PerlIO_printf(Perl_debug_log, "~ tying lastbr %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
9409                           SvPV_nolen_const(mysv_val1),
9410                           (IV)REG_NODE_NUM(lastbr),
9411                           SvPV_nolen_const(mysv_val2),
9412                           (IV)REG_NODE_NUM(ender),
9413                           (IV)(ender - lastbr)
9414             );
9415         });
9416         REGTAIL(pRExC_state, lastbr, ender);
9417
9418         if (have_branch && !SIZE_ONLY) {
9419             char is_nothing= 1;
9420             if (depth==1)
9421                 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
9422
9423             /* Hook the tails of the branches to the closing node. */
9424             for (br = ret; br; br = regnext(br)) {
9425                 const U8 op = PL_regkind[OP(br)];
9426                 if (op == BRANCH) {
9427                     REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
9428                     if (OP(NEXTOPER(br)) != NOTHING || regnext(NEXTOPER(br)) != ender)
9429                         is_nothing= 0;
9430                 }
9431                 else if (op == BRANCHJ) {
9432                     REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
9433                     /* for now we always disable this optimisation * /
9434                     if (OP(NEXTOPER(NEXTOPER(br))) != NOTHING || regnext(NEXTOPER(NEXTOPER(br))) != ender)
9435                     */
9436                         is_nothing= 0;
9437                 }
9438             }
9439             if (is_nothing) {
9440                 br= PL_regkind[OP(ret)] != BRANCH ? regnext(ret) : ret;
9441                 DEBUG_PARSE_r(if (!SIZE_ONLY) {
9442                     SV * const mysv_val1=sv_newmortal();
9443                     SV * const mysv_val2=sv_newmortal();
9444                     DEBUG_PARSE_MSG("NADA");
9445                     regprop(RExC_rx, mysv_val1, ret);
9446                     regprop(RExC_rx, mysv_val2, ender);
9447                     PerlIO_printf(Perl_debug_log, "~ converting ret %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
9448                                   SvPV_nolen_const(mysv_val1),
9449                                   (IV)REG_NODE_NUM(ret),
9450                                   SvPV_nolen_const(mysv_val2),
9451                                   (IV)REG_NODE_NUM(ender),
9452                                   (IV)(ender - ret)
9453                     );
9454                 });
9455                 OP(br)= NOTHING;
9456                 if (OP(ender) == TAIL) {
9457                     NEXT_OFF(br)= 0;
9458                     RExC_emit= br + 1;
9459                 } else {
9460                     regnode *opt;
9461                     for ( opt= br + 1; opt < ender ; opt++ )
9462                         OP(opt)= OPTIMIZED;
9463                     NEXT_OFF(br)= ender - br;
9464                 }
9465             }
9466         }
9467     }
9468
9469     {
9470         const char *p;
9471         static const char parens[] = "=!<,>";
9472
9473         if (paren && (p = strchr(parens, paren))) {
9474             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
9475             int flag = (p - parens) > 1;
9476
9477             if (paren == '>')
9478                 node = SUSPEND, flag = 0;
9479             reginsert(pRExC_state, node,ret, depth+1);
9480             Set_Node_Cur_Length(ret, parse_start);
9481             Set_Node_Offset(ret, parse_start + 1);
9482             ret->flags = flag;
9483             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
9484         }
9485     }
9486
9487     /* Check for proper termination. */
9488     if (paren) {
9489         /* restore original flags, but keep (?p) */
9490         RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY);
9491         if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
9492             RExC_parse = oregcomp_parse;
9493             vFAIL("Unmatched (");
9494         }
9495     }
9496     else if (!paren && RExC_parse < RExC_end) {
9497         if (*RExC_parse == ')') {
9498             RExC_parse++;
9499             vFAIL("Unmatched )");
9500         }
9501         else
9502             FAIL("Junk on end of regexp");      /* "Can't happen". */
9503         assert(0); /* NOTREACHED */
9504     }
9505
9506     if (RExC_in_lookbehind) {
9507         RExC_in_lookbehind--;
9508     }
9509     if (after_freeze > RExC_npar)
9510         RExC_npar = after_freeze;
9511     return(ret);
9512 }
9513
9514 /*
9515  - regbranch - one alternative of an | operator
9516  *
9517  * Implements the concatenation operator.
9518  *
9519  * Returns NULL, setting *flagp to RESTART_UTF8 if the sizing scan needs to be
9520  * restarted.
9521  */
9522 STATIC regnode *
9523 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
9524 {
9525     dVAR;
9526     regnode *ret;
9527     regnode *chain = NULL;
9528     regnode *latest;
9529     I32 flags = 0, c = 0;
9530     GET_RE_DEBUG_FLAGS_DECL;
9531
9532     PERL_ARGS_ASSERT_REGBRANCH;
9533
9534     DEBUG_PARSE("brnc");
9535
9536     if (first)
9537         ret = NULL;
9538     else {
9539         if (!SIZE_ONLY && RExC_extralen)
9540             ret = reganode(pRExC_state, BRANCHJ,0);
9541         else {
9542             ret = reg_node(pRExC_state, BRANCH);
9543             Set_Node_Length(ret, 1);
9544         }
9545     }
9546
9547     if (!first && SIZE_ONLY)
9548         RExC_extralen += 1;                     /* BRANCHJ */
9549
9550     *flagp = WORST;                     /* Tentatively. */
9551
9552     RExC_parse--;
9553     nextchar(pRExC_state);
9554     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
9555         flags &= ~TRYAGAIN;
9556         latest = regpiece(pRExC_state, &flags,depth+1);
9557         if (latest == NULL) {
9558             if (flags & TRYAGAIN)
9559                 continue;
9560             if (flags & RESTART_UTF8) {
9561                 *flagp = RESTART_UTF8;
9562                 return NULL;
9563             }
9564             FAIL2("panic: regpiece returned NULL, flags=%#"UVxf"", (UV) flags);
9565         }
9566         else if (ret == NULL)
9567             ret = latest;
9568         *flagp |= flags&(HASWIDTH|POSTPONED);
9569         if (chain == NULL)      /* First piece. */
9570             *flagp |= flags&SPSTART;
9571         else {
9572             RExC_naughty++;
9573             REGTAIL(pRExC_state, chain, latest);
9574         }
9575         chain = latest;
9576         c++;
9577     }
9578     if (chain == NULL) {        /* Loop ran zero times. */
9579         chain = reg_node(pRExC_state, NOTHING);
9580         if (ret == NULL)
9581             ret = chain;
9582     }
9583     if (c == 1) {
9584         *flagp |= flags&SIMPLE;
9585     }
9586
9587     return ret;
9588 }
9589
9590 /*
9591  - regpiece - something followed by possible [*+?]
9592  *
9593  * Note that the branching code sequences used for ? and the general cases
9594  * of * and + are somewhat optimized:  they use the same NOTHING node as
9595  * both the endmarker for their branch list and the body of the last branch.
9596  * It might seem that this node could be dispensed with entirely, but the
9597  * endmarker role is not redundant.
9598  *
9599  * Returns NULL, setting *flagp to TRYAGAIN if regatom() returns NULL with
9600  * TRYAGAIN.
9601  * Returns NULL, setting *flagp to RESTART_UTF8 if the sizing scan needs to be
9602  * restarted.
9603  */
9604 STATIC regnode *
9605 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
9606 {
9607     dVAR;
9608     regnode *ret;
9609     char op;
9610     char *next;
9611     I32 flags;
9612     const char * const origparse = RExC_parse;
9613     I32 min;
9614     I32 max = REG_INFTY;
9615 #ifdef RE_TRACK_PATTERN_OFFSETS
9616     char *parse_start;
9617 #endif
9618     const char *maxpos = NULL;
9619
9620     /* Save the original in case we change the emitted regop to a FAIL. */
9621     regnode * const orig_emit = RExC_emit;
9622
9623     GET_RE_DEBUG_FLAGS_DECL;
9624
9625     PERL_ARGS_ASSERT_REGPIECE;
9626
9627     DEBUG_PARSE("piec");
9628
9629     ret = regatom(pRExC_state, &flags,depth+1);
9630     if (ret == NULL) {
9631         if (flags & (TRYAGAIN|RESTART_UTF8))
9632             *flagp |= flags & (TRYAGAIN|RESTART_UTF8);
9633         else
9634             FAIL2("panic: regatom returned NULL, flags=%#"UVxf"", (UV) flags);
9635         return(NULL);
9636     }
9637
9638     op = *RExC_parse;
9639
9640     if (op == '{' && regcurly(RExC_parse, FALSE)) {
9641         maxpos = NULL;
9642 #ifdef RE_TRACK_PATTERN_OFFSETS
9643         parse_start = RExC_parse; /* MJD */
9644 #endif
9645         next = RExC_parse + 1;
9646         while (isDIGIT(*next) || *next == ',') {
9647             if (*next == ',') {
9648                 if (maxpos)
9649                     break;
9650                 else
9651                     maxpos = next;
9652             }
9653             next++;
9654         }
9655         if (*next == '}') {             /* got one */
9656             if (!maxpos)
9657                 maxpos = next;
9658             RExC_parse++;
9659             min = atoi(RExC_parse);
9660             if (*maxpos == ',')
9661                 maxpos++;
9662             else
9663                 maxpos = RExC_parse;
9664             max = atoi(maxpos);
9665             if (!max && *maxpos != '0')
9666                 max = REG_INFTY;                /* meaning "infinity" */
9667             else if (max >= REG_INFTY)
9668                 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
9669             RExC_parse = next;
9670             nextchar(pRExC_state);
9671             if (max < min) {    /* If can't match, warn and optimize to fail
9672                                    unconditionally */
9673                 if (SIZE_ONLY) {
9674                     ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
9675
9676                     /* We can't back off the size because we have to reserve
9677                      * enough space for all the things we are about to throw
9678                      * away, but we can shrink it by the ammount we are about
9679                      * to re-use here */
9680                     RExC_size = PREVOPER(RExC_size) - regarglen[(U8)OPFAIL];
9681                 }
9682                 else {
9683                     RExC_emit = orig_emit;
9684                 }
9685                 ret = reg_node(pRExC_state, OPFAIL);
9686                 return ret;
9687             }
9688
9689         do_curly:
9690             if ((flags&SIMPLE)) {
9691                 RExC_naughty += 2 + RExC_naughty / 2;
9692                 reginsert(pRExC_state, CURLY, ret, depth+1);
9693                 Set_Node_Offset(ret, parse_start+1); /* MJD */
9694                 Set_Node_Cur_Length(ret, parse_start);
9695             }
9696             else {
9697                 regnode * const w = reg_node(pRExC_state, WHILEM);
9698
9699                 w->flags = 0;
9700                 REGTAIL(pRExC_state, ret, w);
9701                 if (!SIZE_ONLY && RExC_extralen) {
9702                     reginsert(pRExC_state, LONGJMP,ret, depth+1);
9703                     reginsert(pRExC_state, NOTHING,ret, depth+1);
9704                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
9705                 }
9706                 reginsert(pRExC_state, CURLYX,ret, depth+1);
9707                                 /* MJD hk */
9708                 Set_Node_Offset(ret, parse_start+1);
9709                 Set_Node_Length(ret,
9710                                 op == '{' ? (RExC_parse - parse_start) : 1);
9711
9712                 if (!SIZE_ONLY && RExC_extralen)
9713                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
9714                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
9715                 if (SIZE_ONLY)
9716                     RExC_whilem_seen++, RExC_extralen += 3;
9717                 RExC_naughty += 4 + RExC_naughty;       /* compound interest */
9718             }
9719             ret->flags = 0;
9720
9721             if (min > 0)
9722                 *flagp = WORST;
9723             if (max > 0)
9724                 *flagp |= HASWIDTH;
9725             if (!SIZE_ONLY) {
9726                 ARG1_SET(ret, (U16)min);
9727                 ARG2_SET(ret, (U16)max);
9728             }
9729
9730             goto nest_check;
9731         }
9732     }
9733
9734     if (!ISMULT1(op)) {
9735         *flagp = flags;
9736         return(ret);
9737     }
9738
9739 #if 0                           /* Now runtime fix should be reliable. */
9740
9741     /* if this is reinstated, don't forget to put this back into perldiag:
9742
9743             =item Regexp *+ operand could be empty at {#} in regex m/%s/
9744
9745            (F) The part of the regexp subject to either the * or + quantifier
9746            could match an empty string. The {#} shows in the regular
9747            expression about where the problem was discovered.
9748
9749     */
9750
9751     if (!(flags&HASWIDTH) && op != '?')
9752       vFAIL("Regexp *+ operand could be empty");
9753 #endif
9754
9755 #ifdef RE_TRACK_PATTERN_OFFSETS
9756     parse_start = RExC_parse;
9757 #endif
9758     nextchar(pRExC_state);
9759
9760     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
9761
9762     if (op == '*' && (flags&SIMPLE)) {
9763         reginsert(pRExC_state, STAR, ret, depth+1);
9764         ret->flags = 0;
9765         RExC_naughty += 4;
9766     }
9767     else if (op == '*') {
9768         min = 0;
9769         goto do_curly;
9770     }
9771     else if (op == '+' && (flags&SIMPLE)) {
9772         reginsert(pRExC_state, PLUS, ret, depth+1);
9773         ret->flags = 0;
9774         RExC_naughty += 3;
9775     }
9776     else if (op == '+') {
9777         min = 1;
9778         goto do_curly;
9779     }
9780     else if (op == '?') {
9781         min = 0; max = 1;
9782         goto do_curly;
9783     }
9784   nest_check:
9785     if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
9786         SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
9787         ckWARN3reg(RExC_parse,
9788                    "%.*s matches null string many times",
9789                    (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
9790                    origparse);
9791         (void)ReREFCNT_inc(RExC_rx_sv);
9792     }
9793
9794     if (RExC_parse < RExC_end && *RExC_parse == '?') {
9795         nextchar(pRExC_state);
9796         reginsert(pRExC_state, MINMOD, ret, depth+1);
9797         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
9798     }
9799     else
9800     if (RExC_parse < RExC_end && *RExC_parse == '+') {
9801         regnode *ender;
9802         nextchar(pRExC_state);
9803         ender = reg_node(pRExC_state, SUCCEED);
9804         REGTAIL(pRExC_state, ret, ender);
9805         reginsert(pRExC_state, SUSPEND, ret, depth+1);
9806         ret->flags = 0;
9807         ender = reg_node(pRExC_state, TAIL);
9808         REGTAIL(pRExC_state, ret, ender);
9809     }
9810
9811     if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
9812         RExC_parse++;
9813         vFAIL("Nested quantifiers");
9814     }
9815
9816     return(ret);
9817 }
9818
9819 STATIC bool
9820 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state, regnode** node_p, UV *valuep, I32 *flagp, U32 depth, bool in_char_class,
9821         const bool strict   /* Apply stricter parsing rules? */
9822     )
9823 {
9824    
9825  /* This is expected to be called by a parser routine that has recognized '\N'
9826    and needs to handle the rest. RExC_parse is expected to point at the first
9827    char following the N at the time of the call.  On successful return,
9828    RExC_parse has been updated to point to just after the sequence identified
9829    by this routine, and <*flagp> has been updated.
9830
9831    The \N may be inside (indicated by the boolean <in_char_class>) or outside a
9832    character class.
9833
9834    \N may begin either a named sequence, or if outside a character class, mean
9835    to match a non-newline.  For non single-quoted regexes, the tokenizer has
9836    attempted to decide which, and in the case of a named sequence, converted it
9837    into one of the forms: \N{} (if the sequence is null), or \N{U+c1.c2...},
9838    where c1... are the characters in the sequence.  For single-quoted regexes,
9839    the tokenizer passes the \N sequence through unchanged; this code will not
9840    attempt to determine this nor expand those, instead raising a syntax error.
9841    The net effect is that if the beginning of the passed-in pattern isn't '{U+'
9842    or there is no '}', it signals that this \N occurrence means to match a
9843    non-newline.
9844
9845    Only the \N{U+...} form should occur in a character class, for the same
9846    reason that '.' inside a character class means to just match a period: it
9847    just doesn't make sense.
9848
9849    The function raises an error (via vFAIL), and doesn't return for various
9850    syntax errors.  Otherwise it returns TRUE and sets <node_p> or <valuep> on
9851    success; it returns FALSE otherwise. Returns FALSE, setting *flagp to
9852    RESTART_UTF8 if the sizing scan needs to be restarted. Such a restart is
9853    only possible if node_p is non-NULL.
9854
9855
9856    If <valuep> is non-null, it means the caller can accept an input sequence
9857    consisting of a just a single code point; <*valuep> is set to that value
9858    if the input is such.
9859
9860    If <node_p> is non-null it signifies that the caller can accept any other
9861    legal sequence (i.e., one that isn't just a single code point).  <*node_p>
9862    is set as follows:
9863     1) \N means not-a-NL: points to a newly created REG_ANY node;
9864     2) \N{}:              points to a new NOTHING node;
9865     3) otherwise:         points to a new EXACT node containing the resolved
9866                           string.
9867    Note that FALSE is returned for single code point sequences if <valuep> is
9868    null.
9869  */
9870
9871     char * endbrace;    /* '}' following the name */
9872     char* p;
9873     char *endchar;      /* Points to '.' or '}' ending cur char in the input
9874                            stream */
9875     bool has_multiple_chars; /* true if the input stream contains a sequence of
9876                                 more than one character */
9877
9878     GET_RE_DEBUG_FLAGS_DECL;
9879  
9880     PERL_ARGS_ASSERT_GROK_BSLASH_N;
9881
9882     GET_RE_DEBUG_FLAGS;
9883
9884     assert(cBOOL(node_p) ^ cBOOL(valuep));  /* Exactly one should be set */
9885
9886     /* The [^\n] meaning of \N ignores spaces and comments under the /x
9887      * modifier.  The other meaning does not */
9888     p = (RExC_flags & RXf_PMf_EXTENDED)
9889         ? regwhite( pRExC_state, RExC_parse )
9890         : RExC_parse;
9891
9892     /* Disambiguate between \N meaning a named character versus \N meaning
9893      * [^\n].  The former is assumed when it can't be the latter. */
9894     if (*p != '{' || regcurly(p, FALSE)) {
9895         RExC_parse = p;
9896         if (! node_p) {
9897             /* no bare \N in a charclass */
9898             if (in_char_class) {
9899                 vFAIL("\\N in a character class must be a named character: \\N{...}");
9900             }
9901             return FALSE;
9902         }
9903         nextchar(pRExC_state);
9904         *node_p = reg_node(pRExC_state, REG_ANY);
9905         *flagp |= HASWIDTH|SIMPLE;
9906         RExC_naughty++;
9907         RExC_parse--;
9908         Set_Node_Length(*node_p, 1); /* MJD */
9909         return TRUE;
9910     }
9911
9912     /* Here, we have decided it should be a named character or sequence */
9913
9914     /* The test above made sure that the next real character is a '{', but
9915      * under the /x modifier, it could be separated by space (or a comment and
9916      * \n) and this is not allowed (for consistency with \x{...} and the
9917      * tokenizer handling of \N{NAME}). */
9918     if (*RExC_parse != '{') {
9919         vFAIL("Missing braces on \\N{}");
9920     }
9921
9922     RExC_parse++;       /* Skip past the '{' */
9923
9924     if (! (endbrace = strchr(RExC_parse, '}')) /* no trailing brace */
9925         || ! (endbrace == RExC_parse            /* nothing between the {} */
9926               || (endbrace - RExC_parse >= 2    /* U+ (bad hex is checked below */
9927                   && strnEQ(RExC_parse, "U+", 2)))) /* for a better error msg) */
9928     {
9929         if (endbrace) RExC_parse = endbrace;    /* position msg's '<--HERE' */
9930         vFAIL("\\N{NAME} must be resolved by the lexer");
9931     }
9932
9933     if (endbrace == RExC_parse) {   /* empty: \N{} */
9934         bool ret = TRUE;
9935         if (node_p) {
9936             *node_p = reg_node(pRExC_state,NOTHING);
9937         }
9938         else if (in_char_class) {
9939             if (SIZE_ONLY && in_char_class) {
9940                 if (strict) {
9941                     RExC_parse++;   /* Position after the "}" */
9942                     vFAIL("Zero length \\N{}");
9943                 }
9944                 else {
9945                     ckWARNreg(RExC_parse,
9946                               "Ignoring zero length \\N{} in character class");
9947                 }
9948             }
9949             ret = FALSE;
9950         }
9951         else {
9952             return FALSE;
9953         }
9954         nextchar(pRExC_state);
9955         return ret;
9956     }
9957
9958     RExC_uni_semantics = 1; /* Unicode named chars imply Unicode semantics */
9959     RExC_parse += 2;    /* Skip past the 'U+' */
9960
9961     endchar = RExC_parse + strcspn(RExC_parse, ".}");
9962
9963     /* Code points are separated by dots.  If none, there is only one code
9964      * point, and is terminated by the brace */
9965     has_multiple_chars = (endchar < endbrace);
9966
9967     if (valuep && (! has_multiple_chars || in_char_class)) {
9968         /* We only pay attention to the first char of
9969         multichar strings being returned in char classes. I kinda wonder
9970         if this makes sense as it does change the behaviour
9971         from earlier versions, OTOH that behaviour was broken
9972         as well. XXX Solution is to recharacterize as
9973         [rest-of-class]|multi1|multi2... */
9974
9975         STRLEN length_of_hex = (STRLEN)(endchar - RExC_parse);
9976         I32 grok_hex_flags = PERL_SCAN_ALLOW_UNDERSCORES
9977             | PERL_SCAN_DISALLOW_PREFIX
9978             | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
9979
9980         *valuep = grok_hex(RExC_parse, &length_of_hex, &grok_hex_flags, NULL);
9981
9982         /* The tokenizer should have guaranteed validity, but it's possible to
9983          * bypass it by using single quoting, so check */
9984         if (length_of_hex == 0
9985             || length_of_hex != (STRLEN)(endchar - RExC_parse) )
9986         {
9987             RExC_parse += length_of_hex;        /* Includes all the valid */
9988             RExC_parse += (RExC_orig_utf8)      /* point to after 1st invalid */
9989                             ? UTF8SKIP(RExC_parse)
9990                             : 1;
9991             /* Guard against malformed utf8 */
9992             if (RExC_parse >= endchar) {
9993                 RExC_parse = endchar;
9994             }
9995             vFAIL("Invalid hexadecimal number in \\N{U+...}");
9996         }
9997
9998         if (in_char_class && has_multiple_chars) {
9999             if (strict) {
10000                 RExC_parse = endbrace;
10001                 vFAIL("\\N{} in character class restricted to one character");
10002             }
10003             else {
10004                 ckWARNreg(endchar, "Using just the first character returned by \\N{} in character class");
10005             }
10006         }
10007
10008         RExC_parse = endbrace + 1;
10009     }
10010     else if (! node_p || ! has_multiple_chars) {
10011
10012         /* Here, the input is legal, but not according to the caller's
10013          * options.  We fail without advancing the parse, so that the
10014          * caller can try again */
10015         RExC_parse = p;
10016         return FALSE;
10017     }
10018     else {
10019
10020         /* What is done here is to convert this to a sub-pattern of the form
10021          * (?:\x{char1}\x{char2}...)
10022          * and then call reg recursively.  That way, it retains its atomicness,
10023          * while not having to worry about special handling that some code
10024          * points may have.  toke.c has converted the original Unicode values
10025          * to native, so that we can just pass on the hex values unchanged.  We
10026          * do have to set a flag to keep recoding from happening in the
10027          * recursion */
10028
10029         SV * substitute_parse = newSVpvn_flags("?:", 2, SVf_UTF8|SVs_TEMP);
10030         STRLEN len;
10031         char *orig_end = RExC_end;
10032         I32 flags;
10033
10034         while (RExC_parse < endbrace) {
10035
10036             /* Convert to notation the rest of the code understands */
10037             sv_catpv(substitute_parse, "\\x{");
10038             sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse);
10039             sv_catpv(substitute_parse, "}");
10040
10041             /* Point to the beginning of the next character in the sequence. */
10042             RExC_parse = endchar + 1;
10043             endchar = RExC_parse + strcspn(RExC_parse, ".}");
10044         }
10045         sv_catpv(substitute_parse, ")");
10046
10047         RExC_parse = SvPV(substitute_parse, len);
10048
10049         /* Don't allow empty number */
10050         if (len < 8) {
10051             vFAIL("Invalid hexadecimal number in \\N{U+...}");
10052         }
10053         RExC_end = RExC_parse + len;
10054
10055         /* The values are Unicode, and therefore not subject to recoding */
10056         RExC_override_recoding = 1;
10057
10058         if (!(*node_p = reg(pRExC_state, 1, &flags, depth+1))) {
10059             if (flags & RESTART_UTF8) {
10060                 *flagp = RESTART_UTF8;
10061                 return FALSE;
10062             }
10063             FAIL2("panic: reg returned NULL to grok_bslash_N, flags=%#"UVxf"",
10064                   (UV) flags);
10065         } 
10066         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
10067
10068         RExC_parse = endbrace;
10069         RExC_end = orig_end;
10070         RExC_override_recoding = 0;
10071
10072         nextchar(pRExC_state);
10073     }
10074
10075     return TRUE;
10076 }
10077
10078
10079 /*
10080  * reg_recode
10081  *
10082  * It returns the code point in utf8 for the value in *encp.
10083  *    value: a code value in the source encoding
10084  *    encp:  a pointer to an Encode object
10085  *
10086  * If the result from Encode is not a single character,
10087  * it returns U+FFFD (Replacement character) and sets *encp to NULL.
10088  */
10089 STATIC UV
10090 S_reg_recode(pTHX_ const char value, SV **encp)
10091 {
10092     STRLEN numlen = 1;
10093     SV * const sv = newSVpvn_flags(&value, numlen, SVs_TEMP);
10094     const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
10095     const STRLEN newlen = SvCUR(sv);
10096     UV uv = UNICODE_REPLACEMENT;
10097
10098     PERL_ARGS_ASSERT_REG_RECODE;
10099
10100     if (newlen)
10101         uv = SvUTF8(sv)
10102              ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
10103              : *(U8*)s;
10104
10105     if (!newlen || numlen != newlen) {
10106         uv = UNICODE_REPLACEMENT;
10107         *encp = NULL;
10108     }
10109     return uv;
10110 }
10111
10112 PERL_STATIC_INLINE U8
10113 S_compute_EXACTish(pTHX_ RExC_state_t *pRExC_state)
10114 {
10115     U8 op;
10116
10117     PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
10118
10119     if (! FOLD) {
10120         return EXACT;
10121     }
10122
10123     op = get_regex_charset(RExC_flags);
10124     if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
10125         op--; /* /a is same as /u, and map /aa's offset to what /a's would have
10126                  been, so there is no hole */
10127     }
10128
10129     return op + EXACTF;
10130 }
10131
10132 PERL_STATIC_INLINE void
10133 S_alloc_maybe_populate_EXACT(pTHX_ RExC_state_t *pRExC_state, regnode *node, I32* flagp, STRLEN len, UV code_point)
10134 {
10135     /* This knows the details about sizing an EXACTish node, setting flags for
10136      * it (by setting <*flagp>, and potentially populating it with a single
10137      * character.
10138      *
10139      * If <len> (the length in bytes) is non-zero, this function assumes that
10140      * the node has already been populated, and just does the sizing.  In this
10141      * case <code_point> should be the final code point that has already been
10142      * placed into the node.  This value will be ignored except that under some
10143      * circumstances <*flagp> is set based on it.
10144      *
10145      * If <len> is zero, the function assumes that the node is to contain only
10146      * the single character given by <code_point> and calculates what <len>
10147      * should be.  In pass 1, it sizes the node appropriately.  In pass 2, it
10148      * additionally will populate the node's STRING with <code_point>, if <len>
10149      * is 0.  In both cases <*flagp> is appropriately set
10150      *
10151      * It knows that under FOLD, the Latin Sharp S and UTF characters above
10152      * 255, must be folded (the former only when the rules indicate it can
10153      * match 'ss') */
10154
10155     bool len_passed_in = cBOOL(len != 0);
10156     U8 character[UTF8_MAXBYTES_CASE+1];
10157
10158     PERL_ARGS_ASSERT_ALLOC_MAYBE_POPULATE_EXACT;
10159
10160     if (! len_passed_in) {
10161         if (UTF) {
10162             if (FOLD && (! LOC || code_point > 255)) {
10163                 _to_uni_fold_flags(NATIVE_TO_UNI(code_point),
10164                                    character,
10165                                    &len,
10166                                    FOLD_FLAGS_FULL | ((LOC)
10167                                                      ? FOLD_FLAGS_LOCALE
10168                                                      : (ASCII_FOLD_RESTRICTED)
10169                                                        ? FOLD_FLAGS_NOMIX_ASCII
10170                                                        : 0));
10171             }
10172             else {
10173                 uvchr_to_utf8( character, code_point);
10174                 len = UTF8SKIP(character);
10175             }
10176         }
10177         else if (! FOLD
10178                  || code_point != LATIN_SMALL_LETTER_SHARP_S
10179                  || ASCII_FOLD_RESTRICTED
10180                  || ! AT_LEAST_UNI_SEMANTICS)
10181         {
10182             *character = (U8) code_point;
10183             len = 1;
10184         }
10185         else {
10186             *character = 's';
10187             *(character + 1) = 's';
10188             len = 2;
10189         }
10190     }
10191
10192     if (SIZE_ONLY) {
10193         RExC_size += STR_SZ(len);
10194     }
10195     else {
10196         RExC_emit += STR_SZ(len);
10197         STR_LEN(node) = len;
10198         if (! len_passed_in) {
10199             Copy((char *) character, STRING(node), len, char);
10200         }
10201     }
10202
10203     *flagp |= HASWIDTH;
10204
10205     /* A single character node is SIMPLE, except for the special-cased SHARP S
10206      * under /di. */
10207     if ((len == 1 || (UTF && len == UNISKIP(code_point)))
10208         && (code_point != LATIN_SMALL_LETTER_SHARP_S
10209             || ! FOLD || ! DEPENDS_SEMANTICS))
10210     {
10211         *flagp |= SIMPLE;
10212     }
10213 }
10214
10215 /*
10216  - regatom - the lowest level
10217
10218    Try to identify anything special at the start of the pattern. If there
10219    is, then handle it as required. This may involve generating a single regop,
10220    such as for an assertion; or it may involve recursing, such as to
10221    handle a () structure.
10222
10223    If the string doesn't start with something special then we gobble up
10224    as much literal text as we can.
10225
10226    Once we have been able to handle whatever type of thing started the
10227    sequence, we return.
10228
10229    Note: we have to be careful with escapes, as they can be both literal
10230    and special, and in the case of \10 and friends, context determines which.
10231
10232    A summary of the code structure is:
10233
10234    switch (first_byte) {
10235         cases for each special:
10236             handle this special;
10237             break;
10238         case '\\':
10239             switch (2nd byte) {
10240                 cases for each unambiguous special:
10241                     handle this special;
10242                     break;
10243                 cases for each ambigous special/literal:
10244                     disambiguate;
10245                     if (special)  handle here
10246                     else goto defchar;
10247                 default: // unambiguously literal:
10248                     goto defchar;
10249             }
10250         default:  // is a literal char
10251             // FALL THROUGH
10252         defchar:
10253             create EXACTish node for literal;
10254             while (more input and node isn't full) {
10255                 switch (input_byte) {
10256                    cases for each special;
10257                        make sure parse pointer is set so that the next call to
10258                            regatom will see this special first
10259                        goto loopdone; // EXACTish node terminated by prev. char
10260                    default:
10261                        append char to EXACTISH node;
10262                 }
10263                 get next input byte;
10264             }
10265         loopdone:
10266    }
10267    return the generated node;
10268
10269    Specifically there are two separate switches for handling
10270    escape sequences, with the one for handling literal escapes requiring
10271    a dummy entry for all of the special escapes that are actually handled
10272    by the other.
10273
10274    Returns NULL, setting *flagp to TRYAGAIN if reg() returns NULL with
10275    TRYAGAIN.  
10276    Returns NULL, setting *flagp to RESTART_UTF8 if the sizing scan needs to be
10277    restarted.
10278    Otherwise does not return NULL.
10279 */
10280
10281 STATIC regnode *
10282 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
10283 {
10284     dVAR;
10285     regnode *ret = NULL;
10286     I32 flags = 0;
10287     char *parse_start = RExC_parse;
10288     U8 op;
10289     int invert = 0;
10290
10291     GET_RE_DEBUG_FLAGS_DECL;
10292
10293     *flagp = WORST;             /* Tentatively. */
10294
10295     DEBUG_PARSE("atom");
10296
10297     PERL_ARGS_ASSERT_REGATOM;
10298
10299 tryagain:
10300     switch ((U8)*RExC_parse) {
10301     case '^':
10302         RExC_seen_zerolen++;
10303         nextchar(pRExC_state);
10304         if (RExC_flags & RXf_PMf_MULTILINE)
10305             ret = reg_node(pRExC_state, MBOL);
10306         else if (RExC_flags & RXf_PMf_SINGLELINE)
10307             ret = reg_node(pRExC_state, SBOL);
10308         else
10309             ret = reg_node(pRExC_state, BOL);
10310         Set_Node_Length(ret, 1); /* MJD */
10311         break;
10312     case '$':
10313         nextchar(pRExC_state);
10314         if (*RExC_parse)
10315             RExC_seen_zerolen++;
10316         if (RExC_flags & RXf_PMf_MULTILINE)
10317             ret = reg_node(pRExC_state, MEOL);
10318         else if (RExC_flags & RXf_PMf_SINGLELINE)
10319             ret = reg_node(pRExC_state, SEOL);
10320         else
10321             ret = reg_node(pRExC_state, EOL);
10322         Set_Node_Length(ret, 1); /* MJD */
10323         break;
10324     case '.':
10325         nextchar(pRExC_state);
10326         if (RExC_flags & RXf_PMf_SINGLELINE)
10327             ret = reg_node(pRExC_state, SANY);
10328         else
10329             ret = reg_node(pRExC_state, REG_ANY);
10330         *flagp |= HASWIDTH|SIMPLE;
10331         RExC_naughty++;
10332         Set_Node_Length(ret, 1); /* MJD */
10333         break;
10334     case '[':
10335     {
10336         char * const oregcomp_parse = ++RExC_parse;
10337         ret = regclass(pRExC_state, flagp,depth+1,
10338                        FALSE, /* means parse the whole char class */
10339                        TRUE, /* allow multi-char folds */
10340                        FALSE, /* don't silence non-portable warnings. */
10341                        NULL);
10342         if (*RExC_parse != ']') {
10343             RExC_parse = oregcomp_parse;
10344             vFAIL("Unmatched [");
10345         }
10346         if (ret == NULL) {
10347             if (*flagp & RESTART_UTF8)
10348                 return NULL;
10349             FAIL2("panic: regclass returned NULL to regatom, flags=%#"UVxf"",
10350                   (UV) *flagp);
10351         }
10352         nextchar(pRExC_state);
10353         Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
10354         break;
10355     }
10356     case '(':
10357         nextchar(pRExC_state);
10358         ret = reg(pRExC_state, 2, &flags,depth+1);
10359         if (ret == NULL) {
10360                 if (flags & TRYAGAIN) {
10361                     if (RExC_parse == RExC_end) {
10362                          /* Make parent create an empty node if needed. */
10363                         *flagp |= TRYAGAIN;
10364                         return(NULL);
10365                     }
10366                     goto tryagain;
10367                 }
10368                 if (flags & RESTART_UTF8) {
10369                     *flagp = RESTART_UTF8;
10370                     return NULL;
10371                 }
10372                 FAIL2("panic: reg returned NULL to regatom, flags=%#"UVxf"", (UV) flags);
10373         }
10374         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
10375         break;
10376     case '|':
10377     case ')':
10378         if (flags & TRYAGAIN) {
10379             *flagp |= TRYAGAIN;
10380             return NULL;
10381         }
10382         vFAIL("Internal urp");
10383                                 /* Supposed to be caught earlier. */
10384         break;
10385     case '{':
10386         if (!regcurly(RExC_parse, FALSE)) {
10387             RExC_parse++;
10388             goto defchar;
10389         }
10390         /* FALL THROUGH */
10391     case '?':
10392     case '+':
10393     case '*':
10394         RExC_parse++;
10395         vFAIL("Quantifier follows nothing");
10396         break;
10397     case '\\':
10398         /* Special Escapes
10399
10400            This switch handles escape sequences that resolve to some kind
10401            of special regop and not to literal text. Escape sequnces that
10402            resolve to literal text are handled below in the switch marked
10403            "Literal Escapes".
10404
10405            Every entry in this switch *must* have a corresponding entry
10406            in the literal escape switch. However, the opposite is not
10407            required, as the default for this switch is to jump to the
10408            literal text handling code.
10409         */
10410         switch ((U8)*++RExC_parse) {
10411             U8 arg;
10412         /* Special Escapes */
10413         case 'A':
10414             RExC_seen_zerolen++;
10415             ret = reg_node(pRExC_state, SBOL);
10416             *flagp |= SIMPLE;
10417             goto finish_meta_pat;
10418         case 'G':
10419             ret = reg_node(pRExC_state, GPOS);
10420             RExC_seen |= REG_SEEN_GPOS;
10421             *flagp |= SIMPLE;
10422             goto finish_meta_pat;
10423         case 'K':
10424             RExC_seen_zerolen++;
10425             ret = reg_node(pRExC_state, KEEPS);
10426             *flagp |= SIMPLE;
10427             /* XXX:dmq : disabling in-place substitution seems to
10428              * be necessary here to avoid cases of memory corruption, as
10429              * with: C<$_="x" x 80; s/x\K/y/> -- rgs
10430              */
10431             RExC_seen |= REG_SEEN_LOOKBEHIND;
10432             goto finish_meta_pat;
10433         case 'Z':
10434             ret = reg_node(pRExC_state, SEOL);
10435             *flagp |= SIMPLE;
10436             RExC_seen_zerolen++;                /* Do not optimize RE away */
10437             goto finish_meta_pat;
10438         case 'z':
10439             ret = reg_node(pRExC_state, EOS);
10440             *flagp |= SIMPLE;
10441             RExC_seen_zerolen++;                /* Do not optimize RE away */
10442             goto finish_meta_pat;
10443         case 'C':
10444             ret = reg_node(pRExC_state, CANY);
10445             RExC_seen |= REG_SEEN_CANY;
10446             *flagp |= HASWIDTH|SIMPLE;
10447             goto finish_meta_pat;
10448         case 'X':
10449             ret = reg_node(pRExC_state, CLUMP);
10450             *flagp |= HASWIDTH;
10451             goto finish_meta_pat;
10452
10453         case 'W':
10454             invert = 1;
10455             /* FALLTHROUGH */
10456         case 'w':
10457             arg = ANYOF_WORDCHAR;
10458             goto join_posix;
10459
10460         case 'b':
10461             RExC_seen_zerolen++;
10462             RExC_seen |= REG_SEEN_LOOKBEHIND;
10463             op = BOUND + get_regex_charset(RExC_flags);
10464             if (op > BOUNDA) {  /* /aa is same as /a */
10465                 op = BOUNDA;
10466             }
10467             ret = reg_node(pRExC_state, op);
10468             FLAGS(ret) = get_regex_charset(RExC_flags);
10469             *flagp |= SIMPLE;
10470             if (! SIZE_ONLY && (U8) *(RExC_parse + 1) == '{') {
10471                 ckWARNdep(RExC_parse, "\"\\b{\" is deprecated; use \"\\b\\{\" or \"\\b[{]\" instead");
10472             }
10473             goto finish_meta_pat;
10474         case 'B':
10475             RExC_seen_zerolen++;
10476             RExC_seen |= REG_SEEN_LOOKBEHIND;
10477             op = NBOUND + get_regex_charset(RExC_flags);
10478             if (op > NBOUNDA) { /* /aa is same as /a */
10479                 op = NBOUNDA;
10480             }
10481             ret = reg_node(pRExC_state, op);
10482             FLAGS(ret) = get_regex_charset(RExC_flags);
10483             *flagp |= SIMPLE;
10484             if (! SIZE_ONLY && (U8) *(RExC_parse + 1) == '{') {
10485                 ckWARNdep(RExC_parse, "\"\\B{\" is deprecated; use \"\\B\\{\" or \"\\B[{]\" instead");
10486             }
10487             goto finish_meta_pat;
10488
10489         case 'D':
10490             invert = 1;
10491             /* FALLTHROUGH */
10492         case 'd':
10493             arg = ANYOF_DIGIT;
10494             goto join_posix;
10495
10496         case 'R':
10497             ret = reg_node(pRExC_state, LNBREAK);
10498             *flagp |= HASWIDTH|SIMPLE;
10499             goto finish_meta_pat;
10500
10501         case 'H':
10502             invert = 1;
10503             /* FALLTHROUGH */
10504         case 'h':
10505             arg = ANYOF_BLANK;
10506             op = POSIXU;
10507             goto join_posix_op_known;
10508
10509         case 'V':
10510             invert = 1;
10511             /* FALLTHROUGH */
10512         case 'v':
10513             arg = ANYOF_VERTWS;
10514             op = POSIXU;
10515             goto join_posix_op_known;
10516
10517         case 'S':
10518             invert = 1;
10519             /* FALLTHROUGH */
10520         case 's':
10521             arg = ANYOF_SPACE;
10522
10523         join_posix:
10524
10525             op = POSIXD + get_regex_charset(RExC_flags);
10526             if (op > POSIXA) {  /* /aa is same as /a */
10527                 op = POSIXA;
10528             }
10529
10530         join_posix_op_known:
10531
10532             if (invert) {
10533                 op += NPOSIXD - POSIXD;
10534             }
10535
10536             ret = reg_node(pRExC_state, op);
10537             if (! SIZE_ONLY) {
10538                 FLAGS(ret) = namedclass_to_classnum(arg);
10539             }
10540
10541             *flagp |= HASWIDTH|SIMPLE;
10542             /* FALL THROUGH */
10543
10544          finish_meta_pat:           
10545             nextchar(pRExC_state);
10546             Set_Node_Length(ret, 2); /* MJD */
10547             break;          
10548         case 'p':
10549         case 'P':
10550             {
10551 #ifdef DEBUGGING
10552                 char* parse_start = RExC_parse - 2;
10553 #endif
10554
10555                 RExC_parse--;
10556
10557                 ret = regclass(pRExC_state, flagp,depth+1,
10558                                TRUE, /* means just parse this element */
10559                                FALSE, /* don't allow multi-char folds */
10560                                FALSE, /* don't silence non-portable warnings.
10561                                          It would be a bug if these returned
10562                                          non-portables */
10563                                NULL);
10564                 /* regclass() can only return RESTART_UTF8 if multi-char folds
10565                    are allowed.  */
10566                 if (!ret)
10567                     FAIL2("panic: regclass returned NULL to regatom, flags=%#"UVxf"",
10568                           (UV) *flagp);
10569
10570                 RExC_parse--;
10571
10572                 Set_Node_Offset(ret, parse_start + 2);
10573                 Set_Node_Cur_Length(ret, parse_start);
10574                 nextchar(pRExC_state);
10575             }
10576             break;
10577         case 'N': 
10578             /* Handle \N and \N{NAME} with multiple code points here and not
10579              * below because it can be multicharacter. join_exact() will join
10580              * them up later on.  Also this makes sure that things like
10581              * /\N{BLAH}+/ and \N{BLAH} being multi char Just Happen. dmq.
10582              * The options to the grok function call causes it to fail if the
10583              * sequence is just a single code point.  We then go treat it as
10584              * just another character in the current EXACT node, and hence it
10585              * gets uniform treatment with all the other characters.  The
10586              * special treatment for quantifiers is not needed for such single
10587              * character sequences */
10588             ++RExC_parse;
10589             if (! grok_bslash_N(pRExC_state, &ret, NULL, flagp, depth, FALSE,
10590                                 FALSE /* not strict */ )) {
10591                 if (*flagp & RESTART_UTF8)
10592                     return NULL;
10593                 RExC_parse--;
10594                 goto defchar;
10595             }
10596             break;
10597         case 'k':    /* Handle \k<NAME> and \k'NAME' */
10598         parse_named_seq:
10599         {   
10600             char ch= RExC_parse[1];         
10601             if (ch != '<' && ch != '\'' && ch != '{') {
10602                 RExC_parse++;
10603                 vFAIL2("Sequence %.2s... not terminated",parse_start);
10604             } else {
10605                 /* this pretty much dupes the code for (?P=...) in reg(), if
10606                    you change this make sure you change that */
10607                 char* name_start = (RExC_parse += 2);
10608                 U32 num = 0;
10609                 SV *sv_dat = reg_scan_name(pRExC_state,
10610                     SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
10611                 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
10612                 if (RExC_parse == name_start || *RExC_parse != ch)
10613                     vFAIL2("Sequence %.3s... not terminated",parse_start);
10614
10615                 if (!SIZE_ONLY) {
10616                     num = add_data( pRExC_state, 1, "S" );
10617                     RExC_rxi->data->data[num]=(void*)sv_dat;
10618                     SvREFCNT_inc_simple_void(sv_dat);
10619                 }
10620
10621                 RExC_sawback = 1;
10622                 ret = reganode(pRExC_state,
10623                                ((! FOLD)
10624                                  ? NREF
10625                                  : (ASCII_FOLD_RESTRICTED)
10626                                    ? NREFFA
10627                                    : (AT_LEAST_UNI_SEMANTICS)
10628                                      ? NREFFU
10629                                      : (LOC)
10630                                        ? NREFFL
10631                                        : NREFF),
10632                                 num);
10633                 *flagp |= HASWIDTH;
10634
10635                 /* override incorrect value set in reganode MJD */
10636                 Set_Node_Offset(ret, parse_start+1);
10637                 Set_Node_Cur_Length(ret, parse_start);
10638                 nextchar(pRExC_state);
10639
10640             }
10641             break;
10642         }
10643         case 'g': 
10644         case '1': case '2': case '3': case '4':
10645         case '5': case '6': case '7': case '8': case '9':
10646             {
10647                 I32 num;
10648                 bool isg = *RExC_parse == 'g';
10649                 bool isrel = 0; 
10650                 bool hasbrace = 0;
10651                 if (isg) {
10652                     RExC_parse++;
10653                     if (*RExC_parse == '{') {
10654                         RExC_parse++;
10655                         hasbrace = 1;
10656                     }
10657                     if (*RExC_parse == '-') {
10658                         RExC_parse++;
10659                         isrel = 1;
10660                     }
10661                     if (hasbrace && !isDIGIT(*RExC_parse)) {
10662                         if (isrel) RExC_parse--;
10663                         RExC_parse -= 2;                            
10664                         goto parse_named_seq;
10665                 }   }
10666                 num = atoi(RExC_parse);
10667                 if (isg && num == 0) {
10668                     if (*RExC_parse == '0') {
10669                         vFAIL("Reference to invalid group 0");
10670                     }
10671                     else {
10672                         vFAIL("Unterminated \\g... pattern");
10673                     }
10674                 }
10675                 if (isrel) {
10676                     num = RExC_npar - num;
10677                     if (num < 1)
10678                         vFAIL("Reference to nonexistent or unclosed group");
10679                 }
10680                 if (!isg && num > 9 && num >= RExC_npar && *RExC_parse != '8' && *RExC_parse != '9')
10681                     /* Probably a character specified in octal, e.g. \35 */
10682                     goto defchar;
10683                 else {
10684 #ifdef RE_TRACK_PATTERN_OFFSETS
10685                     char * const parse_start = RExC_parse - 1; /* MJD */
10686 #endif
10687                     while (isDIGIT(*RExC_parse))
10688                         RExC_parse++;
10689                     if (hasbrace) {
10690                         if (*RExC_parse != '}') 
10691                             vFAIL("Unterminated \\g{...} pattern");
10692                         RExC_parse++;
10693                     }    
10694                     if (!SIZE_ONLY) {
10695                         if (num > (I32)RExC_rx->nparens)
10696                             vFAIL("Reference to nonexistent group");
10697                     }
10698                     RExC_sawback = 1;
10699                     ret = reganode(pRExC_state,
10700                                    ((! FOLD)
10701                                      ? REF
10702                                      : (ASCII_FOLD_RESTRICTED)
10703                                        ? REFFA
10704                                        : (AT_LEAST_UNI_SEMANTICS)
10705                                          ? REFFU
10706                                          : (LOC)
10707                                            ? REFFL
10708                                            : REFF),
10709                                     num);
10710                     *flagp |= HASWIDTH;
10711
10712                     /* override incorrect value set in reganode MJD */
10713                     Set_Node_Offset(ret, parse_start+1);
10714                     Set_Node_Cur_Length(ret, parse_start);
10715                     RExC_parse--;
10716                     nextchar(pRExC_state);
10717                 }
10718             }
10719             break;
10720         case '\0':
10721             if (RExC_parse >= RExC_end)
10722                 FAIL("Trailing \\");
10723             /* FALL THROUGH */
10724         default:
10725             /* Do not generate "unrecognized" warnings here, we fall
10726                back into the quick-grab loop below */
10727             parse_start--;
10728             goto defchar;
10729         }
10730         break;
10731
10732     case '#':
10733         if (RExC_flags & RXf_PMf_EXTENDED) {
10734             if ( reg_skipcomment( pRExC_state ) )
10735                 goto tryagain;
10736         }
10737         /* FALL THROUGH */
10738
10739     default:
10740
10741             parse_start = RExC_parse - 1;
10742
10743             RExC_parse++;
10744
10745         defchar: {
10746             STRLEN len = 0;
10747             UV ender;
10748             char *p;
10749             char *s;
10750 #define MAX_NODE_STRING_SIZE 127
10751             char foldbuf[MAX_NODE_STRING_SIZE+UTF8_MAXBYTES_CASE];
10752             char *s0;
10753             U8 upper_parse = MAX_NODE_STRING_SIZE;
10754             STRLEN foldlen;
10755             U8 node_type;
10756             bool next_is_quantifier;
10757             char * oldp = NULL;
10758
10759             /* If a folding node contains only code points that don't
10760              * participate in folds, it can be changed into an EXACT node,
10761              * which allows the optimizer more things to look for */
10762             bool maybe_exact;
10763
10764             ender = 0;
10765             node_type = compute_EXACTish(pRExC_state);
10766             ret = reg_node(pRExC_state, node_type);
10767
10768             /* In pass1, folded, we use a temporary buffer instead of the
10769              * actual node, as the node doesn't exist yet */
10770             s = (SIZE_ONLY && FOLD) ? foldbuf : STRING(ret);
10771
10772             s0 = s;
10773
10774         reparse:
10775
10776             /* We do the EXACTFish to EXACT node only if folding, and not if in
10777              * locale, as whether a character folds or not isn't known until
10778              * runtime */
10779             maybe_exact = FOLD && ! LOC;
10780
10781             /* XXX The node can hold up to 255 bytes, yet this only goes to
10782              * 127.  I (khw) do not know why.  Keeping it somewhat less than
10783              * 255 allows us to not have to worry about overflow due to
10784              * converting to utf8 and fold expansion, but that value is
10785              * 255-UTF8_MAXBYTES_CASE.  join_exact() may join adjacent nodes
10786              * split up by this limit into a single one using the real max of
10787              * 255.  Even at 127, this breaks under rare circumstances.  If
10788              * folding, we do not want to split a node at a character that is a
10789              * non-final in a multi-char fold, as an input string could just
10790              * happen to want to match across the node boundary.  The join
10791              * would solve that problem if the join actually happens.  But a
10792              * series of more than two nodes in a row each of 127 would cause
10793              * the first join to succeed to get to 254, but then there wouldn't
10794              * be room for the next one, which could at be one of those split
10795              * multi-char folds.  I don't know of any fool-proof solution.  One
10796              * could back off to end with only a code point that isn't such a
10797              * non-final, but it is possible for there not to be any in the
10798              * entire node. */
10799             for (p = RExC_parse - 1;
10800                  len < upper_parse && p < RExC_end;
10801                  len++)
10802             {
10803                 oldp = p;
10804
10805                 if (RExC_flags & RXf_PMf_EXTENDED)
10806                     p = regwhite( pRExC_state, p );
10807                 switch ((U8)*p) {
10808                 case '^':
10809                 case '$':
10810                 case '.':
10811                 case '[':
10812                 case '(':
10813                 case ')':
10814                 case '|':
10815                     goto loopdone;
10816                 case '\\':
10817                     /* Literal Escapes Switch
10818
10819                        This switch is meant to handle escape sequences that
10820                        resolve to a literal character.
10821
10822                        Every escape sequence that represents something
10823                        else, like an assertion or a char class, is handled
10824                        in the switch marked 'Special Escapes' above in this
10825                        routine, but also has an entry here as anything that
10826                        isn't explicitly mentioned here will be treated as
10827                        an unescaped equivalent literal.
10828                     */
10829
10830                     switch ((U8)*++p) {
10831                     /* These are all the special escapes. */
10832                     case 'A':             /* Start assertion */
10833                     case 'b': case 'B':   /* Word-boundary assertion*/
10834                     case 'C':             /* Single char !DANGEROUS! */
10835                     case 'd': case 'D':   /* digit class */
10836                     case 'g': case 'G':   /* generic-backref, pos assertion */
10837                     case 'h': case 'H':   /* HORIZWS */
10838                     case 'k': case 'K':   /* named backref, keep marker */
10839                     case 'p': case 'P':   /* Unicode property */
10840                               case 'R':   /* LNBREAK */
10841                     case 's': case 'S':   /* space class */
10842                     case 'v': case 'V':   /* VERTWS */
10843                     case 'w': case 'W':   /* word class */
10844                     case 'X':             /* eXtended Unicode "combining character sequence" */
10845                     case 'z': case 'Z':   /* End of line/string assertion */
10846                         --p;
10847                         goto loopdone;
10848
10849                     /* Anything after here is an escape that resolves to a
10850                        literal. (Except digits, which may or may not)
10851                      */
10852                     case 'n':
10853                         ender = '\n';
10854                         p++;
10855                         break;
10856                     case 'N': /* Handle a single-code point named character. */
10857                         /* The options cause it to fail if a multiple code
10858                          * point sequence.  Handle those in the switch() above
10859                          * */
10860                         RExC_parse = p + 1;
10861                         if (! grok_bslash_N(pRExC_state, NULL, &ender,
10862                                             flagp, depth, FALSE,
10863                                             FALSE /* not strict */ ))
10864                         {
10865                             if (*flagp & RESTART_UTF8)
10866                                 FAIL("panic: grok_bslash_N set RESTART_UTF8");
10867                             RExC_parse = p = oldp;
10868                             goto loopdone;
10869                         }
10870                         p = RExC_parse;
10871                         if (ender > 0xff) {
10872                             REQUIRE_UTF8;
10873                         }
10874                         break;
10875                     case 'r':
10876                         ender = '\r';
10877                         p++;
10878                         break;
10879                     case 't':
10880                         ender = '\t';
10881                         p++;
10882                         break;
10883                     case 'f':
10884                         ender = '\f';
10885                         p++;
10886                         break;
10887                     case 'e':
10888                           ender = ASCII_TO_NATIVE('\033');
10889                         p++;
10890                         break;
10891                     case 'a':
10892                           ender = ASCII_TO_NATIVE('\007');
10893                         p++;
10894                         break;
10895                     case 'o':
10896                         {
10897                             UV result;
10898                             const char* error_msg;
10899
10900                             bool valid = grok_bslash_o(&p,
10901                                                        &result,
10902                                                        &error_msg,
10903                                                        TRUE, /* out warnings */
10904                                                        FALSE, /* not strict */
10905                                                        TRUE, /* Output warnings
10906                                                                 for non-
10907                                                                 portables */
10908                                                        UTF);
10909                             if (! valid) {
10910                                 RExC_parse = p; /* going to die anyway; point
10911                                                    to exact spot of failure */
10912                                 vFAIL(error_msg);
10913                             }
10914                             ender = result;
10915                             if (PL_encoding && ender < 0x100) {
10916                                 goto recode_encoding;
10917                             }
10918                             if (ender > 0xff) {
10919                                 REQUIRE_UTF8;
10920                             }
10921                             break;
10922                         }
10923                     case 'x':
10924                         {
10925                             UV result = UV_MAX; /* initialize to erroneous
10926                                                    value */
10927                             const char* error_msg;
10928
10929                             bool valid = grok_bslash_x(&p,
10930                                                        &result,
10931                                                        &error_msg,
10932                                                        TRUE, /* out warnings */
10933                                                        FALSE, /* not strict */
10934                                                        TRUE, /* Output warnings
10935                                                                 for non-
10936                                                                 portables */
10937                                                        UTF);
10938                             if (! valid) {
10939                                 RExC_parse = p; /* going to die anyway; point
10940                                                    to exact spot of failure */
10941                                 vFAIL(error_msg);
10942                             }
10943                             ender = result;
10944
10945                             if (PL_encoding && ender < 0x100) {
10946                                 goto recode_encoding;
10947                             }
10948                             if (ender > 0xff) {
10949                                 REQUIRE_UTF8;
10950                             }
10951                             break;
10952                         }
10953                     case 'c':
10954                         p++;
10955                         ender = grok_bslash_c(*p++, UTF, SIZE_ONLY);
10956                         break;
10957                     case '8': case '9': /* must be a backreference */
10958                         --p;
10959                         goto loopdone;
10960                     case '1': case '2': case '3':case '4':
10961                     case '5': case '6': case '7':
10962                         /* When we parse backslash escapes there is ambiguity between
10963                          * backreferences and octal escapes. Any escape from \1 - \9 is
10964                          * a backreference, any multi-digit escape which does not start with
10965                          * 0 and which when evaluated as decimal could refer to an already
10966                          * parsed capture buffer is a backslash. Anything else is octal.
10967                          *
10968                          * Note this implies that \118 could be interpreted as 118 OR as
10969                          * "\11" . "8" depending on whether there were 118 capture buffers
10970                          * defined already in the pattern.
10971                          */
10972                         if ( !isDIGIT(p[1]) || atoi(p) <= RExC_npar )
10973                         {  /* Not to be treated as an octal constant, go
10974                                    find backref */
10975                             --p;
10976                             goto loopdone;
10977                         }
10978                     case '0':
10979                         {
10980                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
10981                             STRLEN numlen = 3;
10982                             ender = grok_oct(p, &numlen, &flags, NULL);
10983                             if (ender > 0xff) {
10984                                 REQUIRE_UTF8;
10985                             }
10986                             p += numlen;
10987                             if (SIZE_ONLY   /* like \08, \178 */
10988                                 && numlen < 3
10989                                 && p < RExC_end
10990                                 && isDIGIT(*p) && ckWARN(WARN_REGEXP))
10991                             {
10992                                 reg_warn_non_literal_string(
10993                                          p + 1,
10994                                          form_short_octal_warning(p, numlen));
10995                             }
10996                         }
10997                         if (PL_encoding && ender < 0x100)
10998                             goto recode_encoding;
10999                         break;
11000                     recode_encoding:
11001                         if (! RExC_override_recoding) {
11002                             SV* enc = PL_encoding;
11003                             ender = reg_recode((const char)(U8)ender, &enc);
11004                             if (!enc && SIZE_ONLY)
11005                                 ckWARNreg(p, "Invalid escape in the specified encoding");
11006                             REQUIRE_UTF8;
11007                         }
11008                         break;
11009                     case '\0':
11010                         if (p >= RExC_end)
11011                             FAIL("Trailing \\");
11012                         /* FALL THROUGH */
11013                     default:
11014                         if (!SIZE_ONLY&& isALPHANUMERIC(*p)) {
11015                             /* Include any { following the alpha to emphasize
11016                              * that it could be part of an escape at some point
11017                              * in the future */
11018                             int len = (isALPHA(*p) && *(p + 1) == '{') ? 2 : 1;
11019                             ckWARN3reg(p + len, "Unrecognized escape \\%.*s passed through", len, p);
11020                         }
11021                         goto normal_default;
11022                     } /* End of switch on '\' */
11023                     break;
11024                 default:    /* A literal character */
11025
11026                     if (! SIZE_ONLY
11027                         && RExC_flags & RXf_PMf_EXTENDED
11028                         && ckWARN_d(WARN_DEPRECATED)
11029                         && is_PATWS_non_low(p, UTF))
11030                     {
11031                         vWARN_dep(p + ((UTF) ? UTF8SKIP(p) : 1),
11032                                 "Escape literal pattern white space under /x");
11033                     }
11034
11035                   normal_default:
11036                     if (UTF8_IS_START(*p) && UTF) {
11037                         STRLEN numlen;
11038                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
11039                                                &numlen, UTF8_ALLOW_DEFAULT);
11040                         p += numlen;
11041                     }
11042                     else
11043                         ender = (U8) *p++;
11044                     break;
11045                 } /* End of switch on the literal */
11046
11047                 /* Here, have looked at the literal character and <ender>
11048                  * contains its ordinal, <p> points to the character after it
11049                  */
11050
11051                 if ( RExC_flags & RXf_PMf_EXTENDED)
11052                     p = regwhite( pRExC_state, p );
11053
11054                 /* If the next thing is a quantifier, it applies to this
11055                  * character only, which means that this character has to be in
11056                  * its own node and can't just be appended to the string in an
11057                  * existing node, so if there are already other characters in
11058                  * the node, close the node with just them, and set up to do
11059                  * this character again next time through, when it will be the
11060                  * only thing in its new node */
11061                 if ((next_is_quantifier = (p < RExC_end && ISMULT2(p))) && len)
11062                 {
11063                     p = oldp;
11064                     goto loopdone;
11065                 }
11066
11067                 if (! FOLD) {
11068                     if (UTF) {
11069                         const STRLEN unilen = reguni(pRExC_state, ender, s);
11070                         if (unilen > 0) {
11071                            s   += unilen;
11072                            len += unilen;
11073                         }
11074
11075                         /* The loop increments <len> each time, as all but this
11076                          * path (and one other) through it add a single byte to
11077                          * the EXACTish node.  But this one has changed len to
11078                          * be the correct final value, so subtract one to
11079                          * cancel out the increment that follows */
11080                         len--;
11081                     }
11082                     else {
11083                         REGC((char)ender, s++);
11084                     }
11085                 }
11086                 else /* FOLD */
11087                      if (! ( UTF
11088                         /* See comments for join_exact() as to why we fold this
11089                          * non-UTF at compile time */
11090                         || (node_type == EXACTFU
11091                             && ender == LATIN_SMALL_LETTER_SHARP_S)))
11092                 {
11093                     *(s++) = (char) ender;
11094                     maybe_exact &= ! IS_IN_SOME_FOLD_L1(ender);
11095                 }
11096                 else {  /* UTF */
11097
11098                     /* Prime the casefolded buffer.  Locale rules, which apply
11099                      * only to code points < 256, aren't known until execution,
11100                      * so for them, just output the original character using
11101                      * utf8.  If we start to fold non-UTF patterns, be sure to
11102                      * update join_exact() */
11103                     if (LOC && ender < 256) {
11104                         if (UNI_IS_INVARIANT(ender)) {
11105                             *s = (U8) ender;
11106                             foldlen = 1;
11107                         } else {
11108                             *s = UTF8_TWO_BYTE_HI(ender);
11109                             *(s + 1) = UTF8_TWO_BYTE_LO(ender);
11110                             foldlen = 2;
11111                         }
11112                     }
11113                     else {
11114                         UV folded = _to_uni_fold_flags(
11115                                        ender,
11116                                        (U8 *) s,
11117                                        &foldlen,
11118                                        FOLD_FLAGS_FULL
11119                                        | ((LOC) ?  FOLD_FLAGS_LOCALE
11120                                                 : (ASCII_FOLD_RESTRICTED)
11121                                                   ? FOLD_FLAGS_NOMIX_ASCII
11122                                                   : 0)
11123                                         );
11124
11125                         /* If this node only contains non-folding code points
11126                          * so far, see if this new one is also non-folding */
11127                         if (maybe_exact) {
11128                             if (folded != ender) {
11129                                 maybe_exact = FALSE;
11130                             }
11131                             else {
11132                                 /* Here the fold is the original; we have
11133                                  * to check further to see if anything
11134                                  * folds to it */
11135                                 if (! PL_utf8_foldable) {
11136                                     SV* swash = swash_init("utf8",
11137                                                        "_Perl_Any_Folds",
11138                                                        &PL_sv_undef, 1, 0);
11139                                     PL_utf8_foldable =
11140                                                 _get_swash_invlist(swash);
11141                                     SvREFCNT_dec_NN(swash);
11142                                 }
11143                                 if (_invlist_contains_cp(PL_utf8_foldable,
11144                                                          ender))
11145                                 {
11146                                     maybe_exact = FALSE;
11147                                 }
11148                             }
11149                         }
11150                         ender = folded;
11151                     }
11152                     s += foldlen;
11153
11154                     /* The loop increments <len> each time, as all but this
11155                      * path (and one other) through it add a single byte to the
11156                      * EXACTish node.  But this one has changed len to be the
11157                      * correct final value, so subtract one to cancel out the
11158                      * increment that follows */
11159                     len += foldlen - 1;
11160                 }
11161
11162                 if (next_is_quantifier) {
11163
11164                     /* Here, the next input is a quantifier, and to get here,
11165                      * the current character is the only one in the node.
11166                      * Also, here <len> doesn't include the final byte for this
11167                      * character */
11168                     len++;
11169                     goto loopdone;
11170                 }
11171
11172             } /* End of loop through literal characters */
11173
11174             /* Here we have either exhausted the input or ran out of room in
11175              * the node.  (If we encountered a character that can't be in the
11176              * node, transfer is made directly to <loopdone>, and so we
11177              * wouldn't have fallen off the end of the loop.)  In the latter
11178              * case, we artificially have to split the node into two, because
11179              * we just don't have enough space to hold everything.  This
11180              * creates a problem if the final character participates in a
11181              * multi-character fold in the non-final position, as a match that
11182              * should have occurred won't, due to the way nodes are matched,
11183              * and our artificial boundary.  So back off until we find a non-
11184              * problematic character -- one that isn't at the beginning or
11185              * middle of such a fold.  (Either it doesn't participate in any
11186              * folds, or appears only in the final position of all the folds it
11187              * does participate in.)  A better solution with far fewer false
11188              * positives, and that would fill the nodes more completely, would
11189              * be to actually have available all the multi-character folds to
11190              * test against, and to back-off only far enough to be sure that
11191              * this node isn't ending with a partial one.  <upper_parse> is set
11192              * further below (if we need to reparse the node) to include just
11193              * up through that final non-problematic character that this code
11194              * identifies, so when it is set to less than the full node, we can
11195              * skip the rest of this */
11196             if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
11197
11198                 const STRLEN full_len = len;
11199
11200                 assert(len >= MAX_NODE_STRING_SIZE);
11201
11202                 /* Here, <s> points to the final byte of the final character.
11203                  * Look backwards through the string until find a non-
11204                  * problematic character */
11205
11206                 if (! UTF) {
11207
11208                     /* These two have no multi-char folds to non-UTF characters
11209                      */
11210                     if (ASCII_FOLD_RESTRICTED || LOC) {
11211                         goto loopdone;
11212                     }
11213
11214                     while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { }
11215                     len = s - s0 + 1;
11216                 }
11217                 else {
11218                     if (!  PL_NonL1NonFinalFold) {
11219                         PL_NonL1NonFinalFold = _new_invlist_C_array(
11220                                         NonL1_Perl_Non_Final_Folds_invlist);
11221                     }
11222
11223                     /* Point to the first byte of the final character */
11224                     s = (char *) utf8_hop((U8 *) s, -1);
11225
11226                     while (s >= s0) {   /* Search backwards until find
11227                                            non-problematic char */
11228                         if (UTF8_IS_INVARIANT(*s)) {
11229
11230                             /* There are no ascii characters that participate
11231                              * in multi-char folds under /aa.  In EBCDIC, the
11232                              * non-ascii invariants are all control characters,
11233                              * so don't ever participate in any folds. */
11234                             if (ASCII_FOLD_RESTRICTED
11235                                 || ! IS_NON_FINAL_FOLD(*s))
11236                             {
11237                                 break;
11238                             }
11239                         }
11240                         else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
11241
11242                             /* No Latin1 characters participate in multi-char
11243                              * folds under /l */
11244                             if (LOC
11245                                 || ! IS_NON_FINAL_FOLD(TWO_BYTE_UTF8_TO_UNI(
11246                                                                 *s, *(s+1))))
11247                             {
11248                                 break;
11249                             }
11250                         }
11251                         else if (! _invlist_contains_cp(
11252                                         PL_NonL1NonFinalFold,
11253                                         valid_utf8_to_uvchr((U8 *) s, NULL)))
11254                         {
11255                             break;
11256                         }
11257
11258                         /* Here, the current character is problematic in that
11259                          * it does occur in the non-final position of some
11260                          * fold, so try the character before it, but have to
11261                          * special case the very first byte in the string, so
11262                          * we don't read outside the string */
11263                         s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
11264                     } /* End of loop backwards through the string */
11265
11266                     /* If there were only problematic characters in the string,
11267                      * <s> will point to before s0, in which case the length
11268                      * should be 0, otherwise include the length of the
11269                      * non-problematic character just found */
11270                     len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
11271                 }
11272
11273                 /* Here, have found the final character, if any, that is
11274                  * non-problematic as far as ending the node without splitting
11275                  * it across a potential multi-char fold.  <len> contains the
11276                  * number of bytes in the node up-to and including that
11277                  * character, or is 0 if there is no such character, meaning
11278                  * the whole node contains only problematic characters.  In
11279                  * this case, give up and just take the node as-is.  We can't
11280                  * do any better */
11281                 if (len == 0) {
11282                     len = full_len;
11283                 } else {
11284
11285                     /* Here, the node does contain some characters that aren't
11286                      * problematic.  If one such is the final character in the
11287                      * node, we are done */
11288                     if (len == full_len) {
11289                         goto loopdone;
11290                     }
11291                     else if (len + ((UTF) ? UTF8SKIP(s) : 1) == full_len) {
11292
11293                         /* If the final character is problematic, but the
11294                          * penultimate is not, back-off that last character to
11295                          * later start a new node with it */
11296                         p = oldp;
11297                         goto loopdone;
11298                     }
11299
11300                     /* Here, the final non-problematic character is earlier
11301                      * in the input than the penultimate character.  What we do
11302                      * is reparse from the beginning, going up only as far as
11303                      * this final ok one, thus guaranteeing that the node ends
11304                      * in an acceptable character.  The reason we reparse is
11305                      * that we know how far in the character is, but we don't
11306                      * know how to correlate its position with the input parse.
11307                      * An alternate implementation would be to build that
11308                      * correlation as we go along during the original parse,
11309                      * but that would entail extra work for every node, whereas
11310                      * this code gets executed only when the string is too
11311                      * large for the node, and the final two characters are
11312                      * problematic, an infrequent occurrence.  Yet another
11313                      * possible strategy would be to save the tail of the
11314                      * string, and the next time regatom is called, initialize
11315                      * with that.  The problem with this is that unless you
11316                      * back off one more character, you won't be guaranteed
11317                      * regatom will get called again, unless regbranch,
11318                      * regpiece ... are also changed.  If you do back off that
11319                      * extra character, so that there is input guaranteed to
11320                      * force calling regatom, you can't handle the case where
11321                      * just the first character in the node is acceptable.  I
11322                      * (khw) decided to try this method which doesn't have that
11323                      * pitfall; if performance issues are found, we can do a
11324                      * combination of the current approach plus that one */
11325                     upper_parse = len;
11326                     len = 0;
11327                     s = s0;
11328                     goto reparse;
11329                 }
11330             }   /* End of verifying node ends with an appropriate char */
11331
11332         loopdone:   /* Jumped to when encounters something that shouldn't be in
11333                        the node */
11334
11335             /* I (khw) don't know if you can get here with zero length, but the
11336              * old code handled this situation by creating a zero-length EXACT
11337              * node.  Might as well be NOTHING instead */
11338             if (len == 0) {
11339                 OP(ret) = NOTHING;
11340             }
11341             else{
11342
11343                 /* If 'maybe_exact' is still set here, means there are no
11344                  * code points in the node that participate in folds */
11345                 if (FOLD && maybe_exact) {
11346                     OP(ret) = EXACT;
11347                 }
11348                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, len, ender);
11349             }
11350
11351             RExC_parse = p - 1;
11352             Set_Node_Cur_Length(ret, parse_start);
11353             nextchar(pRExC_state);
11354             {
11355                 /* len is STRLEN which is unsigned, need to copy to signed */
11356                 IV iv = len;
11357                 if (iv < 0)
11358                     vFAIL("Internal disaster");
11359             }
11360
11361         } /* End of label 'defchar:' */
11362         break;
11363     } /* End of giant switch on input character */
11364
11365     return(ret);
11366 }
11367
11368 STATIC char *
11369 S_regwhite( RExC_state_t *pRExC_state, char *p )
11370 {
11371     const char *e = RExC_end;
11372
11373     PERL_ARGS_ASSERT_REGWHITE;
11374
11375     while (p < e) {
11376         if (isSPACE(*p))
11377             ++p;
11378         else if (*p == '#') {
11379             bool ended = 0;
11380             do {
11381                 if (*p++ == '\n') {
11382                     ended = 1;
11383                     break;
11384                 }
11385             } while (p < e);
11386             if (!ended)
11387                 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
11388         }
11389         else
11390             break;
11391     }
11392     return p;
11393 }
11394
11395 STATIC char *
11396 S_regpatws( RExC_state_t *pRExC_state, char *p , const bool recognize_comment )
11397 {
11398     /* Returns the next non-pattern-white space, non-comment character (the
11399      * latter only if 'recognize_comment is true) in the string p, which is
11400      * ended by RExC_end.  If there is no line break ending a comment,
11401      * RExC_seen has added the REG_SEEN_RUN_ON_COMMENT flag; */
11402     const char *e = RExC_end;
11403
11404     PERL_ARGS_ASSERT_REGPATWS;
11405
11406     while (p < e) {
11407         STRLEN len;
11408         if ((len = is_PATWS_safe(p, e, UTF))) {
11409             p += len;
11410         }
11411         else if (recognize_comment && *p == '#') {
11412             bool ended = 0;
11413             do {
11414                 p++;
11415                 if (is_LNBREAK_safe(p, e, UTF)) {
11416                     ended = 1;
11417                     break;
11418                 }
11419             } while (p < e);
11420             if (!ended)
11421                 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
11422         }
11423         else
11424             break;
11425     }
11426     return p;
11427 }
11428
11429 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
11430    Character classes ([:foo:]) can also be negated ([:^foo:]).
11431    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
11432    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
11433    but trigger failures because they are currently unimplemented. */
11434
11435 #define POSIXCC_DONE(c)   ((c) == ':')
11436 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
11437 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
11438
11439 PERL_STATIC_INLINE I32
11440 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value, const bool strict)
11441 {
11442     dVAR;
11443     I32 namedclass = OOB_NAMEDCLASS;
11444
11445     PERL_ARGS_ASSERT_REGPPOSIXCC;
11446
11447     if (value == '[' && RExC_parse + 1 < RExC_end &&
11448         /* I smell either [: or [= or [. -- POSIX has been here, right? */
11449         POSIXCC(UCHARAT(RExC_parse)))
11450     {
11451         const char c = UCHARAT(RExC_parse);
11452         char* const s = RExC_parse++;
11453
11454         while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
11455             RExC_parse++;
11456         if (RExC_parse == RExC_end) {
11457             if (strict) {
11458
11459                 /* Try to give a better location for the error (than the end of
11460                  * the string) by looking for the matching ']' */
11461                 RExC_parse = s;
11462                 while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
11463                     RExC_parse++;
11464                 }
11465                 vFAIL2("Unmatched '%c' in POSIX class", c);
11466             }
11467             /* Grandfather lone [:, [=, [. */
11468             RExC_parse = s;
11469         }
11470         else {
11471             const char* const t = RExC_parse++; /* skip over the c */
11472             assert(*t == c);
11473
11474             if (UCHARAT(RExC_parse) == ']') {
11475                 const char *posixcc = s + 1;
11476                 RExC_parse++; /* skip over the ending ] */
11477
11478                 if (*s == ':') {
11479                     const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
11480                     const I32 skip = t - posixcc;
11481
11482                     /* Initially switch on the length of the name.  */
11483                     switch (skip) {
11484                     case 4:
11485                         if (memEQ(posixcc, "word", 4)) /* this is not POSIX,
11486                                                           this is the Perl \w
11487                                                         */
11488                             namedclass = ANYOF_WORDCHAR;
11489                         break;
11490                     case 5:
11491                         /* Names all of length 5.  */
11492                         /* alnum alpha ascii blank cntrl digit graph lower
11493                            print punct space upper  */
11494                         /* Offset 4 gives the best switch position.  */
11495                         switch (posixcc[4]) {
11496                         case 'a':
11497                             if (memEQ(posixcc, "alph", 4)) /* alpha */
11498                                 namedclass = ANYOF_ALPHA;
11499                             break;
11500                         case 'e':
11501                             if (memEQ(posixcc, "spac", 4)) /* space */
11502                                 namedclass = ANYOF_PSXSPC;
11503                             break;
11504                         case 'h':
11505                             if (memEQ(posixcc, "grap", 4)) /* graph */
11506                                 namedclass = ANYOF_GRAPH;
11507                             break;
11508                         case 'i':
11509                             if (memEQ(posixcc, "asci", 4)) /* ascii */
11510                                 namedclass = ANYOF_ASCII;
11511                             break;
11512                         case 'k':
11513                             if (memEQ(posixcc, "blan", 4)) /* blank */
11514                                 namedclass = ANYOF_BLANK;
11515                             break;
11516                         case 'l':
11517                             if (memEQ(posixcc, "cntr", 4)) /* cntrl */
11518                                 namedclass = ANYOF_CNTRL;
11519                             break;
11520                         case 'm':
11521                             if (memEQ(posixcc, "alnu", 4)) /* alnum */
11522                                 namedclass = ANYOF_ALPHANUMERIC;
11523                             break;
11524                         case 'r':
11525                             if (memEQ(posixcc, "lowe", 4)) /* lower */
11526                                 namedclass = (FOLD) ? ANYOF_CASED : ANYOF_LOWER;
11527                             else if (memEQ(posixcc, "uppe", 4)) /* upper */
11528                                 namedclass = (FOLD) ? ANYOF_CASED : ANYOF_UPPER;
11529                             break;
11530                         case 't':
11531                             if (memEQ(posixcc, "digi", 4)) /* digit */
11532                                 namedclass = ANYOF_DIGIT;
11533                             else if (memEQ(posixcc, "prin", 4)) /* print */
11534                                 namedclass = ANYOF_PRINT;
11535                             else if (memEQ(posixcc, "punc", 4)) /* punct */
11536                                 namedclass = ANYOF_PUNCT;
11537                             break;
11538                         }
11539                         break;
11540                     case 6:
11541                         if (memEQ(posixcc, "xdigit", 6))
11542                             namedclass = ANYOF_XDIGIT;
11543                         break;
11544                     }
11545
11546                     if (namedclass == OOB_NAMEDCLASS)
11547                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
11548                                       t - s - 1, s + 1);
11549
11550                     /* The #defines are structured so each complement is +1 to
11551                      * the normal one */
11552                     if (complement) {
11553                         namedclass++;
11554                     }
11555                     assert (posixcc[skip] == ':');
11556                     assert (posixcc[skip+1] == ']');
11557                 } else if (!SIZE_ONLY) {
11558                     /* [[=foo=]] and [[.foo.]] are still future. */
11559
11560                     /* adjust RExC_parse so the warning shows after
11561                        the class closes */
11562                     while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
11563                         RExC_parse++;
11564                     vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
11565                 }
11566             } else {
11567                 /* Maternal grandfather:
11568                  * "[:" ending in ":" but not in ":]" */
11569                 if (strict) {
11570                     vFAIL("Unmatched '[' in POSIX class");
11571                 }
11572
11573                 /* Grandfather lone [:, [=, [. */
11574                 RExC_parse = s;
11575             }
11576         }
11577     }
11578
11579     return namedclass;
11580 }
11581
11582 STATIC bool
11583 S_could_it_be_a_POSIX_class(pTHX_ RExC_state_t *pRExC_state)
11584 {
11585     /* This applies some heuristics at the current parse position (which should
11586      * be at a '[') to see if what follows might be intended to be a [:posix:]
11587      * class.  It returns true if it really is a posix class, of course, but it
11588      * also can return true if it thinks that what was intended was a posix
11589      * class that didn't quite make it.
11590      *
11591      * It will return true for
11592      *      [:alphanumerics:
11593      *      [:alphanumerics]  (as long as the ] isn't followed immediately by a
11594      *                         ')' indicating the end of the (?[
11595      *      [:any garbage including %^&$ punctuation:]
11596      *
11597      * This is designed to be called only from S_handle_regex_sets; it could be
11598      * easily adapted to be called from the spot at the beginning of regclass()
11599      * that checks to see in a normal bracketed class if the surrounding []
11600      * have been omitted ([:word:] instead of [[:word:]]).  But doing so would
11601      * change long-standing behavior, so I (khw) didn't do that */
11602     char* p = RExC_parse + 1;
11603     char first_char = *p;
11604
11605     PERL_ARGS_ASSERT_COULD_IT_BE_A_POSIX_CLASS;
11606
11607     assert(*(p - 1) == '[');
11608
11609     if (! POSIXCC(first_char)) {
11610         return FALSE;
11611     }
11612
11613     p++;
11614     while (p < RExC_end && isWORDCHAR(*p)) p++;
11615
11616     if (p >= RExC_end) {
11617         return FALSE;
11618     }
11619
11620     if (p - RExC_parse > 2    /* Got at least 1 word character */
11621         && (*p == first_char
11622             || (*p == ']' && p + 1 < RExC_end && *(p + 1) != ')')))
11623     {
11624         return TRUE;
11625     }
11626
11627     p = (char *) memchr(RExC_parse, ']', RExC_end - RExC_parse);
11628
11629     return (p
11630             && p - RExC_parse > 2 /* [:] evaluates to colon;
11631                                       [::] is a bad posix class. */
11632             && first_char == *(p - 1));
11633 }
11634
11635 STATIC regnode *
11636 S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist, I32 *flagp, U32 depth,
11637                    char * const oregcomp_parse)
11638 {
11639     /* Handle the (?[...]) construct to do set operations */
11640
11641     U8 curchar;
11642     UV start, end;      /* End points of code point ranges */
11643     SV* result_string;
11644     char *save_end, *save_parse;
11645     SV* final;
11646     STRLEN len;
11647     regnode* node;
11648     AV* stack;
11649     const bool save_fold = FOLD;
11650
11651     GET_RE_DEBUG_FLAGS_DECL;
11652
11653     PERL_ARGS_ASSERT_HANDLE_REGEX_SETS;
11654
11655     if (LOC) {
11656         vFAIL("(?[...]) not valid in locale");
11657     }
11658     RExC_uni_semantics = 1;
11659
11660     /* This will return only an ANYOF regnode, or (unlikely) something smaller
11661      * (such as EXACT).  Thus we can skip most everything if just sizing.  We
11662      * call regclass to handle '[]' so as to not have to reinvent its parsing
11663      * rules here (throwing away the size it computes each time).  And, we exit
11664      * upon an unescaped ']' that isn't one ending a regclass.  To do both
11665      * these things, we need to realize that something preceded by a backslash
11666      * is escaped, so we have to keep track of backslashes */
11667     if (SIZE_ONLY) {
11668         UV depth = 0; /* how many nested (?[...]) constructs */
11669
11670         Perl_ck_warner_d(aTHX_
11671             packWARN(WARN_EXPERIMENTAL__REGEX_SETS),
11672             "The regex_sets feature is experimental" REPORT_LOCATION,
11673             (int) (RExC_parse - RExC_precomp) , RExC_precomp, RExC_parse);
11674
11675         while (RExC_parse < RExC_end) {
11676             SV* current = NULL;
11677             RExC_parse = regpatws(pRExC_state, RExC_parse,
11678                                 TRUE); /* means recognize comments */
11679             switch (*RExC_parse) {
11680                 case '?':
11681                     if (RExC_parse[1] == '[') depth++, RExC_parse++;
11682                     /* FALL THROUGH */
11683                 default:
11684                     break;
11685                 case '\\':
11686                     /* Skip the next byte (which could cause us to end up in
11687                      * the middle of a UTF-8 character, but since none of those
11688                      * are confusable with anything we currently handle in this
11689                      * switch (invariants all), it's safe.  We'll just hit the
11690                      * default: case next time and keep on incrementing until
11691                      * we find one of the invariants we do handle. */
11692                     RExC_parse++;
11693                     break;
11694                 case '[':
11695                 {
11696                     /* If this looks like it is a [:posix:] class, leave the
11697                      * parse pointer at the '[' to fool regclass() into
11698                      * thinking it is part of a '[[:posix:]]'.  That function
11699                      * will use strict checking to force a syntax error if it
11700                      * doesn't work out to a legitimate class */
11701                     bool is_posix_class
11702                                     = could_it_be_a_POSIX_class(pRExC_state);
11703                     if (! is_posix_class) {
11704                         RExC_parse++;
11705                     }
11706
11707                     /* regclass() can only return RESTART_UTF8 if multi-char
11708                        folds are allowed.  */
11709                     if (!regclass(pRExC_state, flagp,depth+1,
11710                                   is_posix_class, /* parse the whole char
11711                                                      class only if not a
11712                                                      posix class */
11713                                   FALSE, /* don't allow multi-char folds */
11714                                   TRUE, /* silence non-portable warnings. */
11715                                   &current))
11716                         FAIL2("panic: regclass returned NULL to handle_sets, flags=%#"UVxf"",
11717                               (UV) *flagp);
11718
11719                     /* function call leaves parse pointing to the ']', except
11720                      * if we faked it */
11721                     if (is_posix_class) {
11722                         RExC_parse--;
11723                     }
11724
11725                     SvREFCNT_dec(current);   /* In case it returned something */
11726                     break;
11727                 }
11728
11729                 case ']':
11730                     if (depth--) break;
11731                     RExC_parse++;
11732                     if (RExC_parse < RExC_end
11733                         && *RExC_parse == ')')
11734                     {
11735                         node = reganode(pRExC_state, ANYOF, 0);
11736                         RExC_size += ANYOF_SKIP;
11737                         nextchar(pRExC_state);
11738                         Set_Node_Length(node,
11739                                 RExC_parse - oregcomp_parse + 1); /* MJD */
11740                         return node;
11741                     }
11742                     goto no_close;
11743             }
11744             RExC_parse++;
11745         }
11746
11747         no_close:
11748         FAIL("Syntax error in (?[...])");
11749     }
11750
11751     /* Pass 2 only after this.  Everything in this construct is a
11752      * metacharacter.  Operands begin with either a '\' (for an escape
11753      * sequence), or a '[' for a bracketed character class.  Any other
11754      * character should be an operator, or parenthesis for grouping.  Both
11755      * types of operands are handled by calling regclass() to parse them.  It
11756      * is called with a parameter to indicate to return the computed inversion
11757      * list.  The parsing here is implemented via a stack.  Each entry on the
11758      * stack is a single character representing one of the operators, or the
11759      * '('; or else a pointer to an operand inversion list. */
11760
11761 #define IS_OPERAND(a)  (! SvIOK(a))
11762
11763     /* The stack starts empty.  It is a syntax error if the first thing parsed
11764      * is a binary operator; everything else is pushed on the stack.  When an
11765      * operand is parsed, the top of the stack is examined.  If it is a binary
11766      * operator, the item before it should be an operand, and both are replaced
11767      * by the result of doing that operation on the new operand and the one on
11768      * the stack.   Thus a sequence of binary operands is reduced to a single
11769      * one before the next one is parsed.
11770      *
11771      * A unary operator may immediately follow a binary in the input, for
11772      * example
11773      *      [a] + ! [b]
11774      * When an operand is parsed and the top of the stack is a unary operator,
11775      * the operation is performed, and then the stack is rechecked to see if
11776      * this new operand is part of a binary operation; if so, it is handled as
11777      * above.
11778      *
11779      * A '(' is simply pushed on the stack; it is valid only if the stack is
11780      * empty, or the top element of the stack is an operator or another '('
11781      * (for which the parenthesized expression will become an operand).  By the
11782      * time the corresponding ')' is parsed everything in between should have
11783      * been parsed and evaluated to a single operand (or else is a syntax
11784      * error), and is handled as a regular operand */
11785
11786     sv_2mortal((SV *)(stack = newAV()));
11787
11788     while (RExC_parse < RExC_end) {
11789         I32 top_index = av_tindex(stack);
11790         SV** top_ptr;
11791         SV* current = NULL;
11792
11793         /* Skip white space */
11794         RExC_parse = regpatws(pRExC_state, RExC_parse,
11795                                 TRUE); /* means recognize comments */
11796         if (RExC_parse >= RExC_end) {
11797             Perl_croak(aTHX_ "panic: Read past end of '(?[ ])'");
11798         }
11799         if ((curchar = UCHARAT(RExC_parse)) == ']') {
11800             break;
11801         }
11802
11803         switch (curchar) {
11804
11805             case '?':
11806                 if (av_tindex(stack) >= 0   /* This makes sure that we can
11807                                                safely subtract 1 from
11808                                                RExC_parse in the next clause.
11809                                                If we have something on the
11810                                                stack, we have parsed something
11811                                              */
11812                     && UCHARAT(RExC_parse - 1) == '('
11813                     && RExC_parse < RExC_end)
11814                 {
11815                     /* If is a '(?', could be an embedded '(?flags:(?[...])'.
11816                      * This happens when we have some thing like
11817                      *
11818                      *   my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
11819                      *   ...
11820                      *   qr/(?[ \p{Digit} & $thai_or_lao ])/;
11821                      *
11822                      * Here we would be handling the interpolated
11823                      * '$thai_or_lao'.  We handle this by a recursive call to
11824                      * ourselves which returns the inversion list the
11825                      * interpolated expression evaluates to.  We use the flags
11826                      * from the interpolated pattern. */
11827                     U32 save_flags = RExC_flags;
11828                     const char * const save_parse = ++RExC_parse;
11829
11830                     parse_lparen_question_flags(pRExC_state);
11831
11832                     if (RExC_parse == save_parse  /* Makes sure there was at
11833                                                      least one flag (or this
11834                                                      embedding wasn't compiled)
11835                                                    */
11836                         || RExC_parse >= RExC_end - 4
11837                         || UCHARAT(RExC_parse) != ':'
11838                         || UCHARAT(++RExC_parse) != '('
11839                         || UCHARAT(++RExC_parse) != '?'
11840                         || UCHARAT(++RExC_parse) != '[')
11841                     {
11842
11843                         /* In combination with the above, this moves the
11844                          * pointer to the point just after the first erroneous
11845                          * character (or if there are no flags, to where they
11846                          * should have been) */
11847                         if (RExC_parse >= RExC_end - 4) {
11848                             RExC_parse = RExC_end;
11849                         }
11850                         else if (RExC_parse != save_parse) {
11851                             RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
11852                         }
11853                         vFAIL("Expecting '(?flags:(?[...'");
11854                     }
11855                     RExC_parse++;
11856                     (void) handle_regex_sets(pRExC_state, &current, flagp,
11857                                                     depth+1, oregcomp_parse);
11858
11859                     /* Here, 'current' contains the embedded expression's
11860                      * inversion list, and RExC_parse points to the trailing
11861                      * ']'; the next character should be the ')' which will be
11862                      * paired with the '(' that has been put on the stack, so
11863                      * the whole embedded expression reduces to '(operand)' */
11864                     RExC_parse++;
11865
11866                     RExC_flags = save_flags;
11867                     goto handle_operand;
11868                 }
11869                 /* FALL THROUGH */
11870
11871             default:
11872                 RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
11873                 vFAIL("Unexpected character");
11874
11875             case '\\':
11876                 /* regclass() can only return RESTART_UTF8 if multi-char
11877                    folds are allowed.  */
11878                 if (!regclass(pRExC_state, flagp,depth+1,
11879                               TRUE, /* means parse just the next thing */
11880                               FALSE, /* don't allow multi-char folds */
11881                               FALSE, /* don't silence non-portable warnings.  */
11882                               &current))
11883                     FAIL2("panic: regclass returned NULL to handle_sets, flags=%#"UVxf"",
11884                           (UV) *flagp);
11885                 /* regclass() will return with parsing just the \ sequence,
11886                  * leaving the parse pointer at the next thing to parse */
11887                 RExC_parse--;
11888                 goto handle_operand;
11889
11890             case '[':   /* Is a bracketed character class */
11891             {
11892                 bool is_posix_class = could_it_be_a_POSIX_class(pRExC_state);
11893
11894                 if (! is_posix_class) {
11895                     RExC_parse++;
11896                 }
11897
11898                 /* regclass() can only return RESTART_UTF8 if multi-char
11899                    folds are allowed.  */
11900                 if(!regclass(pRExC_state, flagp,depth+1,
11901                              is_posix_class, /* parse the whole char class
11902                                                 only if not a posix class */
11903                              FALSE, /* don't allow multi-char folds */
11904                              FALSE, /* don't silence non-portable warnings.  */
11905                              &current))
11906                     FAIL2("panic: regclass returned NULL to handle_sets, flags=%#"UVxf"",
11907                           (UV) *flagp);
11908                 /* function call leaves parse pointing to the ']', except if we
11909                  * faked it */
11910                 if (is_posix_class) {
11911                     RExC_parse--;
11912                 }
11913
11914                 goto handle_operand;
11915             }
11916
11917             case '&':
11918             case '|':
11919             case '+':
11920             case '-':
11921             case '^':
11922                 if (top_index < 0
11923                     || ( ! (top_ptr = av_fetch(stack, top_index, FALSE)))
11924                     || ! IS_OPERAND(*top_ptr))
11925                 {
11926                     RExC_parse++;
11927                     vFAIL2("Unexpected binary operator '%c' with no preceding operand", curchar);
11928                 }
11929                 av_push(stack, newSVuv(curchar));
11930                 break;
11931
11932             case '!':
11933                 av_push(stack, newSVuv(curchar));
11934                 break;
11935
11936             case '(':
11937                 if (top_index >= 0) {
11938                     top_ptr = av_fetch(stack, top_index, FALSE);
11939                     assert(top_ptr);
11940                     if (IS_OPERAND(*top_ptr)) {
11941                         RExC_parse++;
11942                         vFAIL("Unexpected '(' with no preceding operator");
11943                     }
11944                 }
11945                 av_push(stack, newSVuv(curchar));
11946                 break;
11947
11948             case ')':
11949             {
11950                 SV* lparen;
11951                 if (top_index < 1
11952                     || ! (current = av_pop(stack))
11953                     || ! IS_OPERAND(current)
11954                     || ! (lparen = av_pop(stack))
11955                     || IS_OPERAND(lparen)
11956                     || SvUV(lparen) != '(')
11957                 {
11958                     SvREFCNT_dec(current);
11959                     RExC_parse++;
11960                     vFAIL("Unexpected ')'");
11961                 }
11962                 top_index -= 2;
11963                 SvREFCNT_dec_NN(lparen);
11964
11965                 /* FALL THROUGH */
11966             }
11967
11968               handle_operand:
11969
11970                 /* Here, we have an operand to process, in 'current' */
11971
11972                 if (top_index < 0) {    /* Just push if stack is empty */
11973                     av_push(stack, current);
11974                 }
11975                 else {
11976                     SV* top = av_pop(stack);
11977                     SV *prev = NULL;
11978                     char current_operator;
11979
11980                     if (IS_OPERAND(top)) {
11981                         SvREFCNT_dec_NN(top);
11982                         SvREFCNT_dec_NN(current);
11983                         vFAIL("Operand with no preceding operator");
11984                     }
11985                     current_operator = (char) SvUV(top);
11986                     switch (current_operator) {
11987                         case '(':   /* Push the '(' back on followed by the new
11988                                        operand */
11989                             av_push(stack, top);
11990                             av_push(stack, current);
11991                             SvREFCNT_inc(top);  /* Counters the '_dec' done
11992                                                    just after the 'break', so
11993                                                    it doesn't get wrongly freed
11994                                                  */
11995                             break;
11996
11997                         case '!':
11998                             _invlist_invert(current);
11999
12000                             /* Unlike binary operators, the top of the stack,
12001                              * now that this unary one has been popped off, may
12002                              * legally be an operator, and we now have operand
12003                              * for it. */
12004                             top_index--;
12005                             SvREFCNT_dec_NN(top);
12006                             goto handle_operand;
12007
12008                         case '&':
12009                             prev = av_pop(stack);
12010                             _invlist_intersection(prev,
12011                                                    current,
12012                                                    &current);
12013                             av_push(stack, current);
12014                             break;
12015
12016                         case '|':
12017                         case '+':
12018                             prev = av_pop(stack);
12019                             _invlist_union(prev, current, &current);
12020                             av_push(stack, current);
12021                             break;
12022
12023                         case '-':
12024                             prev = av_pop(stack);;
12025                             _invlist_subtract(prev, current, &current);
12026                             av_push(stack, current);
12027                             break;
12028
12029                         case '^':   /* The union minus the intersection */
12030                         {
12031                             SV* i = NULL;
12032                             SV* u = NULL;
12033                             SV* element;
12034
12035                             prev = av_pop(stack);
12036                             _invlist_union(prev, current, &u);
12037                             _invlist_intersection(prev, current, &i);
12038                             /* _invlist_subtract will overwrite current
12039                                 without freeing what it already contains */
12040                             element = current;
12041                             _invlist_subtract(u, i, &current);
12042                             av_push(stack, current);
12043                             SvREFCNT_dec_NN(i);
12044                             SvREFCNT_dec_NN(u);
12045                             SvREFCNT_dec_NN(element);
12046                             break;
12047                         }
12048
12049                         default:
12050                             Perl_croak(aTHX_ "panic: Unexpected item on '(?[ ])' stack");
12051                 }
12052                 SvREFCNT_dec_NN(top);
12053                 SvREFCNT_dec(prev);
12054             }
12055         }
12056
12057         RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
12058     }
12059
12060     if (av_tindex(stack) < 0   /* Was empty */
12061         || ((final = av_pop(stack)) == NULL)
12062         || ! IS_OPERAND(final)
12063         || av_tindex(stack) >= 0)  /* More left on stack */
12064     {
12065         vFAIL("Incomplete expression within '(?[ ])'");
12066     }
12067
12068     /* Here, 'final' is the resultant inversion list from evaluating the
12069      * expression.  Return it if so requested */
12070     if (return_invlist) {
12071         *return_invlist = final;
12072         return END;
12073     }
12074
12075     /* Otherwise generate a resultant node, based on 'final'.  regclass() is
12076      * expecting a string of ranges and individual code points */
12077     invlist_iterinit(final);
12078     result_string = newSVpvs("");
12079     while (invlist_iternext(final, &start, &end)) {
12080         if (start == end) {
12081             Perl_sv_catpvf(aTHX_ result_string, "\\x{%"UVXf"}", start);
12082         }
12083         else {
12084             Perl_sv_catpvf(aTHX_ result_string, "\\x{%"UVXf"}-\\x{%"UVXf"}",
12085                                                      start,          end);
12086         }
12087     }
12088
12089     save_parse = RExC_parse;
12090     RExC_parse = SvPV(result_string, len);
12091     save_end = RExC_end;
12092     RExC_end = RExC_parse + len;
12093
12094     /* We turn off folding around the call, as the class we have constructed
12095      * already has all folding taken into consideration, and we don't want
12096      * regclass() to add to that */
12097     RExC_flags &= ~RXf_PMf_FOLD;
12098     /* regclass() can only return RESTART_UTF8 if multi-char folds are allowed.
12099      */
12100     node = regclass(pRExC_state, flagp,depth+1,
12101                     FALSE, /* means parse the whole char class */
12102                     FALSE, /* don't allow multi-char folds */
12103                     TRUE, /* silence non-portable warnings.  The above may very
12104                              well have generated non-portable code points, but
12105                              they're valid on this machine */
12106                     NULL);
12107     if (!node)
12108         FAIL2("panic: regclass returned NULL to handle_sets, flags=%#"UVxf,
12109                     PTR2UV(flagp));
12110     if (save_fold) {
12111         RExC_flags |= RXf_PMf_FOLD;
12112     }
12113     RExC_parse = save_parse + 1;
12114     RExC_end = save_end;
12115     SvREFCNT_dec_NN(final);
12116     SvREFCNT_dec_NN(result_string);
12117
12118     nextchar(pRExC_state);
12119     Set_Node_Length(node, RExC_parse - oregcomp_parse + 1); /* MJD */
12120     return node;
12121 }
12122 #undef IS_OPERAND
12123
12124 /* The names of properties whose definitions are not known at compile time are
12125  * stored in this SV, after a constant heading.  So if the length has been
12126  * changed since initialization, then there is a run-time definition. */
12127 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION (SvCUR(listsv) != initial_listsv_len)
12128
12129 STATIC regnode *
12130 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth,
12131                  const bool stop_at_1,  /* Just parse the next thing, don't
12132                                            look for a full character class */
12133                  bool allow_multi_folds,
12134                  const bool silence_non_portable,   /* Don't output warnings
12135                                                        about too large
12136                                                        characters */
12137                  SV** ret_invlist)  /* Return an inversion list, not a node */
12138 {
12139     /* parse a bracketed class specification.  Most of these will produce an
12140      * ANYOF node; but something like [a] will produce an EXACT node; [aA], an
12141      * EXACTFish node; [[:ascii:]], a POSIXA node; etc.  It is more complex
12142      * under /i with multi-character folds: it will be rewritten following the
12143      * paradigm of this example, where the <multi-fold>s are characters which
12144      * fold to multiple character sequences:
12145      *      /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
12146      * gets effectively rewritten as:
12147      *      /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
12148      * reg() gets called (recursively) on the rewritten version, and this
12149      * function will return what it constructs.  (Actually the <multi-fold>s
12150      * aren't physically removed from the [abcdefghi], it's just that they are
12151      * ignored in the recursion by means of a flag:
12152      * <RExC_in_multi_char_class>.)
12153      *
12154      * ANYOF nodes contain a bit map for the first 256 characters, with the
12155      * corresponding bit set if that character is in the list.  For characters
12156      * above 255, a range list or swash is used.  There are extra bits for \w,
12157      * etc. in locale ANYOFs, as what these match is not determinable at
12158      * compile time
12159      *
12160      * Returns NULL, setting *flagp to RESTART_UTF8 if the sizing scan needs
12161      * to be restarted.  This can only happen if ret_invlist is non-NULL.
12162      */
12163
12164     dVAR;
12165     UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
12166     IV range = 0;
12167     UV value = OOB_UNICODE, save_value = OOB_UNICODE;
12168     regnode *ret;
12169     STRLEN numlen;
12170     IV namedclass = OOB_NAMEDCLASS;
12171     char *rangebegin = NULL;
12172     bool need_class = 0;
12173     SV *listsv = NULL;
12174     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
12175                                       than just initialized.  */
12176     SV* properties = NULL;    /* Code points that match \p{} \P{} */
12177     SV* posixes = NULL;     /* Code points that match classes like, [:word:],
12178                                extended beyond the Latin1 range */
12179     UV element_count = 0;   /* Number of distinct elements in the class.
12180                                Optimizations may be possible if this is tiny */
12181     AV * multi_char_matches = NULL; /* Code points that fold to more than one
12182                                        character; used under /i */
12183     UV n;
12184     char * stop_ptr = RExC_end;    /* where to stop parsing */
12185     const bool skip_white = cBOOL(ret_invlist); /* ignore unescaped white
12186                                                    space? */
12187     const bool strict = cBOOL(ret_invlist); /* Apply strict parsing rules? */
12188
12189     /* Unicode properties are stored in a swash; this holds the current one
12190      * being parsed.  If this swash is the only above-latin1 component of the
12191      * character class, an optimization is to pass it directly on to the
12192      * execution engine.  Otherwise, it is set to NULL to indicate that there
12193      * are other things in the class that have to be dealt with at execution
12194      * time */
12195     SV* swash = NULL;           /* Code points that match \p{} \P{} */
12196
12197     /* Set if a component of this character class is user-defined; just passed
12198      * on to the engine */
12199     bool has_user_defined_property = FALSE;
12200
12201     /* inversion list of code points this node matches only when the target
12202      * string is in UTF-8.  (Because is under /d) */
12203     SV* depends_list = NULL;
12204
12205     /* inversion list of code points this node matches.  For much of the
12206      * function, it includes only those that match regardless of the utf8ness
12207      * of the target string */
12208     SV* cp_list = NULL;
12209
12210 #ifdef EBCDIC
12211     /* In a range, counts how many 0-2 of the ends of it came from literals,
12212      * not escapes.  Thus we can tell if 'A' was input vs \x{C1} */
12213     UV literal_endpoint = 0;
12214 #endif
12215     bool invert = FALSE;    /* Is this class to be complemented */
12216
12217     /* Is there any thing like \W or [:^digit:] that matches above the legal
12218      * Unicode range? */
12219     bool runtime_posix_matches_above_Unicode = FALSE;
12220
12221     regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
12222         case we need to change the emitted regop to an EXACT. */
12223     const char * orig_parse = RExC_parse;
12224     const I32 orig_size = RExC_size;
12225     GET_RE_DEBUG_FLAGS_DECL;
12226
12227     PERL_ARGS_ASSERT_REGCLASS;
12228 #ifndef DEBUGGING
12229     PERL_UNUSED_ARG(depth);
12230 #endif
12231
12232     DEBUG_PARSE("clas");
12233
12234     /* Assume we are going to generate an ANYOF node. */
12235     ret = reganode(pRExC_state, ANYOF, 0);
12236
12237     if (SIZE_ONLY) {
12238         RExC_size += ANYOF_SKIP;
12239         listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
12240     }
12241     else {
12242         ANYOF_FLAGS(ret) = 0;
12243
12244         RExC_emit += ANYOF_SKIP;
12245         if (LOC) {
12246             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
12247         }
12248         listsv = newSVpvs_flags("# comment\n", SVs_TEMP);
12249         initial_listsv_len = SvCUR(listsv);
12250         SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated.  */
12251     }
12252
12253     if (skip_white) {
12254         RExC_parse = regpatws(pRExC_state, RExC_parse,
12255                               FALSE /* means don't recognize comments */);
12256     }
12257
12258     if (UCHARAT(RExC_parse) == '^') {   /* Complement of range. */
12259         RExC_parse++;
12260         invert = TRUE;
12261         allow_multi_folds = FALSE;
12262         RExC_naughty++;
12263         if (skip_white) {
12264             RExC_parse = regpatws(pRExC_state, RExC_parse,
12265                                   FALSE /* means don't recognize comments */);
12266         }
12267     }
12268
12269     /* Check that they didn't say [:posix:] instead of [[:posix:]] */
12270     if (!SIZE_ONLY && RExC_parse < RExC_end && POSIXCC(UCHARAT(RExC_parse))) {
12271         const char *s = RExC_parse;
12272         const char  c = *s++;
12273
12274         while (isWORDCHAR(*s))
12275             s++;
12276         if (*s && c == *s && s[1] == ']') {
12277             SAVEFREESV(RExC_rx_sv);
12278             ckWARN3reg(s+2,
12279                        "POSIX syntax [%c %c] belongs inside character classes",
12280                        c, c);
12281             (void)ReREFCNT_inc(RExC_rx_sv);
12282         }
12283     }
12284
12285     /* If the caller wants us to just parse a single element, accomplish this
12286      * by faking the loop ending condition */
12287     if (stop_at_1 && RExC_end > RExC_parse) {
12288         stop_ptr = RExC_parse + 1;
12289     }
12290
12291     /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */
12292     if (UCHARAT(RExC_parse) == ']')
12293         goto charclassloop;
12294
12295 parseit:
12296     while (1) {
12297         if  (RExC_parse >= stop_ptr) {
12298             break;
12299         }
12300
12301         if (skip_white) {
12302             RExC_parse = regpatws(pRExC_state, RExC_parse,
12303                                   FALSE /* means don't recognize comments */);
12304         }
12305
12306         if  (UCHARAT(RExC_parse) == ']') {
12307             break;
12308         }
12309
12310     charclassloop:
12311
12312         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
12313         save_value = value;
12314         save_prevvalue = prevvalue;
12315
12316         if (!range) {
12317             rangebegin = RExC_parse;
12318             element_count++;
12319         }
12320         if (UTF) {
12321             value = utf8n_to_uvchr((U8*)RExC_parse,
12322                                    RExC_end - RExC_parse,
12323                                    &numlen, UTF8_ALLOW_DEFAULT);
12324             RExC_parse += numlen;
12325         }
12326         else
12327             value = UCHARAT(RExC_parse++);
12328
12329         if (value == '['
12330             && RExC_parse < RExC_end
12331             && POSIXCC(UCHARAT(RExC_parse)))
12332         {
12333             namedclass = regpposixcc(pRExC_state, value, strict);
12334         }
12335         else if (value == '\\') {
12336             if (UTF) {
12337                 value = utf8n_to_uvchr((U8*)RExC_parse,
12338                                    RExC_end - RExC_parse,
12339                                    &numlen, UTF8_ALLOW_DEFAULT);
12340                 RExC_parse += numlen;
12341             }
12342             else
12343                 value = UCHARAT(RExC_parse++);
12344
12345             /* Some compilers cannot handle switching on 64-bit integer
12346              * values, therefore value cannot be an UV.  Yes, this will
12347              * be a problem later if we want switch on Unicode.
12348              * A similar issue a little bit later when switching on
12349              * namedclass. --jhi */
12350
12351             /* If the \ is escaping white space when white space is being
12352              * skipped, it means that that white space is wanted literally, and
12353              * is already in 'value'.  Otherwise, need to translate the escape
12354              * into what it signifies. */
12355             if (! skip_white || ! is_PATWS_cp(value)) switch ((I32)value) {
12356
12357             case 'w':   namedclass = ANYOF_WORDCHAR;    break;
12358             case 'W':   namedclass = ANYOF_NWORDCHAR;   break;
12359             case 's':   namedclass = ANYOF_SPACE;       break;
12360             case 'S':   namedclass = ANYOF_NSPACE;      break;
12361             case 'd':   namedclass = ANYOF_DIGIT;       break;
12362             case 'D':   namedclass = ANYOF_NDIGIT;      break;
12363             case 'v':   namedclass = ANYOF_VERTWS;      break;
12364             case 'V':   namedclass = ANYOF_NVERTWS;     break;
12365             case 'h':   namedclass = ANYOF_HORIZWS;     break;
12366             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
12367             case 'N':  /* Handle \N{NAME} in class */
12368                 {
12369                     /* We only pay attention to the first char of 
12370                     multichar strings being returned. I kinda wonder
12371                     if this makes sense as it does change the behaviour
12372                     from earlier versions, OTOH that behaviour was broken
12373                     as well. */
12374                     if (! grok_bslash_N(pRExC_state, NULL, &value, flagp, depth,
12375                                       TRUE, /* => charclass */
12376                                       strict))
12377                     {
12378                         if (*flagp & RESTART_UTF8)
12379                             FAIL("panic: grok_bslash_N set RESTART_UTF8");
12380                         goto parseit;
12381                     }
12382                 }
12383                 break;
12384             case 'p':
12385             case 'P':
12386                 {
12387                 char *e;
12388
12389                 /* We will handle any undefined properties ourselves */
12390                 U8 swash_init_flags = _CORE_SWASH_INIT_RETURN_IF_UNDEF;
12391
12392                 if (RExC_parse >= RExC_end)
12393                     vFAIL2("Empty \\%c{}", (U8)value);
12394                 if (*RExC_parse == '{') {
12395                     const U8 c = (U8)value;
12396                     e = strchr(RExC_parse++, '}');
12397                     if (!e)
12398                         vFAIL2("Missing right brace on \\%c{}", c);
12399                     while (isSPACE(UCHARAT(RExC_parse)))
12400                         RExC_parse++;
12401                     if (e == RExC_parse)
12402                         vFAIL2("Empty \\%c{}", c);
12403                     n = e - RExC_parse;
12404                     while (isSPACE(UCHARAT(RExC_parse + n - 1)))
12405                         n--;
12406                 }
12407                 else {
12408                     e = RExC_parse;
12409                     n = 1;
12410                 }
12411                 if (!SIZE_ONLY) {
12412                     SV* invlist;
12413                     char* name;
12414
12415                     if (UCHARAT(RExC_parse) == '^') {
12416                          RExC_parse++;
12417                          n--;
12418                          /* toggle.  (The rhs xor gets the single bit that
12419                           * differs between P and p; the other xor inverts just
12420                           * that bit) */
12421                          value ^= 'P' ^ 'p';
12422
12423                          while (isSPACE(UCHARAT(RExC_parse))) {
12424                               RExC_parse++;
12425                               n--;
12426                          }
12427                     }
12428                     /* Try to get the definition of the property into
12429                      * <invlist>.  If /i is in effect, the effective property
12430                      * will have its name be <__NAME_i>.  The design is
12431                      * discussed in commit
12432                      * 2f833f5208e26b208886e51e09e2c072b5eabb46 */
12433                     Newx(name, n + sizeof("_i__\n"), char);
12434
12435                     sprintf(name, "%s%.*s%s\n",
12436                                     (FOLD) ? "__" : "",
12437                                     (int)n,
12438                                     RExC_parse,
12439                                     (FOLD) ? "_i" : ""
12440                     );
12441
12442                     /* Look up the property name, and get its swash and
12443                      * inversion list, if the property is found  */
12444                     if (swash) {
12445                         SvREFCNT_dec_NN(swash);
12446                     }
12447                     swash = _core_swash_init("utf8", name, &PL_sv_undef,
12448                                              1, /* binary */
12449                                              0, /* not tr/// */
12450                                              NULL, /* No inversion list */
12451                                              &swash_init_flags
12452                                             );
12453                     if (! swash || ! (invlist = _get_swash_invlist(swash))) {
12454                         if (swash) {
12455                             SvREFCNT_dec_NN(swash);
12456                             swash = NULL;
12457                         }
12458
12459                         /* Here didn't find it.  It could be a user-defined
12460                          * property that will be available at run-time.  If we
12461                          * accept only compile-time properties, is an error;
12462                          * otherwise add it to the list for run-time look up */
12463                         if (ret_invlist) {
12464                             RExC_parse = e + 1;
12465                             vFAIL3("Property '%.*s' is unknown", (int) n, name);
12466                         }
12467                         Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%s\n",
12468                                         (value == 'p' ? '+' : '!'),
12469                                         name);
12470                         has_user_defined_property = TRUE;
12471
12472                         /* We don't know yet, so have to assume that the
12473                          * property could match something in the Latin1 range,
12474                          * hence something that isn't utf8.  Note that this
12475                          * would cause things in <depends_list> to match
12476                          * inappropriately, except that any \p{}, including
12477                          * this one forces Unicode semantics, which means there
12478                          * is <no depends_list> */
12479                         ANYOF_FLAGS(ret) |= ANYOF_NONBITMAP_NON_UTF8;
12480                     }
12481                     else {
12482
12483                         /* Here, did get the swash and its inversion list.  If
12484                          * the swash is from a user-defined property, then this
12485                          * whole character class should be regarded as such */
12486                         has_user_defined_property =
12487                                     (swash_init_flags
12488                                      & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY);
12489
12490                         /* Invert if asking for the complement */
12491                         if (value == 'P') {
12492                             _invlist_union_complement_2nd(properties,
12493                                                           invlist,
12494                                                           &properties);
12495
12496                             /* The swash can't be used as-is, because we've
12497                              * inverted things; delay removing it to here after
12498                              * have copied its invlist above */
12499                             SvREFCNT_dec_NN(swash);
12500                             swash = NULL;
12501                         }
12502                         else {
12503                             _invlist_union(properties, invlist, &properties);
12504                         }
12505                     }
12506                     Safefree(name);
12507                 }
12508                 RExC_parse = e + 1;
12509                 namedclass = ANYOF_UNIPROP;  /* no official name, but it's
12510                                                 named */
12511
12512                 /* \p means they want Unicode semantics */
12513                 RExC_uni_semantics = 1;
12514                 }
12515                 break;
12516             case 'n':   value = '\n';                   break;
12517             case 'r':   value = '\r';                   break;
12518             case 't':   value = '\t';                   break;
12519             case 'f':   value = '\f';                   break;
12520             case 'b':   value = '\b';                   break;
12521             case 'e':   value = ASCII_TO_NATIVE('\033');break;
12522             case 'a':   value = ASCII_TO_NATIVE('\007');break;
12523             case 'o':
12524                 RExC_parse--;   /* function expects to be pointed at the 'o' */
12525                 {
12526                     const char* error_msg;
12527                     bool valid = grok_bslash_o(&RExC_parse,
12528                                                &value,
12529                                                &error_msg,
12530                                                SIZE_ONLY,   /* warnings in pass
12531                                                                1 only */
12532                                                strict,
12533                                                silence_non_portable,
12534                                                UTF);
12535                     if (! valid) {
12536                         vFAIL(error_msg);
12537                     }
12538                 }
12539                 if (PL_encoding && value < 0x100) {
12540                     goto recode_encoding;
12541                 }
12542                 break;
12543             case 'x':
12544                 RExC_parse--;   /* function expects to be pointed at the 'x' */
12545                 {
12546                     const char* error_msg;
12547                     bool valid = grok_bslash_x(&RExC_parse,
12548                                                &value,
12549                                                &error_msg,
12550                                                TRUE, /* Output warnings */
12551                                                strict,
12552                                                silence_non_portable,
12553                                                UTF);
12554                     if (! valid) {
12555                         vFAIL(error_msg);
12556                     }
12557                 }
12558                 if (PL_encoding && value < 0x100)
12559                     goto recode_encoding;
12560                 break;
12561             case 'c':
12562                 value = grok_bslash_c(*RExC_parse++, UTF, SIZE_ONLY);
12563                 break;
12564             case '0': case '1': case '2': case '3': case '4':
12565             case '5': case '6': case '7':
12566                 {
12567                     /* Take 1-3 octal digits */
12568                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
12569                     numlen = (strict) ? 4 : 3;
12570                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
12571                     RExC_parse += numlen;
12572                     if (numlen != 3) {
12573                         if (strict) {
12574                             RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1;
12575                             vFAIL("Need exactly 3 octal digits");
12576                         }
12577                         else if (! SIZE_ONLY /* like \08, \178 */
12578                                  && numlen < 3
12579                                  && RExC_parse < RExC_end
12580                                  && isDIGIT(*RExC_parse)
12581                                  && ckWARN(WARN_REGEXP))
12582                         {
12583                             SAVEFREESV(RExC_rx_sv);
12584                             reg_warn_non_literal_string(
12585                                  RExC_parse + 1,
12586                                  form_short_octal_warning(RExC_parse, numlen));
12587                             (void)ReREFCNT_inc(RExC_rx_sv);
12588                         }
12589                     }
12590                     if (PL_encoding && value < 0x100)
12591                         goto recode_encoding;
12592                     break;
12593                 }
12594             recode_encoding:
12595                 if (! RExC_override_recoding) {
12596                     SV* enc = PL_encoding;
12597                     value = reg_recode((const char)(U8)value, &enc);
12598                     if (!enc) {
12599                         if (strict) {
12600                             vFAIL("Invalid escape in the specified encoding");
12601                         }
12602                         else if (SIZE_ONLY) {
12603                             ckWARNreg(RExC_parse,
12604                                   "Invalid escape in the specified encoding");
12605                         }
12606                     }
12607                     break;
12608                 }
12609             default:
12610                 /* Allow \_ to not give an error */
12611                 if (!SIZE_ONLY && isWORDCHAR(value) && value != '_') {
12612                     if (strict) {
12613                         vFAIL2("Unrecognized escape \\%c in character class",
12614                                (int)value);
12615                     }
12616                     else {
12617                         SAVEFREESV(RExC_rx_sv);
12618                         ckWARN2reg(RExC_parse,
12619                             "Unrecognized escape \\%c in character class passed through",
12620                             (int)value);
12621                         (void)ReREFCNT_inc(RExC_rx_sv);
12622                     }
12623                 }
12624                 break;
12625             }   /* End of switch on char following backslash */
12626         } /* end of handling backslash escape sequences */
12627 #ifdef EBCDIC
12628         else
12629             literal_endpoint++;
12630 #endif
12631
12632         /* Here, we have the current token in 'value' */
12633
12634         /* What matches in a locale is not known until runtime.  This includes
12635          * what the Posix classes (like \w, [:space:]) match.  Room must be
12636          * reserved (one time per class) to store such classes, either if Perl
12637          * is compiled so that locale nodes always should have this space, or
12638          * if there is such class info to be stored.  The space will contain a
12639          * bit for each named class that is to be matched against.  This isn't
12640          * needed for \p{} and pseudo-classes, as they are not affected by
12641          * locale, and hence are dealt with separately */
12642         if (LOC
12643             && ! need_class
12644             && (ANYOF_LOCALE == ANYOF_CLASS
12645                 || (namedclass > OOB_NAMEDCLASS && namedclass < ANYOF_MAX)))
12646         {
12647             need_class = 1;
12648             if (SIZE_ONLY) {
12649                 RExC_size += ANYOF_CLASS_SKIP - ANYOF_SKIP;
12650             }
12651             else {
12652                 RExC_emit += ANYOF_CLASS_SKIP - ANYOF_SKIP;
12653                 ANYOF_CLASS_ZERO(ret);
12654             }
12655             ANYOF_FLAGS(ret) |= ANYOF_CLASS;
12656         }
12657
12658         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
12659
12660             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
12661              * literal, as is the character that began the false range, i.e.
12662              * the 'a' in the examples */
12663             if (range) {
12664                 if (!SIZE_ONLY) {
12665                     const int w = (RExC_parse >= rangebegin)
12666                                   ? RExC_parse - rangebegin
12667                                   : 0;
12668                     if (strict) {
12669                         vFAIL4("False [] range \"%*.*s\"", w, w, rangebegin);
12670                     }
12671                     else {
12672                         SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
12673                         ckWARN4reg(RExC_parse,
12674                                 "False [] range \"%*.*s\"",
12675                                 w, w, rangebegin);
12676                         (void)ReREFCNT_inc(RExC_rx_sv);
12677                         cp_list = add_cp_to_invlist(cp_list, '-');
12678                         cp_list = add_cp_to_invlist(cp_list, prevvalue);
12679                     }
12680                 }
12681
12682                 range = 0; /* this was not a true range */
12683                 element_count += 2; /* So counts for three values */
12684             }
12685
12686             if (! SIZE_ONLY) {
12687                 U8 classnum = namedclass_to_classnum(namedclass);
12688                 if (namedclass >= ANYOF_MAX) {  /* If a special class */
12689                     if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */
12690
12691                         /* Here, should be \h, \H, \v, or \V.  Neither /d nor
12692                          * /l make a difference in what these match.  There
12693                          * would be problems if these characters had folds
12694                          * other than themselves, as cp_list is subject to
12695                          * folding. */
12696                         if (classnum != _CC_VERTSPACE) {
12697                             assert(   namedclass == ANYOF_HORIZWS
12698                                    || namedclass == ANYOF_NHORIZWS);
12699
12700                             /* It turns out that \h is just a synonym for
12701                              * XPosixBlank */
12702                             classnum = _CC_BLANK;
12703                         }
12704
12705                         _invlist_union_maybe_complement_2nd(
12706                                 cp_list,
12707                                 PL_XPosix_ptrs[classnum],
12708                                 cBOOL(namedclass % 2), /* Complement if odd
12709                                                           (NHORIZWS, NVERTWS)
12710                                                         */
12711                                 &cp_list);
12712                     }
12713                 }
12714                 else if (classnum == _CC_ASCII) {
12715 #ifdef HAS_ISASCII
12716                     if (LOC) {
12717                         ANYOF_CLASS_SET(ret, namedclass);
12718                     }
12719                     else
12720 #endif  /* Not isascii(); just use the hard-coded definition for it */
12721                         _invlist_union_maybe_complement_2nd(
12722                                 posixes,
12723                                 PL_ASCII,
12724                                 cBOOL(namedclass % 2), /* Complement if odd
12725                                                           (NASCII) */
12726                                 &posixes);
12727                 }
12728                 else {  /* Garden variety class */
12729
12730                     /* The ascii range inversion list */
12731                     SV* ascii_source = PL_Posix_ptrs[classnum];
12732
12733                     /* The full Latin1 range inversion list */
12734                     SV* l1_source = PL_L1Posix_ptrs[classnum];
12735
12736                     /* This code is structured into two major clauses.  The
12737                      * first is for classes whose complete definitions may not
12738                      * already be known.  It not, the Latin1 definition
12739                      * (guaranteed to already known) is used plus code is
12740                      * generated to load the rest at run-time (only if needed).
12741                      * If the complete definition is known, it drops down to
12742                      * the second clause, where the complete definition is
12743                      * known */
12744
12745                     if (classnum < _FIRST_NON_SWASH_CC) {
12746
12747                         /* Here, the class has a swash, which may or not
12748                          * already be loaded */
12749
12750                         /* The name of the property to use to match the full
12751                          * eXtended Unicode range swash for this character
12752                          * class */
12753                         const char *Xname = swash_property_names[classnum];
12754
12755                         /* If returning the inversion list, we can't defer
12756                          * getting this until runtime */
12757                         if (ret_invlist && !  PL_utf8_swash_ptrs[classnum]) {
12758                             PL_utf8_swash_ptrs[classnum] =
12759                                 _core_swash_init("utf8", Xname, &PL_sv_undef,
12760                                              1, /* binary */
12761                                              0, /* not tr/// */
12762                                              NULL, /* No inversion list */
12763                                              NULL  /* No flags */
12764                                             );
12765                             assert(PL_utf8_swash_ptrs[classnum]);
12766                         }
12767                         if ( !  PL_utf8_swash_ptrs[classnum]) {
12768                             if (namedclass % 2 == 0) { /* A non-complemented
12769                                                           class */
12770                                 /* If not /a matching, there are code points we
12771                                  * don't know at compile time.  Arrange for the
12772                                  * unknown matches to be loaded at run-time, if
12773                                  * needed */
12774                                 if (! AT_LEAST_ASCII_RESTRICTED) {
12775                                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::%s\n",
12776                                                                  Xname);
12777                                 }
12778                                 if (LOC) {  /* Under locale, set run-time
12779                                                lookup */
12780                                     ANYOF_CLASS_SET(ret, namedclass);
12781                                 }
12782                                 else {
12783                                     /* Add the current class's code points to
12784                                      * the running total */
12785                                     _invlist_union(posixes,
12786                                                    (AT_LEAST_ASCII_RESTRICTED)
12787                                                         ? ascii_source
12788                                                         : l1_source,
12789                                                    &posixes);
12790                                 }
12791                             }
12792                             else {  /* A complemented class */
12793                                 if (AT_LEAST_ASCII_RESTRICTED) {
12794                                     /* Under /a should match everything above
12795                                      * ASCII, plus the complement of the set's
12796                                      * ASCII matches */
12797                                     _invlist_union_complement_2nd(posixes,
12798                                                                   ascii_source,
12799                                                                   &posixes);
12800                                 }
12801                                 else {
12802                                     /* Arrange for the unknown matches to be
12803                                      * loaded at run-time, if needed */
12804                                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::%s\n",
12805                                                                  Xname);
12806                                     runtime_posix_matches_above_Unicode = TRUE;
12807                                     if (LOC) {
12808                                         ANYOF_CLASS_SET(ret, namedclass);
12809                                     }
12810                                     else {
12811
12812                                         /* We want to match everything in
12813                                          * Latin1, except those things that
12814                                          * l1_source matches */
12815                                         SV* scratch_list = NULL;
12816                                         _invlist_subtract(PL_Latin1, l1_source,
12817                                                           &scratch_list);
12818
12819                                         /* Add the list from this class to the
12820                                          * running total */
12821                                         if (! posixes) {
12822                                             posixes = scratch_list;
12823                                         }
12824                                         else {
12825                                             _invlist_union(posixes,
12826                                                            scratch_list,
12827                                                            &posixes);
12828                                             SvREFCNT_dec_NN(scratch_list);
12829                                         }
12830                                         if (DEPENDS_SEMANTICS) {
12831                                             ANYOF_FLAGS(ret)
12832                                                   |= ANYOF_NON_UTF8_LATIN1_ALL;
12833                                         }
12834                                     }
12835                                 }
12836                             }
12837                             goto namedclass_done;
12838                         }
12839
12840                         /* Here, there is a swash loaded for the class.  If no
12841                          * inversion list for it yet, get it */
12842                         if (! PL_XPosix_ptrs[classnum]) {
12843                             PL_XPosix_ptrs[classnum]
12844                              = _swash_to_invlist(PL_utf8_swash_ptrs[classnum]);
12845                         }
12846                     }
12847
12848                     /* Here there is an inversion list already loaded for the
12849                      * entire class */
12850
12851                     if (namedclass % 2 == 0) {  /* A non-complemented class,
12852                                                    like ANYOF_PUNCT */
12853                         if (! LOC) {
12854                             /* For non-locale, just add it to any existing list
12855                              * */
12856                             _invlist_union(posixes,
12857                                            (AT_LEAST_ASCII_RESTRICTED)
12858                                                ? ascii_source
12859                                                : PL_XPosix_ptrs[classnum],
12860                                            &posixes);
12861                         }
12862                         else {  /* Locale */
12863                             SV* scratch_list = NULL;
12864
12865                             /* For above Latin1 code points, we use the full
12866                              * Unicode range */
12867                             _invlist_intersection(PL_AboveLatin1,
12868                                                   PL_XPosix_ptrs[classnum],
12869                                                   &scratch_list);
12870                             /* And set the output to it, adding instead if
12871                              * there already is an output.  Checking if
12872                              * 'posixes' is NULL first saves an extra clone.
12873                              * Its reference count will be decremented at the
12874                              * next union, etc, or if this is the only
12875                              * instance, at the end of the routine */
12876                             if (! posixes) {
12877                                 posixes = scratch_list;
12878                             }
12879                             else {
12880                                 _invlist_union(posixes, scratch_list, &posixes);
12881                                 SvREFCNT_dec_NN(scratch_list);
12882                             }
12883
12884 #ifndef HAS_ISBLANK
12885                             if (namedclass != ANYOF_BLANK) {
12886 #endif
12887                                 /* Set this class in the node for runtime
12888                                  * matching */
12889                                 ANYOF_CLASS_SET(ret, namedclass);
12890 #ifndef HAS_ISBLANK
12891                             }
12892                             else {
12893                                 /* No isblank(), use the hard-coded ASCII-range
12894                                  * blanks, adding them to the running total. */
12895
12896                                 _invlist_union(posixes, ascii_source, &posixes);
12897                             }
12898 #endif
12899                         }
12900                     }
12901                     else {  /* A complemented class, like ANYOF_NPUNCT */
12902                         if (! LOC) {
12903                             _invlist_union_complement_2nd(
12904                                                 posixes,
12905                                                 (AT_LEAST_ASCII_RESTRICTED)
12906                                                     ? ascii_source
12907                                                     : PL_XPosix_ptrs[classnum],
12908                                                 &posixes);
12909                             /* Under /d, everything in the upper half of the
12910                              * Latin1 range matches this complement */
12911                             if (DEPENDS_SEMANTICS) {
12912                                 ANYOF_FLAGS(ret) |= ANYOF_NON_UTF8_LATIN1_ALL;
12913                             }
12914                         }
12915                         else {  /* Locale */
12916                             SV* scratch_list = NULL;
12917                             _invlist_subtract(PL_AboveLatin1,
12918                                               PL_XPosix_ptrs[classnum],
12919                                               &scratch_list);
12920                             if (! posixes) {
12921                                 posixes = scratch_list;
12922                             }
12923                             else {
12924                                 _invlist_union(posixes, scratch_list, &posixes);
12925                                 SvREFCNT_dec_NN(scratch_list);
12926                             }
12927 #ifndef HAS_ISBLANK
12928                             if (namedclass != ANYOF_NBLANK) {
12929 #endif
12930                                 ANYOF_CLASS_SET(ret, namedclass);
12931 #ifndef HAS_ISBLANK
12932                             }
12933                             else {
12934                                 /* Get the list of all code points in Latin1
12935                                  * that are not ASCII blanks, and add them to
12936                                  * the running total */
12937                                 _invlist_subtract(PL_Latin1, ascii_source,
12938                                                   &scratch_list);
12939                                 _invlist_union(posixes, scratch_list, &posixes);
12940                                 SvREFCNT_dec_NN(scratch_list);
12941                             }
12942 #endif
12943                         }
12944                     }
12945                 }
12946               namedclass_done:
12947                 continue;   /* Go get next character */
12948             }
12949         } /* end of namedclass \blah */
12950
12951         /* Here, we have a single value.  If 'range' is set, it is the ending
12952          * of a range--check its validity.  Later, we will handle each
12953          * individual code point in the range.  If 'range' isn't set, this
12954          * could be the beginning of a range, so check for that by looking
12955          * ahead to see if the next real character to be processed is the range
12956          * indicator--the minus sign */
12957
12958         if (skip_white) {
12959             RExC_parse = regpatws(pRExC_state, RExC_parse,
12960                                 FALSE /* means don't recognize comments */);
12961         }
12962
12963         if (range) {
12964             if (prevvalue > value) /* b-a */ {
12965                 const int w = RExC_parse - rangebegin;
12966                 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
12967                 range = 0; /* not a valid range */
12968             }
12969         }
12970         else {
12971             prevvalue = value; /* save the beginning of the potential range */
12972             if (! stop_at_1     /* Can't be a range if parsing just one thing */
12973                 && *RExC_parse == '-')
12974             {
12975                 char* next_char_ptr = RExC_parse + 1;
12976                 if (skip_white) {   /* Get the next real char after the '-' */
12977                     next_char_ptr = regpatws(pRExC_state,
12978                                              RExC_parse + 1,
12979                                              FALSE); /* means don't recognize
12980                                                         comments */
12981                 }
12982
12983                 /* If the '-' is at the end of the class (just before the ']',
12984                  * it is a literal minus; otherwise it is a range */
12985                 if (next_char_ptr < RExC_end && *next_char_ptr != ']') {
12986                     RExC_parse = next_char_ptr;
12987
12988                     /* a bad range like \w-, [:word:]- ? */
12989                     if (namedclass > OOB_NAMEDCLASS) {
12990                         if (strict || ckWARN(WARN_REGEXP)) {
12991                             const int w =
12992                                 RExC_parse >= rangebegin ?
12993                                 RExC_parse - rangebegin : 0;
12994                             if (strict) {
12995                                 vFAIL4("False [] range \"%*.*s\"",
12996                                     w, w, rangebegin);
12997                             }
12998                             else {
12999                                 vWARN4(RExC_parse,
13000                                     "False [] range \"%*.*s\"",
13001                                     w, w, rangebegin);
13002                             }
13003                         }
13004                         if (!SIZE_ONLY) {
13005                             cp_list = add_cp_to_invlist(cp_list, '-');
13006                         }
13007                         element_count++;
13008                     } else
13009                         range = 1;      /* yeah, it's a range! */
13010                     continue;   /* but do it the next time */
13011                 }
13012             }
13013         }
13014
13015         /* Here, <prevvalue> is the beginning of the range, if any; or <value>
13016          * if not */
13017
13018         /* non-Latin1 code point implies unicode semantics.  Must be set in
13019          * pass1 so is there for the whole of pass 2 */
13020         if (value > 255) {
13021             RExC_uni_semantics = 1;
13022         }
13023
13024         /* Ready to process either the single value, or the completed range.
13025          * For single-valued non-inverted ranges, we consider the possibility
13026          * of multi-char folds.  (We made a conscious decision to not do this
13027          * for the other cases because it can often lead to non-intuitive
13028          * results.  For example, you have the peculiar case that:
13029          *  "s s" =~ /^[^\xDF]+$/i => Y
13030          *  "ss"  =~ /^[^\xDF]+$/i => N
13031          *
13032          * See [perl #89750] */
13033         if (FOLD && allow_multi_folds && value == prevvalue) {
13034             if (value == LATIN_SMALL_LETTER_SHARP_S
13035                 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
13036                                                         value)))
13037             {
13038                 /* Here <value> is indeed a multi-char fold.  Get what it is */
13039
13040                 U8 foldbuf[UTF8_MAXBYTES_CASE];
13041                 STRLEN foldlen;
13042
13043                 UV folded = _to_uni_fold_flags(
13044                                 value,
13045                                 foldbuf,
13046                                 &foldlen,
13047                                 FOLD_FLAGS_FULL
13048                                 | ((LOC) ?  FOLD_FLAGS_LOCALE
13049                                             : (ASCII_FOLD_RESTRICTED)
13050                                               ? FOLD_FLAGS_NOMIX_ASCII
13051                                               : 0)
13052                                 );
13053
13054                 /* Here, <folded> should be the first character of the
13055                  * multi-char fold of <value>, with <foldbuf> containing the
13056                  * whole thing.  But, if this fold is not allowed (because of
13057                  * the flags), <fold> will be the same as <value>, and should
13058                  * be processed like any other character, so skip the special
13059                  * handling */
13060                 if (folded != value) {
13061
13062                     /* Skip if we are recursed, currently parsing the class
13063                      * again.  Otherwise add this character to the list of
13064                      * multi-char folds. */
13065                     if (! RExC_in_multi_char_class) {
13066                         AV** this_array_ptr;
13067                         AV* this_array;
13068                         STRLEN cp_count = utf8_length(foldbuf,
13069                                                       foldbuf + foldlen);
13070                         SV* multi_fold = sv_2mortal(newSVpvn("", 0));
13071
13072                         Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%"UVXf"}", value);
13073
13074
13075                         if (! multi_char_matches) {
13076                             multi_char_matches = newAV();
13077                         }
13078
13079                         /* <multi_char_matches> is actually an array of arrays.
13080                          * There will be one or two top-level elements: [2],
13081                          * and/or [3].  The [2] element is an array, each
13082                          * element thereof is a character which folds to TWO
13083                          * characters; [3] is for folds to THREE characters.
13084                          * (Unicode guarantees a maximum of 3 characters in any
13085                          * fold.)  When we rewrite the character class below,
13086                          * we will do so such that the longest folds are
13087                          * written first, so that it prefers the longest
13088                          * matching strings first.  This is done even if it
13089                          * turns out that any quantifier is non-greedy, out of
13090                          * programmer laziness.  Tom Christiansen has agreed
13091                          * that this is ok.  This makes the test for the
13092                          * ligature 'ffi' come before the test for 'ff' */
13093                         if (av_exists(multi_char_matches, cp_count)) {
13094                             this_array_ptr = (AV**) av_fetch(multi_char_matches,
13095                                                              cp_count, FALSE);
13096                             this_array = *this_array_ptr;
13097                         }
13098                         else {
13099                             this_array = newAV();
13100                             av_store(multi_char_matches, cp_count,
13101                                      (SV*) this_array);
13102                         }
13103                         av_push(this_array, multi_fold);
13104                     }
13105
13106                     /* This element should not be processed further in this
13107                      * class */
13108                     element_count--;
13109                     value = save_value;
13110                     prevvalue = save_prevvalue;
13111                     continue;
13112                 }
13113             }
13114         }
13115
13116         /* Deal with this element of the class */
13117         if (! SIZE_ONLY) {
13118 #ifndef EBCDIC
13119             cp_list = _add_range_to_invlist(cp_list, prevvalue, value);
13120 #else
13121             SV* this_range = _new_invlist(1);
13122             _append_range_to_invlist(this_range, prevvalue, value);
13123
13124             /* In EBCDIC, the ranges 'A-Z' and 'a-z' are each not contiguous.
13125              * If this range was specified using something like 'i-j', we want
13126              * to include only the 'i' and the 'j', and not anything in
13127              * between, so exclude non-ASCII, non-alphabetics from it.
13128              * However, if the range was specified with something like
13129              * [\x89-\x91] or [\x89-j], all code points within it should be
13130              * included.  literal_endpoint==2 means both ends of the range used
13131              * a literal character, not \x{foo} */
13132             if (literal_endpoint == 2
13133                 && (prevvalue >= 'a' && value <= 'z')
13134                     || (prevvalue >= 'A' && value <= 'Z'))
13135             {
13136                 _invlist_intersection(this_range, PL_Posix_ptrs[_CC_ALPHA],
13137                                       &this_range);
13138             }
13139             _invlist_union(cp_list, this_range, &cp_list);
13140             literal_endpoint = 0;
13141 #endif
13142         }
13143
13144         range = 0; /* this range (if it was one) is done now */
13145     } /* End of loop through all the text within the brackets */
13146
13147     /* If anything in the class expands to more than one character, we have to
13148      * deal with them by building up a substitute parse string, and recursively
13149      * calling reg() on it, instead of proceeding */
13150     if (multi_char_matches) {
13151         SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
13152         I32 cp_count;
13153         STRLEN len;
13154         char *save_end = RExC_end;
13155         char *save_parse = RExC_parse;
13156         bool first_time = TRUE;     /* First multi-char occurrence doesn't get
13157                                        a "|" */
13158         I32 reg_flags;
13159
13160         assert(! invert);
13161 #if 0   /* Have decided not to deal with multi-char folds in inverted classes,
13162            because too confusing */
13163         if (invert) {
13164             sv_catpv(substitute_parse, "(?:");
13165         }
13166 #endif
13167
13168         /* Look at the longest folds first */
13169         for (cp_count = av_len(multi_char_matches); cp_count > 0; cp_count--) {
13170
13171             if (av_exists(multi_char_matches, cp_count)) {
13172                 AV** this_array_ptr;
13173                 SV* this_sequence;
13174
13175                 this_array_ptr = (AV**) av_fetch(multi_char_matches,
13176                                                  cp_count, FALSE);
13177                 while ((this_sequence = av_pop(*this_array_ptr)) !=
13178                                                                 &PL_sv_undef)
13179                 {
13180                     if (! first_time) {
13181                         sv_catpv(substitute_parse, "|");
13182                     }
13183                     first_time = FALSE;
13184
13185                     sv_catpv(substitute_parse, SvPVX(this_sequence));
13186                 }
13187             }
13188         }
13189
13190         /* If the character class contains anything else besides these
13191          * multi-character folds, have to include it in recursive parsing */
13192         if (element_count) {
13193             sv_catpv(substitute_parse, "|[");
13194             sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
13195             sv_catpv(substitute_parse, "]");
13196         }
13197
13198         sv_catpv(substitute_parse, ")");
13199 #if 0
13200         if (invert) {
13201             /* This is a way to get the parse to skip forward a whole named
13202              * sequence instead of matching the 2nd character when it fails the
13203              * first */
13204             sv_catpv(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
13205         }
13206 #endif
13207
13208         RExC_parse = SvPV(substitute_parse, len);
13209         RExC_end = RExC_parse + len;
13210         RExC_in_multi_char_class = 1;
13211         RExC_emit = (regnode *)orig_emit;
13212
13213         ret = reg(pRExC_state, 1, &reg_flags, depth+1);
13214
13215         *flagp |= reg_flags&(HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_UTF8);
13216
13217         RExC_parse = save_parse;
13218         RExC_end = save_end;
13219         RExC_in_multi_char_class = 0;
13220         SvREFCNT_dec_NN(multi_char_matches);
13221         return ret;
13222     }
13223
13224     /* If the character class contains only a single element, it may be
13225      * optimizable into another node type which is smaller and runs faster.
13226      * Check if this is the case for this class */
13227     if (element_count == 1 && ! ret_invlist) {
13228         U8 op = END;
13229         U8 arg = 0;
13230
13231         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class, like \w or
13232                                               [:digit:] or \p{foo} */
13233
13234             /* All named classes are mapped into POSIXish nodes, with its FLAG
13235              * argument giving which class it is */
13236             switch ((I32)namedclass) {
13237                 case ANYOF_UNIPROP:
13238                     break;
13239
13240                 /* These don't depend on the charset modifiers.  They always
13241                  * match under /u rules */
13242                 case ANYOF_NHORIZWS:
13243                 case ANYOF_HORIZWS:
13244                     namedclass = ANYOF_BLANK + namedclass - ANYOF_HORIZWS;
13245                     /* FALLTHROUGH */
13246
13247                 case ANYOF_NVERTWS:
13248                 case ANYOF_VERTWS:
13249                     op = POSIXU;
13250                     goto join_posix;
13251
13252                 /* The actual POSIXish node for all the rest depends on the
13253                  * charset modifier.  The ones in the first set depend only on
13254                  * ASCII or, if available on this platform, locale */
13255                 case ANYOF_ASCII:
13256                 case ANYOF_NASCII:
13257 #ifdef HAS_ISASCII
13258                     op = (LOC) ? POSIXL : POSIXA;
13259 #else
13260                     op = POSIXA;
13261 #endif
13262                     goto join_posix;
13263
13264                 case ANYOF_NCASED:
13265                 case ANYOF_LOWER:
13266                 case ANYOF_NLOWER:
13267                 case ANYOF_UPPER:
13268                 case ANYOF_NUPPER:
13269                     /* under /a could be alpha */
13270                     if (FOLD) {
13271                         if (ASCII_RESTRICTED) {
13272                             namedclass = ANYOF_ALPHA + (namedclass % 2);
13273                         }
13274                         else if (! LOC) {
13275                             break;
13276                         }
13277                     }
13278                     /* FALLTHROUGH */
13279
13280                 /* The rest have more possibilities depending on the charset.
13281                  * We take advantage of the enum ordering of the charset
13282                  * modifiers to get the exact node type, */
13283                 default:
13284                     op = POSIXD + get_regex_charset(RExC_flags);
13285                     if (op > POSIXA) { /* /aa is same as /a */
13286                         op = POSIXA;
13287                     }
13288 #ifndef HAS_ISBLANK
13289                     if (op == POSIXL
13290                         && (namedclass == ANYOF_BLANK
13291                             || namedclass == ANYOF_NBLANK))
13292                     {
13293                         op = POSIXA;
13294                     }
13295 #endif
13296
13297                 join_posix:
13298                     /* The odd numbered ones are the complements of the
13299                      * next-lower even number one */
13300                     if (namedclass % 2 == 1) {
13301                         invert = ! invert;
13302                         namedclass--;
13303                     }
13304                     arg = namedclass_to_classnum(namedclass);
13305                     break;
13306             }
13307         }
13308         else if (value == prevvalue) {
13309
13310             /* Here, the class consists of just a single code point */
13311
13312             if (invert) {
13313                 if (! LOC && value == '\n') {
13314                     op = REG_ANY; /* Optimize [^\n] */
13315                     *flagp |= HASWIDTH|SIMPLE;
13316                     RExC_naughty++;
13317                 }
13318             }
13319             else if (value < 256 || UTF) {
13320
13321                 /* Optimize a single value into an EXACTish node, but not if it
13322                  * would require converting the pattern to UTF-8. */
13323                 op = compute_EXACTish(pRExC_state);
13324             }
13325         } /* Otherwise is a range */
13326         else if (! LOC) {   /* locale could vary these */
13327             if (prevvalue == '0') {
13328                 if (value == '9') {
13329                     arg = _CC_DIGIT;
13330                     op = POSIXA;
13331                 }
13332             }
13333         }
13334
13335         /* Here, we have changed <op> away from its initial value iff we found
13336          * an optimization */
13337         if (op != END) {
13338
13339             /* Throw away this ANYOF regnode, and emit the calculated one,
13340              * which should correspond to the beginning, not current, state of
13341              * the parse */
13342             const char * cur_parse = RExC_parse;
13343             RExC_parse = (char *)orig_parse;
13344             if ( SIZE_ONLY) {
13345                 if (! LOC) {
13346
13347                     /* To get locale nodes to not use the full ANYOF size would
13348                      * require moving the code above that writes the portions
13349                      * of it that aren't in other nodes to after this point.
13350                      * e.g.  ANYOF_CLASS_SET */
13351                     RExC_size = orig_size;
13352                 }
13353             }
13354             else {
13355                 RExC_emit = (regnode *)orig_emit;
13356                 if (PL_regkind[op] == POSIXD) {
13357                     if (invert) {
13358                         op += NPOSIXD - POSIXD;
13359                     }
13360                 }
13361             }
13362
13363             ret = reg_node(pRExC_state, op);
13364
13365             if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
13366                 if (! SIZE_ONLY) {
13367                     FLAGS(ret) = arg;
13368                 }
13369                 *flagp |= HASWIDTH|SIMPLE;
13370             }
13371             else if (PL_regkind[op] == EXACT) {
13372                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value);
13373             }
13374
13375             RExC_parse = (char *) cur_parse;
13376
13377             SvREFCNT_dec(posixes);
13378             SvREFCNT_dec(cp_list);
13379             return ret;
13380         }
13381     }
13382
13383     if (SIZE_ONLY)
13384         return ret;
13385     /****** !SIZE_ONLY (Pass 2) AFTER HERE *********/
13386
13387     /* If folding, we calculate all characters that could fold to or from the
13388      * ones already on the list */
13389     if (FOLD && cp_list) {
13390         UV start, end;  /* End points of code point ranges */
13391
13392         SV* fold_intersection = NULL;
13393
13394         /* If the highest code point is within Latin1, we can use the
13395          * compiled-in Alphas list, and not have to go out to disk.  This
13396          * yields two false positives, the masculine and feminine ordinal
13397          * indicators, which are weeded out below using the
13398          * IS_IN_SOME_FOLD_L1() macro */
13399         if (invlist_highest(cp_list) < 256) {
13400             _invlist_intersection(PL_L1Posix_ptrs[_CC_ALPHA], cp_list,
13401                                                            &fold_intersection);
13402         }
13403         else {
13404
13405             /* Here, there are non-Latin1 code points, so we will have to go
13406              * fetch the list of all the characters that participate in folds
13407              */
13408             if (! PL_utf8_foldable) {
13409                 SV* swash = swash_init("utf8", "_Perl_Any_Folds",
13410                                        &PL_sv_undef, 1, 0);
13411                 PL_utf8_foldable = _get_swash_invlist(swash);
13412                 SvREFCNT_dec_NN(swash);
13413             }
13414
13415             /* This is a hash that for a particular fold gives all characters
13416              * that are involved in it */
13417             if (! PL_utf8_foldclosures) {
13418
13419                 /* If we were unable to find any folds, then we likely won't be
13420                  * able to find the closures.  So just create an empty list.
13421                  * Folding will effectively be restricted to the non-Unicode
13422                  * rules hard-coded into Perl.  (This case happens legitimately
13423                  * during compilation of Perl itself before the Unicode tables
13424                  * are generated) */
13425                 if (_invlist_len(PL_utf8_foldable) == 0) {
13426                     PL_utf8_foldclosures = newHV();
13427                 }
13428                 else {
13429                     /* If the folds haven't been read in, call a fold function
13430                      * to force that */
13431                     if (! PL_utf8_tofold) {
13432                         U8 dummy[UTF8_MAXBYTES+1];
13433
13434                         /* This string is just a short named one above \xff */
13435                         to_utf8_fold((U8*) HYPHEN_UTF8, dummy, NULL);
13436                         assert(PL_utf8_tofold); /* Verify that worked */
13437                     }
13438                     PL_utf8_foldclosures =
13439                                     _swash_inversion_hash(PL_utf8_tofold);
13440                 }
13441             }
13442
13443             /* Only the characters in this class that participate in folds need
13444              * be checked.  Get the intersection of this class and all the
13445              * possible characters that are foldable.  This can quickly narrow
13446              * down a large class */
13447             _invlist_intersection(PL_utf8_foldable, cp_list,
13448                                   &fold_intersection);
13449         }
13450
13451         /* Now look at the foldable characters in this class individually */
13452         invlist_iterinit(fold_intersection);
13453         while (invlist_iternext(fold_intersection, &start, &end)) {
13454             UV j;
13455
13456             /* Locale folding for Latin1 characters is deferred until runtime */
13457             if (LOC && start < 256) {
13458                 start = 256;
13459             }
13460
13461             /* Look at every character in the range */
13462             for (j = start; j <= end; j++) {
13463
13464                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
13465                 STRLEN foldlen;
13466                 SV** listp;
13467
13468                 if (j < 256) {
13469
13470                     /* We have the latin1 folding rules hard-coded here so that
13471                      * an innocent-looking character class, like /[ks]/i won't
13472                      * have to go out to disk to find the possible matches.
13473                      * XXX It would be better to generate these via regen, in
13474                      * case a new version of the Unicode standard adds new
13475                      * mappings, though that is not really likely, and may be
13476                      * caught by the default: case of the switch below. */
13477
13478                     if (IS_IN_SOME_FOLD_L1(j)) {
13479
13480                         /* ASCII is always matched; non-ASCII is matched only
13481                          * under Unicode rules */
13482                         if (isASCII(j) || AT_LEAST_UNI_SEMANTICS) {
13483                             cp_list =
13484                                 add_cp_to_invlist(cp_list, PL_fold_latin1[j]);
13485                         }
13486                         else {
13487                             depends_list =
13488                              add_cp_to_invlist(depends_list, PL_fold_latin1[j]);
13489                         }
13490                     }
13491
13492                     if (HAS_NONLATIN1_FOLD_CLOSURE(j)
13493                         && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
13494                     {
13495                         /* Certain Latin1 characters have matches outside
13496                          * Latin1.  To get here, <j> is one of those
13497                          * characters.   None of these matches is valid for
13498                          * ASCII characters under /aa, which is why the 'if'
13499                          * just above excludes those.  These matches only
13500                          * happen when the target string is utf8.  The code
13501                          * below adds the single fold closures for <j> to the
13502                          * inversion list. */
13503                         switch (j) {
13504                             case 'k':
13505                             case 'K':
13506                                 cp_list =
13507                                     add_cp_to_invlist(cp_list, KELVIN_SIGN);
13508                                 break;
13509                             case 's':
13510                             case 'S':
13511                                 cp_list = add_cp_to_invlist(cp_list,
13512                                                     LATIN_SMALL_LETTER_LONG_S);
13513                                 break;
13514                             case MICRO_SIGN:
13515                                 cp_list = add_cp_to_invlist(cp_list,
13516                                                     GREEK_CAPITAL_LETTER_MU);
13517                                 cp_list = add_cp_to_invlist(cp_list,
13518                                                     GREEK_SMALL_LETTER_MU);
13519                                 break;
13520                             case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
13521                             case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
13522                                 cp_list =
13523                                     add_cp_to_invlist(cp_list, ANGSTROM_SIGN);
13524                                 break;
13525                             case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
13526                                 cp_list = add_cp_to_invlist(cp_list,
13527                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
13528                                 break;
13529                             case LATIN_SMALL_LETTER_SHARP_S:
13530                                 cp_list = add_cp_to_invlist(cp_list,
13531                                                 LATIN_CAPITAL_LETTER_SHARP_S);
13532                                 break;
13533                             case 'F': case 'f':
13534                             case 'I': case 'i':
13535                             case 'L': case 'l':
13536                             case 'T': case 't':
13537                             case 'A': case 'a':
13538                             case 'H': case 'h':
13539                             case 'J': case 'j':
13540                             case 'N': case 'n':
13541                             case 'W': case 'w':
13542                             case 'Y': case 'y':
13543                                 /* These all are targets of multi-character
13544                                  * folds from code points that require UTF8 to
13545                                  * express, so they can't match unless the
13546                                  * target string is in UTF-8, so no action here
13547                                  * is necessary, as regexec.c properly handles
13548                                  * the general case for UTF-8 matching and
13549                                  * multi-char folds */
13550                                 break;
13551                             default:
13552                                 /* Use deprecated warning to increase the
13553                                  * chances of this being output */
13554                                 ckWARN2reg_d(RExC_parse, "Perl folding rules are not up-to-date for 0x%"UVXf"; please use the perlbug utility to report;", j);
13555                                 break;
13556                         }
13557                     }
13558                     continue;
13559                 }
13560
13561                 /* Here is an above Latin1 character.  We don't have the rules
13562                  * hard-coded for it.  First, get its fold.  This is the simple
13563                  * fold, as the multi-character folds have been handled earlier
13564                  * and separated out */
13565                 _to_uni_fold_flags(j, foldbuf, &foldlen,
13566                                                ((LOC)
13567                                                ? FOLD_FLAGS_LOCALE
13568                                                : (ASCII_FOLD_RESTRICTED)
13569                                                   ? FOLD_FLAGS_NOMIX_ASCII
13570                                                   : 0));
13571
13572                 /* Single character fold of above Latin1.  Add everything in
13573                  * its fold closure to the list that this node should match.
13574                  * The fold closures data structure is a hash with the keys
13575                  * being the UTF-8 of every character that is folded to, like
13576                  * 'k', and the values each an array of all code points that
13577                  * fold to its key.  e.g. [ 'k', 'K', KELVIN_SIGN ].
13578                  * Multi-character folds are not included */
13579                 if ((listp = hv_fetch(PL_utf8_foldclosures,
13580                                       (char *) foldbuf, foldlen, FALSE)))
13581                 {
13582                     AV* list = (AV*) *listp;
13583                     IV k;
13584                     for (k = 0; k <= av_len(list); k++) {
13585                         SV** c_p = av_fetch(list, k, FALSE);
13586                         UV c;
13587                         if (c_p == NULL) {
13588                             Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
13589                         }
13590                         c = SvUV(*c_p);
13591
13592                         /* /aa doesn't allow folds between ASCII and non-; /l
13593                          * doesn't allow them between above and below 256 */
13594                         if ((ASCII_FOLD_RESTRICTED
13595                                   && (isASCII(c) != isASCII(j)))
13596                             || (LOC && c < 256)) {
13597                             continue;
13598                         }
13599
13600                         /* Folds involving non-ascii Latin1 characters
13601                          * under /d are added to a separate list */
13602                         if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
13603                         {
13604                             cp_list = add_cp_to_invlist(cp_list, c);
13605                         }
13606                         else {
13607                           depends_list = add_cp_to_invlist(depends_list, c);
13608                         }
13609                     }
13610                 }
13611             }
13612         }
13613         SvREFCNT_dec_NN(fold_intersection);
13614     }
13615
13616     /* And combine the result (if any) with any inversion list from posix
13617      * classes.  The lists are kept separate up to now because we don't want to
13618      * fold the classes (folding of those is automatically handled by the swash
13619      * fetching code) */
13620     if (posixes) {
13621         if (! DEPENDS_SEMANTICS) {
13622             if (cp_list) {
13623                 _invlist_union(cp_list, posixes, &cp_list);
13624                 SvREFCNT_dec_NN(posixes);
13625             }
13626             else {
13627                 cp_list = posixes;
13628             }
13629         }
13630         else {
13631             /* Under /d, we put into a separate list the Latin1 things that
13632              * match only when the target string is utf8 */
13633             SV* nonascii_but_latin1_properties = NULL;
13634             _invlist_intersection(posixes, PL_Latin1,
13635                                   &nonascii_but_latin1_properties);
13636             _invlist_subtract(nonascii_but_latin1_properties, PL_ASCII,
13637                               &nonascii_but_latin1_properties);
13638             _invlist_subtract(posixes, nonascii_but_latin1_properties,
13639                               &posixes);
13640             if (cp_list) {
13641                 _invlist_union(cp_list, posixes, &cp_list);
13642                 SvREFCNT_dec_NN(posixes);
13643             }
13644             else {
13645                 cp_list = posixes;
13646             }
13647
13648             if (depends_list) {
13649                 _invlist_union(depends_list, nonascii_but_latin1_properties,
13650                                &depends_list);
13651                 SvREFCNT_dec_NN(nonascii_but_latin1_properties);
13652             }
13653             else {
13654                 depends_list = nonascii_but_latin1_properties;
13655             }
13656         }
13657     }
13658
13659     /* And combine the result (if any) with any inversion list from properties.
13660      * The lists are kept separate up to now so that we can distinguish the two
13661      * in regards to matching above-Unicode.  A run-time warning is generated
13662      * if a Unicode property is matched against a non-Unicode code point. But,
13663      * we allow user-defined properties to match anything, without any warning,
13664      * and we also suppress the warning if there is a portion of the character
13665      * class that isn't a Unicode property, and which matches above Unicode, \W
13666      * or [\x{110000}] for example.
13667      * (Note that in this case, unlike the Posix one above, there is no
13668      * <depends_list>, because having a Unicode property forces Unicode
13669      * semantics */
13670     if (properties) {
13671         bool warn_super = ! has_user_defined_property;
13672         if (cp_list) {
13673
13674             /* If it matters to the final outcome, see if a non-property
13675              * component of the class matches above Unicode.  If so, the
13676              * warning gets suppressed.  This is true even if just a single
13677              * such code point is specified, as though not strictly correct if
13678              * another such code point is matched against, the fact that they
13679              * are using above-Unicode code points indicates they should know
13680              * the issues involved */
13681             if (warn_super) {
13682                 bool non_prop_matches_above_Unicode =
13683                             runtime_posix_matches_above_Unicode
13684                             | (invlist_highest(cp_list) > PERL_UNICODE_MAX);
13685                 if (invert) {
13686                     non_prop_matches_above_Unicode =
13687                                             !  non_prop_matches_above_Unicode;
13688                 }
13689                 warn_super = ! non_prop_matches_above_Unicode;
13690             }
13691
13692             _invlist_union(properties, cp_list, &cp_list);
13693             SvREFCNT_dec_NN(properties);
13694         }
13695         else {
13696             cp_list = properties;
13697         }
13698
13699         if (warn_super) {
13700             OP(ret) = ANYOF_WARN_SUPER;
13701         }
13702     }
13703
13704     /* Here, we have calculated what code points should be in the character
13705      * class.
13706      *
13707      * Now we can see about various optimizations.  Fold calculation (which we
13708      * did above) needs to take place before inversion.  Otherwise /[^k]/i
13709      * would invert to include K, which under /i would match k, which it
13710      * shouldn't.  Therefore we can't invert folded locale now, as it won't be
13711      * folded until runtime */
13712
13713     /* Optimize inverted simple patterns (e.g. [^a-z]) when everything is known
13714      * at compile time.  Besides not inverting folded locale now, we can't
13715      * invert if there are things such as \w, which aren't known until runtime
13716      * */
13717     if (invert
13718         && ! (LOC && (FOLD || (ANYOF_FLAGS(ret) & ANYOF_CLASS)))
13719         && ! depends_list
13720         && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
13721     {
13722         _invlist_invert(cp_list);
13723
13724         /* Any swash can't be used as-is, because we've inverted things */
13725         if (swash) {
13726             SvREFCNT_dec_NN(swash);
13727             swash = NULL;
13728         }
13729
13730         /* Clear the invert flag since have just done it here */
13731         invert = FALSE;
13732     }
13733
13734     if (ret_invlist) {
13735         *ret_invlist = cp_list;
13736         SvREFCNT_dec(swash);
13737
13738         /* Discard the generated node */
13739         if (SIZE_ONLY) {
13740             RExC_size = orig_size;
13741         }
13742         else {
13743             RExC_emit = orig_emit;
13744         }
13745         return orig_emit;
13746     }
13747
13748     /* If we didn't do folding, it's because some information isn't available
13749      * until runtime; set the run-time fold flag for these.  (We don't have to
13750      * worry about properties folding, as that is taken care of by the swash
13751      * fetching) */
13752     if (FOLD && LOC)
13753     {
13754        ANYOF_FLAGS(ret) |= ANYOF_LOC_FOLD;
13755     }
13756
13757     /* Some character classes are equivalent to other nodes.  Such nodes take
13758      * up less room and generally fewer operations to execute than ANYOF nodes.
13759      * Above, we checked for and optimized into some such equivalents for
13760      * certain common classes that are easy to test.  Getting to this point in
13761      * the code means that the class didn't get optimized there.  Since this
13762      * code is only executed in Pass 2, it is too late to save space--it has
13763      * been allocated in Pass 1, and currently isn't given back.  But turning
13764      * things into an EXACTish node can allow the optimizer to join it to any
13765      * adjacent such nodes.  And if the class is equivalent to things like /./,
13766      * expensive run-time swashes can be avoided.  Now that we have more
13767      * complete information, we can find things necessarily missed by the
13768      * earlier code.  I (khw) am not sure how much to look for here.  It would
13769      * be easy, but perhaps too slow, to check any candidates against all the
13770      * node types they could possibly match using _invlistEQ(). */
13771
13772     if (cp_list
13773         && ! invert
13774         && ! depends_list
13775         && ! (ANYOF_FLAGS(ret) & ANYOF_CLASS)
13776         && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
13777     {
13778         UV start, end;
13779         U8 op = END;  /* The optimzation node-type */
13780         const char * cur_parse= RExC_parse;
13781
13782         invlist_iterinit(cp_list);
13783         if (! invlist_iternext(cp_list, &start, &end)) {
13784
13785             /* Here, the list is empty.  This happens, for example, when a
13786              * Unicode property is the only thing in the character class, and
13787              * it doesn't match anything.  (perluniprops.pod notes such
13788              * properties) */
13789             op = OPFAIL;
13790             *flagp |= HASWIDTH|SIMPLE;
13791         }
13792         else if (start == end) {    /* The range is a single code point */
13793             if (! invlist_iternext(cp_list, &start, &end)
13794
13795                     /* Don't do this optimization if it would require changing
13796                      * the pattern to UTF-8 */
13797                 && (start < 256 || UTF))
13798             {
13799                 /* Here, the list contains a single code point.  Can optimize
13800                  * into an EXACT node */
13801
13802                 value = start;
13803
13804                 if (! FOLD) {
13805                     op = EXACT;
13806                 }
13807                 else if (LOC) {
13808
13809                     /* A locale node under folding with one code point can be
13810                      * an EXACTFL, as its fold won't be calculated until
13811                      * runtime */
13812                     op = EXACTFL;
13813                 }
13814                 else {
13815
13816                     /* Here, we are generally folding, but there is only one
13817                      * code point to match.  If we have to, we use an EXACT
13818                      * node, but it would be better for joining with adjacent
13819                      * nodes in the optimization pass if we used the same
13820                      * EXACTFish node that any such are likely to be.  We can
13821                      * do this iff the code point doesn't participate in any
13822                      * folds.  For example, an EXACTF of a colon is the same as
13823                      * an EXACT one, since nothing folds to or from a colon. */
13824                     if (value < 256) {
13825                         if (IS_IN_SOME_FOLD_L1(value)) {
13826                             op = EXACT;
13827                         }
13828                     }
13829                     else {
13830                         if (! PL_utf8_foldable) {
13831                             SV* swash = swash_init("utf8", "_Perl_Any_Folds",
13832                                                 &PL_sv_undef, 1, 0);
13833                             PL_utf8_foldable = _get_swash_invlist(swash);
13834                             SvREFCNT_dec_NN(swash);
13835                         }
13836                         if (_invlist_contains_cp(PL_utf8_foldable, value)) {
13837                             op = EXACT;
13838                         }
13839                     }
13840
13841                     /* If we haven't found the node type, above, it means we
13842                      * can use the prevailing one */
13843                     if (op == END) {
13844                         op = compute_EXACTish(pRExC_state);
13845                     }
13846                 }
13847             }
13848         }
13849         else if (start == 0) {
13850             if (end == UV_MAX) {
13851                 op = SANY;
13852                 *flagp |= HASWIDTH|SIMPLE;
13853                 RExC_naughty++;
13854             }
13855             else if (end == '\n' - 1
13856                     && invlist_iternext(cp_list, &start, &end)
13857                     && start == '\n' + 1 && end == UV_MAX)
13858             {
13859                 op = REG_ANY;
13860                 *flagp |= HASWIDTH|SIMPLE;
13861                 RExC_naughty++;
13862             }
13863         }
13864         invlist_iterfinish(cp_list);
13865
13866         if (op != END) {
13867             RExC_parse = (char *)orig_parse;
13868             RExC_emit = (regnode *)orig_emit;
13869
13870             ret = reg_node(pRExC_state, op);
13871
13872             RExC_parse = (char *)cur_parse;
13873
13874             if (PL_regkind[op] == EXACT) {
13875                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value);
13876             }
13877
13878             SvREFCNT_dec_NN(cp_list);
13879             return ret;
13880         }
13881     }
13882
13883     /* Here, <cp_list> contains all the code points we can determine at
13884      * compile time that match under all conditions.  Go through it, and
13885      * for things that belong in the bitmap, put them there, and delete from
13886      * <cp_list>.  While we are at it, see if everything above 255 is in the
13887      * list, and if so, set a flag to speed up execution */
13888     ANYOF_BITMAP_ZERO(ret);
13889     if (cp_list) {
13890
13891         /* This gets set if we actually need to modify things */
13892         bool change_invlist = FALSE;
13893
13894         UV start, end;
13895
13896         /* Start looking through <cp_list> */
13897         invlist_iterinit(cp_list);
13898         while (invlist_iternext(cp_list, &start, &end)) {
13899             UV high;
13900             int i;
13901
13902             if (end == UV_MAX && start <= 256) {
13903                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE_ALL;
13904             }
13905
13906             /* Quit if are above what we should change */
13907             if (start > 255) {
13908                 break;
13909             }
13910
13911             change_invlist = TRUE;
13912
13913             /* Set all the bits in the range, up to the max that we are doing */
13914             high = (end < 255) ? end : 255;
13915             for (i = start; i <= (int) high; i++) {
13916                 if (! ANYOF_BITMAP_TEST(ret, i)) {
13917                     ANYOF_BITMAP_SET(ret, i);
13918                 }
13919             }
13920         }
13921         invlist_iterfinish(cp_list);
13922
13923         /* Done with loop; remove any code points that are in the bitmap from
13924          * <cp_list> */
13925         if (change_invlist) {
13926             _invlist_subtract(cp_list, PL_Latin1, &cp_list);
13927         }
13928
13929         /* If have completely emptied it, remove it completely */
13930         if (_invlist_len(cp_list) == 0) {
13931             SvREFCNT_dec_NN(cp_list);
13932             cp_list = NULL;
13933         }
13934     }
13935
13936     if (invert) {
13937         ANYOF_FLAGS(ret) |= ANYOF_INVERT;
13938     }
13939
13940     /* Here, the bitmap has been populated with all the Latin1 code points that
13941      * always match.  Can now add to the overall list those that match only
13942      * when the target string is UTF-8 (<depends_list>). */
13943     if (depends_list) {
13944         if (cp_list) {
13945             _invlist_union(cp_list, depends_list, &cp_list);
13946             SvREFCNT_dec_NN(depends_list);
13947         }
13948         else {
13949             cp_list = depends_list;
13950         }
13951     }
13952
13953     /* If there is a swash and more than one element, we can't use the swash in
13954      * the optimization below. */
13955     if (swash && element_count > 1) {
13956         SvREFCNT_dec_NN(swash);
13957         swash = NULL;
13958     }
13959
13960     if (! cp_list
13961         && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
13962     {
13963         ARG_SET(ret, ANYOF_NONBITMAP_EMPTY);
13964     }
13965     else {
13966         /* av[0] stores the character class description in its textual form:
13967          *       used later (regexec.c:Perl_regclass_swash()) to initialize the
13968          *       appropriate swash, and is also useful for dumping the regnode.
13969          * av[1] if NULL, is a placeholder to later contain the swash computed
13970          *       from av[0].  But if no further computation need be done, the
13971          *       swash is stored there now.
13972          * av[2] stores the cp_list inversion list for use in addition or
13973          *       instead of av[0]; used only if av[1] is NULL
13974          * av[3] is set if any component of the class is from a user-defined
13975          *       property; used only if av[1] is NULL */
13976         AV * const av = newAV();
13977         SV *rv;
13978
13979         av_store(av, 0, (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
13980                         ? SvREFCNT_inc(listsv) : &PL_sv_undef);
13981         if (swash) {
13982             av_store(av, 1, swash);
13983             SvREFCNT_dec_NN(cp_list);
13984         }
13985         else {
13986             av_store(av, 1, NULL);
13987             if (cp_list) {
13988                 av_store(av, 2, cp_list);
13989                 av_store(av, 3, newSVuv(has_user_defined_property));
13990             }
13991         }
13992
13993         rv = newRV_noinc(MUTABLE_SV(av));
13994         n = add_data(pRExC_state, 1, "s");
13995         RExC_rxi->data->data[n] = (void*)rv;
13996         ARG_SET(ret, n);
13997     }
13998
13999     *flagp |= HASWIDTH|SIMPLE;
14000     return ret;
14001 }
14002 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
14003
14004
14005 /* reg_skipcomment()
14006
14007    Absorbs an /x style # comments from the input stream.
14008    Returns true if there is more text remaining in the stream.
14009    Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
14010    terminates the pattern without including a newline.
14011
14012    Note its the callers responsibility to ensure that we are
14013    actually in /x mode
14014
14015 */
14016
14017 STATIC bool
14018 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
14019 {
14020     bool ended = 0;
14021
14022     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
14023
14024     while (RExC_parse < RExC_end)
14025         if (*RExC_parse++ == '\n') {
14026             ended = 1;
14027             break;
14028         }
14029     if (!ended) {
14030         /* we ran off the end of the pattern without ending
14031            the comment, so we have to add an \n when wrapping */
14032         RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
14033         return 0;
14034     } else
14035         return 1;
14036 }
14037
14038 /* nextchar()
14039
14040    Advances the parse position, and optionally absorbs
14041    "whitespace" from the inputstream.
14042
14043    Without /x "whitespace" means (?#...) style comments only,
14044    with /x this means (?#...) and # comments and whitespace proper.
14045
14046    Returns the RExC_parse point from BEFORE the scan occurs.
14047
14048    This is the /x friendly way of saying RExC_parse++.
14049 */
14050
14051 STATIC char*
14052 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
14053 {
14054     char* const retval = RExC_parse++;
14055
14056     PERL_ARGS_ASSERT_NEXTCHAR;
14057
14058     for (;;) {
14059         if (RExC_end - RExC_parse >= 3
14060             && *RExC_parse == '('
14061             && RExC_parse[1] == '?'
14062             && RExC_parse[2] == '#')
14063         {
14064             while (*RExC_parse != ')') {
14065                 if (RExC_parse == RExC_end)
14066                     FAIL("Sequence (?#... not terminated");
14067                 RExC_parse++;
14068             }
14069             RExC_parse++;
14070             continue;
14071         }
14072         if (RExC_flags & RXf_PMf_EXTENDED) {
14073             if (isSPACE(*RExC_parse)) {
14074                 RExC_parse++;
14075                 continue;
14076             }
14077             else if (*RExC_parse == '#') {
14078                 if ( reg_skipcomment( pRExC_state ) )
14079                     continue;
14080             }
14081         }
14082         return retval;
14083     }
14084 }
14085
14086 /*
14087 - reg_node - emit a node
14088 */
14089 STATIC regnode *                        /* Location. */
14090 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
14091 {
14092     dVAR;
14093     regnode *ptr;
14094     regnode * const ret = RExC_emit;
14095     GET_RE_DEBUG_FLAGS_DECL;
14096
14097     PERL_ARGS_ASSERT_REG_NODE;
14098
14099     if (SIZE_ONLY) {
14100         SIZE_ALIGN(RExC_size);
14101         RExC_size += 1;
14102         return(ret);
14103     }
14104     if (RExC_emit >= RExC_emit_bound)
14105         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
14106                    op, RExC_emit, RExC_emit_bound);
14107
14108     NODE_ALIGN_FILL(ret);
14109     ptr = ret;
14110     FILL_ADVANCE_NODE(ptr, op);
14111 #ifdef RE_TRACK_PATTERN_OFFSETS
14112     if (RExC_offsets) {         /* MJD */
14113         MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n", 
14114               "reg_node", __LINE__, 
14115               PL_reg_name[op],
14116               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] 
14117                 ? "Overwriting end of array!\n" : "OK",
14118               (UV)(RExC_emit - RExC_emit_start),
14119               (UV)(RExC_parse - RExC_start),
14120               (UV)RExC_offsets[0])); 
14121         Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
14122     }
14123 #endif
14124     RExC_emit = ptr;
14125     return(ret);
14126 }
14127
14128 /*
14129 - reganode - emit a node with an argument
14130 */
14131 STATIC regnode *                        /* Location. */
14132 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
14133 {
14134     dVAR;
14135     regnode *ptr;
14136     regnode * const ret = RExC_emit;
14137     GET_RE_DEBUG_FLAGS_DECL;
14138
14139     PERL_ARGS_ASSERT_REGANODE;
14140
14141     if (SIZE_ONLY) {
14142         SIZE_ALIGN(RExC_size);
14143         RExC_size += 2;
14144         /* 
14145            We can't do this:
14146            
14147            assert(2==regarglen[op]+1); 
14148
14149            Anything larger than this has to allocate the extra amount.
14150            If we changed this to be:
14151            
14152            RExC_size += (1 + regarglen[op]);
14153            
14154            then it wouldn't matter. Its not clear what side effect
14155            might come from that so its not done so far.
14156            -- dmq
14157         */
14158         return(ret);
14159     }
14160     if (RExC_emit >= RExC_emit_bound)
14161         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
14162                    op, RExC_emit, RExC_emit_bound);
14163
14164     NODE_ALIGN_FILL(ret);
14165     ptr = ret;
14166     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
14167 #ifdef RE_TRACK_PATTERN_OFFSETS
14168     if (RExC_offsets) {         /* MJD */
14169         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
14170               "reganode",
14171               __LINE__,
14172               PL_reg_name[op],
14173               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ? 
14174               "Overwriting end of array!\n" : "OK",
14175               (UV)(RExC_emit - RExC_emit_start),
14176               (UV)(RExC_parse - RExC_start),
14177               (UV)RExC_offsets[0])); 
14178         Set_Cur_Node_Offset;
14179     }
14180 #endif            
14181     RExC_emit = ptr;
14182     return(ret);
14183 }
14184
14185 /*
14186 - reguni - emit (if appropriate) a Unicode character
14187 */
14188 STATIC STRLEN
14189 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
14190 {
14191     dVAR;
14192
14193     PERL_ARGS_ASSERT_REGUNI;
14194
14195     return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
14196 }
14197
14198 /*
14199 - reginsert - insert an operator in front of already-emitted operand
14200 *
14201 * Means relocating the operand.
14202 */
14203 STATIC void
14204 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
14205 {
14206     dVAR;
14207     regnode *src;
14208     regnode *dst;
14209     regnode *place;
14210     const int offset = regarglen[(U8)op];
14211     const int size = NODE_STEP_REGNODE + offset;
14212     GET_RE_DEBUG_FLAGS_DECL;
14213
14214     PERL_ARGS_ASSERT_REGINSERT;
14215     PERL_UNUSED_ARG(depth);
14216 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
14217     DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
14218     if (SIZE_ONLY) {
14219         RExC_size += size;
14220         return;
14221     }
14222
14223     src = RExC_emit;
14224     RExC_emit += size;
14225     dst = RExC_emit;
14226     if (RExC_open_parens) {
14227         int paren;
14228         /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
14229         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
14230             if ( RExC_open_parens[paren] >= opnd ) {
14231                 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
14232                 RExC_open_parens[paren] += size;
14233             } else {
14234                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
14235             }
14236             if ( RExC_close_parens[paren] >= opnd ) {
14237                 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
14238                 RExC_close_parens[paren] += size;
14239             } else {
14240                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
14241             }
14242         }
14243     }
14244
14245     while (src > opnd) {
14246         StructCopy(--src, --dst, regnode);
14247 #ifdef RE_TRACK_PATTERN_OFFSETS
14248         if (RExC_offsets) {     /* MJD 20010112 */
14249             MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
14250                   "reg_insert",
14251                   __LINE__,
14252                   PL_reg_name[op],
14253                   (UV)(dst - RExC_emit_start) > RExC_offsets[0] 
14254                     ? "Overwriting end of array!\n" : "OK",
14255                   (UV)(src - RExC_emit_start),
14256                   (UV)(dst - RExC_emit_start),
14257                   (UV)RExC_offsets[0])); 
14258             Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
14259             Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
14260         }
14261 #endif
14262     }
14263     
14264
14265     place = opnd;               /* Op node, where operand used to be. */
14266 #ifdef RE_TRACK_PATTERN_OFFSETS
14267     if (RExC_offsets) {         /* MJD */
14268         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
14269               "reginsert",
14270               __LINE__,
14271               PL_reg_name[op],
14272               (UV)(place - RExC_emit_start) > RExC_offsets[0] 
14273               ? "Overwriting end of array!\n" : "OK",
14274               (UV)(place - RExC_emit_start),
14275               (UV)(RExC_parse - RExC_start),
14276               (UV)RExC_offsets[0]));
14277         Set_Node_Offset(place, RExC_parse);
14278         Set_Node_Length(place, 1);
14279     }
14280 #endif    
14281     src = NEXTOPER(place);
14282     FILL_ADVANCE_NODE(place, op);
14283     Zero(src, offset, regnode);
14284 }
14285
14286 /*
14287 - regtail - set the next-pointer at the end of a node chain of p to val.
14288 - SEE ALSO: regtail_study
14289 */
14290 /* TODO: All three parms should be const */
14291 STATIC void
14292 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
14293 {
14294     dVAR;
14295     regnode *scan;
14296     GET_RE_DEBUG_FLAGS_DECL;
14297
14298     PERL_ARGS_ASSERT_REGTAIL;
14299 #ifndef DEBUGGING
14300     PERL_UNUSED_ARG(depth);
14301 #endif
14302
14303     if (SIZE_ONLY)
14304         return;
14305
14306     /* Find last node. */
14307     scan = p;
14308     for (;;) {
14309         regnode * const temp = regnext(scan);
14310         DEBUG_PARSE_r({
14311             SV * const mysv=sv_newmortal();
14312             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
14313             regprop(RExC_rx, mysv, scan);
14314             PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
14315                 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
14316                     (temp == NULL ? "->" : ""),
14317                     (temp == NULL ? PL_reg_name[OP(val)] : "")
14318             );
14319         });
14320         if (temp == NULL)
14321             break;
14322         scan = temp;
14323     }
14324
14325     if (reg_off_by_arg[OP(scan)]) {
14326         ARG_SET(scan, val - scan);
14327     }
14328     else {
14329         NEXT_OFF(scan) = val - scan;
14330     }
14331 }
14332
14333 #ifdef DEBUGGING
14334 /*
14335 - regtail_study - set the next-pointer at the end of a node chain of p to val.
14336 - Look for optimizable sequences at the same time.
14337 - currently only looks for EXACT chains.
14338
14339 This is experimental code. The idea is to use this routine to perform 
14340 in place optimizations on branches and groups as they are constructed,
14341 with the long term intention of removing optimization from study_chunk so
14342 that it is purely analytical.
14343
14344 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
14345 to control which is which.
14346
14347 */
14348 /* TODO: All four parms should be const */
14349
14350 STATIC U8
14351 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
14352 {
14353     dVAR;
14354     regnode *scan;
14355     U8 exact = PSEUDO;
14356 #ifdef EXPERIMENTAL_INPLACESCAN
14357     I32 min = 0;
14358 #endif
14359     GET_RE_DEBUG_FLAGS_DECL;
14360
14361     PERL_ARGS_ASSERT_REGTAIL_STUDY;
14362
14363
14364     if (SIZE_ONLY)
14365         return exact;
14366
14367     /* Find last node. */
14368
14369     scan = p;
14370     for (;;) {
14371         regnode * const temp = regnext(scan);
14372 #ifdef EXPERIMENTAL_INPLACESCAN
14373         if (PL_regkind[OP(scan)] == EXACT) {
14374             bool has_exactf_sharp_s;    /* Unexamined in this routine */
14375             if (join_exact(pRExC_state,scan,&min, &has_exactf_sharp_s, 1,val,depth+1))
14376                 return EXACT;
14377         }
14378 #endif
14379         if ( exact ) {
14380             switch (OP(scan)) {
14381                 case EXACT:
14382                 case EXACTF:
14383                 case EXACTFA:
14384                 case EXACTFU:
14385                 case EXACTFU_SS:
14386                 case EXACTFU_TRICKYFOLD:
14387                 case EXACTFL:
14388                         if( exact == PSEUDO )
14389                             exact= OP(scan);
14390                         else if ( exact != OP(scan) )
14391                             exact= 0;
14392                 case NOTHING:
14393                     break;
14394                 default:
14395                     exact= 0;
14396             }
14397         }
14398         DEBUG_PARSE_r({
14399             SV * const mysv=sv_newmortal();
14400             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
14401             regprop(RExC_rx, mysv, scan);
14402             PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
14403                 SvPV_nolen_const(mysv),
14404                 REG_NODE_NUM(scan),
14405                 PL_reg_name[exact]);
14406         });
14407         if (temp == NULL)
14408             break;
14409         scan = temp;
14410     }
14411     DEBUG_PARSE_r({
14412         SV * const mysv_val=sv_newmortal();
14413         DEBUG_PARSE_MSG("");
14414         regprop(RExC_rx, mysv_val, val);
14415         PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
14416                       SvPV_nolen_const(mysv_val),
14417                       (IV)REG_NODE_NUM(val),
14418                       (IV)(val - scan)
14419         );
14420     });
14421     if (reg_off_by_arg[OP(scan)]) {
14422         ARG_SET(scan, val - scan);
14423     }
14424     else {
14425         NEXT_OFF(scan) = val - scan;
14426     }
14427
14428     return exact;
14429 }
14430 #endif
14431
14432 /*
14433  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
14434  */
14435 #ifdef DEBUGGING
14436
14437 static void
14438 S_regdump_intflags(pTHX_ const char *lead, const U32 flags)
14439 {
14440     int bit;
14441     int set=0;
14442
14443     for (bit=0; bit<32; bit++) {
14444         if (flags & (1<<bit)) {
14445             if (!set++ && lead)
14446                 PerlIO_printf(Perl_debug_log, "%s",lead);
14447             PerlIO_printf(Perl_debug_log, "%s ",PL_reg_intflags_name[bit]);
14448         }
14449     }
14450     if (lead)  {
14451         if (set)
14452             PerlIO_printf(Perl_debug_log, "\n");
14453         else
14454             PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
14455     }
14456 }
14457
14458 static void 
14459 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
14460 {
14461     int bit;
14462     int set=0;
14463     regex_charset cs;
14464
14465     for (bit=0; bit<32; bit++) {
14466         if (flags & (1<<bit)) {
14467             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
14468                 continue;
14469             }
14470             if (!set++ && lead) 
14471                 PerlIO_printf(Perl_debug_log, "%s",lead);
14472             PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
14473         }               
14474     }      
14475     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
14476             if (!set++ && lead) {
14477                 PerlIO_printf(Perl_debug_log, "%s",lead);
14478             }
14479             switch (cs) {
14480                 case REGEX_UNICODE_CHARSET:
14481                     PerlIO_printf(Perl_debug_log, "UNICODE");
14482                     break;
14483                 case REGEX_LOCALE_CHARSET:
14484                     PerlIO_printf(Perl_debug_log, "LOCALE");
14485                     break;
14486                 case REGEX_ASCII_RESTRICTED_CHARSET:
14487                     PerlIO_printf(Perl_debug_log, "ASCII-RESTRICTED");
14488                     break;
14489                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
14490                     PerlIO_printf(Perl_debug_log, "ASCII-MORE_RESTRICTED");
14491                     break;
14492                 default:
14493                     PerlIO_printf(Perl_debug_log, "UNKNOWN CHARACTER SET");
14494                     break;
14495             }
14496     }
14497     if (lead)  {
14498         if (set) 
14499             PerlIO_printf(Perl_debug_log, "\n");
14500         else 
14501             PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
14502     }            
14503 }   
14504 #endif
14505
14506 void
14507 Perl_regdump(pTHX_ const regexp *r)
14508 {
14509 #ifdef DEBUGGING
14510     dVAR;
14511     SV * const sv = sv_newmortal();
14512     SV *dsv= sv_newmortal();
14513     RXi_GET_DECL(r,ri);
14514     GET_RE_DEBUG_FLAGS_DECL;
14515
14516     PERL_ARGS_ASSERT_REGDUMP;
14517
14518     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
14519
14520     /* Header fields of interest. */
14521     if (r->anchored_substr) {
14522         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr), 
14523             RE_SV_DUMPLEN(r->anchored_substr), 30);
14524         PerlIO_printf(Perl_debug_log,
14525                       "anchored %s%s at %"IVdf" ",
14526                       s, RE_SV_TAIL(r->anchored_substr),
14527                       (IV)r->anchored_offset);
14528     } else if (r->anchored_utf8) {
14529         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8), 
14530             RE_SV_DUMPLEN(r->anchored_utf8), 30);
14531         PerlIO_printf(Perl_debug_log,
14532                       "anchored utf8 %s%s at %"IVdf" ",
14533                       s, RE_SV_TAIL(r->anchored_utf8),
14534                       (IV)r->anchored_offset);
14535     }                 
14536     if (r->float_substr) {
14537         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr), 
14538             RE_SV_DUMPLEN(r->float_substr), 30);
14539         PerlIO_printf(Perl_debug_log,
14540                       "floating %s%s at %"IVdf"..%"UVuf" ",
14541                       s, RE_SV_TAIL(r->float_substr),
14542                       (IV)r->float_min_offset, (UV)r->float_max_offset);
14543     } else if (r->float_utf8) {
14544         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8), 
14545             RE_SV_DUMPLEN(r->float_utf8), 30);
14546         PerlIO_printf(Perl_debug_log,
14547                       "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
14548                       s, RE_SV_TAIL(r->float_utf8),
14549                       (IV)r->float_min_offset, (UV)r->float_max_offset);
14550     }
14551     if (r->check_substr || r->check_utf8)
14552         PerlIO_printf(Perl_debug_log,
14553                       (const char *)
14554                       (r->check_substr == r->float_substr
14555                        && r->check_utf8 == r->float_utf8
14556                        ? "(checking floating" : "(checking anchored"));
14557     if (r->extflags & RXf_NOSCAN)
14558         PerlIO_printf(Perl_debug_log, " noscan");
14559     if (r->extflags & RXf_CHECK_ALL)
14560         PerlIO_printf(Perl_debug_log, " isall");
14561     if (r->check_substr || r->check_utf8)
14562         PerlIO_printf(Perl_debug_log, ") ");
14563
14564     if (ri->regstclass) {
14565         regprop(r, sv, ri->regstclass);
14566         PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
14567     }
14568     if (r->extflags & RXf_ANCH) {
14569         PerlIO_printf(Perl_debug_log, "anchored");
14570         if (r->extflags & RXf_ANCH_BOL)
14571             PerlIO_printf(Perl_debug_log, "(BOL)");
14572         if (r->extflags & RXf_ANCH_MBOL)
14573             PerlIO_printf(Perl_debug_log, "(MBOL)");
14574         if (r->extflags & RXf_ANCH_SBOL)
14575             PerlIO_printf(Perl_debug_log, "(SBOL)");
14576         if (r->extflags & RXf_ANCH_GPOS)
14577             PerlIO_printf(Perl_debug_log, "(GPOS)");
14578         PerlIO_putc(Perl_debug_log, ' ');
14579     }
14580     if (r->extflags & RXf_GPOS_SEEN)
14581         PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
14582     if (r->intflags & PREGf_SKIP)
14583         PerlIO_printf(Perl_debug_log, "plus ");
14584     if (r->intflags & PREGf_IMPLICIT)
14585         PerlIO_printf(Perl_debug_log, "implicit ");
14586     PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
14587     if (r->extflags & RXf_EVAL_SEEN)
14588         PerlIO_printf(Perl_debug_log, "with eval ");
14589     PerlIO_printf(Perl_debug_log, "\n");
14590     DEBUG_FLAGS_r({
14591         regdump_extflags("r->extflags: ",r->extflags);
14592         regdump_intflags("r->intflags: ",r->intflags);
14593     });
14594 #else
14595     PERL_ARGS_ASSERT_REGDUMP;
14596     PERL_UNUSED_CONTEXT;
14597     PERL_UNUSED_ARG(r);
14598 #endif  /* DEBUGGING */
14599 }
14600
14601 /*
14602 - regprop - printable representation of opcode
14603 */
14604 #define EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags) \
14605 STMT_START { \
14606         if (do_sep) {                           \
14607             Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]); \
14608             if (flags & ANYOF_INVERT)           \
14609                 /*make sure the invert info is in each */ \
14610                 sv_catpvs(sv, "^");             \
14611             do_sep = 0;                         \
14612         }                                       \
14613 } STMT_END
14614
14615 void
14616 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
14617 {
14618 #ifdef DEBUGGING
14619     dVAR;
14620     int k;
14621
14622     /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
14623     static const char * const anyofs[] = {
14624 #if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 || _CC_LOWER != 3 \
14625     || _CC_UPPER != 4 || _CC_PUNCT != 5 || _CC_PRINT != 6                   \
14626     || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 || _CC_CASED != 9            \
14627     || _CC_SPACE != 10 || _CC_BLANK != 11 || _CC_XDIGIT != 12               \
14628     || _CC_PSXSPC != 13 || _CC_CNTRL != 14 || _CC_ASCII != 15               \
14629     || _CC_VERTSPACE != 16
14630   #error Need to adjust order of anyofs[]
14631 #endif
14632         "[\\w]",
14633         "[\\W]",
14634         "[\\d]",
14635         "[\\D]",
14636         "[:alpha:]",
14637         "[:^alpha:]",
14638         "[:lower:]",
14639         "[:^lower:]",
14640         "[:upper:]",
14641         "[:^upper:]",
14642         "[:punct:]",
14643         "[:^punct:]",
14644         "[:print:]",
14645         "[:^print:]",
14646         "[:alnum:]",
14647         "[:^alnum:]",
14648         "[:graph:]",
14649         "[:^graph:]",
14650         "[:cased:]",
14651         "[:^cased:]",
14652         "[\\s]",
14653         "[\\S]",
14654         "[:blank:]",
14655         "[:^blank:]",
14656         "[:xdigit:]",
14657         "[:^xdigit:]",
14658         "[:space:]",
14659         "[:^space:]",
14660         "[:cntrl:]",
14661         "[:^cntrl:]",
14662         "[:ascii:]",
14663         "[:^ascii:]",
14664         "[\\v]",
14665         "[\\V]"
14666     };
14667     RXi_GET_DECL(prog,progi);
14668     GET_RE_DEBUG_FLAGS_DECL;
14669     
14670     PERL_ARGS_ASSERT_REGPROP;
14671
14672     sv_setpvs(sv, "");
14673
14674     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
14675         /* It would be nice to FAIL() here, but this may be called from
14676            regexec.c, and it would be hard to supply pRExC_state. */
14677         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
14678     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
14679
14680     k = PL_regkind[OP(o)];
14681
14682     if (k == EXACT) {
14683         sv_catpvs(sv, " ");
14684         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT) 
14685          * is a crude hack but it may be the best for now since 
14686          * we have no flag "this EXACTish node was UTF-8" 
14687          * --jhi */
14688         pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
14689                   PERL_PV_ESCAPE_UNI_DETECT |
14690                   PERL_PV_ESCAPE_NONASCII   |
14691                   PERL_PV_PRETTY_ELLIPSES   |
14692                   PERL_PV_PRETTY_LTGT       |
14693                   PERL_PV_PRETTY_NOCLEAR
14694                   );
14695     } else if (k == TRIE) {
14696         /* print the details of the trie in dumpuntil instead, as
14697          * progi->data isn't available here */
14698         const char op = OP(o);
14699         const U32 n = ARG(o);
14700         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
14701                (reg_ac_data *)progi->data->data[n] :
14702                NULL;
14703         const reg_trie_data * const trie
14704             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
14705         
14706         Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
14707         DEBUG_TRIE_COMPILE_r(
14708             Perl_sv_catpvf(aTHX_ sv,
14709                 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
14710                 (UV)trie->startstate,
14711                 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
14712                 (UV)trie->wordcount,
14713                 (UV)trie->minlen,
14714                 (UV)trie->maxlen,
14715                 (UV)TRIE_CHARCOUNT(trie),
14716                 (UV)trie->uniquecharcount
14717             )
14718         );
14719         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
14720             sv_catpvs(sv, "[");
14721             (void) put_latin1_charclass_innards(sv, IS_ANYOF_TRIE(op)
14722                                                    ? ANYOF_BITMAP(o)
14723                                                    : TRIE_BITMAP(trie));
14724             sv_catpvs(sv, "]");
14725         } 
14726          
14727     } else if (k == CURLY) {
14728         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
14729             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
14730         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
14731     }
14732     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
14733         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
14734     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
14735         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
14736         if ( RXp_PAREN_NAMES(prog) ) {
14737             if ( k != REF || (OP(o) < NREF)) {
14738                 AV *list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
14739                 SV **name= av_fetch(list, ARG(o), 0 );
14740                 if (name)
14741                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
14742             }       
14743             else {
14744                 AV *list= MUTABLE_AV(progi->data->data[ progi->name_list_idx ]);
14745                 SV *sv_dat= MUTABLE_SV(progi->data->data[ ARG( o ) ]);
14746                 I32 *nums=(I32*)SvPVX(sv_dat);
14747                 SV **name= av_fetch(list, nums[0], 0 );
14748                 I32 n;
14749                 if (name) {
14750                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
14751                         Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
14752                                     (n ? "," : ""), (IV)nums[n]);
14753                     }
14754                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
14755                 }
14756             }
14757         }            
14758     } else if (k == GOSUB) 
14759         Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
14760     else if (k == VERB) {
14761         if (!o->flags) 
14762             Perl_sv_catpvf(aTHX_ sv, ":%"SVf, 
14763                            SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
14764     } else if (k == LOGICAL)
14765         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
14766     else if (k == ANYOF) {
14767         const U8 flags = ANYOF_FLAGS(o);
14768         int do_sep = 0;
14769
14770
14771         if (flags & ANYOF_LOCALE)
14772             sv_catpvs(sv, "{loc}");
14773         if (flags & ANYOF_LOC_FOLD)
14774             sv_catpvs(sv, "{i}");
14775         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
14776         if (flags & ANYOF_INVERT)
14777             sv_catpvs(sv, "^");
14778
14779         /* output what the standard cp 0-255 bitmap matches */
14780         do_sep = put_latin1_charclass_innards(sv, ANYOF_BITMAP(o));
14781         
14782         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
14783         /* output any special charclass tests (used entirely under use locale) */
14784         if (ANYOF_CLASS_TEST_ANY_SET(o)) {
14785             int i;
14786             for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++) {
14787                 if (ANYOF_CLASS_TEST(o,i)) {
14788                     sv_catpv(sv, anyofs[i]);
14789                     do_sep = 1;
14790                 }
14791             }
14792         }
14793         
14794         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
14795         
14796         if (flags & ANYOF_NON_UTF8_LATIN1_ALL) {
14797             sv_catpvs(sv, "{non-utf8-latin1-all}");
14798         }
14799
14800         /* output information about the unicode matching */
14801         if (flags & ANYOF_UNICODE_ALL)
14802             sv_catpvs(sv, "{unicode_all}");
14803         else if (ANYOF_NONBITMAP(o)) {
14804             SV *lv; /* Set if there is something outside the bit map. */
14805             SV * sw;
14806             bool byte_output = FALSE;   /* If something in the bitmap has been
14807                                            output */
14808
14809             if (flags & ANYOF_NONBITMAP_NON_UTF8) {
14810                 sv_catpvs(sv, "{outside bitmap}");
14811             }
14812             else {
14813                 sv_catpvs(sv, "{utf8}");
14814             }
14815
14816             /* Get the stuff that wasn't in the bitmap */
14817             sw = regclass_swash(prog, o, FALSE, &lv, NULL);
14818             if (lv && lv != &PL_sv_undef) {
14819                 char *s = savesvpv(lv);
14820                 char * const origs = s;
14821
14822                 while (*s && *s != '\n')
14823                     s++;
14824
14825                 if (*s == '\n') {
14826                     const char * const t = ++s;
14827
14828                     if (byte_output) {
14829                         sv_catpvs(sv, " ");
14830                     }
14831
14832                     while (*s) {
14833                         if (*s == '\n') {
14834
14835                             /* Truncate very long output */
14836                             if (s - origs > 256) {
14837                                 Perl_sv_catpvf(aTHX_ sv,
14838                                                "%.*s...",
14839                                                (int) (s - origs - 1),
14840                                                t);
14841                                 goto out_dump;
14842                             }
14843                             *s = ' ';
14844                         }
14845                         else if (*s == '\t') {
14846                             *s = '-';
14847                         }
14848                         s++;
14849                     }
14850                     if (s[-1] == ' ')
14851                         s[-1] = 0;
14852
14853                     sv_catpv(sv, t);
14854                 }
14855
14856             out_dump:
14857
14858                 Safefree(origs);
14859                 SvREFCNT_dec_NN(lv);
14860             }
14861         }
14862
14863         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
14864     }
14865     else if (k == POSIXD || k == NPOSIXD) {
14866         U8 index = FLAGS(o) * 2;
14867         if (index > (sizeof(anyofs) / sizeof(anyofs[0]))) {
14868             Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
14869         }
14870         else {
14871             sv_catpv(sv, anyofs[index]);
14872         }
14873     }
14874     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
14875         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
14876 #else
14877     PERL_UNUSED_CONTEXT;
14878     PERL_UNUSED_ARG(sv);
14879     PERL_UNUSED_ARG(o);
14880     PERL_UNUSED_ARG(prog);
14881 #endif  /* DEBUGGING */
14882 }
14883
14884 SV *
14885 Perl_re_intuit_string(pTHX_ REGEXP * const r)
14886 {                               /* Assume that RE_INTUIT is set */
14887     dVAR;
14888     struct regexp *const prog = ReANY(r);
14889     GET_RE_DEBUG_FLAGS_DECL;
14890
14891     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
14892     PERL_UNUSED_CONTEXT;
14893
14894     DEBUG_COMPILE_r(
14895         {
14896             const char * const s = SvPV_nolen_const(prog->check_substr
14897                       ? prog->check_substr : prog->check_utf8);
14898
14899             if (!PL_colorset) reginitcolors();
14900             PerlIO_printf(Perl_debug_log,
14901                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
14902                       PL_colors[4],
14903                       prog->check_substr ? "" : "utf8 ",
14904                       PL_colors[5],PL_colors[0],
14905                       s,
14906                       PL_colors[1],
14907                       (strlen(s) > 60 ? "..." : ""));
14908         } );
14909
14910     return prog->check_substr ? prog->check_substr : prog->check_utf8;
14911 }
14912
14913 /* 
14914    pregfree() 
14915    
14916    handles refcounting and freeing the perl core regexp structure. When 
14917    it is necessary to actually free the structure the first thing it 
14918    does is call the 'free' method of the regexp_engine associated to
14919    the regexp, allowing the handling of the void *pprivate; member 
14920    first. (This routine is not overridable by extensions, which is why 
14921    the extensions free is called first.)
14922    
14923    See regdupe and regdupe_internal if you change anything here. 
14924 */
14925 #ifndef PERL_IN_XSUB_RE
14926 void
14927 Perl_pregfree(pTHX_ REGEXP *r)
14928 {
14929     SvREFCNT_dec(r);
14930 }
14931
14932 void
14933 Perl_pregfree2(pTHX_ REGEXP *rx)
14934 {
14935     dVAR;
14936     struct regexp *const r = ReANY(rx);
14937     GET_RE_DEBUG_FLAGS_DECL;
14938
14939     PERL_ARGS_ASSERT_PREGFREE2;
14940
14941     if (r->mother_re) {
14942         ReREFCNT_dec(r->mother_re);
14943     } else {
14944         CALLREGFREE_PVT(rx); /* free the private data */
14945         SvREFCNT_dec(RXp_PAREN_NAMES(r));
14946         Safefree(r->xpv_len_u.xpvlenu_pv);
14947     }        
14948     if (r->substrs) {
14949         SvREFCNT_dec(r->anchored_substr);
14950         SvREFCNT_dec(r->anchored_utf8);
14951         SvREFCNT_dec(r->float_substr);
14952         SvREFCNT_dec(r->float_utf8);
14953         Safefree(r->substrs);
14954     }
14955     RX_MATCH_COPY_FREE(rx);
14956 #ifdef PERL_ANY_COW
14957     SvREFCNT_dec(r->saved_copy);
14958 #endif
14959     Safefree(r->offs);
14960     SvREFCNT_dec(r->qr_anoncv);
14961     rx->sv_u.svu_rx = 0;
14962 }
14963
14964 /*  reg_temp_copy()
14965     
14966     This is a hacky workaround to the structural issue of match results
14967     being stored in the regexp structure which is in turn stored in
14968     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
14969     could be PL_curpm in multiple contexts, and could require multiple
14970     result sets being associated with the pattern simultaneously, such
14971     as when doing a recursive match with (??{$qr})
14972     
14973     The solution is to make a lightweight copy of the regexp structure 
14974     when a qr// is returned from the code executed by (??{$qr}) this
14975     lightweight copy doesn't actually own any of its data except for
14976     the starp/end and the actual regexp structure itself. 
14977     
14978 */    
14979     
14980     
14981 REGEXP *
14982 Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
14983 {
14984     struct regexp *ret;
14985     struct regexp *const r = ReANY(rx);
14986     const bool islv = ret_x && SvTYPE(ret_x) == SVt_PVLV;
14987
14988     PERL_ARGS_ASSERT_REG_TEMP_COPY;
14989
14990     if (!ret_x)
14991         ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
14992     else {
14993         SvOK_off((SV *)ret_x);
14994         if (islv) {
14995             /* For PVLVs, SvANY points to the xpvlv body while sv_u points
14996                to the regexp.  (For SVt_REGEXPs, sv_upgrade has already
14997                made both spots point to the same regexp body.) */
14998             REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
14999             assert(!SvPVX(ret_x));
15000             ret_x->sv_u.svu_rx = temp->sv_any;
15001             temp->sv_any = NULL;
15002             SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
15003             SvREFCNT_dec_NN(temp);
15004             /* SvCUR still resides in the xpvlv struct, so the regexp copy-
15005                ing below will not set it. */
15006             SvCUR_set(ret_x, SvCUR(rx));
15007         }
15008     }
15009     /* This ensures that SvTHINKFIRST(sv) is true, and hence that
15010        sv_force_normal(sv) is called.  */
15011     SvFAKE_on(ret_x);
15012     ret = ReANY(ret_x);
15013     
15014     SvFLAGS(ret_x) |= SvUTF8(rx);
15015     /* We share the same string buffer as the original regexp, on which we
15016        hold a reference count, incremented when mother_re is set below.
15017        The string pointer is copied here, being part of the regexp struct.
15018      */
15019     memcpy(&(ret->xpv_cur), &(r->xpv_cur),
15020            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
15021     if (r->offs) {
15022         const I32 npar = r->nparens+1;
15023         Newx(ret->offs, npar, regexp_paren_pair);
15024         Copy(r->offs, ret->offs, npar, regexp_paren_pair);
15025     }
15026     if (r->substrs) {
15027         Newx(ret->substrs, 1, struct reg_substr_data);
15028         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
15029
15030         SvREFCNT_inc_void(ret->anchored_substr);
15031         SvREFCNT_inc_void(ret->anchored_utf8);
15032         SvREFCNT_inc_void(ret->float_substr);
15033         SvREFCNT_inc_void(ret->float_utf8);
15034
15035         /* check_substr and check_utf8, if non-NULL, point to either their
15036            anchored or float namesakes, and don't hold a second reference.  */
15037     }
15038     RX_MATCH_COPIED_off(ret_x);
15039 #ifdef PERL_ANY_COW
15040     ret->saved_copy = NULL;
15041 #endif
15042     ret->mother_re = ReREFCNT_inc(r->mother_re ? r->mother_re : rx);
15043     SvREFCNT_inc_void(ret->qr_anoncv);
15044     
15045     return ret_x;
15046 }
15047 #endif
15048
15049 /* regfree_internal() 
15050
15051    Free the private data in a regexp. This is overloadable by 
15052    extensions. Perl takes care of the regexp structure in pregfree(), 
15053    this covers the *pprivate pointer which technically perl doesn't 
15054    know about, however of course we have to handle the 
15055    regexp_internal structure when no extension is in use. 
15056    
15057    Note this is called before freeing anything in the regexp 
15058    structure. 
15059  */
15060  
15061 void
15062 Perl_regfree_internal(pTHX_ REGEXP * const rx)
15063 {
15064     dVAR;
15065     struct regexp *const r = ReANY(rx);
15066     RXi_GET_DECL(r,ri);
15067     GET_RE_DEBUG_FLAGS_DECL;
15068
15069     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
15070
15071     DEBUG_COMPILE_r({
15072         if (!PL_colorset)
15073             reginitcolors();
15074         {
15075             SV *dsv= sv_newmortal();
15076             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
15077                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
15078             PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n", 
15079                 PL_colors[4],PL_colors[5],s);
15080         }
15081     });
15082 #ifdef RE_TRACK_PATTERN_OFFSETS
15083     if (ri->u.offsets)
15084         Safefree(ri->u.offsets);             /* 20010421 MJD */
15085 #endif
15086     if (ri->code_blocks) {
15087         int n;
15088         for (n = 0; n < ri->num_code_blocks; n++)
15089             SvREFCNT_dec(ri->code_blocks[n].src_regex);
15090         Safefree(ri->code_blocks);
15091     }
15092
15093     if (ri->data) {
15094         int n = ri->data->count;
15095
15096         while (--n >= 0) {
15097           /* If you add a ->what type here, update the comment in regcomp.h */
15098             switch (ri->data->what[n]) {
15099             case 'a':
15100             case 'r':
15101             case 's':
15102             case 'S':
15103             case 'u':
15104                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
15105                 break;
15106             case 'f':
15107                 Safefree(ri->data->data[n]);
15108                 break;
15109             case 'l':
15110             case 'L':
15111                 break;
15112             case 'T':           
15113                 { /* Aho Corasick add-on structure for a trie node.
15114                      Used in stclass optimization only */
15115                     U32 refcount;
15116                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
15117                     OP_REFCNT_LOCK;
15118                     refcount = --aho->refcount;
15119                     OP_REFCNT_UNLOCK;
15120                     if ( !refcount ) {
15121                         PerlMemShared_free(aho->states);
15122                         PerlMemShared_free(aho->fail);
15123                          /* do this last!!!! */
15124                         PerlMemShared_free(ri->data->data[n]);
15125                         PerlMemShared_free(ri->regstclass);
15126                     }
15127                 }
15128                 break;
15129             case 't':
15130                 {
15131                     /* trie structure. */
15132                     U32 refcount;
15133                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
15134                     OP_REFCNT_LOCK;
15135                     refcount = --trie->refcount;
15136                     OP_REFCNT_UNLOCK;
15137                     if ( !refcount ) {
15138                         PerlMemShared_free(trie->charmap);
15139                         PerlMemShared_free(trie->states);
15140                         PerlMemShared_free(trie->trans);
15141                         if (trie->bitmap)
15142                             PerlMemShared_free(trie->bitmap);
15143                         if (trie->jump)
15144                             PerlMemShared_free(trie->jump);
15145                         PerlMemShared_free(trie->wordinfo);
15146                         /* do this last!!!! */
15147                         PerlMemShared_free(ri->data->data[n]);
15148                     }
15149                 }
15150                 break;
15151             default:
15152                 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
15153             }
15154         }
15155         Safefree(ri->data->what);
15156         Safefree(ri->data);
15157     }
15158
15159     Safefree(ri);
15160 }
15161
15162 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
15163 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
15164 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
15165
15166 /* 
15167    re_dup - duplicate a regexp. 
15168    
15169    This routine is expected to clone a given regexp structure. It is only
15170    compiled under USE_ITHREADS.
15171
15172    After all of the core data stored in struct regexp is duplicated
15173    the regexp_engine.dupe method is used to copy any private data
15174    stored in the *pprivate pointer. This allows extensions to handle
15175    any duplication it needs to do.
15176
15177    See pregfree() and regfree_internal() if you change anything here. 
15178 */
15179 #if defined(USE_ITHREADS)
15180 #ifndef PERL_IN_XSUB_RE
15181 void
15182 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
15183 {
15184     dVAR;
15185     I32 npar;
15186     const struct regexp *r = ReANY(sstr);
15187     struct regexp *ret = ReANY(dstr);
15188     
15189     PERL_ARGS_ASSERT_RE_DUP_GUTS;
15190
15191     npar = r->nparens+1;
15192     Newx(ret->offs, npar, regexp_paren_pair);
15193     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
15194
15195     if (ret->substrs) {
15196         /* Do it this way to avoid reading from *r after the StructCopy().
15197            That way, if any of the sv_dup_inc()s dislodge *r from the L1
15198            cache, it doesn't matter.  */
15199         const bool anchored = r->check_substr
15200             ? r->check_substr == r->anchored_substr
15201             : r->check_utf8 == r->anchored_utf8;
15202         Newx(ret->substrs, 1, struct reg_substr_data);
15203         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
15204
15205         ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
15206         ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
15207         ret->float_substr = sv_dup_inc(ret->float_substr, param);
15208         ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
15209
15210         /* check_substr and check_utf8, if non-NULL, point to either their
15211            anchored or float namesakes, and don't hold a second reference.  */
15212
15213         if (ret->check_substr) {
15214             if (anchored) {
15215                 assert(r->check_utf8 == r->anchored_utf8);
15216                 ret->check_substr = ret->anchored_substr;
15217                 ret->check_utf8 = ret->anchored_utf8;
15218             } else {
15219                 assert(r->check_substr == r->float_substr);
15220                 assert(r->check_utf8 == r->float_utf8);
15221                 ret->check_substr = ret->float_substr;
15222                 ret->check_utf8 = ret->float_utf8;
15223             }
15224         } else if (ret->check_utf8) {
15225             if (anchored) {
15226                 ret->check_utf8 = ret->anchored_utf8;
15227             } else {
15228                 ret->check_utf8 = ret->float_utf8;
15229             }
15230         }
15231     }
15232
15233     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
15234     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
15235
15236     if (ret->pprivate)
15237         RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
15238
15239     if (RX_MATCH_COPIED(dstr))
15240         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
15241     else
15242         ret->subbeg = NULL;
15243 #ifdef PERL_ANY_COW
15244     ret->saved_copy = NULL;
15245 #endif
15246
15247     /* Whether mother_re be set or no, we need to copy the string.  We
15248        cannot refrain from copying it when the storage points directly to
15249        our mother regexp, because that's
15250                1: a buffer in a different thread
15251                2: something we no longer hold a reference on
15252                so we need to copy it locally.  */
15253     RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED(sstr), SvCUR(sstr)+1);
15254     ret->mother_re   = NULL;
15255 }
15256 #endif /* PERL_IN_XSUB_RE */
15257
15258 /*
15259    regdupe_internal()
15260    
15261    This is the internal complement to regdupe() which is used to copy
15262    the structure pointed to by the *pprivate pointer in the regexp.
15263    This is the core version of the extension overridable cloning hook.
15264    The regexp structure being duplicated will be copied by perl prior
15265    to this and will be provided as the regexp *r argument, however 
15266    with the /old/ structures pprivate pointer value. Thus this routine
15267    may override any copying normally done by perl.
15268    
15269    It returns a pointer to the new regexp_internal structure.
15270 */
15271
15272 void *
15273 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
15274 {
15275     dVAR;
15276     struct regexp *const r = ReANY(rx);
15277     regexp_internal *reti;
15278     int len;
15279     RXi_GET_DECL(r,ri);
15280
15281     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
15282     
15283     len = ProgLen(ri);
15284     
15285     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal);
15286     Copy(ri->program, reti->program, len+1, regnode);
15287
15288     reti->num_code_blocks = ri->num_code_blocks;
15289     if (ri->code_blocks) {
15290         int n;
15291         Newxc(reti->code_blocks, ri->num_code_blocks, struct reg_code_block,
15292                 struct reg_code_block);
15293         Copy(ri->code_blocks, reti->code_blocks, ri->num_code_blocks,
15294                 struct reg_code_block);
15295         for (n = 0; n < ri->num_code_blocks; n++)
15296              reti->code_blocks[n].src_regex = (REGEXP*)
15297                     sv_dup_inc((SV*)(ri->code_blocks[n].src_regex), param);
15298     }
15299     else
15300         reti->code_blocks = NULL;
15301
15302     reti->regstclass = NULL;
15303
15304     if (ri->data) {
15305         struct reg_data *d;
15306         const int count = ri->data->count;
15307         int i;
15308
15309         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
15310                 char, struct reg_data);
15311         Newx(d->what, count, U8);
15312
15313         d->count = count;
15314         for (i = 0; i < count; i++) {
15315             d->what[i] = ri->data->what[i];
15316             switch (d->what[i]) {
15317                 /* see also regcomp.h and regfree_internal() */
15318             case 'a': /* actually an AV, but the dup function is identical.  */
15319             case 'r':
15320             case 's':
15321             case 'S':
15322             case 'u': /* actually an HV, but the dup function is identical.  */
15323                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
15324                 break;
15325             case 'f':
15326                 /* This is cheating. */
15327                 Newx(d->data[i], 1, struct regnode_charclass_class);
15328                 StructCopy(ri->data->data[i], d->data[i],
15329                             struct regnode_charclass_class);
15330                 reti->regstclass = (regnode*)d->data[i];
15331                 break;
15332             case 'T':
15333                 /* Trie stclasses are readonly and can thus be shared
15334                  * without duplication. We free the stclass in pregfree
15335                  * when the corresponding reg_ac_data struct is freed.
15336                  */
15337                 reti->regstclass= ri->regstclass;
15338                 /* Fall through */
15339             case 't':
15340                 OP_REFCNT_LOCK;
15341                 ((reg_trie_data*)ri->data->data[i])->refcount++;
15342                 OP_REFCNT_UNLOCK;
15343                 /* Fall through */
15344             case 'l':
15345             case 'L':
15346                 d->data[i] = ri->data->data[i];
15347                 break;
15348             default:
15349                 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
15350             }
15351         }
15352
15353         reti->data = d;
15354     }
15355     else
15356         reti->data = NULL;
15357
15358     reti->name_list_idx = ri->name_list_idx;
15359
15360 #ifdef RE_TRACK_PATTERN_OFFSETS
15361     if (ri->u.offsets) {
15362         Newx(reti->u.offsets, 2*len+1, U32);
15363         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
15364     }
15365 #else
15366     SetProgLen(reti,len);
15367 #endif
15368
15369     return (void*)reti;
15370 }
15371
15372 #endif    /* USE_ITHREADS */
15373
15374 #ifndef PERL_IN_XSUB_RE
15375
15376 /*
15377  - regnext - dig the "next" pointer out of a node
15378  */
15379 regnode *
15380 Perl_regnext(pTHX_ regnode *p)
15381 {
15382     dVAR;
15383     I32 offset;
15384
15385     if (!p)
15386         return(NULL);
15387
15388     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
15389         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(p), (int)REGNODE_MAX);
15390     }
15391
15392     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
15393     if (offset == 0)
15394         return(NULL);
15395
15396     return(p+offset);
15397 }
15398 #endif
15399
15400 STATIC void
15401 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
15402 {
15403     va_list args;
15404     STRLEN l1 = strlen(pat1);
15405     STRLEN l2 = strlen(pat2);
15406     char buf[512];
15407     SV *msv;
15408     const char *message;
15409
15410     PERL_ARGS_ASSERT_RE_CROAK2;
15411
15412     if (l1 > 510)
15413         l1 = 510;
15414     if (l1 + l2 > 510)
15415         l2 = 510 - l1;
15416     Copy(pat1, buf, l1 , char);
15417     Copy(pat2, buf + l1, l2 , char);
15418     buf[l1 + l2] = '\n';
15419     buf[l1 + l2 + 1] = '\0';
15420 #ifdef I_STDARG
15421     /* ANSI variant takes additional second argument */
15422     va_start(args, pat2);
15423 #else
15424     va_start(args);
15425 #endif
15426     msv = vmess(buf, &args);
15427     va_end(args);
15428     message = SvPV_const(msv,l1);
15429     if (l1 > 512)
15430         l1 = 512;
15431     Copy(message, buf, l1 , char);
15432     buf[l1-1] = '\0';                   /* Overwrite \n */
15433     Perl_croak(aTHX_ "%s", buf);
15434 }
15435
15436 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
15437
15438 #ifndef PERL_IN_XSUB_RE
15439 void
15440 Perl_save_re_context(pTHX)
15441 {
15442     dVAR;
15443
15444     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
15445     if (PL_curpm) {
15446         const REGEXP * const rx = PM_GETRE(PL_curpm);
15447         if (rx) {
15448             U32 i;
15449             for (i = 1; i <= RX_NPARENS(rx); i++) {
15450                 char digits[TYPE_CHARS(long)];
15451                 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
15452                 GV *const *const gvp
15453                     = (GV**)hv_fetch(PL_defstash, digits, len, 0);
15454
15455                 if (gvp) {
15456                     GV * const gv = *gvp;
15457                     if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
15458                         save_scalar(gv);
15459                 }
15460             }
15461         }
15462     }
15463 }
15464 #endif
15465
15466 #ifdef DEBUGGING
15467
15468 STATIC void
15469 S_put_byte(pTHX_ SV *sv, int c)
15470 {
15471     PERL_ARGS_ASSERT_PUT_BYTE;
15472
15473     /* Our definition of isPRINT() ignores locales, so only bytes that are
15474        not part of UTF-8 are considered printable. I assume that the same
15475        holds for UTF-EBCDIC.
15476        Also, code point 255 is not printable in either (it's E0 in EBCDIC,
15477        which Wikipedia says:
15478
15479        EO, or Eight Ones, is an 8-bit EBCDIC character code represented as all
15480        ones (binary 1111 1111, hexadecimal FF). It is similar, but not
15481        identical, to the ASCII delete (DEL) or rubout control character. ...
15482        it is typically mapped to hexadecimal code 9F, in order to provide a
15483        unique character mapping in both directions)
15484
15485        So the old condition can be simplified to !isPRINT(c)  */
15486     if (!isPRINT(c)) {
15487         switch (c) {
15488             case '\r': Perl_sv_catpvf(aTHX_ sv, "\\r"); break;
15489             case '\n': Perl_sv_catpvf(aTHX_ sv, "\\n"); break;
15490             case '\t': Perl_sv_catpvf(aTHX_ sv, "\\t"); break;
15491             case '\f': Perl_sv_catpvf(aTHX_ sv, "\\f"); break;
15492             case '\a': Perl_sv_catpvf(aTHX_ sv, "\\a"); break;
15493
15494             default:
15495                 Perl_sv_catpvf(aTHX_ sv, "\\x{%x}", c);
15496                 break;
15497         }
15498     }
15499     else {
15500         const char string = c;
15501         if (c == '-' || c == ']' || c == '\\' || c == '^')
15502             sv_catpvs(sv, "\\");
15503         sv_catpvn(sv, &string, 1);
15504     }
15505 }
15506
15507 STATIC bool
15508 S_put_latin1_charclass_innards(pTHX_ SV *sv, char *bitmap)
15509 {
15510     /* Appends to 'sv' a displayable version of the innards of the bracketed
15511      * character class whose bitmap is 'bitmap';  Returns 'TRUE' if it actually
15512      * output anything */
15513
15514     int i;
15515     int rangestart = -1;
15516     bool has_output_anything = FALSE;
15517
15518     PERL_ARGS_ASSERT_PUT_LATIN1_CHARCLASS_INNARDS;
15519
15520     for (i = 0; i <= 256; i++) {
15521         if (i < 256 && BITMAP_TEST((U8 *) bitmap,i)) {
15522             if (rangestart == -1)
15523                 rangestart = i;
15524         } else if (rangestart != -1) {
15525             int j = i - 1;
15526             if (i <= rangestart + 3) {  /* Individual chars in short ranges */
15527                 for (; rangestart < i; rangestart++)
15528                     put_byte(sv, rangestart);
15529             }
15530             else if (   j > 255
15531                      || ! isALPHANUMERIC(rangestart)
15532                      || ! isALPHANUMERIC(j)
15533                      || isDIGIT(rangestart) != isDIGIT(j)
15534                      || isUPPER(rangestart) != isUPPER(j)
15535                      || isLOWER(rangestart) != isLOWER(j)
15536
15537                         /* This final test should get optimized out except
15538                          * on EBCDIC platforms, where it causes ranges that
15539                          * cross discontinuities like i/j to be shown as hex
15540                          * instead of the misleading, e.g. H-K (since that
15541                          * range includes more than H, I, J, K). */
15542                      || (j - rangestart)
15543                          != NATIVE_TO_ASCII(j) - NATIVE_TO_ASCII(rangestart))
15544             {
15545                 Perl_sv_catpvf(aTHX_ sv, "\\x{%02x}-\\x{%02x}",
15546                                rangestart,
15547                                (j < 256) ? j : 255);
15548             }
15549             else { /* Here, the ends of the range are both digits, or both
15550                       uppercase, or both lowercase; and there's no
15551                       discontinuity in the range (which could happen on EBCDIC
15552                       platforms) */
15553                 put_byte(sv, rangestart);
15554                 sv_catpvs(sv, "-");
15555                 put_byte(sv, j);
15556             }
15557             rangestart = -1;
15558             has_output_anything = TRUE;
15559         }
15560     }
15561
15562     return has_output_anything;
15563 }
15564
15565 #define CLEAR_OPTSTART \
15566     if (optstart) STMT_START { \
15567             DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
15568             optstart=NULL; \
15569     } STMT_END
15570
15571 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
15572
15573 STATIC const regnode *
15574 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
15575             const regnode *last, const regnode *plast, 
15576             SV* sv, I32 indent, U32 depth)
15577 {
15578     dVAR;
15579     U8 op = PSEUDO;     /* Arbitrary non-END op. */
15580     const regnode *next;
15581     const regnode *optstart= NULL;
15582     
15583     RXi_GET_DECL(r,ri);
15584     GET_RE_DEBUG_FLAGS_DECL;
15585
15586     PERL_ARGS_ASSERT_DUMPUNTIL;
15587
15588 #ifdef DEBUG_DUMPUNTIL
15589     PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
15590         last ? last-start : 0,plast ? plast-start : 0);
15591 #endif
15592             
15593     if (plast && plast < last) 
15594         last= plast;
15595
15596     while (PL_regkind[op] != END && (!last || node < last)) {
15597         /* While that wasn't END last time... */
15598         NODE_ALIGN(node);
15599         op = OP(node);
15600         if (op == CLOSE || op == WHILEM)
15601             indent--;
15602         next = regnext((regnode *)node);
15603
15604         /* Where, what. */
15605         if (OP(node) == OPTIMIZED) {
15606             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
15607                 optstart = node;
15608             else
15609                 goto after_print;
15610         } else
15611             CLEAR_OPTSTART;
15612
15613         regprop(r, sv, node);
15614         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
15615                       (int)(2*indent + 1), "", SvPVX_const(sv));
15616         
15617         if (OP(node) != OPTIMIZED) {                  
15618             if (next == NULL)           /* Next ptr. */
15619                 PerlIO_printf(Perl_debug_log, " (0)");
15620             else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
15621                 PerlIO_printf(Perl_debug_log, " (FAIL)");
15622             else 
15623                 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
15624             (void)PerlIO_putc(Perl_debug_log, '\n'); 
15625         }
15626         
15627       after_print:
15628         if (PL_regkind[(U8)op] == BRANCHJ) {
15629             assert(next);
15630             {
15631                 const regnode *nnode = (OP(next) == LONGJMP
15632                                        ? regnext((regnode *)next)
15633                                        : next);
15634                 if (last && nnode > last)
15635                     nnode = last;
15636                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
15637             }
15638         }
15639         else if (PL_regkind[(U8)op] == BRANCH) {
15640             assert(next);
15641             DUMPUNTIL(NEXTOPER(node), next);
15642         }
15643         else if ( PL_regkind[(U8)op]  == TRIE ) {
15644             const regnode *this_trie = node;
15645             const char op = OP(node);
15646             const U32 n = ARG(node);
15647             const reg_ac_data * const ac = op>=AHOCORASICK ?
15648                (reg_ac_data *)ri->data->data[n] :
15649                NULL;
15650             const reg_trie_data * const trie =
15651                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
15652 #ifdef DEBUGGING
15653             AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
15654 #endif
15655             const regnode *nextbranch= NULL;
15656             I32 word_idx;
15657             sv_setpvs(sv, "");
15658             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
15659                 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
15660
15661                 PerlIO_printf(Perl_debug_log, "%*s%s ",
15662                    (int)(2*(indent+3)), "",
15663                     elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
15664                             PL_colors[0], PL_colors[1],
15665                             (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
15666                             PERL_PV_PRETTY_ELLIPSES    |
15667                             PERL_PV_PRETTY_LTGT
15668                             )
15669                             : "???"
15670                 );
15671                 if (trie->jump) {
15672                     U16 dist= trie->jump[word_idx+1];
15673                     PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
15674                                   (UV)((dist ? this_trie + dist : next) - start));
15675                     if (dist) {
15676                         if (!nextbranch)
15677                             nextbranch= this_trie + trie->jump[0];    
15678                         DUMPUNTIL(this_trie + dist, nextbranch);
15679                     }
15680                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
15681                         nextbranch= regnext((regnode *)nextbranch);
15682                 } else {
15683                     PerlIO_printf(Perl_debug_log, "\n");
15684                 }
15685             }
15686             if (last && next > last)
15687                 node= last;
15688             else
15689                 node= next;
15690         }
15691         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
15692             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
15693                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
15694         }
15695         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
15696             assert(next);
15697             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
15698         }
15699         else if ( op == PLUS || op == STAR) {
15700             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
15701         }
15702         else if (PL_regkind[(U8)op] == ANYOF) {
15703             /* arglen 1 + class block */
15704             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_CLASS)
15705                     ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
15706             node = NEXTOPER(node);
15707         }
15708         else if (PL_regkind[(U8)op] == EXACT) {
15709             /* Literal string, where present. */
15710             node += NODE_SZ_STR(node) - 1;
15711             node = NEXTOPER(node);
15712         }
15713         else {
15714             node = NEXTOPER(node);
15715             node += regarglen[(U8)op];
15716         }
15717         if (op == CURLYX || op == OPEN)
15718             indent++;
15719     }
15720     CLEAR_OPTSTART;
15721 #ifdef DEBUG_DUMPUNTIL    
15722     PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
15723 #endif
15724     return node;
15725 }
15726
15727 #endif  /* DEBUGGING */
15728
15729 /*
15730  * Local variables:
15731  * c-indentation-style: bsd
15732  * c-basic-offset: 4
15733  * indent-tabs-mode: nil
15734  * End:
15735  *
15736  * ex: set ts=8 sts=4 sw=4 et:
15737  */