This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regcomp.h: Split two ANYOF flag bits
[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; &regdummy = don't = compiling */
130     I32         naughty;                /* How bad is this pattern? */
131     I32         sawback;                /* Did we see \1, ...? */
132     U32         seen;
133     I32         size;                   /* Code size. */
134     I32         npar;                   /* Capture buffer count, (OPEN). */
135     I32         cpar;                   /* Capture buffer count, (CLOSE). */
136     I32         nestroot;               /* root parens we are in - used by accept */
137     I32         extralen;
138     I32         seen_zerolen;
139     regnode     **open_parens;          /* pointers to open parens */
140     regnode     **close_parens;         /* pointers to close parens */
141     regnode     *opend;                 /* END node in program */
142     I32         utf8;           /* whether the pattern is utf8 or not */
143     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
144                                 /* XXX use this for future optimisation of case
145                                  * where pattern must be upgraded to utf8. */
146     I32         uni_semantics;  /* If a d charset modifier should use unicode
147                                    rules, even if the pattern is not in
148                                    utf8 */
149     HV          *paren_names;           /* Paren names */
150     
151     regnode     **recurse;              /* Recurse regops */
152     I32         recurse_count;          /* Number of recurse regops */
153     I32         in_lookbehind;
154     I32         contains_locale;
155     I32         override_recoding;
156     I32         in_multi_char_class;
157     struct reg_code_block *code_blocks; /* positions of literal (?{})
158                                             within pattern */
159     int         num_code_blocks;        /* size of code_blocks[] */
160     int         code_index;             /* next code_blocks[] slot */
161 #if ADD_TO_REGEXEC
162     char        *starttry;              /* -Dr: where regtry was called. */
163 #define RExC_starttry   (pRExC_state->starttry)
164 #endif
165     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
166 #ifdef DEBUGGING
167     const char  *lastparse;
168     I32         lastnum;
169     AV          *paren_name_list;       /* idx -> name */
170 #define RExC_lastparse  (pRExC_state->lastparse)
171 #define RExC_lastnum    (pRExC_state->lastnum)
172 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
173 #endif
174 } RExC_state_t;
175
176 #define RExC_flags      (pRExC_state->flags)
177 #define RExC_pm_flags   (pRExC_state->pm_flags)
178 #define RExC_precomp    (pRExC_state->precomp)
179 #define RExC_rx_sv      (pRExC_state->rx_sv)
180 #define RExC_rx         (pRExC_state->rx)
181 #define RExC_rxi        (pRExC_state->rxi)
182 #define RExC_start      (pRExC_state->start)
183 #define RExC_end        (pRExC_state->end)
184 #define RExC_parse      (pRExC_state->parse)
185 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
186 #ifdef RE_TRACK_PATTERN_OFFSETS
187 #define RExC_offsets    (pRExC_state->rxi->u.offsets) /* I am not like the others */
188 #endif
189 #define RExC_emit       (pRExC_state->emit)
190 #define RExC_emit_start (pRExC_state->emit_start)
191 #define RExC_emit_bound (pRExC_state->emit_bound)
192 #define RExC_naughty    (pRExC_state->naughty)
193 #define RExC_sawback    (pRExC_state->sawback)
194 #define RExC_seen       (pRExC_state->seen)
195 #define RExC_size       (pRExC_state->size)
196 #define RExC_npar       (pRExC_state->npar)
197 #define RExC_nestroot   (pRExC_state->nestroot)
198 #define RExC_extralen   (pRExC_state->extralen)
199 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
200 #define RExC_utf8       (pRExC_state->utf8)
201 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
202 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
203 #define RExC_open_parens        (pRExC_state->open_parens)
204 #define RExC_close_parens       (pRExC_state->close_parens)
205 #define RExC_opend      (pRExC_state->opend)
206 #define RExC_paren_names        (pRExC_state->paren_names)
207 #define RExC_recurse    (pRExC_state->recurse)
208 #define RExC_recurse_count      (pRExC_state->recurse_count)
209 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
210 #define RExC_contains_locale    (pRExC_state->contains_locale)
211 #define RExC_override_recoding (pRExC_state->override_recoding)
212 #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class)
213
214
215 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
216 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
217         ((*s) == '{' && regcurly(s)))
218
219 #ifdef SPSTART
220 #undef SPSTART          /* dratted cpp namespace... */
221 #endif
222 /*
223  * Flags to be passed up and down.
224  */
225 #define WORST           0       /* Worst case. */
226 #define HASWIDTH        0x01    /* Known to match non-null strings. */
227
228 /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single
229  * character.  (There needs to be a case: in the switch statement in regexec.c
230  * for any node marked SIMPLE.)  Note that this is not the same thing as
231  * REGNODE_SIMPLE */
232 #define SIMPLE          0x02
233 #define SPSTART         0x04    /* Starts with * or + */
234 #define TRYAGAIN        0x08    /* Weeded out a declaration. */
235 #define POSTPONED       0x10    /* (?1),(?&name), (??{...}) or similar */
236
237 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
238
239 /* whether trie related optimizations are enabled */
240 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
241 #define TRIE_STUDY_OPT
242 #define FULL_TRIE_STUDY
243 #define TRIE_STCLASS
244 #endif
245
246
247
248 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
249 #define PBITVAL(paren) (1 << ((paren) & 7))
250 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
251 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
252 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
253
254 /* If not already in utf8, do a longjmp back to the beginning */
255 #define UTF8_LONGJMP 42 /* Choose a value not likely to ever conflict */
256 #define REQUIRE_UTF8    STMT_START {                                       \
257                                      if (! UTF) JMPENV_JUMP(UTF8_LONGJMP); \
258                         } STMT_END
259
260 /* This converts the named class defined in regcomp.h to its equivalent class
261  * number defined in handy.h. */
262 #define namedclass_to_classnum(class)  ((int) ((class) / 2))
263 #define classnum_to_namedclass(classnum)  ((classnum) * 2)
264
265 /* About scan_data_t.
266
267   During optimisation we recurse through the regexp program performing
268   various inplace (keyhole style) optimisations. In addition study_chunk
269   and scan_commit populate this data structure with information about
270   what strings MUST appear in the pattern. We look for the longest 
271   string that must appear at a fixed location, and we look for the
272   longest string that may appear at a floating location. So for instance
273   in the pattern:
274   
275     /FOO[xX]A.*B[xX]BAR/
276     
277   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
278   strings (because they follow a .* construct). study_chunk will identify
279   both FOO and BAR as being the longest fixed and floating strings respectively.
280   
281   The strings can be composites, for instance
282   
283      /(f)(o)(o)/
284      
285   will result in a composite fixed substring 'foo'.
286   
287   For each string some basic information is maintained:
288   
289   - offset or min_offset
290     This is the position the string must appear at, or not before.
291     It also implicitly (when combined with minlenp) tells us how many
292     characters must match before the string we are searching for.
293     Likewise when combined with minlenp and the length of the string it
294     tells us how many characters must appear after the string we have 
295     found.
296   
297   - max_offset
298     Only used for floating strings. This is the rightmost point that
299     the string can appear at. If set to I32 max it indicates that the
300     string can occur infinitely far to the right.
301   
302   - minlenp
303     A pointer to the minimum number of characters of the pattern that the
304     string was found inside. This is important as in the case of positive
305     lookahead or positive lookbehind we can have multiple patterns 
306     involved. Consider
307     
308     /(?=FOO).*F/
309     
310     The minimum length of the pattern overall is 3, the minimum length
311     of the lookahead part is 3, but the minimum length of the part that
312     will actually match is 1. So 'FOO's minimum length is 3, but the 
313     minimum length for the F is 1. This is important as the minimum length
314     is used to determine offsets in front of and behind the string being 
315     looked for.  Since strings can be composites this is the length of the
316     pattern at the time it was committed with a scan_commit. Note that
317     the length is calculated by study_chunk, so that the minimum lengths
318     are not known until the full pattern has been compiled, thus the 
319     pointer to the value.
320   
321   - lookbehind
322   
323     In the case of lookbehind the string being searched for can be
324     offset past the start point of the final matching string. 
325     If this value was just blithely removed from the min_offset it would
326     invalidate some of the calculations for how many chars must match
327     before or after (as they are derived from min_offset and minlen and
328     the length of the string being searched for). 
329     When the final pattern is compiled and the data is moved from the
330     scan_data_t structure into the regexp structure the information
331     about lookbehind is factored in, with the information that would 
332     have been lost precalculated in the end_shift field for the 
333     associated string.
334
335   The fields pos_min and pos_delta are used to store the minimum offset
336   and the delta to the maximum offset at the current point in the pattern.    
337
338 */
339
340 typedef struct scan_data_t {
341     /*I32 len_min;      unused */
342     /*I32 len_delta;    unused */
343     I32 pos_min;
344     I32 pos_delta;
345     SV *last_found;
346     I32 last_end;           /* min value, <0 unless valid. */
347     I32 last_start_min;
348     I32 last_start_max;
349     SV **longest;           /* Either &l_fixed, or &l_float. */
350     SV *longest_fixed;      /* longest fixed string found in pattern */
351     I32 offset_fixed;       /* offset where it starts */
352     I32 *minlen_fixed;      /* pointer to the minlen relevant to the string */
353     I32 lookbehind_fixed;   /* is the position of the string modfied by LB */
354     SV *longest_float;      /* longest floating string found in pattern */
355     I32 offset_float_min;   /* earliest point in string it can appear */
356     I32 offset_float_max;   /* latest point in string it can appear */
357     I32 *minlen_float;      /* pointer to the minlen relevant to the string */
358     I32 lookbehind_float;   /* is the position of the string modified by LB */
359     I32 flags;
360     I32 whilem_c;
361     I32 *last_closep;
362     struct regnode_charclass_class *start_class;
363 } scan_data_t;
364
365 /*
366  * Forward declarations for pregcomp()'s friends.
367  */
368
369 static const scan_data_t zero_scan_data =
370   { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
371
372 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
373 #define SF_BEFORE_SEOL          0x0001
374 #define SF_BEFORE_MEOL          0x0002
375 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
376 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
377
378 #ifdef NO_UNARY_PLUS
379 #  define SF_FIX_SHIFT_EOL      (0+2)
380 #  define SF_FL_SHIFT_EOL               (0+4)
381 #else
382 #  define SF_FIX_SHIFT_EOL      (+2)
383 #  define SF_FL_SHIFT_EOL               (+4)
384 #endif
385
386 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
387 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
388
389 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
390 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
391 #define SF_IS_INF               0x0040
392 #define SF_HAS_PAR              0x0080
393 #define SF_IN_PAR               0x0100
394 #define SF_HAS_EVAL             0x0200
395 #define SCF_DO_SUBSTR           0x0400
396 #define SCF_DO_STCLASS_AND      0x0800
397 #define SCF_DO_STCLASS_OR       0x1000
398 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
399 #define SCF_WHILEM_VISITED_POS  0x2000
400
401 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
402 #define SCF_SEEN_ACCEPT         0x8000 
403
404 #define UTF cBOOL(RExC_utf8)
405
406 /* The enums for all these are ordered so things work out correctly */
407 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
408 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_DEPENDS_CHARSET)
409 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
410 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) >= REGEX_UNICODE_CHARSET)
411 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_RESTRICTED_CHARSET)
412 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) >= REGEX_ASCII_RESTRICTED_CHARSET)
413 #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
414
415 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
416
417 #define OOB_NAMEDCLASS          -1
418
419 /* There is no code point that is out-of-bounds, so this is problematic.  But
420  * its only current use is to initialize a variable that is always set before
421  * looked at. */
422 #define OOB_UNICODE             0xDEADBEEF
423
424 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
425 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
426
427
428 /* length of regex to show in messages that don't mark a position within */
429 #define RegexLengthToShowInErrorMessages 127
430
431 /*
432  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
433  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
434  * op/pragma/warn/regcomp.
435  */
436 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
437 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
438
439 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
440
441 /*
442  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
443  * arg. Show regex, up to a maximum length. If it's too long, chop and add
444  * "...".
445  */
446 #define _FAIL(code) STMT_START {                                        \
447     const char *ellipses = "";                                          \
448     IV len = RExC_end - RExC_precomp;                                   \
449                                                                         \
450     if (!SIZE_ONLY)                                                     \
451         SAVEFREESV(RExC_rx_sv);                                         \
452     if (len > RegexLengthToShowInErrorMessages) {                       \
453         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
454         len = RegexLengthToShowInErrorMessages - 10;                    \
455         ellipses = "...";                                               \
456     }                                                                   \
457     code;                                                               \
458 } STMT_END
459
460 #define FAIL(msg) _FAIL(                            \
461     Perl_croak(aTHX_ "%s in regex m/%.*s%s/",       \
462             msg, (int)len, RExC_precomp, ellipses))
463
464 #define FAIL2(msg,arg) _FAIL(                       \
465     Perl_croak(aTHX_ msg " in regex m/%.*s%s/",     \
466             arg, (int)len, RExC_precomp, ellipses))
467
468 /*
469  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
470  */
471 #define Simple_vFAIL(m) STMT_START {                                    \
472     const IV offset = RExC_parse - RExC_precomp;                        \
473     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
474             m, (int)offset, RExC_precomp, RExC_precomp + offset);       \
475 } STMT_END
476
477 /*
478  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
479  */
480 #define vFAIL(m) STMT_START {                           \
481     if (!SIZE_ONLY)                                     \
482         SAVEFREESV(RExC_rx_sv);                         \
483     Simple_vFAIL(m);                                    \
484 } STMT_END
485
486 /*
487  * Like Simple_vFAIL(), but accepts two arguments.
488  */
489 #define Simple_vFAIL2(m,a1) STMT_START {                        \
490     const IV offset = RExC_parse - RExC_precomp;                        \
491     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1,                   \
492             (int)offset, RExC_precomp, RExC_precomp + offset);  \
493 } STMT_END
494
495 /*
496  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
497  */
498 #define vFAIL2(m,a1) STMT_START {                       \
499     if (!SIZE_ONLY)                                     \
500         SAVEFREESV(RExC_rx_sv);                         \
501     Simple_vFAIL2(m, a1);                               \
502 } STMT_END
503
504
505 /*
506  * Like Simple_vFAIL(), but accepts three arguments.
507  */
508 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
509     const IV offset = RExC_parse - RExC_precomp;                \
510     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2,               \
511             (int)offset, RExC_precomp, RExC_precomp + offset);  \
512 } STMT_END
513
514 /*
515  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
516  */
517 #define vFAIL3(m,a1,a2) STMT_START {                    \
518     if (!SIZE_ONLY)                                     \
519         SAVEFREESV(RExC_rx_sv);                         \
520     Simple_vFAIL3(m, a1, a2);                           \
521 } STMT_END
522
523 /*
524  * Like Simple_vFAIL(), but accepts four arguments.
525  */
526 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
527     const IV offset = RExC_parse - RExC_precomp;                \
528     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,           \
529             (int)offset, RExC_precomp, RExC_precomp + offset);  \
530 } STMT_END
531
532 #define ckWARNreg(loc,m) STMT_START {                                   \
533     const IV offset = loc - RExC_precomp;                               \
534     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
535             (int)offset, RExC_precomp, RExC_precomp + offset);          \
536 } STMT_END
537
538 #define ckWARNregdep(loc,m) STMT_START {                                \
539     const IV offset = loc - RExC_precomp;                               \
540     Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP),     \
541             m REPORT_LOCATION,                                          \
542             (int)offset, RExC_precomp, RExC_precomp + offset);          \
543 } STMT_END
544
545 #define ckWARN2regdep(loc,m, a1) STMT_START {                           \
546     const IV offset = loc - RExC_precomp;                               \
547     Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP),     \
548             m REPORT_LOCATION,                                          \
549             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
550 } STMT_END
551
552 #define ckWARN2reg(loc, m, a1) STMT_START {                             \
553     const IV offset = loc - RExC_precomp;                               \
554     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
555             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
556 } STMT_END
557
558 #define vWARN3(loc, m, a1, a2) STMT_START {                             \
559     const IV offset = loc - RExC_precomp;                               \
560     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
561             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
562 } STMT_END
563
564 #define ckWARN3reg(loc, m, a1, a2) STMT_START {                         \
565     const IV offset = loc - RExC_precomp;                               \
566     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
567             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
568 } STMT_END
569
570 #define vWARN4(loc, m, a1, a2, a3) STMT_START {                         \
571     const IV offset = loc - RExC_precomp;                               \
572     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
573             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
574 } STMT_END
575
576 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START {                     \
577     const IV offset = loc - RExC_precomp;                               \
578     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
579             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
580 } STMT_END
581
582 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START {                     \
583     const IV offset = loc - RExC_precomp;                               \
584     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
585             a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
586 } STMT_END
587
588
589 /* Allow for side effects in s */
590 #define REGC(c,s) STMT_START {                  \
591     if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
592 } STMT_END
593
594 /* Macros for recording node offsets.   20001227 mjd@plover.com 
595  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
596  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
597  * Element 0 holds the number n.
598  * Position is 1 indexed.
599  */
600 #ifndef RE_TRACK_PATTERN_OFFSETS
601 #define Set_Node_Offset_To_R(node,byte)
602 #define Set_Node_Offset(node,byte)
603 #define Set_Cur_Node_Offset
604 #define Set_Node_Length_To_R(node,len)
605 #define Set_Node_Length(node,len)
606 #define Set_Node_Cur_Length(node)
607 #define Node_Offset(n) 
608 #define Node_Length(n) 
609 #define Set_Node_Offset_Length(node,offset,len)
610 #define ProgLen(ri) ri->u.proglen
611 #define SetProgLen(ri,x) ri->u.proglen = x
612 #else
613 #define ProgLen(ri) ri->u.offsets[0]
614 #define SetProgLen(ri,x) ri->u.offsets[0] = x
615 #define Set_Node_Offset_To_R(node,byte) STMT_START {                    \
616     if (! SIZE_ONLY) {                                                  \
617         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
618                     __LINE__, (int)(node), (int)(byte)));               \
619         if((node) < 0) {                                                \
620             Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
621         } else {                                                        \
622             RExC_offsets[2*(node)-1] = (byte);                          \
623         }                                                               \
624     }                                                                   \
625 } STMT_END
626
627 #define Set_Node_Offset(node,byte) \
628     Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
629 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
630
631 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
632     if (! SIZE_ONLY) {                                                  \
633         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
634                 __LINE__, (int)(node), (int)(len)));                    \
635         if((node) < 0) {                                                \
636             Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
637         } else {                                                        \
638             RExC_offsets[2*(node)] = (len);                             \
639         }                                                               \
640     }                                                                   \
641 } STMT_END
642
643 #define Set_Node_Length(node,len) \
644     Set_Node_Length_To_R((node)-RExC_emit_start, len)
645 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
646 #define Set_Node_Cur_Length(node) \
647     Set_Node_Length(node, RExC_parse - parse_start)
648
649 /* Get offsets and lengths */
650 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
651 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
652
653 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
654     Set_Node_Offset_To_R((node)-RExC_emit_start, (offset));     \
655     Set_Node_Length_To_R((node)-RExC_emit_start, (len));        \
656 } STMT_END
657 #endif
658
659 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
660 #define EXPERIMENTAL_INPLACESCAN
661 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
662
663 #define DEBUG_STUDYDATA(str,data,depth)                              \
664 DEBUG_OPTIMISE_MORE_r(if(data){                                      \
665     PerlIO_printf(Perl_debug_log,                                    \
666         "%*s" str "Pos:%"IVdf"/%"IVdf                                \
667         " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s",       \
668         (int)(depth)*2, "",                                          \
669         (IV)((data)->pos_min),                                       \
670         (IV)((data)->pos_delta),                                     \
671         (UV)((data)->flags),                                         \
672         (IV)((data)->whilem_c),                                      \
673         (IV)((data)->last_closep ? *((data)->last_closep) : -1),     \
674         is_inf ? "INF " : ""                                         \
675     );                                                               \
676     if ((data)->last_found)                                          \
677         PerlIO_printf(Perl_debug_log,                                \
678             "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
679             " %sFloat: '%s' @ %"IVdf"/%"IVdf"",                      \
680             SvPVX_const((data)->last_found),                         \
681             (IV)((data)->last_end),                                  \
682             (IV)((data)->last_start_min),                            \
683             (IV)((data)->last_start_max),                            \
684             ((data)->longest &&                                      \
685              (data)->longest==&((data)->longest_fixed)) ? "*" : "",  \
686             SvPVX_const((data)->longest_fixed),                      \
687             (IV)((data)->offset_fixed),                              \
688             ((data)->longest &&                                      \
689              (data)->longest==&((data)->longest_float)) ? "*" : "",  \
690             SvPVX_const((data)->longest_float),                      \
691             (IV)((data)->offset_float_min),                          \
692             (IV)((data)->offset_float_max)                           \
693         );                                                           \
694     PerlIO_printf(Perl_debug_log,"\n");                              \
695 });
696
697 /* Mark that we cannot extend a found fixed substring at this point.
698    Update the longest found anchored substring and the longest found
699    floating substrings if needed. */
700
701 STATIC void
702 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
703 {
704     const STRLEN l = CHR_SVLEN(data->last_found);
705     const STRLEN old_l = CHR_SVLEN(*data->longest);
706     GET_RE_DEBUG_FLAGS_DECL;
707
708     PERL_ARGS_ASSERT_SCAN_COMMIT;
709
710     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
711         SvSetMagicSV(*data->longest, data->last_found);
712         if (*data->longest == data->longest_fixed) {
713             data->offset_fixed = l ? data->last_start_min : data->pos_min;
714             if (data->flags & SF_BEFORE_EOL)
715                 data->flags
716                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
717             else
718                 data->flags &= ~SF_FIX_BEFORE_EOL;
719             data->minlen_fixed=minlenp;
720             data->lookbehind_fixed=0;
721         }
722         else { /* *data->longest == data->longest_float */
723             data->offset_float_min = l ? data->last_start_min : data->pos_min;
724             data->offset_float_max = (l
725                                       ? data->last_start_max
726                                       : data->pos_min + data->pos_delta);
727             if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
728                 data->offset_float_max = I32_MAX;
729             if (data->flags & SF_BEFORE_EOL)
730                 data->flags
731                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
732             else
733                 data->flags &= ~SF_FL_BEFORE_EOL;
734             data->minlen_float=minlenp;
735             data->lookbehind_float=0;
736         }
737     }
738     SvCUR_set(data->last_found, 0);
739     {
740         SV * const sv = data->last_found;
741         if (SvUTF8(sv) && SvMAGICAL(sv)) {
742             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
743             if (mg)
744                 mg->mg_len = 0;
745         }
746     }
747     data->last_end = -1;
748     data->flags &= ~SF_BEFORE_EOL;
749     DEBUG_STUDYDATA("commit: ",data,0);
750 }
751
752 /* Can match anything (initialization) */
753 STATIC void
754 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
755 {
756     PERL_ARGS_ASSERT_CL_ANYTHING;
757
758     ANYOF_BITMAP_SETALL(cl);
759     cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
760
761     /* If any portion of the regex is to operate under locale rules,
762      * initialization includes it.  The reason this isn't done for all regexes
763      * is that the optimizer was written under the assumption that locale was
764      * all-or-nothing.  Given the complexity and lack of documentation in the
765      * optimizer, and that there are inadequate test cases for locale, so many
766      * parts of it may not work properly, it is safest to avoid locale unless
767      * necessary. */
768     if (RExC_contains_locale) {
769         ANYOF_CLASS_SETALL(cl);     /* /l uses class */
770         cl->flags |= ANYOF_LOCALE|ANYOF_CLASS|ANYOF_LOC_FOLD;
771     }
772     else {
773         ANYOF_CLASS_ZERO(cl);       /* Only /l uses class now */
774     }
775 }
776
777 /* Can match anything (initialization) */
778 STATIC int
779 S_cl_is_anything(const struct regnode_charclass_class *cl)
780 {
781     int value;
782
783     PERL_ARGS_ASSERT_CL_IS_ANYTHING;
784
785     for (value = 0; value <= ANYOF_MAX; value += 2)
786         if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
787             return 1;
788     if (!(cl->flags & ANYOF_UNICODE_ALL))
789         return 0;
790     if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
791         return 0;
792     return 1;
793 }
794
795 /* Can match anything (initialization) */
796 STATIC void
797 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
798 {
799     PERL_ARGS_ASSERT_CL_INIT;
800
801     Zero(cl, 1, struct regnode_charclass_class);
802     cl->type = ANYOF;
803     cl_anything(pRExC_state, cl);
804     ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
805 }
806
807 /* These two functions currently do the exact same thing */
808 #define cl_init_zero            S_cl_init
809
810 /* 'AND' a given class with another one.  Can create false positives.  'cl'
811  * should not be inverted.  'and_with->flags & ANYOF_CLASS' should be 0 if
812  * 'and_with' is a regnode_charclass instead of a regnode_charclass_class. */
813 STATIC void
814 S_cl_and(struct regnode_charclass_class *cl,
815         const struct regnode_charclass_class *and_with)
816 {
817     PERL_ARGS_ASSERT_CL_AND;
818
819     assert(PL_regkind[and_with->type] == ANYOF);
820
821     /* I (khw) am not sure all these restrictions are necessary XXX */
822     if (!(ANYOF_CLASS_TEST_ANY_SET(and_with))
823         && !(ANYOF_CLASS_TEST_ANY_SET(cl))
824         && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
825         && !(and_with->flags & ANYOF_LOC_FOLD)
826         && !(cl->flags & ANYOF_LOC_FOLD)) {
827         int i;
828
829         if (and_with->flags & ANYOF_INVERT)
830             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
831                 cl->bitmap[i] &= ~and_with->bitmap[i];
832         else
833             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
834                 cl->bitmap[i] &= and_with->bitmap[i];
835     } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
836
837     if (and_with->flags & ANYOF_INVERT) {
838
839         /* Here, the and'ed node is inverted.  Get the AND of the flags that
840          * aren't affected by the inversion.  Those that are affected are
841          * handled individually below */
842         U8 affected_flags = cl->flags & ~INVERSION_UNAFFECTED_FLAGS;
843         cl->flags &= (and_with->flags & INVERSION_UNAFFECTED_FLAGS);
844         cl->flags |= affected_flags;
845
846         /* We currently don't know how to deal with things that aren't in the
847          * bitmap, but we know that the intersection is no greater than what
848          * is already in cl, so let there be false positives that get sorted
849          * out after the synthetic start class succeeds, and the node is
850          * matched for real. */
851
852         /* The inversion of these two flags indicate that the resulting
853          * intersection doesn't have them */
854         if (and_with->flags & ANYOF_UNICODE_ALL) {
855             cl->flags &= ~ANYOF_UNICODE_ALL;
856         }
857         if (and_with->flags & ANYOF_NON_UTF8_LATIN1_ALL) {
858             cl->flags &= ~ANYOF_NON_UTF8_LATIN1_ALL;
859         }
860     }
861     else {   /* and'd node is not inverted */
862         U8 outside_bitmap_but_not_utf8; /* Temp variable */
863
864         if (! ANYOF_NONBITMAP(and_with)) {
865
866             /* Here 'and_with' doesn't match anything outside the bitmap
867              * (except possibly ANYOF_UNICODE_ALL), which means the
868              * intersection can't either, except for ANYOF_UNICODE_ALL, in
869              * which case we don't know what the intersection is, but it's no
870              * greater than what cl already has, so can just leave it alone,
871              * with possible false positives */
872             if (! (and_with->flags & ANYOF_UNICODE_ALL)) {
873                 ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
874                 cl->flags &= ~ANYOF_NONBITMAP_NON_UTF8;
875             }
876         }
877         else if (! ANYOF_NONBITMAP(cl)) {
878
879             /* Here, 'and_with' does match something outside the bitmap, and cl
880              * doesn't have a list of things to match outside the bitmap.  If
881              * cl can match all code points above 255, the intersection will
882              * be those above-255 code points that 'and_with' matches.  If cl
883              * can't match all Unicode code points, it means that it can't
884              * match anything outside the bitmap (since the 'if' that got us
885              * into this block tested for that), so we leave the bitmap empty.
886              */
887             if (cl->flags & ANYOF_UNICODE_ALL) {
888                 ARG_SET(cl, ARG(and_with));
889
890                 /* and_with's ARG may match things that don't require UTF8.
891                  * And now cl's will too, in spite of this being an 'and'.  See
892                  * the comments below about the kludge */
893                 cl->flags |= and_with->flags & ANYOF_NONBITMAP_NON_UTF8;
894             }
895         }
896         else {
897             /* Here, both 'and_with' and cl match something outside the
898              * bitmap.  Currently we do not do the intersection, so just match
899              * whatever cl had at the beginning.  */
900         }
901
902
903         /* Take the intersection of the two sets of flags.  However, the
904          * ANYOF_NONBITMAP_NON_UTF8 flag is treated as an 'or'.  This is a
905          * kludge around the fact that this flag is not treated like the others
906          * which are initialized in cl_anything().  The way the optimizer works
907          * is that the synthetic start class (SSC) is initialized to match
908          * anything, and then the first time a real node is encountered, its
909          * values are AND'd with the SSC's with the result being the values of
910          * the real node.  However, there are paths through the optimizer where
911          * the AND never gets called, so those initialized bits are set
912          * inappropriately, which is not usually a big deal, as they just cause
913          * false positives in the SSC, which will just mean a probably
914          * imperceptible slow down in execution.  However this bit has a
915          * higher false positive consequence in that it can cause utf8.pm,
916          * utf8_heavy.pl ... to be loaded when not necessary, which is a much
917          * bigger slowdown and also causes significant extra memory to be used.
918          * In order to prevent this, the code now takes a different tack.  The
919          * bit isn't set unless some part of the regular expression needs it,
920          * but once set it won't get cleared.  This means that these extra
921          * modules won't get loaded unless there was some path through the
922          * pattern that would have required them anyway, and  so any false
923          * positives that occur by not ANDing them out when they could be
924          * aren't as severe as they would be if we treated this bit like all
925          * the others */
926         outside_bitmap_but_not_utf8 = (cl->flags | and_with->flags)
927                                       & ANYOF_NONBITMAP_NON_UTF8;
928         cl->flags &= and_with->flags;
929         cl->flags |= outside_bitmap_but_not_utf8;
930     }
931 }
932
933 /* 'OR' a given class with another one.  Can create false positives.  'cl'
934  * should not be inverted.  'or_with->flags & ANYOF_CLASS' should be 0 if
935  * 'or_with' is a regnode_charclass instead of a regnode_charclass_class. */
936 STATIC void
937 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
938 {
939     PERL_ARGS_ASSERT_CL_OR;
940
941     if (or_with->flags & ANYOF_INVERT) {
942
943         /* Here, the or'd node is to be inverted.  This means we take the
944          * complement of everything not in the bitmap, but currently we don't
945          * know what that is, so give up and match anything */
946         if (ANYOF_NONBITMAP(or_with)) {
947             cl_anything(pRExC_state, cl);
948         }
949         /* We do not use
950          * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
951          *   <= (B1 | !B2) | (CL1 | !CL2)
952          * which is wasteful if CL2 is small, but we ignore CL2:
953          *   (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
954          * XXXX Can we handle case-fold?  Unclear:
955          *   (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
956          *   (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
957          */
958         else if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
959              && !(or_with->flags & ANYOF_LOC_FOLD)
960              && !(cl->flags & ANYOF_LOC_FOLD) ) {
961             int i;
962
963             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
964                 cl->bitmap[i] |= ~or_with->bitmap[i];
965         } /* XXXX: logic is complicated otherwise */
966         else {
967             cl_anything(pRExC_state, cl);
968         }
969
970         /* And, we can just take the union of the flags that aren't affected
971          * by the inversion */
972         cl->flags |= or_with->flags & INVERSION_UNAFFECTED_FLAGS;
973
974         /* For the remaining flags:
975             ANYOF_UNICODE_ALL and inverted means to not match anything above
976                     255, which means that the union with cl should just be
977                     what cl has in it, so can ignore this flag
978             ANYOF_NON_UTF8_LATIN1_ALL and inverted means if not utf8 and ord
979                     is 127-255 to match them, but then invert that, so the
980                     union with cl should just be what cl has in it, so can
981                     ignore this flag
982          */
983     } else {    /* 'or_with' is not inverted */
984         /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
985         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
986              && (!(or_with->flags & ANYOF_LOC_FOLD)
987                  || (cl->flags & ANYOF_LOC_FOLD)) ) {
988             int i;
989
990             /* OR char bitmap and class bitmap separately */
991             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
992                 cl->bitmap[i] |= or_with->bitmap[i];
993             ANYOF_CLASS_OR(or_with, cl);
994         }
995         else { /* XXXX: logic is complicated, leave it along for a moment. */
996             cl_anything(pRExC_state, cl);
997         }
998
999         if (ANYOF_NONBITMAP(or_with)) {
1000
1001             /* Use the added node's outside-the-bit-map match if there isn't a
1002              * conflict.  If there is a conflict (both nodes match something
1003              * outside the bitmap, but what they match outside is not the same
1004              * pointer, and hence not easily compared until XXX we extend
1005              * inversion lists this far), give up and allow the start class to
1006              * match everything outside the bitmap.  If that stuff is all above
1007              * 255, can just set UNICODE_ALL, otherwise caould be anything. */
1008             if (! ANYOF_NONBITMAP(cl)) {
1009                 ARG_SET(cl, ARG(or_with));
1010             }
1011             else if (ARG(cl) != ARG(or_with)) {
1012
1013                 if ((or_with->flags & ANYOF_NONBITMAP_NON_UTF8)) {
1014                     cl_anything(pRExC_state, cl);
1015                 }
1016                 else {
1017                     cl->flags |= ANYOF_UNICODE_ALL;
1018                 }
1019             }
1020         }
1021
1022         /* Take the union */
1023         cl->flags |= or_with->flags;
1024     }
1025 }
1026
1027 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1028 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
1029 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1030 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
1031
1032
1033 #ifdef DEBUGGING
1034 /*
1035    dump_trie(trie,widecharmap,revcharmap)
1036    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1037    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1038
1039    These routines dump out a trie in a somewhat readable format.
1040    The _interim_ variants are used for debugging the interim
1041    tables that are used to generate the final compressed
1042    representation which is what dump_trie expects.
1043
1044    Part of the reason for their existence is to provide a form
1045    of documentation as to how the different representations function.
1046
1047 */
1048
1049 /*
1050   Dumps the final compressed table form of the trie to Perl_debug_log.
1051   Used for debugging make_trie().
1052 */
1053
1054 STATIC void
1055 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1056             AV *revcharmap, U32 depth)
1057 {
1058     U32 state;
1059     SV *sv=sv_newmortal();
1060     int colwidth= widecharmap ? 6 : 4;
1061     U16 word;
1062     GET_RE_DEBUG_FLAGS_DECL;
1063
1064     PERL_ARGS_ASSERT_DUMP_TRIE;
1065
1066     PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1067         (int)depth * 2 + 2,"",
1068         "Match","Base","Ofs" );
1069
1070     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1071         SV ** const tmp = av_fetch( revcharmap, state, 0);
1072         if ( tmp ) {
1073             PerlIO_printf( Perl_debug_log, "%*s", 
1074                 colwidth,
1075                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1076                             PL_colors[0], PL_colors[1],
1077                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1078                             PERL_PV_ESCAPE_FIRSTCHAR 
1079                 ) 
1080             );
1081         }
1082     }
1083     PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1084         (int)depth * 2 + 2,"");
1085
1086     for( state = 0 ; state < trie->uniquecharcount ; state++ )
1087         PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1088     PerlIO_printf( Perl_debug_log, "\n");
1089
1090     for( state = 1 ; state < trie->statecount ; state++ ) {
1091         const U32 base = trie->states[ state ].trans.base;
1092
1093         PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
1094
1095         if ( trie->states[ state ].wordnum ) {
1096             PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
1097         } else {
1098             PerlIO_printf( Perl_debug_log, "%6s", "" );
1099         }
1100
1101         PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1102
1103         if ( base ) {
1104             U32 ofs = 0;
1105
1106             while( ( base + ofs  < trie->uniquecharcount ) ||
1107                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
1108                      && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
1109                     ofs++;
1110
1111             PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1112
1113             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1114                 if ( ( base + ofs >= trie->uniquecharcount ) &&
1115                      ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1116                      trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1117                 {
1118                    PerlIO_printf( Perl_debug_log, "%*"UVXf,
1119                     colwidth,
1120                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
1121                 } else {
1122                     PerlIO_printf( Perl_debug_log, "%*s",colwidth,"   ." );
1123                 }
1124             }
1125
1126             PerlIO_printf( Perl_debug_log, "]");
1127
1128         }
1129         PerlIO_printf( Perl_debug_log, "\n" );
1130     }
1131     PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=", (int)depth*2, "");
1132     for (word=1; word <= trie->wordcount; word++) {
1133         PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
1134             (int)word, (int)(trie->wordinfo[word].prev),
1135             (int)(trie->wordinfo[word].len));
1136     }
1137     PerlIO_printf(Perl_debug_log, "\n" );
1138 }    
1139 /*
1140   Dumps a fully constructed but uncompressed trie in list form.
1141   List tries normally only are used for construction when the number of 
1142   possible chars (trie->uniquecharcount) is very high.
1143   Used for debugging make_trie().
1144 */
1145 STATIC void
1146 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
1147                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
1148                          U32 depth)
1149 {
1150     U32 state;
1151     SV *sv=sv_newmortal();
1152     int colwidth= widecharmap ? 6 : 4;
1153     GET_RE_DEBUG_FLAGS_DECL;
1154
1155     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1156
1157     /* print out the table precompression.  */
1158     PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1159         (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1160         "------:-----+-----------------\n" );
1161     
1162     for( state=1 ; state < next_alloc ; state ++ ) {
1163         U16 charid;
1164     
1165         PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
1166             (int)depth * 2 + 2,"", (UV)state  );
1167         if ( ! trie->states[ state ].wordnum ) {
1168             PerlIO_printf( Perl_debug_log, "%5s| ","");
1169         } else {
1170             PerlIO_printf( Perl_debug_log, "W%4x| ",
1171                 trie->states[ state ].wordnum
1172             );
1173         }
1174         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
1175             SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
1176             if ( tmp ) {
1177                 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1178                     colwidth,
1179                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1180                             PL_colors[0], PL_colors[1],
1181                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1182                             PERL_PV_ESCAPE_FIRSTCHAR 
1183                     ) ,
1184                     TRIE_LIST_ITEM(state,charid).forid,
1185                     (UV)TRIE_LIST_ITEM(state,charid).newstate
1186                 );
1187                 if (!(charid % 10)) 
1188                     PerlIO_printf(Perl_debug_log, "\n%*s| ",
1189                         (int)((depth * 2) + 14), "");
1190             }
1191         }
1192         PerlIO_printf( Perl_debug_log, "\n");
1193     }
1194 }    
1195
1196 /*
1197   Dumps a fully constructed but uncompressed trie in table form.
1198   This is the normal DFA style state transition table, with a few 
1199   twists to facilitate compression later. 
1200   Used for debugging make_trie().
1201 */
1202 STATIC void
1203 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
1204                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
1205                           U32 depth)
1206 {
1207     U32 state;
1208     U16 charid;
1209     SV *sv=sv_newmortal();
1210     int colwidth= widecharmap ? 6 : 4;
1211     GET_RE_DEBUG_FLAGS_DECL;
1212
1213     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
1214     
1215     /*
1216        print out the table precompression so that we can do a visual check
1217        that they are identical.
1218      */
1219     
1220     PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1221
1222     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1223         SV ** const tmp = av_fetch( revcharmap, charid, 0);
1224         if ( tmp ) {
1225             PerlIO_printf( Perl_debug_log, "%*s", 
1226                 colwidth,
1227                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1228                             PL_colors[0], PL_colors[1],
1229                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1230                             PERL_PV_ESCAPE_FIRSTCHAR 
1231                 ) 
1232             );
1233         }
1234     }
1235
1236     PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1237
1238     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1239         PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1240     }
1241
1242     PerlIO_printf( Perl_debug_log, "\n" );
1243
1244     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1245
1246         PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ", 
1247             (int)depth * 2 + 2,"",
1248             (UV)TRIE_NODENUM( state ) );
1249
1250         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1251             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1252             if (v)
1253                 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1254             else
1255                 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1256         }
1257         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1258             PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1259         } else {
1260             PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1261             trie->states[ TRIE_NODENUM( state ) ].wordnum );
1262         }
1263     }
1264 }
1265
1266 #endif
1267
1268
1269 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1270   startbranch: the first branch in the whole branch sequence
1271   first      : start branch of sequence of branch-exact nodes.
1272                May be the same as startbranch
1273   last       : Thing following the last branch.
1274                May be the same as tail.
1275   tail       : item following the branch sequence
1276   count      : words in the sequence
1277   flags      : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1278   depth      : indent depth
1279
1280 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1281
1282 A trie is an N'ary tree where the branches are determined by digital
1283 decomposition of the key. IE, at the root node you look up the 1st character and
1284 follow that branch repeat until you find the end of the branches. Nodes can be
1285 marked as "accepting" meaning they represent a complete word. Eg:
1286
1287   /he|she|his|hers/
1288
1289 would convert into the following structure. Numbers represent states, letters
1290 following numbers represent valid transitions on the letter from that state, if
1291 the number is in square brackets it represents an accepting state, otherwise it
1292 will be in parenthesis.
1293
1294       +-h->+-e->[3]-+-r->(8)-+-s->[9]
1295       |    |
1296       |   (2)
1297       |    |
1298      (1)   +-i->(6)-+-s->[7]
1299       |
1300       +-s->(3)-+-h->(4)-+-e->[5]
1301
1302       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1303
1304 This shows that when matching against the string 'hers' we will begin at state 1
1305 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1306 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1307 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1308 single traverse. We store a mapping from accepting to state to which word was
1309 matched, and then when we have multiple possibilities we try to complete the
1310 rest of the regex in the order in which they occured in the alternation.
1311
1312 The only prior NFA like behaviour that would be changed by the TRIE support is
1313 the silent ignoring of duplicate alternations which are of the form:
1314
1315  / (DUPE|DUPE) X? (?{ ... }) Y /x
1316
1317 Thus EVAL blocks following a trie may be called a different number of times with
1318 and without the optimisation. With the optimisations dupes will be silently
1319 ignored. This inconsistent behaviour of EVAL type nodes is well established as
1320 the following demonstrates:
1321
1322  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1323
1324 which prints out 'word' three times, but
1325
1326  'words'=~/(word|word|word)(?{ print $1 })S/
1327
1328 which doesnt print it out at all. This is due to other optimisations kicking in.
1329
1330 Example of what happens on a structural level:
1331
1332 The regexp /(ac|ad|ab)+/ will produce the following debug output:
1333
1334    1: CURLYM[1] {1,32767}(18)
1335    5:   BRANCH(8)
1336    6:     EXACT <ac>(16)
1337    8:   BRANCH(11)
1338    9:     EXACT <ad>(16)
1339   11:   BRANCH(14)
1340   12:     EXACT <ab>(16)
1341   16:   SUCCEED(0)
1342   17:   NOTHING(18)
1343   18: END(0)
1344
1345 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1346 and should turn into:
1347
1348    1: CURLYM[1] {1,32767}(18)
1349    5:   TRIE(16)
1350         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1351           <ac>
1352           <ad>
1353           <ab>
1354   16:   SUCCEED(0)
1355   17:   NOTHING(18)
1356   18: END(0)
1357
1358 Cases where tail != last would be like /(?foo|bar)baz/:
1359
1360    1: BRANCH(4)
1361    2:   EXACT <foo>(8)
1362    4: BRANCH(7)
1363    5:   EXACT <bar>(8)
1364    7: TAIL(8)
1365    8: EXACT <baz>(10)
1366   10: END(0)
1367
1368 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1369 and would end up looking like:
1370
1371     1: TRIE(8)
1372       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1373         <foo>
1374         <bar>
1375    7: TAIL(8)
1376    8: EXACT <baz>(10)
1377   10: END(0)
1378
1379     d = uvuni_to_utf8_flags(d, uv, 0);
1380
1381 is the recommended Unicode-aware way of saying
1382
1383     *(d++) = uv;
1384 */
1385
1386 #define TRIE_STORE_REVCHAR(val)                                            \
1387     STMT_START {                                                           \
1388         if (UTF) {                                                         \
1389             SV *zlopp = newSV(7); /* XXX: optimize me */                   \
1390             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
1391             unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, val); \
1392             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
1393             SvPOK_on(zlopp);                                               \
1394             SvUTF8_on(zlopp);                                              \
1395             av_push(revcharmap, zlopp);                                    \
1396         } else {                                                           \
1397             char ooooff = (char)val;                                           \
1398             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
1399         }                                                                  \
1400         } STMT_END
1401
1402 #define TRIE_READ_CHAR STMT_START {                                                     \
1403     wordlen++;                                                                          \
1404     if ( UTF ) {                                                                        \
1405         /* if it is UTF then it is either already folded, or does not need folding */   \
1406         uvc = utf8n_to_uvuni( (const U8*) uc, UTF8_MAXLEN, &len, uniflags);             \
1407     }                                                                                   \
1408     else if (folder == PL_fold_latin1) {                                                \
1409         /* if we use this folder we have to obey unicode rules on latin-1 data */       \
1410         if ( foldlen > 0 ) {                                                            \
1411            uvc = utf8n_to_uvuni( (const U8*) scan, UTF8_MAXLEN, &len, uniflags );       \
1412            foldlen -= len;                                                              \
1413            scan += len;                                                                 \
1414            len = 0;                                                                     \
1415         } else {                                                                        \
1416             len = 1;                                                                    \
1417             uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, 1);                     \
1418             skiplen = UNISKIP(uvc);                                                     \
1419             foldlen -= skiplen;                                                         \
1420             scan = foldbuf + skiplen;                                                   \
1421         }                                                                               \
1422     } else {                                                                            \
1423         /* raw data, will be folded later if needed */                                  \
1424         uvc = (U32)*uc;                                                                 \
1425         len = 1;                                                                        \
1426     }                                                                                   \
1427 } STMT_END
1428
1429
1430
1431 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
1432     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
1433         U32 ging = TRIE_LIST_LEN( state ) *= 2;                 \
1434         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1435     }                                                           \
1436     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
1437     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
1438     TRIE_LIST_CUR( state )++;                                   \
1439 } STMT_END
1440
1441 #define TRIE_LIST_NEW(state) STMT_START {                       \
1442     Newxz( trie->states[ state ].trans.list,               \
1443         4, reg_trie_trans_le );                                 \
1444      TRIE_LIST_CUR( state ) = 1;                                \
1445      TRIE_LIST_LEN( state ) = 4;                                \
1446 } STMT_END
1447
1448 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
1449     U16 dupe= trie->states[ state ].wordnum;                    \
1450     regnode * const noper_next = regnext( noper );              \
1451                                                                 \
1452     DEBUG_r({                                                   \
1453         /* store the word for dumping */                        \
1454         SV* tmp;                                                \
1455         if (OP(noper) != NOTHING)                               \
1456             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
1457         else                                                    \
1458             tmp = newSVpvn_utf8( "", 0, UTF );                  \
1459         av_push( trie_words, tmp );                             \
1460     });                                                         \
1461                                                                 \
1462     curword++;                                                  \
1463     trie->wordinfo[curword].prev   = 0;                         \
1464     trie->wordinfo[curword].len    = wordlen;                   \
1465     trie->wordinfo[curword].accept = state;                     \
1466                                                                 \
1467     if ( noper_next < tail ) {                                  \
1468         if (!trie->jump)                                        \
1469             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1470         trie->jump[curword] = (U16)(noper_next - convert);      \
1471         if (!jumper)                                            \
1472             jumper = noper_next;                                \
1473         if (!nextbranch)                                        \
1474             nextbranch= regnext(cur);                           \
1475     }                                                           \
1476                                                                 \
1477     if ( dupe ) {                                               \
1478         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
1479         /* chain, so that when the bits of chain are later    */\
1480         /* linked together, the dups appear in the chain      */\
1481         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1482         trie->wordinfo[dupe].prev = curword;                    \
1483     } else {                                                    \
1484         /* we haven't inserted this word yet.                */ \
1485         trie->states[ state ].wordnum = curword;                \
1486     }                                                           \
1487 } STMT_END
1488
1489
1490 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
1491      ( ( base + charid >=  ucharcount                                   \
1492          && base + charid < ubound                                      \
1493          && state == trie->trans[ base - ucharcount + charid ].check    \
1494          && trie->trans[ base - ucharcount + charid ].next )            \
1495            ? trie->trans[ base - ucharcount + charid ].next             \
1496            : ( state==1 ? special : 0 )                                 \
1497       )
1498
1499 #define MADE_TRIE       1
1500 #define MADE_JUMP_TRIE  2
1501 #define MADE_EXACT_TRIE 4
1502
1503 STATIC I32
1504 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1505 {
1506     dVAR;
1507     /* first pass, loop through and scan words */
1508     reg_trie_data *trie;
1509     HV *widecharmap = NULL;
1510     AV *revcharmap = newAV();
1511     regnode *cur;
1512     const U32 uniflags = UTF8_ALLOW_DEFAULT;
1513     STRLEN len = 0;
1514     UV uvc = 0;
1515     U16 curword = 0;
1516     U32 next_alloc = 0;
1517     regnode *jumper = NULL;
1518     regnode *nextbranch = NULL;
1519     regnode *convert = NULL;
1520     U32 *prev_states; /* temp array mapping each state to previous one */
1521     /* we just use folder as a flag in utf8 */
1522     const U8 * folder = NULL;
1523
1524 #ifdef DEBUGGING
1525     const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1526     AV *trie_words = NULL;
1527     /* along with revcharmap, this only used during construction but both are
1528      * useful during debugging so we store them in the struct when debugging.
1529      */
1530 #else
1531     const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1532     STRLEN trie_charcount=0;
1533 #endif
1534     SV *re_trie_maxbuff;
1535     GET_RE_DEBUG_FLAGS_DECL;
1536
1537     PERL_ARGS_ASSERT_MAKE_TRIE;
1538 #ifndef DEBUGGING
1539     PERL_UNUSED_ARG(depth);
1540 #endif
1541
1542     switch (flags) {
1543         case EXACT: break;
1544         case EXACTFA:
1545         case EXACTFU_SS:
1546         case EXACTFU_TRICKYFOLD:
1547         case EXACTFU: folder = PL_fold_latin1; break;
1548         case EXACTF:  folder = PL_fold; break;
1549         case EXACTFL: folder = PL_fold_locale; break;
1550         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
1551     }
1552
1553     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1554     trie->refcount = 1;
1555     trie->startstate = 1;
1556     trie->wordcount = word_count;
1557     RExC_rxi->data->data[ data_slot ] = (void*)trie;
1558     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1559     if (flags == EXACT)
1560         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1561     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
1562                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
1563
1564     DEBUG_r({
1565         trie_words = newAV();
1566     });
1567
1568     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1569     if (!SvIOK(re_trie_maxbuff)) {
1570         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1571     }
1572     DEBUG_TRIE_COMPILE_r({
1573                 PerlIO_printf( Perl_debug_log,
1574                   "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1575                   (int)depth * 2 + 2, "", 
1576                   REG_NODE_NUM(startbranch),REG_NODE_NUM(first), 
1577                   REG_NODE_NUM(last), REG_NODE_NUM(tail),
1578                   (int)depth);
1579     });
1580    
1581    /* Find the node we are going to overwrite */
1582     if ( first == startbranch && OP( last ) != BRANCH ) {
1583         /* whole branch chain */
1584         convert = first;
1585     } else {
1586         /* branch sub-chain */
1587         convert = NEXTOPER( first );
1588     }
1589         
1590     /*  -- First loop and Setup --
1591
1592        We first traverse the branches and scan each word to determine if it
1593        contains widechars, and how many unique chars there are, this is
1594        important as we have to build a table with at least as many columns as we
1595        have unique chars.
1596
1597        We use an array of integers to represent the character codes 0..255
1598        (trie->charmap) and we use a an HV* to store Unicode characters. We use the
1599        native representation of the character value as the key and IV's for the
1600        coded index.
1601
1602        *TODO* If we keep track of how many times each character is used we can
1603        remap the columns so that the table compression later on is more
1604        efficient in terms of memory by ensuring the most common value is in the
1605        middle and the least common are on the outside.  IMO this would be better
1606        than a most to least common mapping as theres a decent chance the most
1607        common letter will share a node with the least common, meaning the node
1608        will not be compressible. With a middle is most common approach the worst
1609        case is when we have the least common nodes twice.
1610
1611      */
1612
1613     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1614         regnode *noper = NEXTOPER( cur );
1615         const U8 *uc = (U8*)STRING( noper );
1616         const U8 *e  = uc + STR_LEN( noper );
1617         STRLEN foldlen = 0;
1618         U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1619         STRLEN skiplen = 0;
1620         const U8 *scan = (U8*)NULL;
1621         U32 wordlen      = 0;         /* required init */
1622         STRLEN chars = 0;
1623         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
1624
1625         if (OP(noper) == NOTHING) {
1626             regnode *noper_next= regnext(noper);
1627             if (noper_next != tail && OP(noper_next) == flags) {
1628                 noper = noper_next;
1629                 uc= (U8*)STRING(noper);
1630                 e= uc + STR_LEN(noper);
1631                 trie->minlen= STR_LEN(noper);
1632             } else {
1633                 trie->minlen= 0;
1634                 continue;
1635             }
1636         }
1637
1638         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
1639             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1640                                           regardless of encoding */
1641             if (OP( noper ) == EXACTFU_SS) {
1642                 /* false positives are ok, so just set this */
1643                 TRIE_BITMAP_SET(trie,0xDF);
1644             }
1645         }
1646         for ( ; uc < e ; uc += len ) {
1647             TRIE_CHARCOUNT(trie)++;
1648             TRIE_READ_CHAR;
1649             chars++;
1650             if ( uvc < 256 ) {
1651                 if ( folder ) {
1652                     U8 folded= folder[ (U8) uvc ];
1653                     if ( !trie->charmap[ folded ] ) {
1654                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
1655                         TRIE_STORE_REVCHAR( folded );
1656                     }
1657                 }
1658                 if ( !trie->charmap[ uvc ] ) {
1659                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1660                     TRIE_STORE_REVCHAR( uvc );
1661                 }
1662                 if ( set_bit ) {
1663                     /* store the codepoint in the bitmap, and its folded
1664                      * equivalent. */
1665                     TRIE_BITMAP_SET(trie, uvc);
1666
1667                     /* store the folded codepoint */
1668                     if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
1669
1670                     if ( !UTF ) {
1671                         /* store first byte of utf8 representation of
1672                            variant codepoints */
1673                         if (! UNI_IS_INVARIANT(uvc)) {
1674                             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
1675                         }
1676                     }
1677                     set_bit = 0; /* We've done our bit :-) */
1678                 }
1679             } else {
1680                 SV** svpp;
1681                 if ( !widecharmap )
1682                     widecharmap = newHV();
1683
1684                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1685
1686                 if ( !svpp )
1687                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1688
1689                 if ( !SvTRUE( *svpp ) ) {
1690                     sv_setiv( *svpp, ++trie->uniquecharcount );
1691                     TRIE_STORE_REVCHAR(uvc);
1692                 }
1693             }
1694         }
1695         if( cur == first ) {
1696             trie->minlen = chars;
1697             trie->maxlen = chars;
1698         } else if (chars < trie->minlen) {
1699             trie->minlen = chars;
1700         } else if (chars > trie->maxlen) {
1701             trie->maxlen = chars;
1702         }
1703         if (OP( noper ) == EXACTFU_SS) {
1704             /* XXX: workaround - 'ss' could match "\x{DF}" so minlen could be 1 and not 2*/
1705             if (trie->minlen > 1)
1706                 trie->minlen= 1;
1707         }
1708         if (OP( noper ) == EXACTFU_TRICKYFOLD) {
1709             /* XXX: workround - things like "\x{1FBE}\x{0308}\x{0301}" can match "\x{0390}" 
1710              *                - We assume that any such sequence might match a 2 byte string */
1711             if (trie->minlen > 2 )
1712                 trie->minlen= 2;
1713         }
1714
1715     } /* end first pass */
1716     DEBUG_TRIE_COMPILE_r(
1717         PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1718                 (int)depth * 2 + 2,"",
1719                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1720                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1721                 (int)trie->minlen, (int)trie->maxlen )
1722     );
1723
1724     /*
1725         We now know what we are dealing with in terms of unique chars and
1726         string sizes so we can calculate how much memory a naive
1727         representation using a flat table  will take. If it's over a reasonable
1728         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1729         conservative but potentially much slower representation using an array
1730         of lists.
1731
1732         At the end we convert both representations into the same compressed
1733         form that will be used in regexec.c for matching with. The latter
1734         is a form that cannot be used to construct with but has memory
1735         properties similar to the list form and access properties similar
1736         to the table form making it both suitable for fast searches and
1737         small enough that its feasable to store for the duration of a program.
1738
1739         See the comment in the code where the compressed table is produced
1740         inplace from the flat tabe representation for an explanation of how
1741         the compression works.
1742
1743     */
1744
1745
1746     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
1747     prev_states[1] = 0;
1748
1749     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1750         /*
1751             Second Pass -- Array Of Lists Representation
1752
1753             Each state will be represented by a list of charid:state records
1754             (reg_trie_trans_le) the first such element holds the CUR and LEN
1755             points of the allocated array. (See defines above).
1756
1757             We build the initial structure using the lists, and then convert
1758             it into the compressed table form which allows faster lookups
1759             (but cant be modified once converted).
1760         */
1761
1762         STRLEN transcount = 1;
1763
1764         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1765             "%*sCompiling trie using list compiler\n",
1766             (int)depth * 2 + 2, ""));
1767
1768         trie->states = (reg_trie_state *)
1769             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1770                                   sizeof(reg_trie_state) );
1771         TRIE_LIST_NEW(1);
1772         next_alloc = 2;
1773
1774         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1775
1776             regnode *noper   = NEXTOPER( cur );
1777             U8 *uc           = (U8*)STRING( noper );
1778             const U8 *e      = uc + STR_LEN( noper );
1779             U32 state        = 1;         /* required init */
1780             U16 charid       = 0;         /* sanity init */
1781             U8 *scan         = (U8*)NULL; /* sanity init */
1782             STRLEN foldlen   = 0;         /* required init */
1783             U32 wordlen      = 0;         /* required init */
1784             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1785             STRLEN skiplen   = 0;
1786
1787             if (OP(noper) == NOTHING) {
1788                 regnode *noper_next= regnext(noper);
1789                 if (noper_next != tail && OP(noper_next) == flags) {
1790                     noper = noper_next;
1791                     uc= (U8*)STRING(noper);
1792                     e= uc + STR_LEN(noper);
1793                 }
1794             }
1795
1796             if (OP(noper) != NOTHING) {
1797                 for ( ; uc < e ; uc += len ) {
1798
1799                     TRIE_READ_CHAR;
1800
1801                     if ( uvc < 256 ) {
1802                         charid = trie->charmap[ uvc ];
1803                     } else {
1804                         SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1805                         if ( !svpp ) {
1806                             charid = 0;
1807                         } else {
1808                             charid=(U16)SvIV( *svpp );
1809                         }
1810                     }
1811                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
1812                     if ( charid ) {
1813
1814                         U16 check;
1815                         U32 newstate = 0;
1816
1817                         charid--;
1818                         if ( !trie->states[ state ].trans.list ) {
1819                             TRIE_LIST_NEW( state );
1820                         }
1821                         for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1822                             if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1823                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1824                                 break;
1825                             }
1826                         }
1827                         if ( ! newstate ) {
1828                             newstate = next_alloc++;
1829                             prev_states[newstate] = state;
1830                             TRIE_LIST_PUSH( state, charid, newstate );
1831                             transcount++;
1832                         }
1833                         state = newstate;
1834                     } else {
1835                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1836                     }
1837                 }
1838             }
1839             TRIE_HANDLE_WORD(state);
1840
1841         } /* end second pass */
1842
1843         /* next alloc is the NEXT state to be allocated */
1844         trie->statecount = next_alloc; 
1845         trie->states = (reg_trie_state *)
1846             PerlMemShared_realloc( trie->states,
1847                                    next_alloc
1848                                    * sizeof(reg_trie_state) );
1849
1850         /* and now dump it out before we compress it */
1851         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1852                                                          revcharmap, next_alloc,
1853                                                          depth+1)
1854         );
1855
1856         trie->trans = (reg_trie_trans *)
1857             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1858         {
1859             U32 state;
1860             U32 tp = 0;
1861             U32 zp = 0;
1862
1863
1864             for( state=1 ; state < next_alloc ; state ++ ) {
1865                 U32 base=0;
1866
1867                 /*
1868                 DEBUG_TRIE_COMPILE_MORE_r(
1869                     PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1870                 );
1871                 */
1872
1873                 if (trie->states[state].trans.list) {
1874                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1875                     U16 maxid=minid;
1876                     U16 idx;
1877
1878                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1879                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1880                         if ( forid < minid ) {
1881                             minid=forid;
1882                         } else if ( forid > maxid ) {
1883                             maxid=forid;
1884                         }
1885                     }
1886                     if ( transcount < tp + maxid - minid + 1) {
1887                         transcount *= 2;
1888                         trie->trans = (reg_trie_trans *)
1889                             PerlMemShared_realloc( trie->trans,
1890                                                      transcount
1891                                                      * sizeof(reg_trie_trans) );
1892                         Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1893                     }
1894                     base = trie->uniquecharcount + tp - minid;
1895                     if ( maxid == minid ) {
1896                         U32 set = 0;
1897                         for ( ; zp < tp ; zp++ ) {
1898                             if ( ! trie->trans[ zp ].next ) {
1899                                 base = trie->uniquecharcount + zp - minid;
1900                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1901                                 trie->trans[ zp ].check = state;
1902                                 set = 1;
1903                                 break;
1904                             }
1905                         }
1906                         if ( !set ) {
1907                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1908                             trie->trans[ tp ].check = state;
1909                             tp++;
1910                             zp = tp;
1911                         }
1912                     } else {
1913                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1914                             const U32 tid = base -  trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1915                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1916                             trie->trans[ tid ].check = state;
1917                         }
1918                         tp += ( maxid - minid + 1 );
1919                     }
1920                     Safefree(trie->states[ state ].trans.list);
1921                 }
1922                 /*
1923                 DEBUG_TRIE_COMPILE_MORE_r(
1924                     PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1925                 );
1926                 */
1927                 trie->states[ state ].trans.base=base;
1928             }
1929             trie->lasttrans = tp + 1;
1930         }
1931     } else {
1932         /*
1933            Second Pass -- Flat Table Representation.
1934
1935            we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1936            We know that we will need Charcount+1 trans at most to store the data
1937            (one row per char at worst case) So we preallocate both structures
1938            assuming worst case.
1939
1940            We then construct the trie using only the .next slots of the entry
1941            structs.
1942
1943            We use the .check field of the first entry of the node temporarily to
1944            make compression both faster and easier by keeping track of how many non
1945            zero fields are in the node.
1946
1947            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1948            transition.
1949
1950            There are two terms at use here: state as a TRIE_NODEIDX() which is a
1951            number representing the first entry of the node, and state as a
1952            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1953            TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1954            are 2 entrys per node. eg:
1955
1956              A B       A B
1957           1. 2 4    1. 3 7
1958           2. 0 3    3. 0 5
1959           3. 0 0    5. 0 0
1960           4. 0 0    7. 0 0
1961
1962            The table is internally in the right hand, idx form. However as we also
1963            have to deal with the states array which is indexed by nodenum we have to
1964            use TRIE_NODENUM() to convert.
1965
1966         */
1967         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1968             "%*sCompiling trie using table compiler\n",
1969             (int)depth * 2 + 2, ""));
1970
1971         trie->trans = (reg_trie_trans *)
1972             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1973                                   * trie->uniquecharcount + 1,
1974                                   sizeof(reg_trie_trans) );
1975         trie->states = (reg_trie_state *)
1976             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1977                                   sizeof(reg_trie_state) );
1978         next_alloc = trie->uniquecharcount + 1;
1979
1980
1981         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1982
1983             regnode *noper   = NEXTOPER( cur );
1984             const U8 *uc     = (U8*)STRING( noper );
1985             const U8 *e      = uc + STR_LEN( noper );
1986
1987             U32 state        = 1;         /* required init */
1988
1989             U16 charid       = 0;         /* sanity init */
1990             U32 accept_state = 0;         /* sanity init */
1991             U8 *scan         = (U8*)NULL; /* sanity init */
1992
1993             STRLEN foldlen   = 0;         /* required init */
1994             U32 wordlen      = 0;         /* required init */
1995             STRLEN skiplen   = 0;
1996             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1997
1998             if (OP(noper) == NOTHING) {
1999                 regnode *noper_next= regnext(noper);
2000                 if (noper_next != tail && OP(noper_next) == flags) {
2001                     noper = noper_next;
2002                     uc= (U8*)STRING(noper);
2003                     e= uc + STR_LEN(noper);
2004                 }
2005             }
2006
2007             if ( OP(noper) != NOTHING ) {
2008                 for ( ; uc < e ; uc += len ) {
2009
2010                     TRIE_READ_CHAR;
2011
2012                     if ( uvc < 256 ) {
2013                         charid = trie->charmap[ uvc ];
2014                     } else {
2015                         SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
2016                         charid = svpp ? (U16)SvIV(*svpp) : 0;
2017                     }
2018                     if ( charid ) {
2019                         charid--;
2020                         if ( !trie->trans[ state + charid ].next ) {
2021                             trie->trans[ state + charid ].next = next_alloc;
2022                             trie->trans[ state ].check++;
2023                             prev_states[TRIE_NODENUM(next_alloc)]
2024                                     = TRIE_NODENUM(state);
2025                             next_alloc += trie->uniquecharcount;
2026                         }
2027                         state = trie->trans[ state + charid ].next;
2028                     } else {
2029                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2030                     }
2031                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
2032                 }
2033             }
2034             accept_state = TRIE_NODENUM( state );
2035             TRIE_HANDLE_WORD(accept_state);
2036
2037         } /* end second pass */
2038
2039         /* and now dump it out before we compress it */
2040         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
2041                                                           revcharmap,
2042                                                           next_alloc, depth+1));
2043
2044         {
2045         /*
2046            * Inplace compress the table.*
2047
2048            For sparse data sets the table constructed by the trie algorithm will
2049            be mostly 0/FAIL transitions or to put it another way mostly empty.
2050            (Note that leaf nodes will not contain any transitions.)
2051
2052            This algorithm compresses the tables by eliminating most such
2053            transitions, at the cost of a modest bit of extra work during lookup:
2054
2055            - Each states[] entry contains a .base field which indicates the
2056            index in the state[] array wheres its transition data is stored.
2057
2058            - If .base is 0 there are no valid transitions from that node.
2059
2060            - If .base is nonzero then charid is added to it to find an entry in
2061            the trans array.
2062
2063            -If trans[states[state].base+charid].check!=state then the
2064            transition is taken to be a 0/Fail transition. Thus if there are fail
2065            transitions at the front of the node then the .base offset will point
2066            somewhere inside the previous nodes data (or maybe even into a node
2067            even earlier), but the .check field determines if the transition is
2068            valid.
2069
2070            XXX - wrong maybe?
2071            The following process inplace converts the table to the compressed
2072            table: We first do not compress the root node 1,and mark all its
2073            .check pointers as 1 and set its .base pointer as 1 as well. This
2074            allows us to do a DFA construction from the compressed table later,
2075            and ensures that any .base pointers we calculate later are greater
2076            than 0.
2077
2078            - We set 'pos' to indicate the first entry of the second node.
2079
2080            - We then iterate over the columns of the node, finding the first and
2081            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
2082            and set the .check pointers accordingly, and advance pos
2083            appropriately and repreat for the next node. Note that when we copy
2084            the next pointers we have to convert them from the original
2085            NODEIDX form to NODENUM form as the former is not valid post
2086            compression.
2087
2088            - If a node has no transitions used we mark its base as 0 and do not
2089            advance the pos pointer.
2090
2091            - If a node only has one transition we use a second pointer into the
2092            structure to fill in allocated fail transitions from other states.
2093            This pointer is independent of the main pointer and scans forward
2094            looking for null transitions that are allocated to a state. When it
2095            finds one it writes the single transition into the "hole".  If the
2096            pointer doesnt find one the single transition is appended as normal.
2097
2098            - Once compressed we can Renew/realloc the structures to release the
2099            excess space.
2100
2101            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
2102            specifically Fig 3.47 and the associated pseudocode.
2103
2104            demq
2105         */
2106         const U32 laststate = TRIE_NODENUM( next_alloc );
2107         U32 state, charid;
2108         U32 pos = 0, zp=0;
2109         trie->statecount = laststate;
2110
2111         for ( state = 1 ; state < laststate ; state++ ) {
2112             U8 flag = 0;
2113             const U32 stateidx = TRIE_NODEIDX( state );
2114             const U32 o_used = trie->trans[ stateidx ].check;
2115             U32 used = trie->trans[ stateidx ].check;
2116             trie->trans[ stateidx ].check = 0;
2117
2118             for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
2119                 if ( flag || trie->trans[ stateidx + charid ].next ) {
2120                     if ( trie->trans[ stateidx + charid ].next ) {
2121                         if (o_used == 1) {
2122                             for ( ; zp < pos ; zp++ ) {
2123                                 if ( ! trie->trans[ zp ].next ) {
2124                                     break;
2125                                 }
2126                             }
2127                             trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
2128                             trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2129                             trie->trans[ zp ].check = state;
2130                             if ( ++zp > pos ) pos = zp;
2131                             break;
2132                         }
2133                         used--;
2134                     }
2135                     if ( !flag ) {
2136                         flag = 1;
2137                         trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
2138                     }
2139                     trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2140                     trie->trans[ pos ].check = state;
2141                     pos++;
2142                 }
2143             }
2144         }
2145         trie->lasttrans = pos + 1;
2146         trie->states = (reg_trie_state *)
2147             PerlMemShared_realloc( trie->states, laststate
2148                                    * sizeof(reg_trie_state) );
2149         DEBUG_TRIE_COMPILE_MORE_r(
2150                 PerlIO_printf( Perl_debug_log,
2151                     "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
2152                     (int)depth * 2 + 2,"",
2153                     (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
2154                     (IV)next_alloc,
2155                     (IV)pos,
2156                     ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
2157             );
2158
2159         } /* end table compress */
2160     }
2161     DEBUG_TRIE_COMPILE_MORE_r(
2162             PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
2163                 (int)depth * 2 + 2, "",
2164                 (UV)trie->statecount,
2165                 (UV)trie->lasttrans)
2166     );
2167     /* resize the trans array to remove unused space */
2168     trie->trans = (reg_trie_trans *)
2169         PerlMemShared_realloc( trie->trans, trie->lasttrans
2170                                * sizeof(reg_trie_trans) );
2171
2172     {   /* Modify the program and insert the new TRIE node */ 
2173         U8 nodetype =(U8)(flags & 0xFF);
2174         char *str=NULL;
2175         
2176 #ifdef DEBUGGING
2177         regnode *optimize = NULL;
2178 #ifdef RE_TRACK_PATTERN_OFFSETS
2179
2180         U32 mjd_offset = 0;
2181         U32 mjd_nodelen = 0;
2182 #endif /* RE_TRACK_PATTERN_OFFSETS */
2183 #endif /* DEBUGGING */
2184         /*
2185            This means we convert either the first branch or the first Exact,
2186            depending on whether the thing following (in 'last') is a branch
2187            or not and whther first is the startbranch (ie is it a sub part of
2188            the alternation or is it the whole thing.)
2189            Assuming its a sub part we convert the EXACT otherwise we convert
2190            the whole branch sequence, including the first.
2191          */
2192         /* Find the node we are going to overwrite */
2193         if ( first != startbranch || OP( last ) == BRANCH ) {
2194             /* branch sub-chain */
2195             NEXT_OFF( first ) = (U16)(last - first);
2196 #ifdef RE_TRACK_PATTERN_OFFSETS
2197             DEBUG_r({
2198                 mjd_offset= Node_Offset((convert));
2199                 mjd_nodelen= Node_Length((convert));
2200             });
2201 #endif
2202             /* whole branch chain */
2203         }
2204 #ifdef RE_TRACK_PATTERN_OFFSETS
2205         else {
2206             DEBUG_r({
2207                 const  regnode *nop = NEXTOPER( convert );
2208                 mjd_offset= Node_Offset((nop));
2209                 mjd_nodelen= Node_Length((nop));
2210             });
2211         }
2212         DEBUG_OPTIMISE_r(
2213             PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
2214                 (int)depth * 2 + 2, "",
2215                 (UV)mjd_offset, (UV)mjd_nodelen)
2216         );
2217 #endif
2218         /* But first we check to see if there is a common prefix we can 
2219            split out as an EXACT and put in front of the TRIE node.  */
2220         trie->startstate= 1;
2221         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
2222             U32 state;
2223             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
2224                 U32 ofs = 0;
2225                 I32 idx = -1;
2226                 U32 count = 0;
2227                 const U32 base = trie->states[ state ].trans.base;
2228
2229                 if ( trie->states[state].wordnum )
2230                         count = 1;
2231
2232                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2233                     if ( ( base + ofs >= trie->uniquecharcount ) &&
2234                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
2235                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2236                     {
2237                         if ( ++count > 1 ) {
2238                             SV **tmp = av_fetch( revcharmap, ofs, 0);
2239                             const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
2240                             if ( state == 1 ) break;
2241                             if ( count == 2 ) {
2242                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2243                                 DEBUG_OPTIMISE_r(
2244                                     PerlIO_printf(Perl_debug_log,
2245                                         "%*sNew Start State=%"UVuf" Class: [",
2246                                         (int)depth * 2 + 2, "",
2247                                         (UV)state));
2248                                 if (idx >= 0) {
2249                                     SV ** const tmp = av_fetch( revcharmap, idx, 0);
2250                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
2251
2252                                     TRIE_BITMAP_SET(trie,*ch);
2253                                     if ( folder )
2254                                         TRIE_BITMAP_SET(trie, folder[ *ch ]);
2255                                     DEBUG_OPTIMISE_r(
2256                                         PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
2257                                     );
2258                                 }
2259                             }
2260                             TRIE_BITMAP_SET(trie,*ch);
2261                             if ( folder )
2262                                 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2263                             DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2264                         }
2265                         idx = ofs;
2266                     }
2267                 }
2268                 if ( count == 1 ) {
2269                     SV **tmp = av_fetch( revcharmap, idx, 0);
2270                     STRLEN len;
2271                     char *ch = SvPV( *tmp, len );
2272                     DEBUG_OPTIMISE_r({
2273                         SV *sv=sv_newmortal();
2274                         PerlIO_printf( Perl_debug_log,
2275                             "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2276                             (int)depth * 2 + 2, "",
2277                             (UV)state, (UV)idx, 
2278                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6, 
2279                                 PL_colors[0], PL_colors[1],
2280                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2281                                 PERL_PV_ESCAPE_FIRSTCHAR 
2282                             )
2283                         );
2284                     });
2285                     if ( state==1 ) {
2286                         OP( convert ) = nodetype;
2287                         str=STRING(convert);
2288                         STR_LEN(convert)=0;
2289                     }
2290                     STR_LEN(convert) += len;
2291                     while (len--)
2292                         *str++ = *ch++;
2293                 } else {
2294 #ifdef DEBUGGING            
2295                     if (state>1)
2296                         DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
2297 #endif
2298                     break;
2299                 }
2300             }
2301             trie->prefixlen = (state-1);
2302             if (str) {
2303                 regnode *n = convert+NODE_SZ_STR(convert);
2304                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
2305                 trie->startstate = state;
2306                 trie->minlen -= (state - 1);
2307                 trie->maxlen -= (state - 1);
2308 #ifdef DEBUGGING
2309                /* At least the UNICOS C compiler choked on this
2310                 * being argument to DEBUG_r(), so let's just have
2311                 * it right here. */
2312                if (
2313 #ifdef PERL_EXT_RE_BUILD
2314                    1
2315 #else
2316                    DEBUG_r_TEST
2317 #endif
2318                    ) {
2319                    regnode *fix = convert;
2320                    U32 word = trie->wordcount;
2321                    mjd_nodelen++;
2322                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2323                    while( ++fix < n ) {
2324                        Set_Node_Offset_Length(fix, 0, 0);
2325                    }
2326                    while (word--) {
2327                        SV ** const tmp = av_fetch( trie_words, word, 0 );
2328                        if (tmp) {
2329                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
2330                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2331                            else
2332                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2333                        }
2334                    }
2335                }
2336 #endif
2337                 if (trie->maxlen) {
2338                     convert = n;
2339                 } else {
2340                     NEXT_OFF(convert) = (U16)(tail - convert);
2341                     DEBUG_r(optimize= n);
2342                 }
2343             }
2344         }
2345         if (!jumper) 
2346             jumper = last; 
2347         if ( trie->maxlen ) {
2348             NEXT_OFF( convert ) = (U16)(tail - convert);
2349             ARG_SET( convert, data_slot );
2350             /* Store the offset to the first unabsorbed branch in 
2351                jump[0], which is otherwise unused by the jump logic. 
2352                We use this when dumping a trie and during optimisation. */
2353             if (trie->jump) 
2354                 trie->jump[0] = (U16)(nextbranch - convert);
2355             
2356             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
2357              *   and there is a bitmap
2358              *   and the first "jump target" node we found leaves enough room
2359              * then convert the TRIE node into a TRIEC node, with the bitmap
2360              * embedded inline in the opcode - this is hypothetically faster.
2361              */
2362             if ( !trie->states[trie->startstate].wordnum
2363                  && trie->bitmap
2364                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2365             {
2366                 OP( convert ) = TRIEC;
2367                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2368                 PerlMemShared_free(trie->bitmap);
2369                 trie->bitmap= NULL;
2370             } else 
2371                 OP( convert ) = TRIE;
2372
2373             /* store the type in the flags */
2374             convert->flags = nodetype;
2375             DEBUG_r({
2376             optimize = convert 
2377                       + NODE_STEP_REGNODE 
2378                       + regarglen[ OP( convert ) ];
2379             });
2380             /* XXX We really should free up the resource in trie now, 
2381                    as we won't use them - (which resources?) dmq */
2382         }
2383         /* needed for dumping*/
2384         DEBUG_r(if (optimize) {
2385             regnode *opt = convert;
2386
2387             while ( ++opt < optimize) {
2388                 Set_Node_Offset_Length(opt,0,0);
2389             }
2390             /* 
2391                 Try to clean up some of the debris left after the 
2392                 optimisation.
2393              */
2394             while( optimize < jumper ) {
2395                 mjd_nodelen += Node_Length((optimize));
2396                 OP( optimize ) = OPTIMIZED;
2397                 Set_Node_Offset_Length(optimize,0,0);
2398                 optimize++;
2399             }
2400             Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2401         });
2402     } /* end node insert */
2403
2404     /*  Finish populating the prev field of the wordinfo array.  Walk back
2405      *  from each accept state until we find another accept state, and if
2406      *  so, point the first word's .prev field at the second word. If the
2407      *  second already has a .prev field set, stop now. This will be the
2408      *  case either if we've already processed that word's accept state,
2409      *  or that state had multiple words, and the overspill words were
2410      *  already linked up earlier.
2411      */
2412     {
2413         U16 word;
2414         U32 state;
2415         U16 prev;
2416
2417         for (word=1; word <= trie->wordcount; word++) {
2418             prev = 0;
2419             if (trie->wordinfo[word].prev)
2420                 continue;
2421             state = trie->wordinfo[word].accept;
2422             while (state) {
2423                 state = prev_states[state];
2424                 if (!state)
2425                     break;
2426                 prev = trie->states[state].wordnum;
2427                 if (prev)
2428                     break;
2429             }
2430             trie->wordinfo[word].prev = prev;
2431         }
2432         Safefree(prev_states);
2433     }
2434
2435
2436     /* and now dump out the compressed format */
2437     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2438
2439     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2440 #ifdef DEBUGGING
2441     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2442     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2443 #else
2444     SvREFCNT_dec_NN(revcharmap);
2445 #endif
2446     return trie->jump 
2447            ? MADE_JUMP_TRIE 
2448            : trie->startstate>1 
2449              ? MADE_EXACT_TRIE 
2450              : MADE_TRIE;
2451 }
2452
2453 STATIC void
2454 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source,  regnode *stclass, U32 depth)
2455 {
2456 /* The Trie is constructed and compressed now so we can build a fail array if it's needed
2457
2458    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2459    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2460    ISBN 0-201-10088-6
2461
2462    We find the fail state for each state in the trie, this state is the longest proper
2463    suffix of the current state's 'word' that is also a proper prefix of another word in our
2464    trie. State 1 represents the word '' and is thus the default fail state. This allows
2465    the DFA not to have to restart after its tried and failed a word at a given point, it
2466    simply continues as though it had been matching the other word in the first place.
2467    Consider
2468       'abcdgu'=~/abcdefg|cdgu/
2469    When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2470    fail, which would bring us to the state representing 'd' in the second word where we would
2471    try 'g' and succeed, proceeding to match 'cdgu'.
2472  */
2473  /* add a fail transition */
2474     const U32 trie_offset = ARG(source);
2475     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2476     U32 *q;
2477     const U32 ucharcount = trie->uniquecharcount;
2478     const U32 numstates = trie->statecount;
2479     const U32 ubound = trie->lasttrans + ucharcount;
2480     U32 q_read = 0;
2481     U32 q_write = 0;
2482     U32 charid;
2483     U32 base = trie->states[ 1 ].trans.base;
2484     U32 *fail;
2485     reg_ac_data *aho;
2486     const U32 data_slot = add_data( pRExC_state, 1, "T" );
2487     GET_RE_DEBUG_FLAGS_DECL;
2488
2489     PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
2490 #ifndef DEBUGGING
2491     PERL_UNUSED_ARG(depth);
2492 #endif
2493
2494
2495     ARG_SET( stclass, data_slot );
2496     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2497     RExC_rxi->data->data[ data_slot ] = (void*)aho;
2498     aho->trie=trie_offset;
2499     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2500     Copy( trie->states, aho->states, numstates, reg_trie_state );
2501     Newxz( q, numstates, U32);
2502     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2503     aho->refcount = 1;
2504     fail = aho->fail;
2505     /* initialize fail[0..1] to be 1 so that we always have
2506        a valid final fail state */
2507     fail[ 0 ] = fail[ 1 ] = 1;
2508
2509     for ( charid = 0; charid < ucharcount ; charid++ ) {
2510         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2511         if ( newstate ) {
2512             q[ q_write ] = newstate;
2513             /* set to point at the root */
2514             fail[ q[ q_write++ ] ]=1;
2515         }
2516     }
2517     while ( q_read < q_write) {
2518         const U32 cur = q[ q_read++ % numstates ];
2519         base = trie->states[ cur ].trans.base;
2520
2521         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2522             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2523             if (ch_state) {
2524                 U32 fail_state = cur;
2525                 U32 fail_base;
2526                 do {
2527                     fail_state = fail[ fail_state ];
2528                     fail_base = aho->states[ fail_state ].trans.base;
2529                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2530
2531                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2532                 fail[ ch_state ] = fail_state;
2533                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2534                 {
2535                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
2536                 }
2537                 q[ q_write++ % numstates] = ch_state;
2538             }
2539         }
2540     }
2541     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2542        when we fail in state 1, this allows us to use the
2543        charclass scan to find a valid start char. This is based on the principle
2544        that theres a good chance the string being searched contains lots of stuff
2545        that cant be a start char.
2546      */
2547     fail[ 0 ] = fail[ 1 ] = 0;
2548     DEBUG_TRIE_COMPILE_r({
2549         PerlIO_printf(Perl_debug_log,
2550                       "%*sStclass Failtable (%"UVuf" states): 0", 
2551                       (int)(depth * 2), "", (UV)numstates
2552         );
2553         for( q_read=1; q_read<numstates; q_read++ ) {
2554             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2555         }
2556         PerlIO_printf(Perl_debug_log, "\n");
2557     });
2558     Safefree(q);
2559     /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2560 }
2561
2562
2563 /*
2564  * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2565  * These need to be revisited when a newer toolchain becomes available.
2566  */
2567 #if defined(__sparc64__) && defined(__GNUC__)
2568 #   if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2569 #       undef  SPARC64_GCC_WORKAROUND
2570 #       define SPARC64_GCC_WORKAROUND 1
2571 #   endif
2572 #endif
2573
2574 #define DEBUG_PEEP(str,scan,depth) \
2575     DEBUG_OPTIMISE_r({if (scan){ \
2576        SV * const mysv=sv_newmortal(); \
2577        regnode *Next = regnext(scan); \
2578        regprop(RExC_rx, mysv, scan); \
2579        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2580        (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2581        Next ? (REG_NODE_NUM(Next)) : 0 ); \
2582    }});
2583
2584
2585 /* The below joins as many adjacent EXACTish nodes as possible into a single
2586  * one.  The regop may be changed if the node(s) contain certain sequences that
2587  * require special handling.  The joining is only done if:
2588  * 1) there is room in the current conglomerated node to entirely contain the
2589  *    next one.
2590  * 2) they are the exact same node type
2591  *
2592  * The adjacent nodes actually may be separated by NOTHING-kind nodes, and
2593  * these get optimized out
2594  *
2595  * If a node is to match under /i (folded), the number of characters it matches
2596  * can be different than its character length if it contains a multi-character
2597  * fold.  *min_subtract is set to the total delta of the input nodes.
2598  *
2599  * And *has_exactf_sharp_s is set to indicate whether or not the node is EXACTF
2600  * and contains LATIN SMALL LETTER SHARP S
2601  *
2602  * This is as good a place as any to discuss the design of handling these
2603  * multi-character fold sequences.  It's been wrong in Perl for a very long
2604  * time.  There are three code points in Unicode whose multi-character folds
2605  * were long ago discovered to mess things up.  The previous designs for
2606  * dealing with these involved assigning a special node for them.  This
2607  * approach doesn't work, as evidenced by this example:
2608  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
2609  * Both these fold to "sss", but if the pattern is parsed to create a node that
2610  * would match just the \xDF, it won't be able to handle the case where a
2611  * successful match would have to cross the node's boundary.  The new approach
2612  * that hopefully generally solves the problem generates an EXACTFU_SS node
2613  * that is "sss".
2614  *
2615  * It turns out that there are problems with all multi-character folds, and not
2616  * just these three.  Now the code is general, for all such cases, but the
2617  * three still have some special handling.  The approach taken is:
2618  * 1)   This routine examines each EXACTFish node that could contain multi-
2619  *      character fold sequences.  It returns in *min_subtract how much to
2620  *      subtract from the the actual length of the string to get a real minimum
2621  *      match length; it is 0 if there are no multi-char folds.  This delta is
2622  *      used by the caller to adjust the min length of the match, and the delta
2623  *      between min and max, so that the optimizer doesn't reject these
2624  *      possibilities based on size constraints.
2625  * 2)   Certain of these sequences require special handling by the trie code,
2626  *      so, if found, this code changes the joined node type to special ops:
2627  *      EXACTFU_TRICKYFOLD and EXACTFU_SS.
2628  * 3)   For the sequence involving the Sharp s (\xDF), the node type EXACTFU_SS
2629  *      is used for an EXACTFU node that contains at least one "ss" sequence in
2630  *      it.  For non-UTF-8 patterns and strings, this is the only case where
2631  *      there is a possible fold length change.  That means that a regular
2632  *      EXACTFU node without UTF-8 involvement doesn't have to concern itself
2633  *      with length changes, and so can be processed faster.  regexec.c takes
2634  *      advantage of this.  Generally, an EXACTFish node that is in UTF-8 is
2635  *      pre-folded by regcomp.c.  This saves effort in regex matching.
2636  *      However, the pre-folding isn't done for non-UTF8 patterns because the
2637  *      fold of the MICRO SIGN requires UTF-8, and we don't want to slow things
2638  *      down by forcing the pattern into UTF8 unless necessary.  Also what
2639  *      EXACTF and EXACTFL nodes fold to isn't known until runtime.  The fold
2640  *      possibilities for the non-UTF8 patterns are quite simple, except for
2641  *      the sharp s.  All the ones that don't involve a UTF-8 target string are
2642  *      members of a fold-pair, and arrays are set up for all of them so that
2643  *      the other member of the pair can be found quickly.  Code elsewhere in
2644  *      this file makes sure that in EXACTFU nodes, the sharp s gets folded to
2645  *      'ss', even if the pattern isn't UTF-8.  This avoids the issues
2646  *      described in the next item.
2647  * 4)   A problem remains for the sharp s in EXACTF nodes.  Whether it matches
2648  *      'ss' or not is not knowable at compile time.  It will match iff the
2649  *      target string is in UTF-8, unlike the EXACTFU nodes, where it always
2650  *      matches; and the EXACTFL and EXACTFA nodes where it never does.  Thus
2651  *      it can't be folded to "ss" at compile time, unlike EXACTFU does (as
2652  *      described in item 3).  An assumption that the optimizer part of
2653  *      regexec.c (probably unwittingly) makes is that a character in the
2654  *      pattern corresponds to at most a single character in the target string.
2655  *      (And I do mean character, and not byte here, unlike other parts of the
2656  *      documentation that have never been updated to account for multibyte
2657  *      Unicode.)  This assumption is wrong only in this case, as all other
2658  *      cases are either 1-1 folds when no UTF-8 is involved; or is true by
2659  *      virtue of having this file pre-fold UTF-8 patterns.   I'm
2660  *      reluctant to try to change this assumption, so instead the code punts.
2661  *      This routine examines EXACTF nodes for the sharp s, and returns a
2662  *      boolean indicating whether or not the node is an EXACTF node that
2663  *      contains a sharp s.  When it is true, the caller sets a flag that later
2664  *      causes the optimizer in this file to not set values for the floating
2665  *      and fixed string lengths, and thus avoids the optimizer code in
2666  *      regexec.c that makes the invalid assumption.  Thus, there is no
2667  *      optimization based on string lengths for EXACTF nodes that contain the
2668  *      sharp s.  This only happens for /id rules (which means the pattern
2669  *      isn't in UTF-8).
2670  */
2671
2672 #define JOIN_EXACT(scan,min_subtract,has_exactf_sharp_s, flags) \
2673     if (PL_regkind[OP(scan)] == EXACT) \
2674         join_exact(pRExC_state,(scan),(min_subtract),has_exactf_sharp_s, (flags),NULL,depth+1)
2675
2676 STATIC U32
2677 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) {
2678     /* Merge several consecutive EXACTish nodes into one. */
2679     regnode *n = regnext(scan);
2680     U32 stringok = 1;
2681     regnode *next = scan + NODE_SZ_STR(scan);
2682     U32 merged = 0;
2683     U32 stopnow = 0;
2684 #ifdef DEBUGGING
2685     regnode *stop = scan;
2686     GET_RE_DEBUG_FLAGS_DECL;
2687 #else
2688     PERL_UNUSED_ARG(depth);
2689 #endif
2690
2691     PERL_ARGS_ASSERT_JOIN_EXACT;
2692 #ifndef EXPERIMENTAL_INPLACESCAN
2693     PERL_UNUSED_ARG(flags);
2694     PERL_UNUSED_ARG(val);
2695 #endif
2696     DEBUG_PEEP("join",scan,depth);
2697
2698     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
2699      * EXACT ones that are mergeable to the current one. */
2700     while (n
2701            && (PL_regkind[OP(n)] == NOTHING
2702                || (stringok && OP(n) == OP(scan)))
2703            && NEXT_OFF(n)
2704            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
2705     {
2706         
2707         if (OP(n) == TAIL || n > next)
2708             stringok = 0;
2709         if (PL_regkind[OP(n)] == NOTHING) {
2710             DEBUG_PEEP("skip:",n,depth);
2711             NEXT_OFF(scan) += NEXT_OFF(n);
2712             next = n + NODE_STEP_REGNODE;
2713 #ifdef DEBUGGING
2714             if (stringok)
2715                 stop = n;
2716 #endif
2717             n = regnext(n);
2718         }
2719         else if (stringok) {
2720             const unsigned int oldl = STR_LEN(scan);
2721             regnode * const nnext = regnext(n);
2722
2723             /* XXX I (khw) kind of doubt that this works on platforms where
2724              * U8_MAX is above 255 because of lots of other assumptions */
2725             /* Don't join if the sum can't fit into a single node */
2726             if (oldl + STR_LEN(n) > U8_MAX)
2727                 break;
2728             
2729             DEBUG_PEEP("merg",n,depth);
2730             merged++;
2731
2732             NEXT_OFF(scan) += NEXT_OFF(n);
2733             STR_LEN(scan) += STR_LEN(n);
2734             next = n + NODE_SZ_STR(n);
2735             /* Now we can overwrite *n : */
2736             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2737 #ifdef DEBUGGING
2738             stop = next - 1;
2739 #endif
2740             n = nnext;
2741             if (stopnow) break;
2742         }
2743
2744 #ifdef EXPERIMENTAL_INPLACESCAN
2745         if (flags && !NEXT_OFF(n)) {
2746             DEBUG_PEEP("atch", val, depth);
2747             if (reg_off_by_arg[OP(n)]) {
2748                 ARG_SET(n, val - n);
2749             }
2750             else {
2751                 NEXT_OFF(n) = val - n;
2752             }
2753             stopnow = 1;
2754         }
2755 #endif
2756     }
2757
2758     *min_subtract = 0;
2759     *has_exactf_sharp_s = FALSE;
2760
2761     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
2762      * can now analyze for sequences of problematic code points.  (Prior to
2763      * this final joining, sequences could have been split over boundaries, and
2764      * hence missed).  The sequences only happen in folding, hence for any
2765      * non-EXACT EXACTish node */
2766     if (OP(scan) != EXACT) {
2767         const U8 * const s0 = (U8*) STRING(scan);
2768         const U8 * s = s0;
2769         const U8 * const s_end = s0 + STR_LEN(scan);
2770
2771         /* One pass is made over the node's string looking for all the
2772          * possibilities.  to avoid some tests in the loop, there are two main
2773          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
2774          * non-UTF-8 */
2775         if (UTF) {
2776
2777             /* Examine the string for a multi-character fold sequence.  UTF-8
2778              * patterns have all characters pre-folded by the time this code is
2779              * executed */
2780             while (s < s_end - 1) /* Can stop 1 before the end, as minimum
2781                                      length sequence we are looking for is 2 */
2782             {
2783                 int count = 0;
2784                 int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end);
2785                 if (! len) {    /* Not a multi-char fold: get next char */
2786                     s += UTF8SKIP(s);
2787                     continue;
2788                 }
2789
2790                 /* Nodes with 'ss' require special handling, except for EXACTFL
2791                  * and EXACTFA for which there is no multi-char fold to this */
2792                 if (len == 2 && *s == 's' && *(s+1) == 's'
2793                     && OP(scan) != EXACTFL && OP(scan) != EXACTFA)
2794                 {
2795                     count = 2;
2796                     OP(scan) = EXACTFU_SS;
2797                     s += 2;
2798                 }
2799                 else if (len == 6   /* len is the same in both ASCII and EBCDIC for these */
2800                          && (memEQ(s, GREEK_SMALL_LETTER_IOTA_UTF8
2801                                       COMBINING_DIAERESIS_UTF8
2802                                       COMBINING_ACUTE_ACCENT_UTF8,
2803                                    6)
2804                              || memEQ(s, GREEK_SMALL_LETTER_UPSILON_UTF8
2805                                          COMBINING_DIAERESIS_UTF8
2806                                          COMBINING_ACUTE_ACCENT_UTF8,
2807                                      6)))
2808                 {
2809                     count = 3;
2810
2811                     /* These two folds require special handling by trie's, so
2812                      * change the node type to indicate this.  If EXACTFA and
2813                      * EXACTFL were ever to be handled by trie's, this would
2814                      * have to be changed.  If this node has already been
2815                      * changed to EXACTFU_SS in this loop, leave it as is.  (I
2816                      * (khw) think it doesn't matter in regexec.c for UTF
2817                      * patterns, but no need to change it */
2818                     if (OP(scan) == EXACTFU) {
2819                         OP(scan) = EXACTFU_TRICKYFOLD;
2820                     }
2821                     s += 6;
2822                 }
2823                 else { /* Here is a generic multi-char fold. */
2824                     const U8* multi_end  = s + len;
2825
2826                     /* Count how many characters in it.  In the case of /l and
2827                      * /aa, no folds which contain ASCII code points are
2828                      * allowed, so check for those, and skip if found.  (In
2829                      * EXACTFL, no folds are allowed to any Latin1 code point,
2830                      * not just ASCII.  But there aren't any of these
2831                      * currently, nor ever likely, so don't take the time to
2832                      * test for them.  The code that generates the
2833                      * is_MULTI_foo() macros croaks should one actually get put
2834                      * into Unicode .) */
2835                     if (OP(scan) != EXACTFL && OP(scan) != EXACTFA) {
2836                         count = utf8_length(s, multi_end);
2837                         s = multi_end;
2838                     }
2839                     else {
2840                         while (s < multi_end) {
2841                             if (isASCII(*s)) {
2842                                 s++;
2843                                 goto next_iteration;
2844                             }
2845                             else {
2846                                 s += UTF8SKIP(s);
2847                             }
2848                             count++;
2849                         }
2850                     }
2851                 }
2852
2853                 /* The delta is how long the sequence is minus 1 (1 is how long
2854                  * the character that folds to the sequence is) */
2855                 *min_subtract += count - 1;
2856             next_iteration: ;
2857             }
2858         }
2859         else if (OP(scan) != EXACTFL && OP(scan) != EXACTFA) {
2860
2861             /* Here, the pattern is not UTF-8.  Look for the multi-char folds
2862              * that are all ASCII.  As in the above case, EXACTFL and EXACTFA
2863              * nodes can't have multi-char folds to this range (and there are
2864              * no existing ones in the upper latin1 range).  In the EXACTF
2865              * case we look also for the sharp s, which can be in the final
2866              * position.  Otherwise we can stop looking 1 byte earlier because
2867              * have to find at least two characters for a multi-fold */
2868             const U8* upper = (OP(scan) == EXACTF) ? s_end : s_end -1;
2869
2870             /* The below is perhaps overboard, but this allows us to save a
2871              * test each time through the loop at the expense of a mask.  This
2872              * is because on both EBCDIC and ASCII machines, 'S' and 's' differ
2873              * by a single bit.  On ASCII they are 32 apart; on EBCDIC, they
2874              * are 64.  This uses an exclusive 'or' to find that bit and then
2875              * inverts it to form a mask, with just a single 0, in the bit
2876              * position where 'S' and 's' differ. */
2877             const U8 S_or_s_mask = (U8) ~ ('S' ^ 's');
2878             const U8 s_masked = 's' & S_or_s_mask;
2879
2880             while (s < upper) {
2881                 int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end);
2882                 if (! len) {    /* Not a multi-char fold. */
2883                     if (*s == LATIN_SMALL_LETTER_SHARP_S && OP(scan) == EXACTF)
2884                     {
2885                         *has_exactf_sharp_s = TRUE;
2886                     }
2887                     s++;
2888                     continue;
2889                 }
2890
2891                 if (len == 2
2892                     && ((*s & S_or_s_mask) == s_masked)
2893                     && ((*(s+1) & S_or_s_mask) == s_masked))
2894                 {
2895
2896                     /* EXACTF nodes need to know that the minimum length
2897                      * changed so that a sharp s in the string can match this
2898                      * ss in the pattern, but they remain EXACTF nodes, as they
2899                      * won't match this unless the target string is is UTF-8,
2900                      * which we don't know until runtime */
2901                     if (OP(scan) != EXACTF) {
2902                         OP(scan) = EXACTFU_SS;
2903                     }
2904                 }
2905
2906                 *min_subtract += len - 1;
2907                 s += len;
2908             }
2909         }
2910     }
2911
2912 #ifdef DEBUGGING
2913     /* Allow dumping but overwriting the collection of skipped
2914      * ops and/or strings with fake optimized ops */
2915     n = scan + NODE_SZ_STR(scan);
2916     while (n <= stop) {
2917         OP(n) = OPTIMIZED;
2918         FLAGS(n) = 0;
2919         NEXT_OFF(n) = 0;
2920         n++;
2921     }
2922 #endif
2923     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2924     return stopnow;
2925 }
2926
2927 /* REx optimizer.  Converts nodes into quicker variants "in place".
2928    Finds fixed substrings.  */
2929
2930 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2931    to the position after last scanned or to NULL. */
2932
2933 #define INIT_AND_WITHP \
2934     assert(!and_withp); \
2935     Newx(and_withp,1,struct regnode_charclass_class); \
2936     SAVEFREEPV(and_withp)
2937
2938 /* this is a chain of data about sub patterns we are processing that
2939    need to be handled separately/specially in study_chunk. Its so
2940    we can simulate recursion without losing state.  */
2941 struct scan_frame;
2942 typedef struct scan_frame {
2943     regnode *last;  /* last node to process in this frame */
2944     regnode *next;  /* next node to process when last is reached */
2945     struct scan_frame *prev; /*previous frame*/
2946     I32 stop; /* what stopparen do we use */
2947 } scan_frame;
2948
2949
2950 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2951
2952 STATIC I32
2953 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2954                         I32 *minlenp, I32 *deltap,
2955                         regnode *last,
2956                         scan_data_t *data,
2957                         I32 stopparen,
2958                         U8* recursed,
2959                         struct regnode_charclass_class *and_withp,
2960                         U32 flags, U32 depth)
2961                         /* scanp: Start here (read-write). */
2962                         /* deltap: Write maxlen-minlen here. */
2963                         /* last: Stop before this one. */
2964                         /* data: string data about the pattern */
2965                         /* stopparen: treat close N as END */
2966                         /* recursed: which subroutines have we recursed into */
2967                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2968 {
2969     dVAR;
2970     I32 min = 0;    /* There must be at least this number of characters to match */
2971     I32 pars = 0, code;
2972     regnode *scan = *scanp, *next;
2973     I32 delta = 0;
2974     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2975     int is_inf_internal = 0;            /* The studied chunk is infinite */
2976     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2977     scan_data_t data_fake;
2978     SV *re_trie_maxbuff = NULL;
2979     regnode *first_non_open = scan;
2980     I32 stopmin = I32_MAX;
2981     scan_frame *frame = NULL;
2982     GET_RE_DEBUG_FLAGS_DECL;
2983
2984     PERL_ARGS_ASSERT_STUDY_CHUNK;
2985
2986 #ifdef DEBUGGING
2987     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2988 #endif
2989
2990     if ( depth == 0 ) {
2991         while (first_non_open && OP(first_non_open) == OPEN)
2992             first_non_open=regnext(first_non_open);
2993     }
2994
2995
2996   fake_study_recurse:
2997     while ( scan && OP(scan) != END && scan < last ){
2998         UV min_subtract = 0;    /* How mmany chars to subtract from the minimum
2999                                    node length to get a real minimum (because
3000                                    the folded version may be shorter) */
3001         bool has_exactf_sharp_s = FALSE;
3002         /* Peephole optimizer: */
3003         DEBUG_STUDYDATA("Peep:", data,depth);
3004         DEBUG_PEEP("Peep",scan,depth);
3005
3006         /* Its not clear to khw or hv why this is done here, and not in the
3007          * clauses that deal with EXACT nodes.  khw's guess is that it's
3008          * because of a previous design */
3009         JOIN_EXACT(scan,&min_subtract, &has_exactf_sharp_s, 0);
3010
3011         /* Follow the next-chain of the current node and optimize
3012            away all the NOTHINGs from it.  */
3013         if (OP(scan) != CURLYX) {
3014             const int max = (reg_off_by_arg[OP(scan)]
3015                        ? I32_MAX
3016                        /* I32 may be smaller than U16 on CRAYs! */
3017                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
3018             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
3019             int noff;
3020             regnode *n = scan;
3021
3022             /* Skip NOTHING and LONGJMP. */
3023             while ((n = regnext(n))
3024                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
3025                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
3026                    && off + noff < max)
3027                 off += noff;
3028             if (reg_off_by_arg[OP(scan)])
3029                 ARG(scan) = off;
3030             else
3031                 NEXT_OFF(scan) = off;
3032         }
3033
3034
3035
3036         /* The principal pseudo-switch.  Cannot be a switch, since we
3037            look into several different things.  */
3038         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
3039                    || OP(scan) == IFTHEN) {
3040             next = regnext(scan);
3041             code = OP(scan);
3042             /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
3043
3044             if (OP(next) == code || code == IFTHEN) {
3045                 /* NOTE - There is similar code to this block below for handling
3046                    TRIE nodes on a re-study.  If you change stuff here check there
3047                    too. */
3048                 I32 max1 = 0, min1 = I32_MAX, num = 0;
3049                 struct regnode_charclass_class accum;
3050                 regnode * const startbranch=scan;
3051
3052                 if (flags & SCF_DO_SUBSTR)
3053                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
3054                 if (flags & SCF_DO_STCLASS)
3055                     cl_init_zero(pRExC_state, &accum);
3056
3057                 while (OP(scan) == code) {
3058                     I32 deltanext, minnext, f = 0, fake;
3059                     struct regnode_charclass_class this_class;
3060
3061                     num++;
3062                     data_fake.flags = 0;
3063                     if (data) {
3064                         data_fake.whilem_c = data->whilem_c;
3065                         data_fake.last_closep = data->last_closep;
3066                     }
3067                     else
3068                         data_fake.last_closep = &fake;
3069
3070                     data_fake.pos_delta = delta;
3071                     next = regnext(scan);
3072                     scan = NEXTOPER(scan);
3073                     if (code != BRANCH)
3074                         scan = NEXTOPER(scan);
3075                     if (flags & SCF_DO_STCLASS) {
3076                         cl_init(pRExC_state, &this_class);
3077                         data_fake.start_class = &this_class;
3078                         f = SCF_DO_STCLASS_AND;
3079                     }
3080                     if (flags & SCF_WHILEM_VISITED_POS)
3081                         f |= SCF_WHILEM_VISITED_POS;
3082
3083                     /* we suppose the run is continuous, last=next...*/
3084                     minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3085                                           next, &data_fake,
3086                                           stopparen, recursed, NULL, f,depth+1);
3087                     if (min1 > minnext)
3088                         min1 = minnext;
3089                     if (max1 < minnext + deltanext)
3090                         max1 = minnext + deltanext;
3091                     if (deltanext == I32_MAX)
3092                         is_inf = is_inf_internal = 1;
3093                     scan = next;
3094                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3095                         pars++;
3096                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
3097                         if ( stopmin > minnext) 
3098                             stopmin = min + min1;
3099                         flags &= ~SCF_DO_SUBSTR;
3100                         if (data)
3101                             data->flags |= SCF_SEEN_ACCEPT;
3102                     }
3103                     if (data) {
3104                         if (data_fake.flags & SF_HAS_EVAL)
3105                             data->flags |= SF_HAS_EVAL;
3106                         data->whilem_c = data_fake.whilem_c;
3107                     }
3108                     if (flags & SCF_DO_STCLASS)
3109                         cl_or(pRExC_state, &accum, &this_class);
3110                 }
3111                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
3112                     min1 = 0;
3113                 if (flags & SCF_DO_SUBSTR) {
3114                     data->pos_min += min1;
3115                     data->pos_delta += max1 - min1;
3116                     if (max1 != min1 || is_inf)
3117                         data->longest = &(data->longest_float);
3118                 }
3119                 min += min1;
3120                 delta += max1 - min1;
3121                 if (flags & SCF_DO_STCLASS_OR) {
3122                     cl_or(pRExC_state, data->start_class, &accum);
3123                     if (min1) {
3124                         cl_and(data->start_class, and_withp);
3125                         flags &= ~SCF_DO_STCLASS;
3126                     }
3127                 }
3128                 else if (flags & SCF_DO_STCLASS_AND) {
3129                     if (min1) {
3130                         cl_and(data->start_class, &accum);
3131                         flags &= ~SCF_DO_STCLASS;
3132                     }
3133                     else {
3134                         /* Switch to OR mode: cache the old value of
3135                          * data->start_class */
3136                         INIT_AND_WITHP;
3137                         StructCopy(data->start_class, and_withp,
3138                                    struct regnode_charclass_class);
3139                         flags &= ~SCF_DO_STCLASS_AND;
3140                         StructCopy(&accum, data->start_class,
3141                                    struct regnode_charclass_class);
3142                         flags |= SCF_DO_STCLASS_OR;
3143                         data->start_class->flags |= ANYOF_EOS;
3144                     }
3145                 }
3146
3147                 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
3148                 /* demq.
3149
3150                    Assuming this was/is a branch we are dealing with: 'scan' now
3151                    points at the item that follows the branch sequence, whatever
3152                    it is. We now start at the beginning of the sequence and look
3153                    for subsequences of
3154
3155                    BRANCH->EXACT=>x1
3156                    BRANCH->EXACT=>x2
3157                    tail
3158
3159                    which would be constructed from a pattern like /A|LIST|OF|WORDS/
3160
3161                    If we can find such a subsequence we need to turn the first
3162                    element into a trie and then add the subsequent branch exact
3163                    strings to the trie.
3164
3165                    We have two cases
3166
3167                      1. patterns where the whole set of branches can be converted. 
3168
3169                      2. patterns where only a subset can be converted.
3170
3171                    In case 1 we can replace the whole set with a single regop
3172                    for the trie. In case 2 we need to keep the start and end
3173                    branches so
3174
3175                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
3176                      becomes BRANCH TRIE; BRANCH X;
3177
3178                   There is an additional case, that being where there is a 
3179                   common prefix, which gets split out into an EXACT like node
3180                   preceding the TRIE node.
3181
3182                   If x(1..n)==tail then we can do a simple trie, if not we make
3183                   a "jump" trie, such that when we match the appropriate word
3184                   we "jump" to the appropriate tail node. Essentially we turn
3185                   a nested if into a case structure of sorts.
3186
3187                 */
3188
3189                     int made=0;
3190                     if (!re_trie_maxbuff) {
3191                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
3192                         if (!SvIOK(re_trie_maxbuff))
3193                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
3194                     }
3195                     if ( SvIV(re_trie_maxbuff)>=0  ) {
3196                         regnode *cur;
3197                         regnode *first = (regnode *)NULL;
3198                         regnode *last = (regnode *)NULL;
3199                         regnode *tail = scan;
3200                         U8 trietype = 0;
3201                         U32 count=0;
3202
3203 #ifdef DEBUGGING
3204                         SV * const mysv = sv_newmortal();       /* for dumping */
3205 #endif
3206                         /* var tail is used because there may be a TAIL
3207                            regop in the way. Ie, the exacts will point to the
3208                            thing following the TAIL, but the last branch will
3209                            point at the TAIL. So we advance tail. If we
3210                            have nested (?:) we may have to move through several
3211                            tails.
3212                          */
3213
3214                         while ( OP( tail ) == TAIL ) {
3215                             /* this is the TAIL generated by (?:) */
3216                             tail = regnext( tail );
3217                         }
3218
3219                         
3220                         DEBUG_TRIE_COMPILE_r({
3221                             regprop(RExC_rx, mysv, tail );
3222                             PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
3223                                 (int)depth * 2 + 2, "", 
3224                                 "Looking for TRIE'able sequences. Tail node is: ", 
3225                                 SvPV_nolen_const( mysv )
3226                             );
3227                         });
3228                         
3229                         /*
3230
3231                             Step through the branches
3232                                 cur represents each branch,
3233                                 noper is the first thing to be matched as part of that branch
3234                                 noper_next is the regnext() of that node.
3235
3236                             We normally handle a case like this /FOO[xyz]|BAR[pqr]/
3237                             via a "jump trie" but we also support building with NOJUMPTRIE,
3238                             which restricts the trie logic to structures like /FOO|BAR/.
3239
3240                             If noper is a trieable nodetype then the branch is a possible optimization
3241                             target. If we are building under NOJUMPTRIE then we require that noper_next
3242                             is the same as scan (our current position in the regex program).
3243
3244                             Once we have two or more consecutive such branches we can create a
3245                             trie of the EXACT's contents and stitch it in place into the program.
3246
3247                             If the sequence represents all of the branches in the alternation we
3248                             replace the entire thing with a single TRIE node.
3249
3250                             Otherwise when it is a subsequence we need to stitch it in place and
3251                             replace only the relevant branches. This means the first branch has
3252                             to remain as it is used by the alternation logic, and its next pointer,
3253                             and needs to be repointed at the item on the branch chain following
3254                             the last branch we have optimized away.
3255
3256                             This could be either a BRANCH, in which case the subsequence is internal,
3257                             or it could be the item following the branch sequence in which case the
3258                             subsequence is at the end (which does not necessarily mean the first node
3259                             is the start of the alternation).
3260
3261                             TRIE_TYPE(X) is a define which maps the optype to a trietype.
3262
3263                                 optype          |  trietype
3264                                 ----------------+-----------
3265                                 NOTHING         | NOTHING
3266                                 EXACT           | EXACT
3267                                 EXACTFU         | EXACTFU
3268                                 EXACTFU_SS      | EXACTFU
3269                                 EXACTFU_TRICKYFOLD | EXACTFU
3270                                 EXACTFA         | 0
3271
3272
3273                         */
3274 #define TRIE_TYPE(X) ( ( NOTHING == (X) ) ? NOTHING :   \
3275                        ( EXACT == (X) )   ? EXACT :        \
3276                        ( EXACTFU == (X) || EXACTFU_SS == (X) || EXACTFU_TRICKYFOLD == (X) ) ? EXACTFU :        \
3277                        0 )
3278
3279                         /* dont use tail as the end marker for this traverse */
3280                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
3281                             regnode * const noper = NEXTOPER( cur );
3282                             U8 noper_type = OP( noper );
3283                             U8 noper_trietype = TRIE_TYPE( noper_type );
3284 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
3285                             regnode * const noper_next = regnext( noper );
3286                             U8 noper_next_type = (noper_next && noper_next != tail) ? OP(noper_next) : 0;
3287                             U8 noper_next_trietype = (noper_next && noper_next != tail) ? TRIE_TYPE( noper_next_type ) :0;
3288 #endif
3289
3290                             DEBUG_TRIE_COMPILE_r({
3291                                 regprop(RExC_rx, mysv, cur);
3292                                 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
3293                                    (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
3294
3295                                 regprop(RExC_rx, mysv, noper);
3296                                 PerlIO_printf( Perl_debug_log, " -> %s",
3297                                     SvPV_nolen_const(mysv));
3298
3299                                 if ( noper_next ) {
3300                                   regprop(RExC_rx, mysv, noper_next );
3301                                   PerlIO_printf( Perl_debug_log,"\t=> %s\t",
3302                                     SvPV_nolen_const(mysv));
3303                                 }
3304                                 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d,tt==%s,nt==%s,nnt==%s)\n",
3305                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
3306                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] 
3307                                 );
3308                             });
3309
3310                             /* Is noper a trieable nodetype that can be merged with the
3311                              * current trie (if there is one)? */
3312                             if ( noper_trietype
3313                                   &&
3314                                   (
3315                                         ( noper_trietype == NOTHING)
3316                                         || ( trietype == NOTHING )
3317                                         || ( trietype == noper_trietype )
3318                                   )
3319 #ifdef NOJUMPTRIE
3320                                   && noper_next == tail
3321 #endif
3322                                   && count < U16_MAX)
3323                             {
3324                                 /* Handle mergable triable node
3325                                  * Either we are the first node in a new trieable sequence,
3326                                  * in which case we do some bookkeeping, otherwise we update
3327                                  * the end pointer. */
3328                                 if ( !first ) {
3329                                     first = cur;
3330                                     if ( noper_trietype == NOTHING ) {
3331 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
3332                                         regnode * const noper_next = regnext( noper );
3333                                         U8 noper_next_type = (noper_next && noper_next!=tail) ? OP(noper_next) : 0;
3334                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
3335 #endif
3336
3337                                         if ( noper_next_trietype ) {
3338                                             trietype = noper_next_trietype;
3339                                         } else if (noper_next_type)  {
3340                                             /* a NOTHING regop is 1 regop wide. We need at least two
3341                                              * for a trie so we can't merge this in */
3342                                             first = NULL;
3343                                         }
3344                                     } else {
3345                                         trietype = noper_trietype;
3346                                     }
3347                                 } else {
3348                                     if ( trietype == NOTHING )
3349                                         trietype = noper_trietype;
3350                                     last = cur;
3351                                 }
3352                                 if (first)
3353                                     count++;
3354                             } /* end handle mergable triable node */
3355                             else {
3356                                 /* handle unmergable node -
3357                                  * noper may either be a triable node which can not be tried
3358                                  * together with the current trie, or a non triable node */
3359                                 if ( last ) {
3360                                     /* If last is set and trietype is not NOTHING then we have found
3361                                      * at least two triable branch sequences in a row of a similar
3362                                      * trietype so we can turn them into a trie. If/when we
3363                                      * allow NOTHING to start a trie sequence this condition will be
3364                                      * required, and it isn't expensive so we leave it in for now. */
3365                                     if ( trietype && trietype != NOTHING )
3366                                         make_trie( pRExC_state,
3367                                                 startbranch, first, cur, tail, count,
3368                                                 trietype, depth+1 );
3369                                     last = NULL; /* note: we clear/update first, trietype etc below, so we dont do it here */
3370                                 }
3371                                 if ( noper_trietype
3372 #ifdef NOJUMPTRIE
3373                                      && noper_next == tail
3374 #endif
3375                                 ){
3376                                     /* noper is triable, so we can start a new trie sequence */
3377                                     count = 1;
3378                                     first = cur;
3379                                     trietype = noper_trietype;
3380                                 } else if (first) {
3381                                     /* if we already saw a first but the current node is not triable then we have
3382                                      * to reset the first information. */
3383                                     count = 0;
3384                                     first = NULL;
3385                                     trietype = 0;
3386                                 }
3387                             } /* end handle unmergable node */
3388                         } /* loop over branches */
3389                         DEBUG_TRIE_COMPILE_r({
3390                             regprop(RExC_rx, mysv, cur);
3391                             PerlIO_printf( Perl_debug_log,
3392                               "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
3393                               "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
3394
3395                         });
3396                         if ( last && trietype ) {
3397                             if ( trietype != NOTHING ) {
3398                                 /* the last branch of the sequence was part of a trie,
3399                                  * so we have to construct it here outside of the loop
3400                                  */
3401                                 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, trietype, depth+1 );
3402 #ifdef TRIE_STUDY_OPT
3403                                 if ( ((made == MADE_EXACT_TRIE &&
3404                                      startbranch == first)
3405                                      || ( first_non_open == first )) &&
3406                                      depth==0 ) {
3407                                     flags |= SCF_TRIE_RESTUDY;
3408                                     if ( startbranch == first
3409                                          && scan == tail )
3410                                     {
3411                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
3412                                     }
3413                                 }
3414 #endif
3415                             } else {
3416                                 /* at this point we know whatever we have is a NOTHING sequence/branch
3417                                  * AND if 'startbranch' is 'first' then we can turn the whole thing into a NOTHING
3418                                  */
3419                                 if ( startbranch == first ) {
3420                                     regnode *opt;
3421                                     /* the entire thing is a NOTHING sequence, something like this:
3422                                      * (?:|) So we can turn it into a plain NOTHING op. */
3423                                     DEBUG_TRIE_COMPILE_r({
3424                                         regprop(RExC_rx, mysv, cur);
3425                                         PerlIO_printf( Perl_debug_log,
3426                                           "%*s- %s (%d) <NOTHING BRANCH SEQUENCE>\n", (int)depth * 2 + 2,
3427                                           "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
3428
3429                                     });
3430                                     OP(startbranch)= NOTHING;
3431                                     NEXT_OFF(startbranch)= tail - startbranch;
3432                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
3433                                         OP(opt)= OPTIMIZED;
3434                                 }
3435                             }
3436                         } /* end if ( last) */
3437                     } /* TRIE_MAXBUF is non zero */
3438                     
3439                 } /* do trie */
3440                 
3441             }
3442             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
3443                 scan = NEXTOPER(NEXTOPER(scan));
3444             } else                      /* single branch is optimized. */
3445                 scan = NEXTOPER(scan);
3446             continue;
3447         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
3448             scan_frame *newframe = NULL;
3449             I32 paren;
3450             regnode *start;
3451             regnode *end;
3452
3453             if (OP(scan) != SUSPEND) {
3454             /* set the pointer */
3455                 if (OP(scan) == GOSUB) {
3456                     paren = ARG(scan);
3457                     RExC_recurse[ARG2L(scan)] = scan;
3458                     start = RExC_open_parens[paren-1];
3459                     end   = RExC_close_parens[paren-1];
3460                 } else {
3461                     paren = 0;
3462                     start = RExC_rxi->program + 1;
3463                     end   = RExC_opend;
3464                 }
3465                 if (!recursed) {
3466                     Newxz(recursed, (((RExC_npar)>>3) +1), U8);
3467                     SAVEFREEPV(recursed);
3468                 }
3469                 if (!PAREN_TEST(recursed,paren+1)) {
3470                     PAREN_SET(recursed,paren+1);
3471                     Newx(newframe,1,scan_frame);
3472                 } else {
3473                     if (flags & SCF_DO_SUBSTR) {
3474                         SCAN_COMMIT(pRExC_state,data,minlenp);
3475                         data->longest = &(data->longest_float);
3476                     }
3477                     is_inf = is_inf_internal = 1;
3478                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3479                         cl_anything(pRExC_state, data->start_class);
3480                     flags &= ~SCF_DO_STCLASS;
3481                 }
3482             } else {
3483                 Newx(newframe,1,scan_frame);
3484                 paren = stopparen;
3485                 start = scan+2;
3486                 end = regnext(scan);
3487             }
3488             if (newframe) {
3489                 assert(start);
3490                 assert(end);
3491                 SAVEFREEPV(newframe);
3492                 newframe->next = regnext(scan);
3493                 newframe->last = last;
3494                 newframe->stop = stopparen;
3495                 newframe->prev = frame;
3496
3497                 frame = newframe;
3498                 scan =  start;
3499                 stopparen = paren;
3500                 last = end;
3501
3502                 continue;
3503             }
3504         }
3505         else if (OP(scan) == EXACT) {
3506             I32 l = STR_LEN(scan);
3507             UV uc;
3508             if (UTF) {
3509                 const U8 * const s = (U8*)STRING(scan);
3510                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
3511                 l = utf8_length(s, s + l);
3512             } else {
3513                 uc = *((U8*)STRING(scan));
3514             }
3515             min += l;
3516             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3517                 /* The code below prefers earlier match for fixed
3518                    offset, later match for variable offset.  */
3519                 if (data->last_end == -1) { /* Update the start info. */
3520                     data->last_start_min = data->pos_min;
3521                     data->last_start_max = is_inf
3522                         ? I32_MAX : data->pos_min + data->pos_delta;
3523                 }
3524                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3525                 if (UTF)
3526                     SvUTF8_on(data->last_found);
3527                 {
3528                     SV * const sv = data->last_found;
3529                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3530                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
3531                     if (mg && mg->mg_len >= 0)
3532                         mg->mg_len += utf8_length((U8*)STRING(scan),
3533                                                   (U8*)STRING(scan)+STR_LEN(scan));
3534                 }
3535                 data->last_end = data->pos_min + l;
3536                 data->pos_min += l; /* As in the first entry. */
3537                 data->flags &= ~SF_BEFORE_EOL;
3538             }
3539             if (flags & SCF_DO_STCLASS_AND) {
3540                 /* Check whether it is compatible with what we know already! */
3541                 int compat = 1;
3542
3543
3544                 /* If compatible, we or it in below.  It is compatible if is
3545                  * in the bitmp and either 1) its bit or its fold is set, or 2)
3546                  * it's for a locale.  Even if there isn't unicode semantics
3547                  * here, at runtime there may be because of matching against a
3548                  * utf8 string, so accept a possible false positive for
3549                  * latin1-range folds */
3550                 if (uc >= 0x100 ||
3551                     (!(data->start_class->flags & ANYOF_LOCALE)
3552                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
3553                     && (!(data->start_class->flags & ANYOF_LOC_FOLD)
3554                         || !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3555                     )
3556                 {
3557                     compat = 0;
3558                 }
3559                 ANYOF_CLASS_ZERO(data->start_class);
3560                 ANYOF_BITMAP_ZERO(data->start_class);
3561                 if (compat)
3562                     ANYOF_BITMAP_SET(data->start_class, uc);
3563                 else if (uc >= 0x100) {
3564                     int i;
3565
3566                     /* Some Unicode code points fold to the Latin1 range; as
3567                      * XXX temporary code, instead of figuring out if this is
3568                      * one, just assume it is and set all the start class bits
3569                      * that could be some such above 255 code point's fold
3570                      * which will generate fals positives.  As the code
3571                      * elsewhere that does compute the fold settles down, it
3572                      * can be extracted out and re-used here */
3573                     for (i = 0; i < 256; i++){
3574                         if (HAS_NONLATIN1_FOLD_CLOSURE(i)) {
3575                             ANYOF_BITMAP_SET(data->start_class, i);
3576                         }
3577                     }
3578                 }
3579                 data->start_class->flags &= ~ANYOF_EOS;
3580                 if (uc < 0x100)
3581                   data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3582             }
3583             else if (flags & SCF_DO_STCLASS_OR) {
3584                 /* false positive possible if the class is case-folded */
3585                 if (uc < 0x100)
3586                     ANYOF_BITMAP_SET(data->start_class, uc);
3587                 else
3588                     data->start_class->flags |= ANYOF_UNICODE_ALL;
3589                 data->start_class->flags &= ~ANYOF_EOS;
3590                 cl_and(data->start_class, and_withp);
3591             }
3592             flags &= ~SCF_DO_STCLASS;
3593         }
3594         else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3595             I32 l = STR_LEN(scan);
3596             UV uc = *((U8*)STRING(scan));
3597
3598             /* Search for fixed substrings supports EXACT only. */
3599             if (flags & SCF_DO_SUBSTR) {
3600                 assert(data);
3601                 SCAN_COMMIT(pRExC_state, data, minlenp);
3602             }
3603             if (UTF) {
3604                 const U8 * const s = (U8 *)STRING(scan);
3605                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
3606                 l = utf8_length(s, s + l);
3607             }
3608             if (has_exactf_sharp_s) {
3609                 RExC_seen |= REG_SEEN_EXACTF_SHARP_S;
3610             }
3611             min += l - min_subtract;
3612             assert (min >= 0);
3613             delta += min_subtract;
3614             if (flags & SCF_DO_SUBSTR) {
3615                 data->pos_min += l - min_subtract;
3616                 if (data->pos_min < 0) {
3617                     data->pos_min = 0;
3618                 }
3619                 data->pos_delta += min_subtract;
3620                 if (min_subtract) {
3621                     data->longest = &(data->longest_float);
3622                 }
3623             }
3624             if (flags & SCF_DO_STCLASS_AND) {
3625                 /* Check whether it is compatible with what we know already! */
3626                 int compat = 1;
3627                 if (uc >= 0x100 ||
3628                  (!(data->start_class->flags & ANYOF_LOCALE)
3629                   && !ANYOF_BITMAP_TEST(data->start_class, uc)
3630                   && !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3631                 {
3632                     compat = 0;
3633                 }
3634                 ANYOF_CLASS_ZERO(data->start_class);
3635                 ANYOF_BITMAP_ZERO(data->start_class);
3636                 if (compat) {
3637                     ANYOF_BITMAP_SET(data->start_class, uc);
3638                     data->start_class->flags &= ~ANYOF_EOS;
3639                     if (OP(scan) == EXACTFL) {
3640                         /* XXX This set is probably no longer necessary, and
3641                          * probably wrong as LOCALE now is on in the initial
3642                          * state */
3643                         data->start_class->flags |= ANYOF_LOCALE|ANYOF_LOC_FOLD;
3644                     }
3645                     else {
3646
3647                         /* Also set the other member of the fold pair.  In case
3648                          * that unicode semantics is called for at runtime, use
3649                          * the full latin1 fold.  (Can't do this for locale,
3650                          * because not known until runtime) */
3651                         ANYOF_BITMAP_SET(data->start_class, PL_fold_latin1[uc]);
3652
3653                         /* All other (EXACTFL handled above) folds except under
3654                          * /iaa that include s, S, and sharp_s also may include
3655                          * the others */
3656                         if (OP(scan) != EXACTFA) {
3657                             if (uc == 's' || uc == 'S') {
3658                                 ANYOF_BITMAP_SET(data->start_class,
3659                                                  LATIN_SMALL_LETTER_SHARP_S);
3660                             }
3661                             else if (uc == LATIN_SMALL_LETTER_SHARP_S) {
3662                                 ANYOF_BITMAP_SET(data->start_class, 's');
3663                                 ANYOF_BITMAP_SET(data->start_class, 'S');
3664                             }
3665                         }
3666                     }
3667                 }
3668                 else if (uc >= 0x100) {
3669                     int i;
3670                     for (i = 0; i < 256; i++){
3671                         if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)) {
3672                             ANYOF_BITMAP_SET(data->start_class, i);
3673                         }
3674                     }
3675                 }
3676             }
3677             else if (flags & SCF_DO_STCLASS_OR) {
3678                 if (data->start_class->flags & ANYOF_LOC_FOLD) {
3679                     /* false positive possible if the class is case-folded.
3680                        Assume that the locale settings are the same... */
3681                     if (uc < 0x100) {
3682                         ANYOF_BITMAP_SET(data->start_class, uc);
3683                         if (OP(scan) != EXACTFL) {
3684
3685                             /* And set the other member of the fold pair, but
3686                              * can't do that in locale because not known until
3687                              * run-time */
3688                             ANYOF_BITMAP_SET(data->start_class,
3689                                              PL_fold_latin1[uc]);
3690
3691                             /* All folds except under /iaa that include s, S,
3692                              * and sharp_s also may include the others */
3693                             if (OP(scan) != EXACTFA) {
3694                                 if (uc == 's' || uc == 'S') {
3695                                     ANYOF_BITMAP_SET(data->start_class,
3696                                                    LATIN_SMALL_LETTER_SHARP_S);
3697                                 }
3698                                 else if (uc == LATIN_SMALL_LETTER_SHARP_S) {
3699                                     ANYOF_BITMAP_SET(data->start_class, 's');
3700                                     ANYOF_BITMAP_SET(data->start_class, 'S');
3701                                 }
3702                             }
3703                         }
3704                     }
3705                     data->start_class->flags &= ~ANYOF_EOS;
3706                 }
3707                 cl_and(data->start_class, and_withp);
3708             }
3709             flags &= ~SCF_DO_STCLASS;
3710         }
3711         else if (REGNODE_VARIES(OP(scan))) {
3712             I32 mincount, maxcount, minnext, deltanext, fl = 0;
3713             I32 f = flags, pos_before = 0;
3714             regnode * const oscan = scan;
3715             struct regnode_charclass_class this_class;
3716             struct regnode_charclass_class *oclass = NULL;
3717             I32 next_is_eval = 0;
3718
3719             switch (PL_regkind[OP(scan)]) {
3720             case WHILEM:                /* End of (?:...)* . */
3721                 scan = NEXTOPER(scan);
3722                 goto finish;
3723             case PLUS:
3724                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3725                     next = NEXTOPER(scan);
3726                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3727                         mincount = 1;
3728                         maxcount = REG_INFTY;
3729                         next = regnext(scan);
3730                         scan = NEXTOPER(scan);
3731                         goto do_curly;
3732                     }
3733                 }
3734                 if (flags & SCF_DO_SUBSTR)
3735                     data->pos_min++;
3736                 min++;
3737                 /* Fall through. */
3738             case STAR:
3739                 if (flags & SCF_DO_STCLASS) {
3740                     mincount = 0;
3741                     maxcount = REG_INFTY;
3742                     next = regnext(scan);
3743                     scan = NEXTOPER(scan);
3744                     goto do_curly;
3745                 }
3746                 is_inf = is_inf_internal = 1;
3747                 scan = regnext(scan);
3748                 if (flags & SCF_DO_SUBSTR) {
3749                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
3750                     data->longest = &(data->longest_float);
3751                 }
3752                 goto optimize_curly_tail;
3753             case CURLY:
3754                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3755                     && (scan->flags == stopparen))
3756                 {
3757                     mincount = 1;
3758                     maxcount = 1;
3759                 } else {
3760                     mincount = ARG1(scan);
3761                     maxcount = ARG2(scan);
3762                 }
3763                 next = regnext(scan);
3764                 if (OP(scan) == CURLYX) {
3765                     I32 lp = (data ? *(data->last_closep) : 0);
3766                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3767                 }
3768                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3769                 next_is_eval = (OP(scan) == EVAL);
3770               do_curly:
3771                 if (flags & SCF_DO_SUBSTR) {
3772                     if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3773                     pos_before = data->pos_min;
3774                 }
3775                 if (data) {
3776                     fl = data->flags;
3777                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3778                     if (is_inf)
3779                         data->flags |= SF_IS_INF;
3780                 }
3781                 if (flags & SCF_DO_STCLASS) {
3782                     cl_init(pRExC_state, &this_class);
3783                     oclass = data->start_class;
3784                     data->start_class = &this_class;
3785                     f |= SCF_DO_STCLASS_AND;
3786                     f &= ~SCF_DO_STCLASS_OR;
3787                 }
3788                 /* Exclude from super-linear cache processing any {n,m}
3789                    regops for which the combination of input pos and regex
3790                    pos is not enough information to determine if a match
3791                    will be possible.
3792
3793                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
3794                    regex pos at the \s*, the prospects for a match depend not
3795                    only on the input position but also on how many (bar\s*)
3796                    repeats into the {4,8} we are. */
3797                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
3798                     f &= ~SCF_WHILEM_VISITED_POS;
3799
3800                 /* This will finish on WHILEM, setting scan, or on NULL: */
3801                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, 
3802                                       last, data, stopparen, recursed, NULL,
3803                                       (mincount == 0
3804                                         ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3805
3806                 if (flags & SCF_DO_STCLASS)
3807                     data->start_class = oclass;
3808                 if (mincount == 0 || minnext == 0) {
3809                     if (flags & SCF_DO_STCLASS_OR) {
3810                         cl_or(pRExC_state, data->start_class, &this_class);
3811                     }
3812                     else if (flags & SCF_DO_STCLASS_AND) {
3813                         /* Switch to OR mode: cache the old value of
3814                          * data->start_class */
3815                         INIT_AND_WITHP;
3816                         StructCopy(data->start_class, and_withp,
3817                                    struct regnode_charclass_class);
3818                         flags &= ~SCF_DO_STCLASS_AND;
3819                         StructCopy(&this_class, data->start_class,
3820                                    struct regnode_charclass_class);
3821                         flags |= SCF_DO_STCLASS_OR;
3822                         data->start_class->flags |= ANYOF_EOS;
3823                     }
3824                 } else {                /* Non-zero len */
3825                     if (flags & SCF_DO_STCLASS_OR) {
3826                         cl_or(pRExC_state, data->start_class, &this_class);
3827                         cl_and(data->start_class, and_withp);
3828                     }
3829                     else if (flags & SCF_DO_STCLASS_AND)
3830                         cl_and(data->start_class, &this_class);
3831                     flags &= ~SCF_DO_STCLASS;
3832                 }
3833                 if (!scan)              /* It was not CURLYX, but CURLY. */
3834                     scan = next;
3835                 if ( /* ? quantifier ok, except for (?{ ... }) */
3836                     (next_is_eval || !(mincount == 0 && maxcount == 1))
3837                     && (minnext == 0) && (deltanext == 0)
3838                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3839                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
3840                 {
3841                     /* Fatal warnings may leak the regexp without this: */
3842                     SAVEFREESV(RExC_rx_sv);
3843                     ckWARNreg(RExC_parse,
3844                               "Quantifier unexpected on zero-length expression");
3845                     (void)ReREFCNT_inc(RExC_rx_sv);
3846                 }
3847
3848                 min += minnext * mincount;
3849                 is_inf_internal |= ((maxcount == REG_INFTY
3850                                      && (minnext + deltanext) > 0)
3851                                     || deltanext == I32_MAX);
3852                 is_inf |= is_inf_internal;
3853                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3854
3855                 /* Try powerful optimization CURLYX => CURLYN. */
3856                 if (  OP(oscan) == CURLYX && data
3857                       && data->flags & SF_IN_PAR
3858                       && !(data->flags & SF_HAS_EVAL)
3859                       && !deltanext && minnext == 1 ) {
3860                     /* Try to optimize to CURLYN.  */
3861                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3862                     regnode * const nxt1 = nxt;
3863 #ifdef DEBUGGING
3864                     regnode *nxt2;
3865 #endif
3866
3867                     /* Skip open. */
3868                     nxt = regnext(nxt);
3869                     if (!REGNODE_SIMPLE(OP(nxt))
3870                         && !(PL_regkind[OP(nxt)] == EXACT
3871                              && STR_LEN(nxt) == 1))
3872                         goto nogo;
3873 #ifdef DEBUGGING
3874                     nxt2 = nxt;
3875 #endif
3876                     nxt = regnext(nxt);
3877                     if (OP(nxt) != CLOSE)
3878                         goto nogo;
3879                     if (RExC_open_parens) {
3880                         RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3881                         RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3882                     }
3883                     /* Now we know that nxt2 is the only contents: */
3884                     oscan->flags = (U8)ARG(nxt);
3885                     OP(oscan) = CURLYN;
3886                     OP(nxt1) = NOTHING; /* was OPEN. */
3887
3888 #ifdef DEBUGGING
3889                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3890                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
3891                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
3892                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
3893                     OP(nxt + 1) = OPTIMIZED; /* was count. */
3894                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
3895 #endif
3896                 }
3897               nogo:
3898
3899                 /* Try optimization CURLYX => CURLYM. */
3900                 if (  OP(oscan) == CURLYX && data
3901                       && !(data->flags & SF_HAS_PAR)
3902                       && !(data->flags & SF_HAS_EVAL)
3903                       && !deltanext     /* atom is fixed width */
3904                       && minnext != 0   /* CURLYM can't handle zero width */
3905                       && ! (RExC_seen & REG_SEEN_EXACTF_SHARP_S) /* Nor \xDF */
3906                 ) {
3907                     /* XXXX How to optimize if data == 0? */
3908                     /* Optimize to a simpler form.  */
3909                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3910                     regnode *nxt2;
3911
3912                     OP(oscan) = CURLYM;
3913                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3914                             && (OP(nxt2) != WHILEM))
3915                         nxt = nxt2;
3916                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
3917                     /* Need to optimize away parenths. */
3918                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
3919                         /* Set the parenth number.  */
3920                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3921
3922                         oscan->flags = (U8)ARG(nxt);
3923                         if (RExC_open_parens) {
3924                             RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3925                             RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3926                         }
3927                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
3928                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
3929
3930 #ifdef DEBUGGING
3931                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3932                         OP(nxt + 1) = OPTIMIZED; /* was count. */
3933                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
3934                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
3935 #endif
3936 #if 0
3937                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
3938                             regnode *nnxt = regnext(nxt1);
3939                             if (nnxt == nxt) {
3940                                 if (reg_off_by_arg[OP(nxt1)])
3941                                     ARG_SET(nxt1, nxt2 - nxt1);
3942                                 else if (nxt2 - nxt1 < U16_MAX)
3943                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
3944                                 else
3945                                     OP(nxt) = NOTHING;  /* Cannot beautify */
3946                             }
3947                             nxt1 = nnxt;
3948                         }
3949 #endif
3950                         /* Optimize again: */
3951                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3952                                     NULL, stopparen, recursed, NULL, 0,depth+1);
3953                     }
3954                     else
3955                         oscan->flags = 0;
3956                 }
3957                 else if ((OP(oscan) == CURLYX)
3958                          && (flags & SCF_WHILEM_VISITED_POS)
3959                          /* See the comment on a similar expression above.
3960                             However, this time it's not a subexpression
3961                             we care about, but the expression itself. */
3962                          && (maxcount == REG_INFTY)
3963                          && data && ++data->whilem_c < 16) {
3964                     /* This stays as CURLYX, we can put the count/of pair. */
3965                     /* Find WHILEM (as in regexec.c) */
3966                     regnode *nxt = oscan + NEXT_OFF(oscan);
3967
3968                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3969                         nxt += ARG(nxt);
3970                     PREVOPER(nxt)->flags = (U8)(data->whilem_c
3971                         | (RExC_whilem_seen << 4)); /* On WHILEM */
3972                 }
3973                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3974                     pars++;
3975                 if (flags & SCF_DO_SUBSTR) {
3976                     SV *last_str = NULL;
3977                     int counted = mincount != 0;
3978
3979                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3980 #if defined(SPARC64_GCC_WORKAROUND)
3981                         I32 b = 0;
3982                         STRLEN l = 0;
3983                         const char *s = NULL;
3984                         I32 old = 0;
3985
3986                         if (pos_before >= data->last_start_min)
3987                             b = pos_before;
3988                         else
3989                             b = data->last_start_min;
3990
3991                         l = 0;
3992                         s = SvPV_const(data->last_found, l);
3993                         old = b - data->last_start_min;
3994
3995 #else
3996                         I32 b = pos_before >= data->last_start_min
3997                             ? pos_before : data->last_start_min;
3998                         STRLEN l;
3999                         const char * const s = SvPV_const(data->last_found, l);
4000                         I32 old = b - data->last_start_min;
4001 #endif
4002
4003                         if (UTF)
4004                             old = utf8_hop((U8*)s, old) - (U8*)s;
4005                         l -= old;
4006                         /* Get the added string: */
4007                         last_str = newSVpvn_utf8(s  + old, l, UTF);
4008                         if (deltanext == 0 && pos_before == b) {
4009                             /* What was added is a constant string */
4010                             if (mincount > 1) {
4011                                 SvGROW(last_str, (mincount * l) + 1);
4012                                 repeatcpy(SvPVX(last_str) + l,
4013                                           SvPVX_const(last_str), l, mincount - 1);
4014                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
4015                                 /* Add additional parts. */
4016                                 SvCUR_set(data->last_found,
4017                                           SvCUR(data->last_found) - l);
4018                                 sv_catsv(data->last_found, last_str);
4019                                 {
4020                                     SV * sv = data->last_found;
4021                                     MAGIC *mg =
4022                                         SvUTF8(sv) && SvMAGICAL(sv) ?
4023                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
4024                                     if (mg && mg->mg_len >= 0)
4025                                         mg->mg_len += CHR_SVLEN(last_str) - l;
4026                                 }
4027                                 data->last_end += l * (mincount - 1);
4028                             }
4029                         } else {
4030                             /* start offset must point into the last copy */
4031                             data->last_start_min += minnext * (mincount - 1);
4032                             data->last_start_max += is_inf ? I32_MAX
4033                                 : (maxcount - 1) * (minnext + data->pos_delta);
4034                         }
4035                     }
4036                     /* It is counted once already... */
4037                     data->pos_min += minnext * (mincount - counted);
4038                     data->pos_delta += - counted * deltanext +
4039                         (minnext + deltanext) * maxcount - minnext * mincount;
4040                     if (mincount != maxcount) {
4041                          /* Cannot extend fixed substrings found inside
4042                             the group.  */
4043                         SCAN_COMMIT(pRExC_state,data,minlenp);
4044                         if (mincount && last_str) {
4045                             SV * const sv = data->last_found;
4046                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
4047                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
4048
4049                             if (mg)
4050                                 mg->mg_len = -1;
4051                             sv_setsv(sv, last_str);
4052                             data->last_end = data->pos_min;
4053                             data->last_start_min =
4054                                 data->pos_min - CHR_SVLEN(last_str);
4055                             data->last_start_max = is_inf
4056                                 ? I32_MAX
4057                                 : data->pos_min + data->pos_delta
4058                                 - CHR_SVLEN(last_str);
4059                         }
4060                         data->longest = &(data->longest_float);
4061                     }
4062                     SvREFCNT_dec(last_str);
4063                 }
4064                 if (data && (fl & SF_HAS_EVAL))
4065                     data->flags |= SF_HAS_EVAL;
4066               optimize_curly_tail:
4067                 if (OP(oscan) != CURLYX) {
4068                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
4069                            && NEXT_OFF(next))
4070                         NEXT_OFF(oscan) += NEXT_OFF(next);
4071                 }
4072                 continue;
4073             default:                    /* REF, ANYOFV, and CLUMP only? */
4074                 if (flags & SCF_DO_SUBSTR) {
4075                     SCAN_COMMIT(pRExC_state,data,minlenp);      /* Cannot expect anything... */
4076                     data->longest = &(data->longest_float);
4077                 }
4078                 is_inf = is_inf_internal = 1;
4079                 if (flags & SCF_DO_STCLASS_OR)
4080                     cl_anything(pRExC_state, data->start_class);
4081                 flags &= ~SCF_DO_STCLASS;
4082                 break;
4083             }
4084         }
4085         else if (OP(scan) == LNBREAK) {
4086             if (flags & SCF_DO_STCLASS) {
4087                 int value = 0;
4088                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
4089                 if (flags & SCF_DO_STCLASS_AND) {
4090                     for (value = 0; value < 256; value++)
4091                         if (!is_VERTWS_cp(value))
4092                             ANYOF_BITMAP_CLEAR(data->start_class, value);
4093                 }
4094                 else {
4095                     for (value = 0; value < 256; value++)
4096                         if (is_VERTWS_cp(value))
4097                             ANYOF_BITMAP_SET(data->start_class, value);
4098                 }
4099                 if (flags & SCF_DO_STCLASS_OR)
4100                     cl_and(data->start_class, and_withp);
4101                 flags &= ~SCF_DO_STCLASS;
4102             }
4103             min++;
4104             delta++;    /* Because of the 2 char string cr-lf */
4105             if (flags & SCF_DO_SUBSTR) {
4106                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4107                 data->pos_min += 1;
4108                 data->pos_delta += 1;
4109                 data->longest = &(data->longest_float);
4110             }
4111         }
4112         else if (REGNODE_SIMPLE(OP(scan))) {
4113             int value = 0;
4114
4115             if (flags & SCF_DO_SUBSTR) {
4116                 SCAN_COMMIT(pRExC_state,data,minlenp);
4117                 data->pos_min++;
4118             }
4119             min++;
4120             if (flags & SCF_DO_STCLASS) {
4121                 int loop_max = 256;
4122                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
4123
4124                 /* Some of the logic below assumes that switching
4125                    locale on will only add false positives. */
4126                 switch (PL_regkind[OP(scan)]) {
4127                     U8 classnum;
4128
4129                 case SANY:
4130                 default:
4131                   do_default:
4132                     /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
4133                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4134                         cl_anything(pRExC_state, data->start_class);
4135                     break;
4136                 case REG_ANY:
4137                     if (OP(scan) == SANY)
4138                         goto do_default;
4139                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
4140                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
4141                                  || ANYOF_CLASS_TEST_ANY_SET(data->start_class));
4142                         cl_anything(pRExC_state, data->start_class);
4143                     }
4144                     if (flags & SCF_DO_STCLASS_AND || !value)
4145                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
4146                     break;
4147                 case ANYOF:
4148                     if (flags & SCF_DO_STCLASS_AND)
4149                         cl_and(data->start_class,
4150                                (struct regnode_charclass_class*)scan);
4151                     else
4152                         cl_or(pRExC_state, data->start_class,
4153                               (struct regnode_charclass_class*)scan);
4154                     break;
4155                 case POSIXA:
4156                     loop_max = 128;
4157                 case POSIXL:
4158                 case POSIXD:
4159                 case POSIXU:
4160                     classnum = FLAGS(scan);
4161                     if (flags & SCF_DO_STCLASS_AND) {
4162                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4163                             ANYOF_CLASS_CLEAR(data->start_class, classnum_to_namedclass(classnum) + 1);
4164                             for (value = 0; value < loop_max; value++) {
4165                                 if (! _generic_isCC(UNI_TO_NATIVE(value), classnum)) {
4166                                     ANYOF_BITMAP_CLEAR(data->start_class, UNI_TO_NATIVE(value));
4167                                 }
4168                             }
4169                         }
4170                     }
4171                     else {
4172                         if (data->start_class->flags & ANYOF_LOCALE) {
4173                             ANYOF_CLASS_SET(data->start_class, classnum_to_namedclass(classnum));
4174                         }
4175                         else {
4176
4177                         /* Even if under locale, set the bits for non-locale
4178                          * in case it isn't a true locale-node.  This will
4179                          * create false positives if it truly is locale */
4180                         for (value = 0; value < loop_max; value++) {
4181                             if (_generic_isCC(UNI_TO_NATIVE(value), classnum)) {
4182                                 ANYOF_BITMAP_SET(data->start_class, UNI_TO_NATIVE(value));
4183                             }
4184                         }
4185                         }
4186                     }
4187                     break;
4188                 case NPOSIXA:
4189                     loop_max = 128;
4190                 case NPOSIXL:
4191                 case NPOSIXU:
4192                 case NPOSIXD:
4193                     classnum = FLAGS(scan);
4194                     if (flags & SCF_DO_STCLASS_AND) {
4195                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4196                             ANYOF_CLASS_CLEAR(data->start_class, classnum_to_namedclass(classnum));
4197                             for (value = 0; value < loop_max; value++) {
4198                                 if (_generic_isCC(UNI_TO_NATIVE(value), classnum)) {
4199                                     ANYOF_BITMAP_CLEAR(data->start_class, UNI_TO_NATIVE(value));
4200                                 }
4201                             }
4202                         }
4203                     }
4204                     else {
4205                         if (data->start_class->flags & ANYOF_LOCALE) {
4206                             ANYOF_CLASS_SET(data->start_class, classnum_to_namedclass(classnum) + 1);
4207                         }
4208                         else {
4209
4210                         /* Even if under locale, set the bits for non-locale in
4211                          * case it isn't a true locale-node.  This will create
4212                          * false positives if it truly is locale */
4213                         for (value = 0; value < loop_max; value++) {
4214                             if (! _generic_isCC(UNI_TO_NATIVE(value), classnum)) {
4215                                 ANYOF_BITMAP_SET(data->start_class, UNI_TO_NATIVE(value));
4216                             }
4217                         }
4218                         if (PL_regkind[OP(scan)] == NPOSIXD) {
4219                             data->start_class->flags |= ANYOF_NON_UTF8_LATIN1_ALL;
4220                         }
4221                         }
4222                     }
4223                     break;
4224                 }
4225                 if (flags & SCF_DO_STCLASS_OR)
4226                     cl_and(data->start_class, and_withp);
4227                 flags &= ~SCF_DO_STCLASS;
4228             }
4229         }
4230         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
4231             data->flags |= (OP(scan) == MEOL
4232                             ? SF_BEFORE_MEOL
4233                             : SF_BEFORE_SEOL);
4234             SCAN_COMMIT(pRExC_state, data, minlenp);
4235
4236         }
4237         else if (  PL_regkind[OP(scan)] == BRANCHJ
4238                  /* Lookbehind, or need to calculate parens/evals/stclass: */
4239                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
4240                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
4241             if ( OP(scan) == UNLESSM &&
4242                  scan->flags == 0 &&
4243                  OP(NEXTOPER(NEXTOPER(scan))) == NOTHING &&
4244                  OP(regnext(NEXTOPER(NEXTOPER(scan)))) == SUCCEED
4245             ) {
4246                 regnode *opt;
4247                 regnode *upto= regnext(scan);
4248                 DEBUG_PARSE_r({
4249                     SV * const mysv_val=sv_newmortal();
4250                     DEBUG_STUDYDATA("OPFAIL",data,depth);
4251
4252                     /*DEBUG_PARSE_MSG("opfail");*/
4253                     regprop(RExC_rx, mysv_val, upto);
4254                     PerlIO_printf(Perl_debug_log, "~ replace with OPFAIL pointed at %s (%"IVdf") offset %"IVdf"\n",
4255                                   SvPV_nolen_const(mysv_val),
4256                                   (IV)REG_NODE_NUM(upto),
4257                                   (IV)(upto - scan)
4258                     );
4259                 });
4260                 OP(scan) = OPFAIL;
4261                 NEXT_OFF(scan) = upto - scan;
4262                 for (opt= scan + 1; opt < upto ; opt++)
4263                     OP(opt) = OPTIMIZED;
4264                 scan= upto;
4265                 continue;
4266             }
4267             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY 
4268                 || OP(scan) == UNLESSM )
4269             {
4270                 /* Negative Lookahead/lookbehind
4271                    In this case we can't do fixed string optimisation.
4272                 */
4273
4274                 I32 deltanext, minnext, fake = 0;
4275                 regnode *nscan;
4276                 struct regnode_charclass_class intrnl;
4277                 int f = 0;
4278
4279                 data_fake.flags = 0;
4280                 if (data) {
4281                     data_fake.whilem_c = data->whilem_c;
4282                     data_fake.last_closep = data->last_closep;
4283                 }
4284                 else
4285                     data_fake.last_closep = &fake;
4286                 data_fake.pos_delta = delta;
4287                 if ( flags & SCF_DO_STCLASS && !scan->flags
4288                      && OP(scan) == IFMATCH ) { /* Lookahead */
4289                     cl_init(pRExC_state, &intrnl);
4290                     data_fake.start_class = &intrnl;
4291                     f |= SCF_DO_STCLASS_AND;
4292                 }
4293                 if (flags & SCF_WHILEM_VISITED_POS)
4294                     f |= SCF_WHILEM_VISITED_POS;
4295                 next = regnext(scan);
4296                 nscan = NEXTOPER(NEXTOPER(scan));
4297                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, 
4298                     last, &data_fake, stopparen, recursed, NULL, f, depth+1);
4299                 if (scan->flags) {
4300                     if (deltanext) {
4301                         FAIL("Variable length lookbehind not implemented");
4302                     }
4303                     else if (minnext > (I32)U8_MAX) {
4304                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
4305                     }
4306                     scan->flags = (U8)minnext;
4307                 }
4308                 if (data) {
4309                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4310                         pars++;
4311                     if (data_fake.flags & SF_HAS_EVAL)
4312                         data->flags |= SF_HAS_EVAL;
4313                     data->whilem_c = data_fake.whilem_c;
4314                 }
4315                 if (f & SCF_DO_STCLASS_AND) {
4316                     if (flags & SCF_DO_STCLASS_OR) {
4317                         /* OR before, AND after: ideally we would recurse with
4318                          * data_fake to get the AND applied by study of the
4319                          * remainder of the pattern, and then derecurse;
4320                          * *** HACK *** for now just treat as "no information".
4321                          * See [perl #56690].
4322                          */
4323                         cl_init(pRExC_state, data->start_class);
4324                     }  else {
4325                         /* AND before and after: combine and continue */
4326                         const int was = (data->start_class->flags & ANYOF_EOS);
4327
4328                         cl_and(data->start_class, &intrnl);
4329                         if (was)
4330                             data->start_class->flags |= ANYOF_EOS;
4331                     }
4332                 }
4333             }
4334 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
4335             else {
4336                 /* Positive Lookahead/lookbehind
4337                    In this case we can do fixed string optimisation,
4338                    but we must be careful about it. Note in the case of
4339                    lookbehind the positions will be offset by the minimum
4340                    length of the pattern, something we won't know about
4341                    until after the recurse.
4342                 */
4343                 I32 deltanext, fake = 0;
4344                 regnode *nscan;
4345                 struct regnode_charclass_class intrnl;
4346                 int f = 0;
4347                 /* We use SAVEFREEPV so that when the full compile 
4348                     is finished perl will clean up the allocated 
4349                     minlens when it's all done. This way we don't
4350                     have to worry about freeing them when we know
4351                     they wont be used, which would be a pain.
4352                  */
4353                 I32 *minnextp;
4354                 Newx( minnextp, 1, I32 );
4355                 SAVEFREEPV(minnextp);
4356
4357                 if (data) {
4358                     StructCopy(data, &data_fake, scan_data_t);
4359                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
4360                         f |= SCF_DO_SUBSTR;
4361                         if (scan->flags) 
4362                             SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
4363                         data_fake.last_found=newSVsv(data->last_found);
4364                     }
4365                 }
4366                 else
4367                     data_fake.last_closep = &fake;
4368                 data_fake.flags = 0;
4369                 data_fake.pos_delta = delta;
4370                 if (is_inf)
4371                     data_fake.flags |= SF_IS_INF;
4372                 if ( flags & SCF_DO_STCLASS && !scan->flags
4373                      && OP(scan) == IFMATCH ) { /* Lookahead */
4374                     cl_init(pRExC_state, &intrnl);
4375                     data_fake.start_class = &intrnl;
4376                     f |= SCF_DO_STCLASS_AND;
4377                 }
4378                 if (flags & SCF_WHILEM_VISITED_POS)
4379                     f |= SCF_WHILEM_VISITED_POS;
4380                 next = regnext(scan);
4381                 nscan = NEXTOPER(NEXTOPER(scan));
4382
4383                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, 
4384                     last, &data_fake, stopparen, recursed, NULL, f,depth+1);
4385                 if (scan->flags) {
4386                     if (deltanext) {
4387                         FAIL("Variable length lookbehind not implemented");
4388                     }
4389                     else if (*minnextp > (I32)U8_MAX) {
4390                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
4391                     }
4392                     scan->flags = (U8)*minnextp;
4393                 }
4394
4395                 *minnextp += min;
4396
4397                 if (f & SCF_DO_STCLASS_AND) {
4398                     const int was = (data->start_class->flags & ANYOF_EOS);
4399
4400                     cl_and(data->start_class, &intrnl);
4401                     if (was)
4402                         data->start_class->flags |= ANYOF_EOS;
4403                 }
4404                 if (data) {
4405                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4406                         pars++;
4407                     if (data_fake.flags & SF_HAS_EVAL)
4408                         data->flags |= SF_HAS_EVAL;
4409                     data->whilem_c = data_fake.whilem_c;
4410                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
4411                         if (RExC_rx->minlen<*minnextp)
4412                             RExC_rx->minlen=*minnextp;
4413                         SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
4414                         SvREFCNT_dec_NN(data_fake.last_found);
4415                         
4416                         if ( data_fake.minlen_fixed != minlenp ) 
4417                         {
4418                             data->offset_fixed= data_fake.offset_fixed;
4419                             data->minlen_fixed= data_fake.minlen_fixed;
4420                             data->lookbehind_fixed+= scan->flags;
4421                         }
4422                         if ( data_fake.minlen_float != minlenp )
4423                         {
4424                             data->minlen_float= data_fake.minlen_float;
4425                             data->offset_float_min=data_fake.offset_float_min;
4426                             data->offset_float_max=data_fake.offset_float_max;
4427                             data->lookbehind_float+= scan->flags;
4428                         }
4429                     }
4430                 }
4431             }
4432 #endif
4433         }
4434         else if (OP(scan) == OPEN) {
4435             if (stopparen != (I32)ARG(scan))
4436                 pars++;
4437         }
4438         else if (OP(scan) == CLOSE) {
4439             if (stopparen == (I32)ARG(scan)) {
4440                 break;
4441             }
4442             if ((I32)ARG(scan) == is_par) {
4443                 next = regnext(scan);
4444
4445                 if ( next && (OP(next) != WHILEM) && next < last)
4446                     is_par = 0;         /* Disable optimization */
4447             }
4448             if (data)
4449                 *(data->last_closep) = ARG(scan);
4450         }
4451         else if (OP(scan) == EVAL) {
4452                 if (data)
4453                     data->flags |= SF_HAS_EVAL;
4454         }
4455         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
4456             if (flags & SCF_DO_SUBSTR) {
4457                 SCAN_COMMIT(pRExC_state,data,minlenp);
4458                 flags &= ~SCF_DO_SUBSTR;
4459             }
4460             if (data && OP(scan)==ACCEPT) {
4461                 data->flags |= SCF_SEEN_ACCEPT;
4462                 if (stopmin > min)
4463                     stopmin = min;
4464             }
4465         }
4466         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
4467         {
4468                 if (flags & SCF_DO_SUBSTR) {
4469                     SCAN_COMMIT(pRExC_state,data,minlenp);
4470                     data->longest = &(data->longest_float);
4471                 }
4472                 is_inf = is_inf_internal = 1;
4473                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4474                     cl_anything(pRExC_state, data->start_class);
4475                 flags &= ~SCF_DO_STCLASS;
4476         }
4477         else if (OP(scan) == GPOS) {
4478             if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
4479                 !(delta || is_inf || (data && data->pos_delta))) 
4480             {
4481                 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
4482                     RExC_rx->extflags |= RXf_ANCH_GPOS;
4483                 if (RExC_rx->gofs < (U32)min)
4484                     RExC_rx->gofs = min;
4485             } else {
4486                 RExC_rx->extflags |= RXf_GPOS_FLOAT;
4487                 RExC_rx->gofs = 0;
4488             }       
4489         }
4490 #ifdef TRIE_STUDY_OPT
4491 #ifdef FULL_TRIE_STUDY
4492         else if (PL_regkind[OP(scan)] == TRIE) {
4493             /* NOTE - There is similar code to this block above for handling
4494                BRANCH nodes on the initial study.  If you change stuff here
4495                check there too. */
4496             regnode *trie_node= scan;
4497             regnode *tail= regnext(scan);
4498             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4499             I32 max1 = 0, min1 = I32_MAX;
4500             struct regnode_charclass_class accum;
4501
4502             if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
4503                 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
4504             if (flags & SCF_DO_STCLASS)
4505                 cl_init_zero(pRExC_state, &accum);
4506                 
4507             if (!trie->jump) {
4508                 min1= trie->minlen;
4509                 max1= trie->maxlen;
4510             } else {
4511                 const regnode *nextbranch= NULL;
4512                 U32 word;
4513                 
4514                 for ( word=1 ; word <= trie->wordcount ; word++) 
4515                 {
4516                     I32 deltanext=0, minnext=0, f = 0, fake;
4517                     struct regnode_charclass_class this_class;
4518                     
4519                     data_fake.flags = 0;
4520                     if (data) {
4521                         data_fake.whilem_c = data->whilem_c;
4522                         data_fake.last_closep = data->last_closep;
4523                     }
4524                     else
4525                         data_fake.last_closep = &fake;
4526                     data_fake.pos_delta = delta;
4527                     if (flags & SCF_DO_STCLASS) {
4528                         cl_init(pRExC_state, &this_class);
4529                         data_fake.start_class = &this_class;
4530                         f = SCF_DO_STCLASS_AND;
4531                     }
4532                     if (flags & SCF_WHILEM_VISITED_POS)
4533                         f |= SCF_WHILEM_VISITED_POS;
4534     
4535                     if (trie->jump[word]) {
4536                         if (!nextbranch)
4537                             nextbranch = trie_node + trie->jump[0];
4538                         scan= trie_node + trie->jump[word];
4539                         /* We go from the jump point to the branch that follows
4540                            it. Note this means we need the vestigal unused branches
4541                            even though they arent otherwise used.
4542                          */
4543                         minnext = study_chunk(pRExC_state, &scan, minlenp, 
4544                             &deltanext, (regnode *)nextbranch, &data_fake, 
4545                             stopparen, recursed, NULL, f,depth+1);
4546                     }
4547                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
4548                         nextbranch= regnext((regnode*)nextbranch);
4549                     
4550                     if (min1 > (I32)(minnext + trie->minlen))
4551                         min1 = minnext + trie->minlen;
4552                     if (max1 < (I32)(minnext + deltanext + trie->maxlen))
4553                         max1 = minnext + deltanext + trie->maxlen;
4554                     if (deltanext == I32_MAX)
4555                         is_inf = is_inf_internal = 1;
4556                     
4557                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4558                         pars++;
4559                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4560                         if ( stopmin > min + min1) 
4561                             stopmin = min + min1;
4562                         flags &= ~SCF_DO_SUBSTR;
4563                         if (data)
4564                             data->flags |= SCF_SEEN_ACCEPT;
4565                     }
4566                     if (data) {
4567                         if (data_fake.flags & SF_HAS_EVAL)
4568                             data->flags |= SF_HAS_EVAL;
4569                         data->whilem_c = data_fake.whilem_c;
4570                     }
4571                     if (flags & SCF_DO_STCLASS)
4572                         cl_or(pRExC_state, &accum, &this_class);
4573                 }
4574             }
4575             if (flags & SCF_DO_SUBSTR) {
4576                 data->pos_min += min1;
4577                 data->pos_delta += max1 - min1;
4578                 if (max1 != min1 || is_inf)
4579                     data->longest = &(data->longest_float);
4580             }
4581             min += min1;
4582             delta += max1 - min1;
4583             if (flags & SCF_DO_STCLASS_OR) {
4584                 cl_or(pRExC_state, data->start_class, &accum);
4585                 if (min1) {
4586                     cl_and(data->start_class, and_withp);
4587                     flags &= ~SCF_DO_STCLASS;
4588                 }
4589             }
4590             else if (flags & SCF_DO_STCLASS_AND) {
4591                 if (min1) {
4592                     cl_and(data->start_class, &accum);
4593                     flags &= ~SCF_DO_STCLASS;
4594                 }
4595                 else {
4596                     /* Switch to OR mode: cache the old value of
4597                      * data->start_class */
4598                     INIT_AND_WITHP;
4599                     StructCopy(data->start_class, and_withp,
4600                                struct regnode_charclass_class);
4601                     flags &= ~SCF_DO_STCLASS_AND;
4602                     StructCopy(&accum, data->start_class,
4603                                struct regnode_charclass_class);
4604                     flags |= SCF_DO_STCLASS_OR;
4605                     data->start_class->flags |= ANYOF_EOS;
4606                 }
4607             }
4608             scan= tail;
4609             continue;
4610         }
4611 #else
4612         else if (PL_regkind[OP(scan)] == TRIE) {
4613             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4614             U8*bang=NULL;
4615             
4616             min += trie->minlen;
4617             delta += (trie->maxlen - trie->minlen);
4618             flags &= ~SCF_DO_STCLASS; /* xxx */
4619             if (flags & SCF_DO_SUBSTR) {
4620                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4621                 data->pos_min += trie->minlen;
4622                 data->pos_delta += (trie->maxlen - trie->minlen);
4623                 if (trie->maxlen != trie->minlen)
4624                     data->longest = &(data->longest_float);
4625             }
4626             if (trie->jump) /* no more substrings -- for now /grr*/
4627                 flags &= ~SCF_DO_SUBSTR; 
4628         }
4629 #endif /* old or new */
4630 #endif /* TRIE_STUDY_OPT */
4631
4632         /* Else: zero-length, ignore. */
4633         scan = regnext(scan);
4634     }
4635     if (frame) {
4636         last = frame->last;
4637         scan = frame->next;
4638         stopparen = frame->stop;
4639         frame = frame->prev;
4640         goto fake_study_recurse;
4641     }
4642
4643   finish:
4644     assert(!frame);
4645     DEBUG_STUDYDATA("pre-fin:",data,depth);
4646
4647     *scanp = scan;
4648     *deltap = is_inf_internal ? I32_MAX : delta;
4649     if (flags & SCF_DO_SUBSTR && is_inf)
4650         data->pos_delta = I32_MAX - data->pos_min;
4651     if (is_par > (I32)U8_MAX)
4652         is_par = 0;
4653     if (is_par && pars==1 && data) {
4654         data->flags |= SF_IN_PAR;
4655         data->flags &= ~SF_HAS_PAR;
4656     }
4657     else if (pars && data) {
4658         data->flags |= SF_HAS_PAR;
4659         data->flags &= ~SF_IN_PAR;
4660     }
4661     if (flags & SCF_DO_STCLASS_OR)
4662         cl_and(data->start_class, and_withp);
4663     if (flags & SCF_TRIE_RESTUDY)
4664         data->flags |=  SCF_TRIE_RESTUDY;
4665     
4666     DEBUG_STUDYDATA("post-fin:",data,depth);
4667     
4668     return min < stopmin ? min : stopmin;
4669 }
4670
4671 STATIC U32
4672 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
4673 {
4674     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
4675
4676     PERL_ARGS_ASSERT_ADD_DATA;
4677
4678     Renewc(RExC_rxi->data,
4679            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
4680            char, struct reg_data);
4681     if(count)
4682         Renew(RExC_rxi->data->what, count + n, U8);
4683     else
4684         Newx(RExC_rxi->data->what, n, U8);
4685     RExC_rxi->data->count = count + n;
4686     Copy(s, RExC_rxi->data->what + count, n, U8);
4687     return count;
4688 }
4689
4690 /*XXX: todo make this not included in a non debugging perl */
4691 #ifndef PERL_IN_XSUB_RE
4692 void
4693 Perl_reginitcolors(pTHX)
4694 {
4695     dVAR;
4696     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
4697     if (s) {
4698         char *t = savepv(s);
4699         int i = 0;
4700         PL_colors[0] = t;
4701         while (++i < 6) {
4702             t = strchr(t, '\t');
4703             if (t) {
4704                 *t = '\0';
4705                 PL_colors[i] = ++t;
4706             }
4707             else
4708                 PL_colors[i] = t = (char *)"";
4709         }
4710     } else {
4711         int i = 0;
4712         while (i < 6)
4713             PL_colors[i++] = (char *)"";
4714     }
4715     PL_colorset = 1;
4716 }
4717 #endif
4718
4719
4720 #ifdef TRIE_STUDY_OPT
4721 #define CHECK_RESTUDY_GOTO_butfirst(dOsomething)            \
4722     STMT_START {                                            \
4723         if (                                                \
4724               (data.flags & SCF_TRIE_RESTUDY)               \
4725               && ! restudied++                              \
4726         ) {                                                 \
4727             dOsomething;                                    \
4728             goto reStudy;                                   \
4729         }                                                   \
4730     } STMT_END
4731 #else
4732 #define CHECK_RESTUDY_GOTO_butfirst
4733 #endif        
4734
4735 /*
4736  * pregcomp - compile a regular expression into internal code
4737  *
4738  * Decides which engine's compiler to call based on the hint currently in
4739  * scope
4740  */
4741
4742 #ifndef PERL_IN_XSUB_RE 
4743
4744 /* return the currently in-scope regex engine (or the default if none)  */
4745
4746 regexp_engine const *
4747 Perl_current_re_engine(pTHX)
4748 {
4749     dVAR;
4750
4751     if (IN_PERL_COMPILETIME) {
4752         HV * const table = GvHV(PL_hintgv);
4753         SV **ptr;
4754
4755         if (!table)
4756             return &PL_core_reg_engine;
4757         ptr = hv_fetchs(table, "regcomp", FALSE);
4758         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
4759             return &PL_core_reg_engine;
4760         return INT2PTR(regexp_engine*,SvIV(*ptr));
4761     }
4762     else {
4763         SV *ptr;
4764         if (!PL_curcop->cop_hints_hash)
4765             return &PL_core_reg_engine;
4766         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
4767         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
4768             return &PL_core_reg_engine;
4769         return INT2PTR(regexp_engine*,SvIV(ptr));
4770     }
4771 }
4772
4773
4774 REGEXP *
4775 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
4776 {
4777     dVAR;
4778     regexp_engine const *eng = current_re_engine();
4779     GET_RE_DEBUG_FLAGS_DECL;
4780
4781     PERL_ARGS_ASSERT_PREGCOMP;
4782
4783     /* Dispatch a request to compile a regexp to correct regexp engine. */
4784     DEBUG_COMPILE_r({
4785         PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4786                         PTR2UV(eng));
4787     });
4788     return CALLREGCOMP_ENG(eng, pattern, flags);
4789 }
4790 #endif
4791
4792 /* public(ish) entry point for the perl core's own regex compiling code.
4793  * It's actually a wrapper for Perl_re_op_compile that only takes an SV
4794  * pattern rather than a list of OPs, and uses the internal engine rather
4795  * than the current one */
4796
4797 REGEXP *
4798 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
4799 {
4800     SV *pat = pattern; /* defeat constness! */
4801     PERL_ARGS_ASSERT_RE_COMPILE;
4802     return Perl_re_op_compile(aTHX_ &pat, 1, NULL,
4803 #ifdef PERL_IN_XSUB_RE
4804                                 &my_reg_engine,
4805 #else
4806                                 &PL_core_reg_engine,
4807 #endif
4808                                 NULL, NULL, rx_flags, 0);
4809 }
4810
4811 /* see if there are any run-time code blocks in the pattern.
4812  * False positives are allowed */
4813
4814 static bool
4815 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state, OP *expr,
4816                     U32 pm_flags, char *pat, STRLEN plen)
4817 {
4818     int n = 0;
4819     STRLEN s;
4820
4821     /* avoid infinitely recursing when we recompile the pattern parcelled up
4822      * as qr'...'. A single constant qr// string can't have have any
4823      * run-time component in it, and thus, no runtime code. (A non-qr
4824      * string, however, can, e.g. $x =~ '(?{})') */
4825     if  ((pm_flags & PMf_IS_QR) && expr && expr->op_type == OP_CONST)
4826         return 0;
4827
4828     for (s = 0; s < plen; s++) {
4829         if (n < pRExC_state->num_code_blocks
4830             && s == pRExC_state->code_blocks[n].start)
4831         {
4832             s = pRExC_state->code_blocks[n].end;
4833             n++;
4834             continue;
4835         }
4836         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
4837          * positives here */
4838         if (pat[s] == '(' && pat[s+1] == '?' &&
4839             (pat[s+2] == '{' || (pat[s+2] == '?' && pat[s+3] == '{'))
4840         )
4841             return 1;
4842     }
4843     return 0;
4844 }
4845
4846 /* Handle run-time code blocks. We will already have compiled any direct
4847  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
4848  * copy of it, but with any literal code blocks blanked out and
4849  * appropriate chars escaped; then feed it into
4850  *
4851  *    eval "qr'modified_pattern'"
4852  *
4853  * For example,
4854  *
4855  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
4856  *
4857  * becomes
4858  *
4859  *    qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno'
4860  *
4861  * After eval_sv()-ing that, grab any new code blocks from the returned qr
4862  * and merge them with any code blocks of the original regexp.
4863  *
4864  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
4865  * instead, just save the qr and return FALSE; this tells our caller that
4866  * the original pattern needs upgrading to utf8.
4867  */
4868
4869 static bool
4870 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
4871     char *pat, STRLEN plen)
4872 {
4873     SV *qr;
4874
4875     GET_RE_DEBUG_FLAGS_DECL;
4876
4877     if (pRExC_state->runtime_code_qr) {
4878         /* this is the second time we've been called; this should
4879          * only happen if the main pattern got upgraded to utf8
4880          * during compilation; re-use the qr we compiled first time
4881          * round (which should be utf8 too)
4882          */
4883         qr = pRExC_state->runtime_code_qr;
4884         pRExC_state->runtime_code_qr = NULL;
4885         assert(RExC_utf8 && SvUTF8(qr));
4886     }
4887     else {
4888         int n = 0;
4889         STRLEN s;
4890         char *p, *newpat;
4891         int newlen = plen + 6; /* allow for "qr''x\0" extra chars */
4892         SV *sv, *qr_ref;
4893         dSP;
4894
4895         /* determine how many extra chars we need for ' and \ escaping */
4896         for (s = 0; s < plen; s++) {
4897             if (pat[s] == '\'' || pat[s] == '\\')
4898                 newlen++;
4899         }
4900
4901         Newx(newpat, newlen, char);
4902         p = newpat;
4903         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
4904
4905         for (s = 0; s < plen; s++) {
4906             if (n < pRExC_state->num_code_blocks
4907                 && s == pRExC_state->code_blocks[n].start)
4908             {
4909                 /* blank out literal code block */
4910                 assert(pat[s] == '(');
4911                 while (s <= pRExC_state->code_blocks[n].end) {
4912                     *p++ = '_';
4913                     s++;
4914                 }
4915                 s--;
4916                 n++;
4917                 continue;
4918             }
4919             if (pat[s] == '\'' || pat[s] == '\\')
4920                 *p++ = '\\';
4921             *p++ = pat[s];
4922         }
4923         *p++ = '\'';
4924         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED)
4925             *p++ = 'x';
4926         *p++ = '\0';
4927         DEBUG_COMPILE_r({
4928             PerlIO_printf(Perl_debug_log,
4929                 "%sre-parsing pattern for runtime code:%s %s\n",
4930                 PL_colors[4],PL_colors[5],newpat);
4931         });
4932
4933         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
4934         Safefree(newpat);
4935
4936         ENTER;
4937         SAVETMPS;
4938         save_re_context();
4939         PUSHSTACKi(PERLSI_REQUIRE);
4940         /* this causes the toker to collapse \\ into \ when parsing
4941          * qr''; normally only q'' does this. It also alters hints
4942          * handling */
4943         PL_reg_state.re_reparsing = TRUE;
4944         eval_sv(sv, G_SCALAR);
4945         SvREFCNT_dec_NN(sv);
4946         SPAGAIN;
4947         qr_ref = POPs;
4948         PUTBACK;
4949         {
4950             SV * const errsv = ERRSV;
4951             if (SvTRUE_NN(errsv))
4952             {
4953                 Safefree(pRExC_state->code_blocks);
4954                 /* use croak_sv ? */
4955                 Perl_croak_nocontext("%s", SvPV_nolen_const(errsv));
4956             }
4957         }
4958         assert(SvROK(qr_ref));
4959         qr = SvRV(qr_ref);
4960         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
4961         /* the leaving below frees the tmp qr_ref.
4962          * Give qr a life of its own */
4963         SvREFCNT_inc(qr);
4964         POPSTACK;
4965         FREETMPS;
4966         LEAVE;
4967
4968     }
4969
4970     if (!RExC_utf8 && SvUTF8(qr)) {
4971         /* first time through; the pattern got upgraded; save the
4972          * qr for the next time through */
4973         assert(!pRExC_state->runtime_code_qr);
4974         pRExC_state->runtime_code_qr = qr;
4975         return 0;
4976     }
4977
4978
4979     /* extract any code blocks within the returned qr//  */
4980
4981
4982     /* merge the main (r1) and run-time (r2) code blocks into one */
4983     {
4984         RXi_GET_DECL(ReANY((REGEXP *)qr), r2);
4985         struct reg_code_block *new_block, *dst;
4986         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
4987         int i1 = 0, i2 = 0;
4988
4989         if (!r2->num_code_blocks) /* we guessed wrong */
4990         {
4991             SvREFCNT_dec_NN(qr);
4992             return 1;
4993         }
4994
4995         Newx(new_block,
4996             r1->num_code_blocks + r2->num_code_blocks,
4997             struct reg_code_block);
4998         dst = new_block;
4999
5000         while (    i1 < r1->num_code_blocks
5001                 || i2 < r2->num_code_blocks)
5002         {
5003             struct reg_code_block *src;
5004             bool is_qr = 0;
5005
5006             if (i1 == r1->num_code_blocks) {
5007                 src = &r2->code_blocks[i2++];
5008                 is_qr = 1;
5009             }
5010             else if (i2 == r2->num_code_blocks)
5011                 src = &r1->code_blocks[i1++];
5012             else if (  r1->code_blocks[i1].start
5013                      < r2->code_blocks[i2].start)
5014             {
5015                 src = &r1->code_blocks[i1++];
5016                 assert(src->end < r2->code_blocks[i2].start);
5017             }
5018             else {
5019                 assert(  r1->code_blocks[i1].start
5020                        > r2->code_blocks[i2].start);
5021                 src = &r2->code_blocks[i2++];
5022                 is_qr = 1;
5023                 assert(src->end < r1->code_blocks[i1].start);
5024             }
5025
5026             assert(pat[src->start] == '(');
5027             assert(pat[src->end]   == ')');
5028             dst->start      = src->start;
5029             dst->end        = src->end;
5030             dst->block      = src->block;
5031             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
5032                                     : src->src_regex;
5033             dst++;
5034         }
5035         r1->num_code_blocks += r2->num_code_blocks;
5036         Safefree(r1->code_blocks);
5037         r1->code_blocks = new_block;
5038     }
5039
5040     SvREFCNT_dec_NN(qr);
5041     return 1;
5042 }
5043
5044
5045 STATIC bool
5046 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)
5047 {
5048     /* This is the common code for setting up the floating and fixed length
5049      * string data extracted from Perlre_op_compile() below.  Returns a boolean
5050      * as to whether succeeded or not */
5051
5052     I32 t,ml;
5053
5054     if (! (longest_length
5055            || (eol /* Can't have SEOL and MULTI */
5056                && (! meol || (RExC_flags & RXf_PMf_MULTILINE)))
5057           )
5058             /* See comments for join_exact for why REG_SEEN_EXACTF_SHARP_S */
5059         || (RExC_seen & REG_SEEN_EXACTF_SHARP_S))
5060     {
5061         return FALSE;
5062     }
5063
5064     /* copy the information about the longest from the reg_scan_data
5065         over to the program. */
5066     if (SvUTF8(sv_longest)) {
5067         *rx_utf8 = sv_longest;
5068         *rx_substr = NULL;
5069     } else {
5070         *rx_substr = sv_longest;
5071         *rx_utf8 = NULL;
5072     }
5073     /* end_shift is how many chars that must be matched that
5074         follow this item. We calculate it ahead of time as once the
5075         lookbehind offset is added in we lose the ability to correctly
5076         calculate it.*/
5077     ml = minlen ? *(minlen) : (I32)longest_length;
5078     *rx_end_shift = ml - offset
5079         - longest_length + (SvTAIL(sv_longest) != 0)
5080         + lookbehind;
5081
5082     t = (eol/* Can't have SEOL and MULTI */
5083          && (! meol || (RExC_flags & RXf_PMf_MULTILINE)));
5084     fbm_compile(sv_longest, t ? FBMcf_TAIL : 0);
5085
5086     return TRUE;
5087 }
5088
5089 /*
5090  * Perl_re_op_compile - the perl internal RE engine's function to compile a
5091  * regular expression into internal code.
5092  * The pattern may be passed either as:
5093  *    a list of SVs (patternp plus pat_count)
5094  *    a list of OPs (expr)
5095  * If both are passed, the SV list is used, but the OP list indicates
5096  * which SVs are actually pre-compiled code blocks
5097  *
5098  * The SVs in the list have magic and qr overloading applied to them (and
5099  * the list may be modified in-place with replacement SVs in the latter
5100  * case).
5101  *
5102  * If the pattern hasn't changed from old_re, then old_re will be
5103  * returned.
5104  *
5105  * eng is the current engine. If that engine has an op_comp method, then
5106  * handle directly (i.e. we assume that op_comp was us); otherwise, just
5107  * do the initial concatenation of arguments and pass on to the external
5108  * engine.
5109  *
5110  * If is_bare_re is not null, set it to a boolean indicating whether the
5111  * arg list reduced (after overloading) to a single bare regex which has
5112  * been returned (i.e. /$qr/).
5113  *
5114  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
5115  *
5116  * pm_flags contains the PMf_* flags, typically based on those from the
5117  * pm_flags field of the related PMOP. Currently we're only interested in
5118  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
5119  *
5120  * We can't allocate space until we know how big the compiled form will be,
5121  * but we can't compile it (and thus know how big it is) until we've got a
5122  * place to put the code.  So we cheat:  we compile it twice, once with code
5123  * generation turned off and size counting turned on, and once "for real".
5124  * This also means that we don't allocate space until we are sure that the
5125  * thing really will compile successfully, and we never have to move the
5126  * code and thus invalidate pointers into it.  (Note that it has to be in
5127  * one piece because free() must be able to free it all.) [NB: not true in perl]
5128  *
5129  * Beware that the optimization-preparation code in here knows about some
5130  * of the structure of the compiled regexp.  [I'll say.]
5131  */
5132
5133 REGEXP *
5134 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
5135                     OP *expr, const regexp_engine* eng, REGEXP *VOL old_re,
5136                      bool *is_bare_re, U32 orig_rx_flags, U32 pm_flags)
5137 {
5138     dVAR;
5139     REGEXP *rx;
5140     struct regexp *r;
5141     regexp_internal *ri;
5142     STRLEN plen;
5143     char  * VOL exp;
5144     char* xend;
5145     regnode *scan;
5146     I32 flags;
5147     I32 minlen = 0;
5148     U32 rx_flags;
5149     SV * VOL pat;
5150     SV * VOL code_blocksv = NULL;
5151
5152     /* these are all flags - maybe they should be turned
5153      * into a single int with different bit masks */
5154     I32 sawlookahead = 0;
5155     I32 sawplus = 0;
5156     I32 sawopen = 0;
5157     bool used_setjump = FALSE;
5158     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
5159     bool code_is_utf8 = 0;
5160     bool VOL recompile = 0;
5161     bool runtime_code = 0;
5162     U8 jump_ret = 0;
5163     dJMPENV;
5164     scan_data_t data;
5165     RExC_state_t RExC_state;
5166     RExC_state_t * const pRExC_state = &RExC_state;
5167 #ifdef TRIE_STUDY_OPT    
5168     int restudied;
5169     RExC_state_t copyRExC_state;
5170 #endif    
5171     GET_RE_DEBUG_FLAGS_DECL;
5172
5173     PERL_ARGS_ASSERT_RE_OP_COMPILE;
5174
5175     DEBUG_r(if (!PL_colorset) reginitcolors());
5176
5177 #ifndef PERL_IN_XSUB_RE
5178     /* Initialize these here instead of as-needed, as is quick and avoids
5179      * having to test them each time otherwise */
5180     if (! PL_AboveLatin1) {
5181         PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
5182         PL_ASCII = _new_invlist_C_array(ASCII_invlist);
5183         PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
5184
5185         PL_L1Posix_ptrs[_CC_ALPHANUMERIC]
5186                                 = _new_invlist_C_array(L1PosixAlnum_invlist);
5187         PL_Posix_ptrs[_CC_ALPHANUMERIC]
5188                                 = _new_invlist_C_array(PosixAlnum_invlist);
5189
5190         PL_L1Posix_ptrs[_CC_ALPHA]
5191                                 = _new_invlist_C_array(L1PosixAlpha_invlist);
5192         PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(PosixAlpha_invlist);
5193
5194         PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(PosixBlank_invlist);
5195         PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(XPosixBlank_invlist);
5196         PL_L1Cased = _new_invlist_C_array(L1Cased_invlist);
5197
5198         PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(PosixCntrl_invlist);
5199         PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(XPosixCntrl_invlist);
5200
5201         PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(PosixDigit_invlist);
5202
5203         PL_L1Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(L1PosixGraph_invlist);
5204         PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(PosixGraph_invlist);
5205
5206         PL_L1Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(L1PosixLower_invlist);
5207         PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(PosixLower_invlist);
5208
5209         PL_L1Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(L1PosixPrint_invlist);
5210         PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(PosixPrint_invlist);
5211
5212         PL_L1Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(L1PosixPunct_invlist);
5213         PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(PosixPunct_invlist);
5214
5215         PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(PerlSpace_invlist);
5216         PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(XPerlSpace_invlist);
5217         PL_Posix_ptrs[_CC_PSXSPC] = _new_invlist_C_array(PosixSpace_invlist);
5218         PL_XPosix_ptrs[_CC_PSXSPC] = _new_invlist_C_array(XPosixSpace_invlist);
5219
5220         PL_L1Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(L1PosixUpper_invlist);
5221         PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(PosixUpper_invlist);
5222
5223         PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(VertSpace_invlist);
5224
5225         PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(PosixWord_invlist);
5226         PL_L1Posix_ptrs[_CC_WORDCHAR]
5227                                 = _new_invlist_C_array(L1PosixWord_invlist);
5228
5229         PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(PosixXDigit_invlist);
5230         PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(XPosixXDigit_invlist);
5231
5232         PL_HasMultiCharFold = _new_invlist_C_array(_Perl_Multi_Char_Folds_invlist);
5233     }
5234 #endif
5235
5236     pRExC_state->code_blocks = NULL;
5237     pRExC_state->num_code_blocks = 0;
5238
5239     if (is_bare_re)
5240         *is_bare_re = FALSE;
5241
5242     if (expr && (expr->op_type == OP_LIST ||
5243                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
5244
5245         /* is the source UTF8, and how many code blocks are there? */
5246         OP *o;
5247         int ncode = 0;
5248
5249         for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
5250             if (o->op_type == OP_CONST && SvUTF8(cSVOPo_sv))
5251                 code_is_utf8 = 1;
5252             else if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
5253                 /* count of DO blocks */
5254                 ncode++;
5255         }
5256         if (ncode) {
5257             pRExC_state->num_code_blocks = ncode;
5258             Newx(pRExC_state->code_blocks, ncode, struct reg_code_block);
5259         }
5260     }
5261
5262     if (pat_count) {
5263         /* handle a list of SVs */
5264
5265         SV **svp;
5266
5267         /* apply magic and RE overloading to each arg */
5268         for (svp = patternp; svp < patternp + pat_count; svp++) {
5269             SV *rx = *svp;
5270             SvGETMAGIC(rx);
5271             if (SvROK(rx) && SvAMAGIC(rx)) {
5272                 SV *sv = AMG_CALLunary(rx, regexp_amg);
5273                 if (sv) {
5274                     if (SvROK(sv))
5275                         sv = SvRV(sv);
5276                     if (SvTYPE(sv) != SVt_REGEXP)
5277                         Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
5278                     *svp = sv;
5279                 }
5280             }
5281         }
5282
5283         if (pat_count > 1) {
5284             /* concat multiple args and find any code block indexes */
5285
5286             OP *o = NULL;
5287             int n = 0;
5288             bool utf8 = 0;
5289             STRLEN orig_patlen = 0;
5290
5291             if (pRExC_state->num_code_blocks) {
5292                 o = cLISTOPx(expr)->op_first;
5293                 assert(   o->op_type == OP_PUSHMARK
5294                        || (o->op_type == OP_NULL && o->op_targ == OP_PUSHMARK)
5295                        || o->op_type == OP_PADRANGE);
5296                 o = o->op_sibling;
5297             }
5298
5299             pat = newSVpvn("", 0);
5300             SAVEFREESV(pat);
5301
5302             /* determine if the pattern is going to be utf8 (needed
5303              * in advance to align code block indices correctly).
5304              * XXX This could fail to be detected for an arg with
5305              * overloading but not concat overloading; but the main effect
5306              * in this obscure case is to need a 'use re eval' for a
5307              * literal code block */
5308             for (svp = patternp; svp < patternp + pat_count; svp++) {
5309                 if (SvUTF8(*svp))
5310                     utf8 = 1;
5311             }
5312             if (utf8)
5313                 SvUTF8_on(pat);
5314
5315             for (svp = patternp; svp < patternp + pat_count; svp++) {
5316                 SV *sv, *msv = *svp;
5317                 SV *rx;
5318                 bool code = 0;
5319                 /* we make the assumption here that each op in the list of
5320                  * op_siblings maps to one SV pushed onto the stack,
5321                  * except for code blocks, with have both an OP_NULL and
5322                  * and OP_CONST.
5323                  * This allows us to match up the list of SVs against the
5324                  * list of OPs to find the next code block.
5325                  *
5326                  * Note that       PUSHMARK PADSV PADSV ..
5327                  * is optimised to
5328                  *                 PADRANGE NULL  NULL  ..
5329                  * so the alignment still works. */
5330                 if (o) {
5331                     if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5332                         assert(n < pRExC_state->num_code_blocks);
5333                         pRExC_state->code_blocks[n].start = SvCUR(pat);
5334                         pRExC_state->code_blocks[n].block = o;
5335                         pRExC_state->code_blocks[n].src_regex = NULL;
5336                         n++;
5337                         code = 1;
5338                         o = o->op_sibling; /* skip CONST */
5339                         assert(o);
5340                     }
5341                     o = o->op_sibling;;
5342                 }
5343
5344                 if ((SvAMAGIC(pat) || SvAMAGIC(msv)) &&
5345                         (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
5346                 {
5347                     sv_setsv(pat, sv);
5348                     /* overloading involved: all bets are off over literal
5349                      * code. Pretend we haven't seen it */
5350                     pRExC_state->num_code_blocks -= n;
5351                     n = 0;
5352                     rx = NULL;
5353
5354                 }
5355                 else  {
5356                     while (SvAMAGIC(msv)
5357                             && (sv = AMG_CALLunary(msv, string_amg))
5358                             && sv != msv
5359                             &&  !(   SvROK(msv)
5360                                   && SvROK(sv)
5361                                   && SvRV(msv) == SvRV(sv))
5362                     ) {
5363                         msv = sv;
5364                         SvGETMAGIC(msv);
5365                     }
5366                     if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
5367                         msv = SvRV(msv);
5368                     orig_patlen = SvCUR(pat);
5369                     sv_catsv_nomg(pat, msv);
5370                     rx = msv;
5371                     if (code)
5372                         pRExC_state->code_blocks[n-1].end = SvCUR(pat)-1;
5373                 }
5374
5375                 /* extract any code blocks within any embedded qr//'s */
5376                 if (rx && SvTYPE(rx) == SVt_REGEXP
5377                     && RX_ENGINE((REGEXP*)rx)->op_comp)
5378                 {
5379
5380                     RXi_GET_DECL(ReANY((REGEXP *)rx), ri);
5381                     if (ri->num_code_blocks) {
5382                         int i;
5383                         /* the presence of an embedded qr// with code means
5384                          * we should always recompile: the text of the
5385                          * qr// may not have changed, but it may be a
5386                          * different closure than last time */
5387                         recompile = 1;
5388                         Renew(pRExC_state->code_blocks,
5389                             pRExC_state->num_code_blocks + ri->num_code_blocks,
5390                             struct reg_code_block);
5391                         pRExC_state->num_code_blocks += ri->num_code_blocks;
5392                         for (i=0; i < ri->num_code_blocks; i++) {
5393                             struct reg_code_block *src, *dst;
5394                             STRLEN offset =  orig_patlen
5395                                 + ReANY((REGEXP *)rx)->pre_prefix;
5396                             assert(n < pRExC_state->num_code_blocks);
5397                             src = &ri->code_blocks[i];
5398                             dst = &pRExC_state->code_blocks[n];
5399                             dst->start      = src->start + offset;
5400                             dst->end        = src->end   + offset;
5401                             dst->block      = src->block;
5402                             dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
5403                                                     src->src_regex
5404                                                         ? src->src_regex
5405                                                         : (REGEXP*)rx);
5406                             n++;
5407                         }
5408                     }
5409                 }
5410             }
5411             SvSETMAGIC(pat);
5412         }
5413         else {
5414             SV *sv;
5415             pat = *patternp;
5416             while (SvAMAGIC(pat)
5417                     && (sv = AMG_CALLunary(pat, string_amg))
5418                     && sv != pat)
5419             {
5420                 pat = sv;
5421                 SvGETMAGIC(pat);
5422             }
5423         }
5424
5425         /* handle bare regex: foo =~ $re */
5426         {
5427             SV *re = pat;
5428             if (SvROK(re))
5429                 re = SvRV(re);
5430             if (SvTYPE(re) == SVt_REGEXP) {
5431                 if (is_bare_re)
5432                     *is_bare_re = TRUE;
5433                 SvREFCNT_inc(re);
5434                 Safefree(pRExC_state->code_blocks);
5435                 return (REGEXP*)re;
5436             }
5437         }
5438     }
5439     else {
5440         /* not a list of SVs, so must be a list of OPs */
5441         assert(expr);
5442         if (expr->op_type == OP_LIST) {
5443             int i = -1;
5444             bool is_code = 0;
5445             OP *o;
5446
5447             pat = newSVpvn("", 0);
5448             SAVEFREESV(pat);
5449             if (code_is_utf8)
5450                 SvUTF8_on(pat);
5451
5452             /* given a list of CONSTs and DO blocks in expr, append all
5453              * the CONSTs to pat, and record the start and end of each
5454              * code block in code_blocks[] (each DO{} op is followed by an
5455              * OP_CONST containing the corresponding literal '(?{...})
5456              * text)
5457              */
5458             for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
5459                 if (o->op_type == OP_CONST) {
5460                     sv_catsv(pat, cSVOPo_sv);
5461                     if (is_code) {
5462                         pRExC_state->code_blocks[i].end = SvCUR(pat)-1;
5463                         is_code = 0;
5464                     }
5465                 }
5466                 else if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5467                     assert(i+1 < pRExC_state->num_code_blocks);
5468                     pRExC_state->code_blocks[++i].start = SvCUR(pat);
5469                     pRExC_state->code_blocks[i].block = o;
5470                     pRExC_state->code_blocks[i].src_regex = NULL;
5471                     is_code = 1;
5472                 }
5473             }
5474         }
5475         else {
5476             assert(expr->op_type == OP_CONST);
5477             pat = cSVOPx_sv(expr);
5478         }
5479     }
5480
5481     exp = SvPV_nomg(pat, plen);
5482
5483     if (!eng->op_comp) {
5484         if ((SvUTF8(pat) && IN_BYTES)
5485                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
5486         {
5487             /* make a temporary copy; either to convert to bytes,
5488              * or to avoid repeating get-magic / overloaded stringify */
5489             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
5490                                         (IN_BYTES ? 0 : SvUTF8(pat)));
5491         }
5492         Safefree(pRExC_state->code_blocks);
5493         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
5494     }
5495
5496     /* ignore the utf8ness if the pattern is 0 length */
5497     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
5498     RExC_uni_semantics = 0;
5499     RExC_contains_locale = 0;
5500     pRExC_state->runtime_code_qr = NULL;
5501
5502     /****************** LONG JUMP TARGET HERE***********************/
5503     /* Longjmp back to here if have to switch in midstream to utf8 */
5504     if (! RExC_orig_utf8) {
5505         JMPENV_PUSH(jump_ret);
5506         used_setjump = TRUE;
5507     }
5508
5509     if (jump_ret == 0) {    /* First time through */
5510         xend = exp + plen;
5511
5512         DEBUG_COMPILE_r({
5513             SV *dsv= sv_newmortal();
5514             RE_PV_QUOTED_DECL(s, RExC_utf8,
5515                 dsv, exp, plen, 60);
5516             PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
5517                            PL_colors[4],PL_colors[5],s);
5518         });
5519     }
5520     else {  /* longjumped back */
5521         U8 *src, *dst;
5522         int n=0;
5523         STRLEN s = 0, d = 0;
5524         bool do_end = 0;
5525
5526         /* If the cause for the longjmp was other than changing to utf8, pop
5527          * our own setjmp, and longjmp to the correct handler */
5528         if (jump_ret != UTF8_LONGJMP) {
5529             JMPENV_POP;
5530             JMPENV_JUMP(jump_ret);
5531         }
5532
5533         GET_RE_DEBUG_FLAGS;
5534
5535         /* It's possible to write a regexp in ascii that represents Unicode
5536         codepoints outside of the byte range, such as via \x{100}. If we
5537         detect such a sequence we have to convert the entire pattern to utf8
5538         and then recompile, as our sizing calculation will have been based
5539         on 1 byte == 1 character, but we will need to use utf8 to encode
5540         at least some part of the pattern, and therefore must convert the whole
5541         thing.
5542         -- dmq */
5543         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
5544             "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
5545
5546         /* upgrade pattern to UTF8, and if there are code blocks,
5547          * recalculate the indices.
5548          * This is essentially an unrolled Perl_bytes_to_utf8() */
5549
5550         src = (U8*)SvPV_nomg(pat, plen);
5551         Newx(dst, plen * 2 + 1, U8);
5552
5553         while (s < plen) {
5554             const UV uv = NATIVE_TO_ASCII(src[s]);
5555             if (UNI_IS_INVARIANT(uv))
5556                 dst[d]   = (U8)UTF_TO_NATIVE(uv);
5557             else {
5558                 dst[d++] = (U8)UTF8_EIGHT_BIT_HI(uv);
5559                 dst[d]   = (U8)UTF8_EIGHT_BIT_LO(uv);
5560             }
5561             if (n < pRExC_state->num_code_blocks) {
5562                 if (!do_end && pRExC_state->code_blocks[n].start == s) {
5563                     pRExC_state->code_blocks[n].start = d;
5564                     assert(dst[d] == '(');
5565                     do_end = 1;
5566                 }
5567                 else if (do_end && pRExC_state->code_blocks[n].end == s) {
5568                     pRExC_state->code_blocks[n].end = d;
5569                     assert(dst[d] == ')');
5570                     do_end = 0;
5571                     n++;
5572                 }
5573             }
5574             s++;
5575             d++;
5576         }
5577         dst[d] = '\0';
5578         plen = d;
5579         exp = (char*) dst;
5580         xend = exp + plen;
5581         SAVEFREEPV(exp);
5582         RExC_orig_utf8 = RExC_utf8 = 1;
5583     }
5584
5585     /* return old regex if pattern hasn't changed */
5586
5587     if (   old_re
5588         && !recompile
5589         && !!RX_UTF8(old_re) == !!RExC_utf8
5590         && RX_PRECOMP(old_re)
5591         && RX_PRELEN(old_re) == plen
5592         && memEQ(RX_PRECOMP(old_re), exp, plen))
5593     {
5594         /* with runtime code, always recompile */
5595         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, expr, pm_flags,
5596                                             exp, plen);
5597         if (!runtime_code) {
5598             if (used_setjump) {
5599                 JMPENV_POP;
5600             }
5601             Safefree(pRExC_state->code_blocks);
5602             return old_re;
5603         }
5604     }
5605     else if ((pm_flags & PMf_USE_RE_EVAL)
5606                 /* this second condition covers the non-regex literal case,
5607                  * i.e.  $foo =~ '(?{})'. */
5608                 || ( !PL_reg_state.re_reparsing && IN_PERL_COMPILETIME
5609                     && (PL_hints & HINT_RE_EVAL))
5610     )
5611         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, expr, pm_flags,
5612                             exp, plen);
5613
5614 #ifdef TRIE_STUDY_OPT
5615     restudied = 0;
5616 #endif
5617
5618     rx_flags = orig_rx_flags;
5619
5620     if (initial_charset == REGEX_LOCALE_CHARSET) {
5621         RExC_contains_locale = 1;
5622     }
5623     else if (RExC_utf8 && initial_charset == REGEX_DEPENDS_CHARSET) {
5624
5625         /* Set to use unicode semantics if the pattern is in utf8 and has the
5626          * 'depends' charset specified, as it means unicode when utf8  */
5627         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
5628     }
5629
5630     RExC_precomp = exp;
5631     RExC_flags = rx_flags;
5632     RExC_pm_flags = pm_flags;
5633
5634     if (runtime_code) {
5635         if (TAINTING_get && TAINT_get)
5636             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
5637
5638         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
5639             /* whoops, we have a non-utf8 pattern, whilst run-time code
5640              * got compiled as utf8. Try again with a utf8 pattern */
5641              JMPENV_JUMP(UTF8_LONGJMP);
5642         }
5643     }
5644     assert(!pRExC_state->runtime_code_qr);
5645
5646     RExC_sawback = 0;
5647
5648     RExC_seen = 0;
5649     RExC_in_lookbehind = 0;
5650     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
5651     RExC_extralen = 0;
5652     RExC_override_recoding = 0;
5653     RExC_in_multi_char_class = 0;
5654
5655     /* First pass: determine size, legality. */
5656     RExC_parse = exp;
5657     RExC_start = exp;
5658     RExC_end = xend;
5659     RExC_naughty = 0;
5660     RExC_npar = 1;
5661     RExC_nestroot = 0;
5662     RExC_size = 0L;
5663     RExC_emit = &PL_regdummy;
5664     RExC_whilem_seen = 0;
5665     RExC_open_parens = NULL;
5666     RExC_close_parens = NULL;
5667     RExC_opend = NULL;
5668     RExC_paren_names = NULL;
5669 #ifdef DEBUGGING
5670     RExC_paren_name_list = NULL;
5671 #endif
5672     RExC_recurse = NULL;
5673     RExC_recurse_count = 0;
5674     pRExC_state->code_index = 0;
5675
5676 #if 0 /* REGC() is (currently) a NOP at the first pass.
5677        * Clever compilers notice this and complain. --jhi */
5678     REGC((U8)REG_MAGIC, (char*)RExC_emit);
5679 #endif
5680     DEBUG_PARSE_r(
5681         PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n");
5682         RExC_lastnum=0;
5683         RExC_lastparse=NULL;
5684     );
5685     /* reg may croak on us, not giving us a chance to free
5686        pRExC_state->code_blocks.  We cannot SAVEFREEPV it now, as we may
5687        need it to survive as long as the regexp (qr/(?{})/).
5688        We must check that code_blocksv is not already set, because we may
5689        have longjmped back. */
5690     if (pRExC_state->code_blocks && !code_blocksv) {
5691         code_blocksv = newSV_type(SVt_PV);
5692         SAVEFREESV(code_blocksv);
5693         SvPV_set(code_blocksv, (char *)pRExC_state->code_blocks);
5694         SvLEN_set(code_blocksv, 1); /*sufficient to make sv_clear free it*/
5695     }
5696     if (reg(pRExC_state, 0, &flags,1) == NULL) {
5697         RExC_precomp = NULL;
5698         return(NULL);
5699     }
5700     if (code_blocksv)
5701         SvLEN_set(code_blocksv,0); /* no you can't have it, sv_clear */
5702
5703     /* Here, finished first pass.  Get rid of any added setjmp */
5704     if (used_setjump) {
5705         JMPENV_POP;
5706     }
5707
5708     DEBUG_PARSE_r({
5709         PerlIO_printf(Perl_debug_log, 
5710             "Required size %"IVdf" nodes\n"
5711             "Starting second pass (creation)\n", 
5712             (IV)RExC_size);
5713         RExC_lastnum=0; 
5714         RExC_lastparse=NULL; 
5715     });
5716
5717     /* The first pass could have found things that force Unicode semantics */
5718     if ((RExC_utf8 || RExC_uni_semantics)
5719          && get_regex_charset(rx_flags) == REGEX_DEPENDS_CHARSET)
5720     {
5721         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
5722     }
5723
5724     /* Small enough for pointer-storage convention?
5725        If extralen==0, this means that we will not need long jumps. */
5726     if (RExC_size >= 0x10000L && RExC_extralen)
5727         RExC_size += RExC_extralen;
5728     else
5729         RExC_extralen = 0;
5730     if (RExC_whilem_seen > 15)
5731         RExC_whilem_seen = 15;
5732
5733     /* Allocate space and zero-initialize. Note, the two step process 
5734        of zeroing when in debug mode, thus anything assigned has to 
5735        happen after that */
5736     rx = (REGEXP*) newSV_type(SVt_REGEXP);
5737     r = ReANY(rx);
5738     Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
5739          char, regexp_internal);
5740     if ( r == NULL || ri == NULL )
5741         FAIL("Regexp out of space");
5742 #ifdef DEBUGGING
5743     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
5744     Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
5745 #else 
5746     /* bulk initialize base fields with 0. */
5747     Zero(ri, sizeof(regexp_internal), char);        
5748 #endif
5749
5750     /* non-zero initialization begins here */
5751     RXi_SET( r, ri );
5752     r->engine= eng;
5753     r->extflags = rx_flags;
5754     if (pm_flags & PMf_IS_QR) {
5755         ri->code_blocks = pRExC_state->code_blocks;
5756         ri->num_code_blocks = pRExC_state->num_code_blocks;
5757     }
5758     else
5759     {
5760         int n;
5761         for (n = 0; n < pRExC_state->num_code_blocks; n++)
5762             if (pRExC_state->code_blocks[n].src_regex)
5763                 SAVEFREESV(pRExC_state->code_blocks[n].src_regex);
5764         SAVEFREEPV(pRExC_state->code_blocks);
5765     }
5766
5767     {
5768         bool has_p     = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
5769         bool has_charset = (get_regex_charset(r->extflags) != REGEX_DEPENDS_CHARSET);
5770
5771         /* The caret is output if there are any defaults: if not all the STD
5772          * flags are set, or if no character set specifier is needed */
5773         bool has_default =
5774                     (((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
5775                     || ! has_charset);
5776         bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
5777         U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD)
5778                             >> RXf_PMf_STD_PMMOD_SHIFT);
5779         const char *fptr = STD_PAT_MODS;        /*"msix"*/
5780         char *p;
5781         /* Allocate for the worst case, which is all the std flags are turned
5782          * on.  If more precision is desired, we could do a population count of
5783          * the flags set.  This could be done with a small lookup table, or by
5784          * shifting, masking and adding, or even, when available, assembly
5785          * language for a machine-language population count.
5786          * We never output a minus, as all those are defaults, so are
5787          * covered by the caret */
5788         const STRLEN wraplen = plen + has_p + has_runon
5789             + has_default       /* If needs a caret */
5790
5791                 /* If needs a character set specifier */
5792             + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
5793             + (sizeof(STD_PAT_MODS) - 1)
5794             + (sizeof("(?:)") - 1);
5795
5796         Newx(p, wraplen + 1, char); /* +1 for the ending NUL */
5797         r->xpv_len_u.xpvlenu_pv = p;
5798         if (RExC_utf8)
5799             SvFLAGS(rx) |= SVf_UTF8;
5800         *p++='('; *p++='?';
5801
5802         /* If a default, cover it using the caret */
5803         if (has_default) {
5804             *p++= DEFAULT_PAT_MOD;
5805         }
5806         if (has_charset) {
5807             STRLEN len;
5808             const char* const name = get_regex_charset_name(r->extflags, &len);
5809             Copy(name, p, len, char);
5810             p += len;
5811         }
5812         if (has_p)
5813             *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
5814         {
5815             char ch;
5816             while((ch = *fptr++)) {
5817                 if(reganch & 1)
5818                     *p++ = ch;
5819                 reganch >>= 1;
5820             }
5821         }
5822
5823         *p++ = ':';
5824         Copy(RExC_precomp, p, plen, char);
5825         assert ((RX_WRAPPED(rx) - p) < 16);
5826         r->pre_prefix = p - RX_WRAPPED(rx);
5827         p += plen;
5828         if (has_runon)
5829             *p++ = '\n';
5830         *p++ = ')';
5831         *p = 0;
5832         SvCUR_set(rx, p - RX_WRAPPED(rx));
5833     }
5834
5835     r->intflags = 0;
5836     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
5837     
5838     if (RExC_seen & REG_SEEN_RECURSE) {
5839         Newxz(RExC_open_parens, RExC_npar,regnode *);
5840         SAVEFREEPV(RExC_open_parens);
5841         Newxz(RExC_close_parens,RExC_npar,regnode *);
5842         SAVEFREEPV(RExC_close_parens);
5843     }
5844
5845     /* Useful during FAIL. */
5846 #ifdef RE_TRACK_PATTERN_OFFSETS
5847     Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
5848     DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
5849                           "%s %"UVuf" bytes for offset annotations.\n",
5850                           ri->u.offsets ? "Got" : "Couldn't get",
5851                           (UV)((2*RExC_size+1) * sizeof(U32))));
5852 #endif
5853     SetProgLen(ri,RExC_size);
5854     RExC_rx_sv = rx;
5855     RExC_rx = r;
5856     RExC_rxi = ri;
5857
5858     /* Second pass: emit code. */
5859     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
5860     RExC_pm_flags = pm_flags;
5861     RExC_parse = exp;
5862     RExC_end = xend;
5863     RExC_naughty = 0;
5864     RExC_npar = 1;
5865     RExC_emit_start = ri->program;
5866     RExC_emit = ri->program;
5867     RExC_emit_bound = ri->program + RExC_size + 1;
5868     pRExC_state->code_index = 0;
5869
5870     REGC((U8)REG_MAGIC, (char*) RExC_emit++);
5871     if (reg(pRExC_state, 0, &flags,1) == NULL) {
5872         ReREFCNT_dec(rx);   
5873         return(NULL);
5874     }
5875     /* XXXX To minimize changes to RE engine we always allocate
5876        3-units-long substrs field. */
5877     Newx(r->substrs, 1, struct reg_substr_data);
5878     if (RExC_recurse_count) {
5879         Newxz(RExC_recurse,RExC_recurse_count,regnode *);
5880         SAVEFREEPV(RExC_recurse);
5881     }
5882
5883 reStudy:
5884     r->minlen = minlen = sawlookahead = sawplus = sawopen = 0;
5885     Zero(r->substrs, 1, struct reg_substr_data);
5886
5887 #ifdef TRIE_STUDY_OPT
5888     if (!restudied) {
5889         StructCopy(&zero_scan_data, &data, scan_data_t);
5890         copyRExC_state = RExC_state;
5891     } else {
5892         U32 seen=RExC_seen;
5893         DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
5894         
5895         RExC_state = copyRExC_state;
5896         if (seen & REG_TOP_LEVEL_BRANCHES) 
5897             RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5898         else
5899             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
5900         StructCopy(&zero_scan_data, &data, scan_data_t);
5901     }
5902 #else
5903     StructCopy(&zero_scan_data, &data, scan_data_t);
5904 #endif    
5905
5906     /* Dig out information for optimizations. */
5907     r->extflags = RExC_flags; /* was pm_op */
5908     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
5909  
5910     if (UTF)
5911         SvUTF8_on(rx);  /* Unicode in it? */
5912     ri->regstclass = NULL;
5913     if (RExC_naughty >= 10)     /* Probably an expensive pattern. */
5914         r->intflags |= PREGf_NAUGHTY;
5915     scan = ri->program + 1;             /* First BRANCH. */
5916
5917     /* testing for BRANCH here tells us whether there is "must appear"
5918        data in the pattern. If there is then we can use it for optimisations */
5919     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /*  Only one top-level choice. */
5920         I32 fake;
5921         STRLEN longest_float_length, longest_fixed_length;
5922         struct regnode_charclass_class ch_class; /* pointed to by data */
5923         int stclass_flag;
5924         I32 last_close = 0; /* pointed to by data */
5925         regnode *first= scan;
5926         regnode *first_next= regnext(first);
5927         /*
5928          * Skip introductions and multiplicators >= 1
5929          * so that we can extract the 'meat' of the pattern that must 
5930          * match in the large if() sequence following.
5931          * NOTE that EXACT is NOT covered here, as it is normally
5932          * picked up by the optimiser separately. 
5933          *
5934          * This is unfortunate as the optimiser isnt handling lookahead
5935          * properly currently.
5936          *
5937          */
5938         while ((OP(first) == OPEN && (sawopen = 1)) ||
5939                /* An OR of *one* alternative - should not happen now. */
5940             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
5941             /* for now we can't handle lookbehind IFMATCH*/
5942             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
5943             (OP(first) == PLUS) ||
5944             (OP(first) == MINMOD) ||
5945                /* An {n,m} with n>0 */
5946             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
5947             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
5948         {
5949                 /* 
5950                  * the only op that could be a regnode is PLUS, all the rest
5951                  * will be regnode_1 or regnode_2.
5952                  *
5953                  */
5954                 if (OP(first) == PLUS)
5955                     sawplus = 1;
5956                 else
5957                     first += regarglen[OP(first)];
5958
5959                 first = NEXTOPER(first);
5960                 first_next= regnext(first);
5961         }
5962
5963         /* Starting-point info. */
5964       again:
5965         DEBUG_PEEP("first:",first,0);
5966         /* Ignore EXACT as we deal with it later. */
5967         if (PL_regkind[OP(first)] == EXACT) {
5968             if (OP(first) == EXACT)
5969                 NOOP;   /* Empty, get anchored substr later. */
5970             else
5971                 ri->regstclass = first;
5972         }
5973 #ifdef TRIE_STCLASS
5974         else if (PL_regkind[OP(first)] == TRIE &&
5975                 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0) 
5976         {
5977             regnode *trie_op;
5978             /* this can happen only on restudy */
5979             if ( OP(first) == TRIE ) {
5980                 struct regnode_1 *trieop = (struct regnode_1 *)
5981                     PerlMemShared_calloc(1, sizeof(struct regnode_1));
5982                 StructCopy(first,trieop,struct regnode_1);
5983                 trie_op=(regnode *)trieop;
5984             } else {
5985                 struct regnode_charclass *trieop = (struct regnode_charclass *)
5986                     PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
5987                 StructCopy(first,trieop,struct regnode_charclass);
5988                 trie_op=(regnode *)trieop;
5989             }
5990             OP(trie_op)+=2;
5991             make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
5992             ri->regstclass = trie_op;
5993         }
5994 #endif
5995         else if (REGNODE_SIMPLE(OP(first)))
5996             ri->regstclass = first;
5997         else if (PL_regkind[OP(first)] == BOUND ||
5998                  PL_regkind[OP(first)] == NBOUND)
5999             ri->regstclass = first;
6000         else if (PL_regkind[OP(first)] == BOL) {
6001             r->extflags |= (OP(first) == MBOL
6002                            ? RXf_ANCH_MBOL
6003                            : (OP(first) == SBOL
6004                               ? RXf_ANCH_SBOL
6005                               : RXf_ANCH_BOL));
6006             first = NEXTOPER(first);
6007             goto again;
6008         }
6009         else if (OP(first) == GPOS) {
6010             r->extflags |= RXf_ANCH_GPOS;
6011             first = NEXTOPER(first);
6012             goto again;
6013         }
6014         else if ((!sawopen || !RExC_sawback) &&
6015             (OP(first) == STAR &&
6016             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
6017             !(r->extflags & RXf_ANCH) && !pRExC_state->num_code_blocks)
6018         {
6019             /* turn .* into ^.* with an implied $*=1 */
6020             const int type =
6021                 (OP(NEXTOPER(first)) == REG_ANY)
6022                     ? RXf_ANCH_MBOL
6023                     : RXf_ANCH_SBOL;
6024             r->extflags |= type;
6025             r->intflags |= PREGf_IMPLICIT;
6026             first = NEXTOPER(first);
6027             goto again;
6028         }
6029         if (sawplus && !sawlookahead && (!sawopen || !RExC_sawback)
6030             && !pRExC_state->num_code_blocks) /* May examine pos and $& */
6031             /* x+ must match at the 1st pos of run of x's */
6032             r->intflags |= PREGf_SKIP;
6033
6034         /* Scan is after the zeroth branch, first is atomic matcher. */
6035 #ifdef TRIE_STUDY_OPT
6036         DEBUG_PARSE_r(
6037             if (!restudied)
6038                 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
6039                               (IV)(first - scan + 1))
6040         );
6041 #else
6042         DEBUG_PARSE_r(
6043             PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
6044                 (IV)(first - scan + 1))
6045         );
6046 #endif
6047
6048
6049         /*
6050         * If there's something expensive in the r.e., find the
6051         * longest literal string that must appear and make it the
6052         * regmust.  Resolve ties in favor of later strings, since
6053         * the regstart check works with the beginning of the r.e.
6054         * and avoiding duplication strengthens checking.  Not a
6055         * strong reason, but sufficient in the absence of others.
6056         * [Now we resolve ties in favor of the earlier string if
6057         * it happens that c_offset_min has been invalidated, since the
6058         * earlier string may buy us something the later one won't.]
6059         */
6060
6061         data.longest_fixed = newSVpvs("");
6062         data.longest_float = newSVpvs("");
6063         data.last_found = newSVpvs("");
6064         data.longest = &(data.longest_fixed);
6065         ENTER_with_name("study_chunk");
6066         SAVEFREESV(data.longest_fixed);
6067         SAVEFREESV(data.longest_float);
6068         SAVEFREESV(data.last_found);
6069         first = scan;
6070         if (!ri->regstclass) {
6071             cl_init(pRExC_state, &ch_class);
6072             data.start_class = &ch_class;
6073             stclass_flag = SCF_DO_STCLASS_AND;
6074         } else                          /* XXXX Check for BOUND? */
6075             stclass_flag = 0;
6076         data.last_closep = &last_close;
6077         
6078         minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
6079             &data, -1, NULL, NULL,
6080             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
6081
6082
6083         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
6084
6085
6086         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
6087              && data.last_start_min == 0 && data.last_end > 0
6088              && !RExC_seen_zerolen
6089              && !(RExC_seen & REG_SEEN_VERBARG)
6090              && (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
6091             r->extflags |= RXf_CHECK_ALL;
6092         scan_commit(pRExC_state, &data,&minlen,0);
6093
6094         longest_float_length = CHR_SVLEN(data.longest_float);
6095
6096         if (! ((SvCUR(data.longest_fixed)  /* ok to leave SvCUR */
6097                    && data.offset_fixed == data.offset_float_min
6098                    && SvCUR(data.longest_fixed) == SvCUR(data.longest_float)))
6099             && S_setup_longest (aTHX_ pRExC_state,
6100                                     data.longest_float,
6101                                     &(r->float_utf8),
6102                                     &(r->float_substr),
6103                                     &(r->float_end_shift),
6104                                     data.lookbehind_float,
6105                                     data.offset_float_min,
6106                                     data.minlen_float,
6107                                     longest_float_length,
6108                                     data.flags & SF_FL_BEFORE_EOL,
6109                                     data.flags & SF_FL_BEFORE_MEOL))
6110         {
6111             r->float_min_offset = data.offset_float_min - data.lookbehind_float;
6112             r->float_max_offset = data.offset_float_max;
6113             if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
6114                 r->float_max_offset -= data.lookbehind_float;
6115             SvREFCNT_inc_simple_void_NN(data.longest_float);
6116         }
6117         else {
6118             r->float_substr = r->float_utf8 = NULL;
6119             longest_float_length = 0;
6120         }
6121
6122         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
6123
6124         if (S_setup_longest (aTHX_ pRExC_state,
6125                                 data.longest_fixed,
6126                                 &(r->anchored_utf8),
6127                                 &(r->anchored_substr),
6128                                 &(r->anchored_end_shift),
6129                                 data.lookbehind_fixed,
6130                                 data.offset_fixed,
6131                                 data.minlen_fixed,
6132                                 longest_fixed_length,
6133                                 data.flags & SF_FIX_BEFORE_EOL,
6134                                 data.flags & SF_FIX_BEFORE_MEOL))
6135         {
6136             r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
6137             SvREFCNT_inc_simple_void_NN(data.longest_fixed);
6138         }
6139         else {
6140             r->anchored_substr = r->anchored_utf8 = NULL;
6141             longest_fixed_length = 0;
6142         }
6143         LEAVE_with_name("study_chunk");
6144
6145         if (ri->regstclass
6146             && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
6147             ri->regstclass = NULL;
6148
6149         if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
6150             && stclass_flag
6151             && !(data.start_class->flags & ANYOF_EOS)
6152             && !cl_is_anything(data.start_class))
6153         {
6154             const U32 n = add_data(pRExC_state, 1, "f");
6155             data.start_class->flags |= ANYOF_IS_SYNTHETIC;
6156
6157             Newx(RExC_rxi->data->data[n], 1,
6158                 struct regnode_charclass_class);
6159             StructCopy(data.start_class,
6160                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
6161                        struct regnode_charclass_class);
6162             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
6163             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
6164             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
6165                       regprop(r, sv, (regnode*)data.start_class);
6166                       PerlIO_printf(Perl_debug_log,
6167                                     "synthetic stclass \"%s\".\n",
6168                                     SvPVX_const(sv));});
6169         }
6170
6171         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
6172         if (longest_fixed_length > longest_float_length) {
6173             r->check_end_shift = r->anchored_end_shift;
6174             r->check_substr = r->anchored_substr;
6175             r->check_utf8 = r->anchored_utf8;
6176             r->check_offset_min = r->check_offset_max = r->anchored_offset;
6177             if (r->extflags & RXf_ANCH_SINGLE)
6178                 r->extflags |= RXf_NOSCAN;
6179         }
6180         else {
6181             r->check_end_shift = r->float_end_shift;
6182             r->check_substr = r->float_substr;
6183             r->check_utf8 = r->float_utf8;
6184             r->check_offset_min = r->float_min_offset;
6185             r->check_offset_max = r->float_max_offset;
6186         }
6187         /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
6188            This should be changed ASAP!  */
6189         if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
6190             r->extflags |= RXf_USE_INTUIT;
6191             if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
6192                 r->extflags |= RXf_INTUIT_TAIL;
6193         }
6194         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
6195         if ( (STRLEN)minlen < longest_float_length )
6196             minlen= longest_float_length;
6197         if ( (STRLEN)minlen < longest_fixed_length )
6198             minlen= longest_fixed_length;     
6199         */
6200     }
6201     else {
6202         /* Several toplevels. Best we can is to set minlen. */
6203         I32 fake;
6204         struct regnode_charclass_class ch_class;
6205         I32 last_close = 0;
6206
6207         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
6208
6209         scan = ri->program + 1;
6210         cl_init(pRExC_state, &ch_class);
6211         data.start_class = &ch_class;
6212         data.last_closep = &last_close;
6213
6214         
6215         minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
6216             &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
6217         
6218         CHECK_RESTUDY_GOTO_butfirst(NOOP);
6219
6220         r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
6221                 = r->float_substr = r->float_utf8 = NULL;
6222
6223         if (!(data.start_class->flags & ANYOF_EOS)
6224             && !cl_is_anything(data.start_class))
6225         {
6226             const U32 n = add_data(pRExC_state, 1, "f");
6227             data.start_class->flags |= ANYOF_IS_SYNTHETIC;
6228
6229             Newx(RExC_rxi->data->data[n], 1,
6230                 struct regnode_charclass_class);
6231             StructCopy(data.start_class,
6232                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
6233                        struct regnode_charclass_class);
6234             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
6235             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
6236             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
6237                       regprop(r, sv, (regnode*)data.start_class);
6238                       PerlIO_printf(Perl_debug_log,
6239                                     "synthetic stclass \"%s\".\n",
6240                                     SvPVX_const(sv));});
6241         }
6242     }
6243
6244     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
6245        the "real" pattern. */
6246     DEBUG_OPTIMISE_r({
6247         PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
6248                       (IV)minlen, (IV)r->minlen);
6249     });
6250     r->minlenret = minlen;
6251     if (r->minlen < minlen) 
6252         r->minlen = minlen;
6253     
6254     if (RExC_seen & REG_SEEN_GPOS)
6255         r->extflags |= RXf_GPOS_SEEN;
6256     if (RExC_seen & REG_SEEN_LOOKBEHIND)
6257         r->extflags |= RXf_LOOKBEHIND_SEEN;
6258     if (pRExC_state->num_code_blocks)
6259         r->extflags |= RXf_EVAL_SEEN;
6260     if (RExC_seen & REG_SEEN_CANY)
6261         r->extflags |= RXf_CANY_SEEN;
6262     if (RExC_seen & REG_SEEN_VERBARG)
6263     {
6264         r->intflags |= PREGf_VERBARG_SEEN;
6265         r->extflags |= RXf_MODIFIES_VARS;
6266     }
6267     if (RExC_seen & REG_SEEN_CUTGROUP)
6268         r->intflags |= PREGf_CUTGROUP_SEEN;
6269     if (pm_flags & PMf_USE_RE_EVAL)
6270         r->intflags |= PREGf_USE_RE_EVAL;
6271     if (RExC_paren_names)
6272         RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
6273     else
6274         RXp_PAREN_NAMES(r) = NULL;
6275
6276 #ifdef STUPID_PATTERN_CHECKS            
6277     if (RX_PRELEN(rx) == 0)
6278         r->extflags |= RXf_NULL;
6279     if (RX_PRELEN(rx) == 3 && memEQ("\\s+", RX_PRECOMP(rx), 3))
6280         r->extflags |= RXf_WHITE;
6281     else if (RX_PRELEN(rx) == 1 && RXp_PRECOMP(rx)[0] == '^')
6282         r->extflags |= RXf_START_ONLY;
6283 #else
6284     {
6285         regnode *first = ri->program + 1;
6286         U8 fop = OP(first);
6287
6288         if (PL_regkind[fop] == NOTHING && OP(NEXTOPER(first)) == END)
6289             r->extflags |= RXf_NULL;
6290         else if (PL_regkind[fop] == BOL && OP(NEXTOPER(first)) == END)
6291             r->extflags |= RXf_START_ONLY;
6292         else if (fop == PLUS && PL_regkind[OP(NEXTOPER(first))] == POSIXD && FLAGS(NEXTOPER(first)) == _CC_SPACE
6293                              && OP(regnext(first)) == END)
6294             r->extflags |= RXf_WHITE;    
6295     }
6296 #endif
6297 #ifdef DEBUGGING
6298     if (RExC_paren_names) {
6299         ri->name_list_idx = add_data( pRExC_state, 1, "a" );
6300         ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
6301     } else
6302 #endif
6303         ri->name_list_idx = 0;
6304
6305     if (RExC_recurse_count) {
6306         for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
6307             const regnode *scan = RExC_recurse[RExC_recurse_count-1];
6308             ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
6309         }
6310     }
6311     Newxz(r->offs, RExC_npar, regexp_paren_pair);
6312     /* assume we don't need to swap parens around before we match */
6313
6314     DEBUG_DUMP_r({
6315         PerlIO_printf(Perl_debug_log,"Final program:\n");
6316         regdump(r);
6317     });
6318 #ifdef RE_TRACK_PATTERN_OFFSETS
6319     DEBUG_OFFSETS_r(if (ri->u.offsets) {
6320         const U32 len = ri->u.offsets[0];
6321         U32 i;
6322         GET_RE_DEBUG_FLAGS_DECL;
6323         PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
6324         for (i = 1; i <= len; i++) {
6325             if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
6326                 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
6327                 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
6328             }
6329         PerlIO_printf(Perl_debug_log, "\n");
6330     });
6331 #endif
6332     return rx;
6333 }
6334
6335
6336 SV*
6337 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
6338                     const U32 flags)
6339 {
6340     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
6341
6342     PERL_UNUSED_ARG(value);
6343
6344     if (flags & RXapif_FETCH) {
6345         return reg_named_buff_fetch(rx, key, flags);
6346     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
6347         Perl_croak_no_modify();
6348         return NULL;
6349     } else if (flags & RXapif_EXISTS) {
6350         return reg_named_buff_exists(rx, key, flags)
6351             ? &PL_sv_yes
6352             : &PL_sv_no;
6353     } else if (flags & RXapif_REGNAMES) {
6354         return reg_named_buff_all(rx, flags);
6355     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
6356         return reg_named_buff_scalar(rx, flags);
6357     } else {
6358         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
6359         return NULL;
6360     }
6361 }
6362
6363 SV*
6364 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
6365                          const U32 flags)
6366 {
6367     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
6368     PERL_UNUSED_ARG(lastkey);
6369
6370     if (flags & RXapif_FIRSTKEY)
6371         return reg_named_buff_firstkey(rx, flags);
6372     else if (flags & RXapif_NEXTKEY)
6373         return reg_named_buff_nextkey(rx, flags);
6374     else {
6375         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags);
6376         return NULL;
6377     }
6378 }
6379
6380 SV*
6381 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
6382                           const U32 flags)
6383 {
6384     AV *retarray = NULL;
6385     SV *ret;
6386     struct regexp *const rx = ReANY(r);
6387
6388     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
6389
6390     if (flags & RXapif_ALL)
6391         retarray=newAV();
6392
6393     if (rx && RXp_PAREN_NAMES(rx)) {
6394         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
6395         if (he_str) {
6396             IV i;
6397             SV* sv_dat=HeVAL(he_str);
6398             I32 *nums=(I32*)SvPVX(sv_dat);
6399             for ( i=0; i<SvIVX(sv_dat); i++ ) {
6400                 if ((I32)(rx->nparens) >= nums[i]
6401                     && rx->offs[nums[i]].start != -1
6402                     && rx->offs[nums[i]].end != -1)
6403                 {
6404                     ret = newSVpvs("");
6405                     CALLREG_NUMBUF_FETCH(r,nums[i],ret);
6406                     if (!retarray)
6407                         return ret;
6408                 } else {
6409                     if (retarray)
6410                         ret = newSVsv(&PL_sv_undef);
6411                 }
6412                 if (retarray)
6413                     av_push(retarray, ret);
6414             }
6415             if (retarray)
6416                 return newRV_noinc(MUTABLE_SV(retarray));
6417         }
6418     }
6419     return NULL;
6420 }
6421
6422 bool
6423 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
6424                            const U32 flags)
6425 {
6426     struct regexp *const rx = ReANY(r);
6427
6428     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
6429
6430     if (rx && RXp_PAREN_NAMES(rx)) {
6431         if (flags & RXapif_ALL) {
6432             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
6433         } else {
6434             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
6435             if (sv) {
6436                 SvREFCNT_dec_NN(sv);
6437                 return TRUE;
6438             } else {
6439                 return FALSE;
6440             }
6441         }
6442     } else {
6443         return FALSE;
6444     }
6445 }
6446
6447 SV*
6448 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
6449 {
6450     struct regexp *const rx = ReANY(r);
6451
6452     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
6453
6454     if ( rx && RXp_PAREN_NAMES(rx) ) {
6455         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
6456
6457         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
6458     } else {
6459         return FALSE;
6460     }
6461 }
6462
6463 SV*
6464 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
6465 {
6466     struct regexp *const rx = ReANY(r);
6467     GET_RE_DEBUG_FLAGS_DECL;
6468
6469     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
6470
6471     if (rx && RXp_PAREN_NAMES(rx)) {
6472         HV *hv = RXp_PAREN_NAMES(rx);
6473         HE *temphe;
6474         while ( (temphe = hv_iternext_flags(hv,0)) ) {
6475             IV i;
6476             IV parno = 0;
6477             SV* sv_dat = HeVAL(temphe);
6478             I32 *nums = (I32*)SvPVX(sv_dat);
6479             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
6480                 if ((I32)(rx->lastparen) >= nums[i] &&
6481                     rx->offs[nums[i]].start != -1 &&
6482                     rx->offs[nums[i]].end != -1)
6483                 {
6484                     parno = nums[i];
6485                     break;
6486                 }
6487             }
6488             if (parno || flags & RXapif_ALL) {
6489                 return newSVhek(HeKEY_hek(temphe));
6490             }
6491         }
6492     }
6493     return NULL;
6494 }
6495
6496 SV*
6497 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
6498 {
6499     SV *ret;
6500     AV *av;
6501     I32 length;
6502     struct regexp *const rx = ReANY(r);
6503
6504     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
6505
6506     if (rx && RXp_PAREN_NAMES(rx)) {
6507         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
6508             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
6509         } else if (flags & RXapif_ONE) {
6510             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
6511             av = MUTABLE_AV(SvRV(ret));
6512             length = av_len(av);
6513             SvREFCNT_dec_NN(ret);
6514             return newSViv(length + 1);
6515         } else {
6516             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags);
6517             return NULL;
6518         }
6519     }
6520     return &PL_sv_undef;
6521 }
6522
6523 SV*
6524 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
6525 {
6526     struct regexp *const rx = ReANY(r);
6527     AV *av = newAV();
6528
6529     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
6530
6531     if (rx && RXp_PAREN_NAMES(rx)) {
6532         HV *hv= RXp_PAREN_NAMES(rx);
6533         HE *temphe;
6534         (void)hv_iterinit(hv);
6535         while ( (temphe = hv_iternext_flags(hv,0)) ) {
6536             IV i;
6537             IV parno = 0;
6538             SV* sv_dat = HeVAL(temphe);
6539             I32 *nums = (I32*)SvPVX(sv_dat);
6540             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
6541                 if ((I32)(rx->lastparen) >= nums[i] &&
6542                     rx->offs[nums[i]].start != -1 &&
6543                     rx->offs[nums[i]].end != -1)
6544                 {
6545                     parno = nums[i];
6546                     break;
6547                 }
6548             }
6549             if (parno || flags & RXapif_ALL) {
6550                 av_push(av, newSVhek(HeKEY_hek(temphe)));
6551             }
6552         }
6553     }
6554
6555     return newRV_noinc(MUTABLE_SV(av));
6556 }
6557
6558 void
6559 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
6560                              SV * const sv)
6561 {
6562     struct regexp *const rx = ReANY(r);
6563     char *s = NULL;
6564     I32 i = 0;
6565     I32 s1, t1;
6566     I32 n = paren;
6567
6568     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
6569         
6570     if ( (    n == RX_BUFF_IDX_CARET_PREMATCH
6571            || n == RX_BUFF_IDX_CARET_FULLMATCH
6572            || n == RX_BUFF_IDX_CARET_POSTMATCH
6573          )
6574          && !(rx->extflags & RXf_PMf_KEEPCOPY)
6575     )
6576         goto ret_undef;
6577
6578     if (!rx->subbeg)
6579         goto ret_undef;
6580
6581     if (n == RX_BUFF_IDX_CARET_FULLMATCH)
6582         /* no need to distinguish between them any more */
6583         n = RX_BUFF_IDX_FULLMATCH;
6584
6585     if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH)
6586         && rx->offs[0].start != -1)
6587     {
6588         /* $`, ${^PREMATCH} */
6589         i = rx->offs[0].start;
6590         s = rx->subbeg;
6591     }
6592     else 
6593     if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH)
6594         && rx->offs[0].end != -1)
6595     {
6596         /* $', ${^POSTMATCH} */
6597         s = rx->subbeg - rx->suboffset + rx->offs[0].end;
6598         i = rx->sublen + rx->suboffset - rx->offs[0].end;
6599     } 
6600     else
6601     if ( 0 <= n && n <= (I32)rx->nparens &&
6602         (s1 = rx->offs[n].start) != -1 &&
6603         (t1 = rx->offs[n].end) != -1)
6604     {
6605         /* $&, ${^MATCH},  $1 ... */
6606         i = t1 - s1;
6607         s = rx->subbeg + s1 - rx->suboffset;
6608     } else {
6609         goto ret_undef;
6610     }          
6611
6612     assert(s >= rx->subbeg);
6613     assert(rx->sublen >= (s - rx->subbeg) + i );
6614     if (i >= 0) {
6615 #if NO_TAINT_SUPPORT
6616         sv_setpvn(sv, s, i);
6617 #else
6618         const int oldtainted = TAINT_get;
6619         TAINT_NOT;
6620         sv_setpvn(sv, s, i);
6621         TAINT_set(oldtainted);
6622 #endif
6623         if ( (rx->extflags & RXf_CANY_SEEN)
6624             ? (RXp_MATCH_UTF8(rx)
6625                         && (!i || is_utf8_string((U8*)s, i)))
6626             : (RXp_MATCH_UTF8(rx)) )
6627         {
6628             SvUTF8_on(sv);
6629         }
6630         else
6631             SvUTF8_off(sv);
6632         if (TAINTING_get) {
6633             if (RXp_MATCH_TAINTED(rx)) {
6634                 if (SvTYPE(sv) >= SVt_PVMG) {
6635                     MAGIC* const mg = SvMAGIC(sv);
6636                     MAGIC* mgt;
6637                     TAINT;
6638                     SvMAGIC_set(sv, mg->mg_moremagic);
6639                     SvTAINT(sv);
6640                     if ((mgt = SvMAGIC(sv))) {
6641                         mg->mg_moremagic = mgt;
6642                         SvMAGIC_set(sv, mg);
6643                     }
6644                 } else {
6645                     TAINT;
6646                     SvTAINT(sv);
6647                 }
6648             } else 
6649                 SvTAINTED_off(sv);
6650         }
6651     } else {
6652       ret_undef:
6653         sv_setsv(sv,&PL_sv_undef);
6654         return;
6655     }
6656 }
6657
6658 void
6659 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
6660                                                          SV const * const value)
6661 {
6662     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
6663
6664     PERL_UNUSED_ARG(rx);
6665     PERL_UNUSED_ARG(paren);
6666     PERL_UNUSED_ARG(value);
6667
6668     if (!PL_localizing)
6669         Perl_croak_no_modify();
6670 }
6671
6672 I32
6673 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
6674                               const I32 paren)
6675 {
6676     struct regexp *const rx = ReANY(r);
6677     I32 i;
6678     I32 s1, t1;
6679
6680     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
6681
6682     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
6683     switch (paren) {
6684       case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */
6685          if (!(rx->extflags & RXf_PMf_KEEPCOPY))
6686             goto warn_undef;
6687         /*FALLTHROUGH*/
6688
6689       case RX_BUFF_IDX_PREMATCH:       /* $` */
6690         if (rx->offs[0].start != -1) {
6691                         i = rx->offs[0].start;
6692                         if (i > 0) {
6693                                 s1 = 0;
6694                                 t1 = i;
6695                                 goto getlen;
6696                         }
6697             }
6698         return 0;
6699
6700       case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */
6701          if (!(rx->extflags & RXf_PMf_KEEPCOPY))
6702             goto warn_undef;
6703       case RX_BUFF_IDX_POSTMATCH:       /* $' */
6704             if (rx->offs[0].end != -1) {
6705                         i = rx->sublen - rx->offs[0].end;
6706                         if (i > 0) {
6707                                 s1 = rx->offs[0].end;
6708                                 t1 = rx->sublen;
6709                                 goto getlen;
6710                         }
6711             }
6712         return 0;
6713
6714       case RX_BUFF_IDX_CARET_FULLMATCH: /* ${^MATCH} */
6715          if (!(rx->extflags & RXf_PMf_KEEPCOPY))
6716             goto warn_undef;
6717         /*FALLTHROUGH*/
6718
6719       /* $& / ${^MATCH}, $1, $2, ... */
6720       default:
6721             if (paren <= (I32)rx->nparens &&
6722             (s1 = rx->offs[paren].start) != -1 &&
6723             (t1 = rx->offs[paren].end) != -1)
6724             {
6725             i = t1 - s1;
6726             goto getlen;
6727         } else {
6728           warn_undef:
6729             if (ckWARN(WARN_UNINITIALIZED))
6730                 report_uninit((const SV *)sv);
6731             return 0;
6732         }
6733     }
6734   getlen:
6735     if (i > 0 && RXp_MATCH_UTF8(rx)) {
6736         const char * const s = rx->subbeg - rx->suboffset + s1;
6737         const U8 *ep;
6738         STRLEN el;
6739
6740         i = t1 - s1;
6741         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
6742                         i = el;
6743     }
6744     return i;
6745 }
6746
6747 SV*
6748 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
6749 {
6750     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
6751         PERL_UNUSED_ARG(rx);
6752         if (0)
6753             return NULL;
6754         else
6755             return newSVpvs("Regexp");
6756 }
6757
6758 /* Scans the name of a named buffer from the pattern.
6759  * If flags is REG_RSN_RETURN_NULL returns null.
6760  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
6761  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
6762  * to the parsed name as looked up in the RExC_paren_names hash.
6763  * If there is an error throws a vFAIL().. type exception.
6764  */
6765
6766 #define REG_RSN_RETURN_NULL    0
6767 #define REG_RSN_RETURN_NAME    1
6768 #define REG_RSN_RETURN_DATA    2
6769
6770 STATIC SV*
6771 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
6772 {
6773     char *name_start = RExC_parse;
6774
6775     PERL_ARGS_ASSERT_REG_SCAN_NAME;
6776
6777     if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
6778          /* skip IDFIRST by using do...while */
6779         if (UTF)
6780             do {
6781                 RExC_parse += UTF8SKIP(RExC_parse);
6782             } while (isALNUM_utf8((U8*)RExC_parse));
6783         else
6784             do {
6785                 RExC_parse++;
6786             } while (isALNUM(*RExC_parse));
6787     } else {
6788         RExC_parse++; /* so the <- from the vFAIL is after the offending character */
6789         vFAIL("Group name must start with a non-digit word character");
6790     }
6791     if ( flags ) {
6792         SV* sv_name
6793             = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
6794                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
6795         if ( flags == REG_RSN_RETURN_NAME)
6796             return sv_name;
6797         else if (flags==REG_RSN_RETURN_DATA) {
6798             HE *he_str = NULL;
6799             SV *sv_dat = NULL;
6800             if ( ! sv_name )      /* should not happen*/
6801                 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
6802             if (RExC_paren_names)
6803                 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
6804             if ( he_str )
6805                 sv_dat = HeVAL(he_str);
6806             if ( ! sv_dat )
6807                 vFAIL("Reference to nonexistent named group");
6808             return sv_dat;
6809         }
6810         else {
6811             Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
6812                        (unsigned long) flags);
6813         }
6814         assert(0); /* NOT REACHED */
6815     }
6816     return NULL;
6817 }
6818
6819 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
6820     int rem=(int)(RExC_end - RExC_parse);                       \
6821     int cut;                                                    \
6822     int num;                                                    \
6823     int iscut=0;                                                \
6824     if (rem>10) {                                               \
6825         rem=10;                                                 \
6826         iscut=1;                                                \
6827     }                                                           \
6828     cut=10-rem;                                                 \
6829     if (RExC_lastparse!=RExC_parse)                             \
6830         PerlIO_printf(Perl_debug_log," >%.*s%-*s",              \
6831             rem, RExC_parse,                                    \
6832             cut + 4,                                            \
6833             iscut ? "..." : "<"                                 \
6834         );                                                      \
6835     else                                                        \
6836         PerlIO_printf(Perl_debug_log,"%16s","");                \
6837                                                                 \
6838     if (SIZE_ONLY)                                              \
6839        num = RExC_size + 1;                                     \
6840     else                                                        \
6841        num=REG_NODE_NUM(RExC_emit);                             \
6842     if (RExC_lastnum!=num)                                      \
6843        PerlIO_printf(Perl_debug_log,"|%4d",num);                \
6844     else                                                        \
6845        PerlIO_printf(Perl_debug_log,"|%4s","");                 \
6846     PerlIO_printf(Perl_debug_log,"|%*s%-4s",                    \
6847         (int)((depth*2)), "",                                   \
6848         (funcname)                                              \
6849     );                                                          \
6850     RExC_lastnum=num;                                           \
6851     RExC_lastparse=RExC_parse;                                  \
6852 })
6853
6854
6855
6856 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
6857     DEBUG_PARSE_MSG((funcname));                            \
6858     PerlIO_printf(Perl_debug_log,"%4s","\n");               \
6859 })
6860 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({           \
6861     DEBUG_PARSE_MSG((funcname));                            \
6862     PerlIO_printf(Perl_debug_log,fmt "\n",args);               \
6863 })
6864
6865 /* This section of code defines the inversion list object and its methods.  The
6866  * interfaces are highly subject to change, so as much as possible is static to
6867  * this file.  An inversion list is here implemented as a malloc'd C UV array
6868  * with some added info that is placed as UVs at the beginning in a header
6869  * portion.  An inversion list for Unicode is an array of code points, sorted
6870  * by ordinal number.  The zeroth element is the first code point in the list.
6871  * The 1th element is the first element beyond that not in the list.  In other
6872  * words, the first range is
6873  *  invlist[0]..(invlist[1]-1)
6874  * The other ranges follow.  Thus every element whose index is divisible by two
6875  * marks the beginning of a range that is in the list, and every element not
6876  * divisible by two marks the beginning of a range not in the list.  A single
6877  * element inversion list that contains the single code point N generally
6878  * consists of two elements
6879  *  invlist[0] == N
6880  *  invlist[1] == N+1
6881  * (The exception is when N is the highest representable value on the
6882  * machine, in which case the list containing just it would be a single
6883  * element, itself.  By extension, if the last range in the list extends to
6884  * infinity, then the first element of that range will be in the inversion list
6885  * at a position that is divisible by two, and is the final element in the
6886  * list.)
6887  * Taking the complement (inverting) an inversion list is quite simple, if the
6888  * first element is 0, remove it; otherwise add a 0 element at the beginning.
6889  * This implementation reserves an element at the beginning of each inversion
6890  * list to contain 0 when the list contains 0, and contains 1 otherwise.  The
6891  * actual beginning of the list is either that element if 0, or the next one if
6892  * 1.
6893  *
6894  * More about inversion lists can be found in "Unicode Demystified"
6895  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
6896  * More will be coming when functionality is added later.
6897  *
6898  * The inversion list data structure is currently implemented as an SV pointing
6899  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
6900  * array of UV whose memory management is automatically handled by the existing
6901  * facilities for SV's.
6902  *
6903  * Some of the methods should always be private to the implementation, and some
6904  * should eventually be made public */
6905
6906 /* The header definitions are in F<inline_invlist.c> */
6907 #define TO_INTERNAL_SIZE(x) ((x + HEADER_LENGTH) * sizeof(UV))
6908 #define FROM_INTERNAL_SIZE(x) ((x / sizeof(UV)) - HEADER_LENGTH)
6909
6910 #define INVLIST_INITIAL_LEN 10
6911
6912 PERL_STATIC_INLINE UV*
6913 S__invlist_array_init(pTHX_ SV* const invlist, const bool will_have_0)
6914 {
6915     /* Returns a pointer to the first element in the inversion list's array.
6916      * This is called upon initialization of an inversion list.  Where the
6917      * array begins depends on whether the list has the code point U+0000
6918      * in it or not.  The other parameter tells it whether the code that
6919      * follows this call is about to put a 0 in the inversion list or not.
6920      * The first element is either the element with 0, if 0, or the next one,
6921      * if 1 */
6922
6923     UV* zero = get_invlist_zero_addr(invlist);
6924
6925     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
6926
6927     /* Must be empty */
6928     assert(! *_get_invlist_len_addr(invlist));
6929
6930     /* 1^1 = 0; 1^0 = 1 */
6931     *zero = 1 ^ will_have_0;
6932     return zero + *zero;
6933 }
6934
6935 PERL_STATIC_INLINE UV*
6936 S_invlist_array(pTHX_ SV* const invlist)
6937 {
6938     /* Returns the pointer to the inversion list's array.  Every time the
6939      * length changes, this needs to be called in case malloc or realloc moved
6940      * it */
6941
6942     PERL_ARGS_ASSERT_INVLIST_ARRAY;
6943
6944     /* Must not be empty.  If these fail, you probably didn't check for <len>
6945      * being non-zero before trying to get the array */
6946     assert(*_get_invlist_len_addr(invlist));
6947     assert(*get_invlist_zero_addr(invlist) == 0
6948            || *get_invlist_zero_addr(invlist) == 1);
6949
6950     /* The array begins either at the element reserved for zero if the
6951      * list contains 0 (that element will be set to 0), or otherwise the next
6952      * element (in which case the reserved element will be set to 1). */
6953     return (UV *) (get_invlist_zero_addr(invlist)
6954                    + *get_invlist_zero_addr(invlist));
6955 }
6956
6957 PERL_STATIC_INLINE void
6958 S_invlist_set_len(pTHX_ SV* const invlist, const UV len)
6959 {
6960     /* Sets the current number of elements stored in the inversion list */
6961
6962     PERL_ARGS_ASSERT_INVLIST_SET_LEN;
6963
6964     *_get_invlist_len_addr(invlist) = len;
6965
6966     assert(len <= SvLEN(invlist));
6967
6968     SvCUR_set(invlist, TO_INTERNAL_SIZE(len));
6969     /* If the list contains U+0000, that element is part of the header,
6970      * and should not be counted as part of the array.  It will contain
6971      * 0 in that case, and 1 otherwise.  So we could flop 0=>1, 1=>0 and
6972      * subtract:
6973      *  SvCUR_set(invlist,
6974      *            TO_INTERNAL_SIZE(len
6975      *                             - (*get_invlist_zero_addr(inv_list) ^ 1)));
6976      * But, this is only valid if len is not 0.  The consequences of not doing
6977      * this is that the memory allocation code may think that 1 more UV is
6978      * being used than actually is, and so might do an unnecessary grow.  That
6979      * seems worth not bothering to make this the precise amount.
6980      *
6981      * Note that when inverting, SvCUR shouldn't change */
6982 }
6983
6984 PERL_STATIC_INLINE IV*
6985 S_get_invlist_previous_index_addr(pTHX_ SV* invlist)
6986 {
6987     /* Return the address of the UV that is reserved to hold the cached index
6988      * */
6989
6990     PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR;
6991
6992     return (IV *) (SvPVX(invlist) + (INVLIST_PREVIOUS_INDEX_OFFSET * sizeof (UV)));
6993 }
6994
6995 PERL_STATIC_INLINE IV
6996 S_invlist_previous_index(pTHX_ SV* const invlist)
6997 {
6998     /* Returns cached index of previous search */
6999
7000     PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX;
7001
7002     return *get_invlist_previous_index_addr(invlist);
7003 }
7004
7005 PERL_STATIC_INLINE void
7006 S_invlist_set_previous_index(pTHX_ SV* const invlist, const IV index)
7007 {
7008     /* Caches <index> for later retrieval */
7009
7010     PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX;
7011
7012     assert(index == 0 || index < (int) _invlist_len(invlist));
7013
7014     *get_invlist_previous_index_addr(invlist) = index;
7015 }
7016
7017 PERL_STATIC_INLINE UV
7018 S_invlist_max(pTHX_ SV* const invlist)
7019 {
7020     /* Returns the maximum number of elements storable in the inversion list's
7021      * array, without having to realloc() */
7022
7023     PERL_ARGS_ASSERT_INVLIST_MAX;
7024
7025     return SvLEN(invlist) == 0  /* This happens under _new_invlist_C_array */
7026            ? _invlist_len(invlist)
7027            : FROM_INTERNAL_SIZE(SvLEN(invlist));
7028 }
7029
7030 PERL_STATIC_INLINE UV*
7031 S_get_invlist_zero_addr(pTHX_ SV* invlist)
7032 {
7033     /* Return the address of the UV that is reserved to hold 0 if the inversion
7034      * list contains 0.  This has to be the last element of the heading, as the
7035      * list proper starts with either it if 0, or the next element if not.
7036      * (But we force it to contain either 0 or 1) */
7037
7038     PERL_ARGS_ASSERT_GET_INVLIST_ZERO_ADDR;
7039
7040     return (UV *) (SvPVX(invlist) + (INVLIST_ZERO_OFFSET * sizeof (UV)));
7041 }
7042
7043 #ifndef PERL_IN_XSUB_RE
7044 SV*
7045 Perl__new_invlist(pTHX_ IV initial_size)
7046 {
7047
7048     /* Return a pointer to a newly constructed inversion list, with enough
7049      * space to store 'initial_size' elements.  If that number is negative, a
7050      * system default is used instead */
7051
7052     SV* new_list;
7053
7054     if (initial_size < 0) {
7055         initial_size = INVLIST_INITIAL_LEN;
7056     }
7057
7058     /* Allocate the initial space */
7059     new_list = newSV(TO_INTERNAL_SIZE(initial_size));
7060     invlist_set_len(new_list, 0);
7061
7062     /* Force iterinit() to be used to get iteration to work */
7063     *get_invlist_iter_addr(new_list) = UV_MAX;
7064
7065     /* This should force a segfault if a method doesn't initialize this
7066      * properly */
7067     *get_invlist_zero_addr(new_list) = UV_MAX;
7068
7069     *get_invlist_previous_index_addr(new_list) = 0;
7070     *get_invlist_version_id_addr(new_list) = INVLIST_VERSION_ID;
7071 #if HEADER_LENGTH != 5
7072 #   error Need to regenerate VERSION_ID by running perl -E 'say int(rand 2**31-1)', and then changing the #if to the new length
7073 #endif
7074
7075     return new_list;
7076 }
7077 #endif
7078
7079 STATIC SV*
7080 S__new_invlist_C_array(pTHX_ UV* list)
7081 {
7082     /* Return a pointer to a newly constructed inversion list, initialized to
7083      * point to <list>, which has to be in the exact correct inversion list
7084      * form, including internal fields.  Thus this is a dangerous routine that
7085      * should not be used in the wrong hands */
7086
7087     SV* invlist = newSV_type(SVt_PV);
7088
7089     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
7090
7091     SvPV_set(invlist, (char *) list);
7092     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
7093                                shouldn't touch it */
7094     SvCUR_set(invlist, TO_INTERNAL_SIZE(_invlist_len(invlist)));
7095
7096     if (*get_invlist_version_id_addr(invlist) != INVLIST_VERSION_ID) {
7097         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
7098     }
7099
7100     /* Initialize the iteration pointer.
7101      * XXX This could be done at compile time in charclass_invlists.h, but I
7102      * (khw) am not confident that the suffixes for specifying the C constant
7103      * UV_MAX are portable, e.g.  'ull' on a 32 bit machine that is configured
7104      * to use 64 bits; might need a Configure probe */
7105     invlist_iterfinish(invlist);
7106
7107     return invlist;
7108 }
7109
7110 STATIC void
7111 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
7112 {
7113     /* Grow the maximum size of an inversion list */
7114
7115     PERL_ARGS_ASSERT_INVLIST_EXTEND;
7116
7117     SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max));
7118 }
7119
7120 PERL_STATIC_INLINE void
7121 S_invlist_trim(pTHX_ SV* const invlist)
7122 {
7123     PERL_ARGS_ASSERT_INVLIST_TRIM;
7124
7125     /* Change the length of the inversion list to how many entries it currently
7126      * has */
7127
7128     SvPV_shrink_to_cur((SV *) invlist);
7129 }
7130
7131 #define _invlist_union_complement_2nd(a, b, output) _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
7132
7133 STATIC void
7134 S__append_range_to_invlist(pTHX_ SV* const invlist, const UV start, const UV end)
7135 {
7136    /* Subject to change or removal.  Append the range from 'start' to 'end' at
7137     * the end of the inversion list.  The range must be above any existing
7138     * ones. */
7139
7140     UV* array;
7141     UV max = invlist_max(invlist);
7142     UV len = _invlist_len(invlist);
7143
7144     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
7145
7146     if (len == 0) { /* Empty lists must be initialized */
7147         array = _invlist_array_init(invlist, start == 0);
7148     }
7149     else {
7150         /* Here, the existing list is non-empty. The current max entry in the
7151          * list is generally the first value not in the set, except when the
7152          * set extends to the end of permissible values, in which case it is
7153          * the first entry in that final set, and so this call is an attempt to
7154          * append out-of-order */
7155
7156         UV final_element = len - 1;
7157         array = invlist_array(invlist);
7158         if (array[final_element] > start
7159             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
7160         {
7161             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",
7162                        array[final_element], start,
7163                        ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
7164         }
7165
7166         /* Here, it is a legal append.  If the new range begins with the first
7167          * value not in the set, it is extending the set, so the new first
7168          * value not in the set is one greater than the newly extended range.
7169          * */
7170         if (array[final_element] == start) {
7171             if (end != UV_MAX) {
7172                 array[final_element] = end + 1;
7173             }
7174             else {
7175                 /* But if the end is the maximum representable on the machine,
7176                  * just let the range that this would extend to have no end */
7177                 invlist_set_len(invlist, len - 1);
7178             }
7179             return;
7180         }
7181     }
7182
7183     /* Here the new range doesn't extend any existing set.  Add it */
7184
7185     len += 2;   /* Includes an element each for the start and end of range */
7186
7187     /* If overflows the existing space, extend, which may cause the array to be
7188      * moved */
7189     if (max < len) {
7190         invlist_extend(invlist, len);
7191         invlist_set_len(invlist, len);  /* Have to set len here to avoid assert
7192                                            failure in invlist_array() */
7193         array = invlist_array(invlist);
7194     }
7195     else {
7196         invlist_set_len(invlist, len);
7197     }
7198
7199     /* The next item on the list starts the range, the one after that is
7200      * one past the new range.  */
7201     array[len - 2] = start;
7202     if (end != UV_MAX) {
7203         array[len - 1] = end + 1;
7204     }
7205     else {
7206         /* But if the end is the maximum representable on the machine, just let
7207          * the range have no end */
7208         invlist_set_len(invlist, len - 1);
7209     }
7210 }
7211
7212 #ifndef PERL_IN_XSUB_RE
7213
7214 IV
7215 Perl__invlist_search(pTHX_ SV* const invlist, const UV cp)
7216 {
7217     /* Searches the inversion list for the entry that contains the input code
7218      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
7219      * return value is the index into the list's array of the range that
7220      * contains <cp> */
7221
7222     IV low = 0;
7223     IV mid;
7224     IV high = _invlist_len(invlist);
7225     const IV highest_element = high - 1;
7226     const UV* array;
7227
7228     PERL_ARGS_ASSERT__INVLIST_SEARCH;
7229
7230     /* If list is empty, return failure. */
7231     if (high == 0) {
7232         return -1;
7233     }
7234
7235     /* (We can't get the array unless we know the list is non-empty) */
7236     array = invlist_array(invlist);
7237
7238     mid = invlist_previous_index(invlist);
7239     assert(mid >=0 && mid <= highest_element);
7240
7241     /* <mid> contains the cache of the result of the previous call to this
7242      * function (0 the first time).  See if this call is for the same result,
7243      * or if it is for mid-1.  This is under the theory that calls to this
7244      * function will often be for related code points that are near each other.
7245      * And benchmarks show that caching gives better results.  We also test
7246      * here if the code point is within the bounds of the list.  These tests
7247      * replace others that would have had to be made anyway to make sure that
7248      * the array bounds were not exceeded, and these give us extra information
7249      * at the same time */
7250     if (cp >= array[mid]) {
7251         if (cp >= array[highest_element]) {
7252             return highest_element;
7253         }
7254
7255         /* Here, array[mid] <= cp < array[highest_element].  This means that
7256          * the final element is not the answer, so can exclude it; it also
7257          * means that <mid> is not the final element, so can refer to 'mid + 1'
7258          * safely */
7259         if (cp < array[mid + 1]) {
7260             return mid;
7261         }
7262         high--;
7263         low = mid + 1;
7264     }
7265     else { /* cp < aray[mid] */
7266         if (cp < array[0]) { /* Fail if outside the array */
7267             return -1;
7268         }
7269         high = mid;
7270         if (cp >= array[mid - 1]) {
7271             goto found_entry;
7272         }
7273     }
7274
7275     /* Binary search.  What we are looking for is <i> such that
7276      *  array[i] <= cp < array[i+1]
7277      * The loop below converges on the i+1.  Note that there may not be an
7278      * (i+1)th element in the array, and things work nonetheless */
7279     while (low < high) {
7280         mid = (low + high) / 2;
7281         assert(mid <= highest_element);
7282         if (array[mid] <= cp) { /* cp >= array[mid] */
7283             low = mid + 1;
7284
7285             /* We could do this extra test to exit the loop early.
7286             if (cp < array[low]) {
7287                 return mid;
7288             }
7289             */
7290         }
7291         else { /* cp < array[mid] */
7292             high = mid;
7293         }
7294     }
7295
7296   found_entry:
7297     high--;
7298     invlist_set_previous_index(invlist, high);
7299     return high;
7300 }
7301
7302 void
7303 Perl__invlist_populate_swatch(pTHX_ SV* const invlist, const UV start, const UV end, U8* swatch)
7304 {
7305     /* populates a swatch of a swash the same way swatch_get() does in utf8.c,
7306      * but is used when the swash has an inversion list.  This makes this much
7307      * faster, as it uses a binary search instead of a linear one.  This is
7308      * intimately tied to that function, and perhaps should be in utf8.c,
7309      * except it is intimately tied to inversion lists as well.  It assumes
7310      * that <swatch> is all 0's on input */
7311
7312     UV current = start;
7313     const IV len = _invlist_len(invlist);
7314     IV i;
7315     const UV * array;
7316
7317     PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
7318
7319     if (len == 0) { /* Empty inversion list */
7320         return;
7321     }
7322
7323     array = invlist_array(invlist);
7324
7325     /* Find which element it is */
7326     i = _invlist_search(invlist, start);
7327
7328     /* We populate from <start> to <end> */
7329     while (current < end) {
7330         UV upper;
7331
7332         /* The inversion list gives the results for every possible code point
7333          * after the first one in the list.  Only those ranges whose index is
7334          * even are ones that the inversion list matches.  For the odd ones,
7335          * and if the initial code point is not in the list, we have to skip
7336          * forward to the next element */
7337         if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
7338             i++;
7339             if (i >= len) { /* Finished if beyond the end of the array */
7340                 return;
7341             }
7342             current = array[i];
7343             if (current >= end) {   /* Finished if beyond the end of what we
7344                                        are populating */
7345                 if (LIKELY(end < UV_MAX)) {
7346                     return;
7347                 }
7348
7349                 /* We get here when the upper bound is the maximum
7350                  * representable on the machine, and we are looking for just
7351                  * that code point.  Have to special case it */
7352                 i = len;
7353                 goto join_end_of_list;
7354             }
7355         }
7356         assert(current >= start);
7357
7358         /* The current range ends one below the next one, except don't go past
7359          * <end> */
7360         i++;
7361         upper = (i < len && array[i] < end) ? array[i] : end;
7362
7363         /* Here we are in a range that matches.  Populate a bit in the 3-bit U8
7364          * for each code point in it */
7365         for (; current < upper; current++) {
7366             const STRLEN offset = (STRLEN)(current - start);
7367             swatch[offset >> 3] |= 1 << (offset & 7);
7368         }
7369
7370     join_end_of_list:
7371
7372         /* Quit if at the end of the list */
7373         if (i >= len) {
7374
7375             /* But first, have to deal with the highest possible code point on
7376              * the platform.  The previous code assumes that <end> is one
7377              * beyond where we want to populate, but that is impossible at the
7378              * platform's infinity, so have to handle it specially */
7379             if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
7380             {
7381                 const STRLEN offset = (STRLEN)(end - start);
7382                 swatch[offset >> 3] |= 1 << (offset & 7);
7383             }
7384             return;
7385         }
7386
7387         /* Advance to the next range, which will be for code points not in the
7388          * inversion list */
7389         current = array[i];
7390     }
7391
7392     return;
7393 }
7394
7395 void
7396 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, bool complement_b, SV** output)
7397 {
7398     /* Take the union of two inversion lists and point <output> to it.  *output
7399      * should be defined upon input, and if it points to one of the two lists,
7400      * the reference count to that list will be decremented.  The first list,
7401      * <a>, may be NULL, in which case a copy of the second list is returned.
7402      * If <complement_b> is TRUE, the union is taken of the complement
7403      * (inversion) of <b> instead of b itself.
7404      *
7405      * The basis for this comes from "Unicode Demystified" Chapter 13 by
7406      * Richard Gillam, published by Addison-Wesley, and explained at some
7407      * length there.  The preface says to incorporate its examples into your
7408      * code at your own risk.
7409      *
7410      * The algorithm is like a merge sort.
7411      *
7412      * XXX A potential performance improvement is to keep track as we go along
7413      * if only one of the inputs contributes to the result, meaning the other
7414      * is a subset of that one.  In that case, we can skip the final copy and
7415      * return the larger of the input lists, but then outside code might need
7416      * to keep track of whether to free the input list or not */
7417
7418     UV* array_a;    /* a's array */
7419     UV* array_b;
7420     UV len_a;       /* length of a's array */
7421     UV len_b;
7422
7423     SV* u;                      /* the resulting union */
7424     UV* array_u;
7425     UV len_u;
7426
7427     UV i_a = 0;             /* current index into a's array */
7428     UV i_b = 0;
7429     UV i_u = 0;
7430
7431     /* running count, as explained in the algorithm source book; items are
7432      * stopped accumulating and are output when the count changes to/from 0.
7433      * The count is incremented when we start a range that's in the set, and
7434      * decremented when we start a range that's not in the set.  So its range
7435      * is 0 to 2.  Only when the count is zero is something not in the set.
7436      */
7437     UV count = 0;
7438
7439     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
7440     assert(a != b);
7441
7442     /* If either one is empty, the union is the other one */
7443     if (a == NULL || ((len_a = _invlist_len(a)) == 0)) {
7444         if (*output == a) {
7445             if (a != NULL) {
7446                 SvREFCNT_dec_NN(a);
7447             }
7448         }
7449         if (*output != b) {
7450             *output = invlist_clone(b);
7451             if (complement_b) {
7452                 _invlist_invert(*output);
7453             }
7454         } /* else *output already = b; */
7455         return;
7456     }
7457     else if ((len_b = _invlist_len(b)) == 0) {
7458         if (*output == b) {
7459             SvREFCNT_dec_NN(b);
7460         }
7461
7462         /* The complement of an empty list is a list that has everything in it,
7463          * so the union with <a> includes everything too */
7464         if (complement_b) {
7465             if (a == *output) {
7466                 SvREFCNT_dec_NN(a);
7467             }
7468             *output = _new_invlist(1);
7469             _append_range_to_invlist(*output, 0, UV_MAX);
7470         }
7471         else if (*output != a) {
7472             *output = invlist_clone(a);
7473         }
7474         /* else *output already = a; */
7475         return;
7476     }
7477
7478     /* Here both lists exist and are non-empty */
7479     array_a = invlist_array(a);
7480     array_b = invlist_array(b);
7481
7482     /* If are to take the union of 'a' with the complement of b, set it
7483      * up so are looking at b's complement. */
7484     if (complement_b) {
7485
7486         /* To complement, we invert: if the first element is 0, remove it.  To
7487          * do this, we just pretend the array starts one later, and clear the
7488          * flag as we don't have to do anything else later */
7489         if (array_b[0] == 0) {
7490             array_b++;
7491             len_b--;
7492             complement_b = FALSE;
7493         }
7494         else {
7495
7496             /* But if the first element is not zero, we unshift a 0 before the
7497              * array.  The data structure reserves a space for that 0 (which
7498              * should be a '1' right now), so physical shifting is unneeded,
7499              * but temporarily change that element to 0.  Before exiting the
7500              * routine, we must restore the element to '1' */
7501             array_b--;
7502             len_b++;
7503             array_b[0] = 0;
7504         }
7505     }
7506
7507     /* Size the union for the worst case: that the sets are completely
7508      * disjoint */
7509     u = _new_invlist(len_a + len_b);
7510
7511     /* Will contain U+0000 if either component does */
7512     array_u = _invlist_array_init(u, (len_a > 0 && array_a[0] == 0)
7513                                       || (len_b > 0 && array_b[0] == 0));
7514
7515     /* Go through each list item by item, stopping when exhausted one of
7516      * them */
7517     while (i_a < len_a && i_b < len_b) {
7518         UV cp;      /* The element to potentially add to the union's array */
7519         bool cp_in_set;   /* is it in the the input list's set or not */
7520
7521         /* We need to take one or the other of the two inputs for the union.
7522          * Since we are merging two sorted lists, we take the smaller of the
7523          * next items.  In case of a tie, we take the one that is in its set
7524          * first.  If we took one not in the set first, it would decrement the
7525          * count, possibly to 0 which would cause it to be output as ending the
7526          * range, and the next time through we would take the same number, and
7527          * output it again as beginning the next range.  By doing it the
7528          * opposite way, there is no possibility that the count will be
7529          * momentarily decremented to 0, and thus the two adjoining ranges will
7530          * be seamlessly merged.  (In a tie and both are in the set or both not
7531          * in the set, it doesn't matter which we take first.) */
7532         if (array_a[i_a] < array_b[i_b]
7533             || (array_a[i_a] == array_b[i_b]
7534                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
7535         {
7536             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
7537             cp= array_a[i_a++];
7538         }
7539         else {
7540             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
7541             cp= array_b[i_b++];
7542         }
7543
7544         /* Here, have chosen which of the two inputs to look at.  Only output
7545          * if the running count changes to/from 0, which marks the
7546          * beginning/end of a range in that's in the set */
7547         if (cp_in_set) {
7548             if (count == 0) {
7549                 array_u[i_u++] = cp;
7550             }
7551             count++;
7552         }
7553         else {
7554             count--;
7555             if (count == 0) {
7556                 array_u[i_u++] = cp;
7557             }
7558         }
7559     }
7560
7561     /* Here, we are finished going through at least one of the lists, which
7562      * means there is something remaining in at most one.  We check if the list
7563      * that hasn't been exhausted is positioned such that we are in the middle
7564      * of a range in its set or not.  (i_a and i_b point to the element beyond
7565      * the one we care about.) If in the set, we decrement 'count'; if 0, there
7566      * is potentially more to output.
7567      * There are four cases:
7568      *  1) Both weren't in their sets, count is 0, and remains 0.  What's left
7569      *     in the union is entirely from the non-exhausted set.
7570      *  2) Both were in their sets, count is 2.  Nothing further should
7571      *     be output, as everything that remains will be in the exhausted
7572      *     list's set, hence in the union; decrementing to 1 but not 0 insures
7573      *     that
7574      *  3) the exhausted was in its set, non-exhausted isn't, count is 1.
7575      *     Nothing further should be output because the union includes
7576      *     everything from the exhausted set.  Not decrementing ensures that.
7577      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1;
7578      *     decrementing to 0 insures that we look at the remainder of the
7579      *     non-exhausted set */
7580     if ((i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
7581         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
7582     {
7583         count--;
7584     }
7585
7586     /* The final length is what we've output so far, plus what else is about to
7587      * be output.  (If 'count' is non-zero, then the input list we exhausted
7588      * has everything remaining up to the machine's limit in its set, and hence
7589      * in the union, so there will be no further output. */
7590     len_u = i_u;
7591     if (count == 0) {
7592         /* At most one of the subexpressions will be non-zero */
7593         len_u += (len_a - i_a) + (len_b - i_b);
7594     }
7595
7596     /* Set result to final length, which can change the pointer to array_u, so
7597      * re-find it */
7598     if (len_u != _invlist_len(u)) {
7599         invlist_set_len(u, len_u);
7600         invlist_trim(u);
7601         array_u = invlist_array(u);
7602     }
7603
7604     /* When 'count' is 0, the list that was exhausted (if one was shorter than
7605      * the other) ended with everything above it not in its set.  That means
7606      * that the remaining part of the union is precisely the same as the
7607      * non-exhausted list, so can just copy it unchanged.  (If both list were
7608      * exhausted at the same time, then the operations below will be both 0.)
7609      */
7610     if (count == 0) {
7611         IV copy_count; /* At most one will have a non-zero copy count */
7612         if ((copy_count = len_a - i_a) > 0) {
7613             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
7614         }
7615         else if ((copy_count = len_b - i_b) > 0) {
7616             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
7617         }
7618     }
7619
7620     /*  We may be removing a reference to one of the inputs */
7621     if (a == *output || b == *output) {
7622         assert(! invlist_is_iterating(*output));
7623         SvREFCNT_dec_NN(*output);
7624     }
7625
7626     /* If we've changed b, restore it */
7627     if (complement_b) {
7628         array_b[0] = 1;
7629     }
7630
7631     *output = u;
7632     return;
7633 }
7634
7635 void
7636 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, bool complement_b, SV** i)
7637 {
7638     /* Take the intersection of two inversion lists and point <i> to it.  *i
7639      * should be defined upon input, and if it points to one of the two lists,
7640      * the reference count to that list will be decremented.
7641      * If <complement_b> is TRUE, the result will be the intersection of <a>
7642      * and the complement (or inversion) of <b> instead of <b> directly.
7643      *
7644      * The basis for this comes from "Unicode Demystified" Chapter 13 by
7645      * Richard Gillam, published by Addison-Wesley, and explained at some
7646      * length there.  The preface says to incorporate its examples into your
7647      * code at your own risk.  In fact, it had bugs
7648      *
7649      * The algorithm is like a merge sort, and is essentially the same as the
7650      * union above
7651      */
7652
7653     UV* array_a;                /* a's array */
7654     UV* array_b;
7655     UV len_a;   /* length of a's array */
7656     UV len_b;
7657
7658     SV* r;                   /* the resulting intersection */
7659     UV* array_r;
7660     UV len_r;
7661
7662     UV i_a = 0;             /* current index into a's array */
7663     UV i_b = 0;
7664     UV i_r = 0;
7665
7666     /* running count, as explained in the algorithm source book; items are
7667      * stopped accumulating and are output when the count changes to/from 2.
7668      * The count is incremented when we start a range that's in the set, and
7669      * decremented when we start a range that's not in the set.  So its range
7670      * is 0 to 2.  Only when the count is 2 is something in the intersection.
7671      */
7672     UV count = 0;
7673
7674     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
7675     assert(a != b);
7676
7677     /* Special case if either one is empty */
7678     len_a = _invlist_len(a);
7679     if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) {
7680
7681         if (len_a != 0 && complement_b) {
7682
7683             /* Here, 'a' is not empty, therefore from the above 'if', 'b' must
7684              * be empty.  Here, also we are using 'b's complement, which hence
7685              * must be every possible code point.  Thus the intersection is
7686              * simply 'a'. */
7687             if (*i != a) {
7688                 *i = invlist_clone(a);
7689
7690                 if (*i == b) {
7691                     SvREFCNT_dec_NN(b);
7692                 }
7693             }
7694             /* else *i is already 'a' */
7695             return;
7696         }
7697
7698         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
7699          * intersection must be empty */
7700         if (*i == a) {
7701             SvREFCNT_dec_NN(a);
7702         }
7703         else if (*i == b) {
7704             SvREFCNT_dec_NN(b);
7705         }
7706         *i = _new_invlist(0);
7707         return;
7708     }
7709
7710     /* Here both lists exist and are non-empty */
7711     array_a = invlist_array(a);
7712     array_b = invlist_array(b);
7713
7714     /* If are to take the intersection of 'a' with the complement of b, set it
7715      * up so are looking at b's complement. */
7716     if (complement_b) {
7717
7718         /* To complement, we invert: if the first element is 0, remove it.  To
7719          * do this, we just pretend the array starts one later, and clear the
7720          * flag as we don't have to do anything else later */
7721         if (array_b[0] == 0) {
7722             array_b++;
7723             len_b--;
7724             complement_b = FALSE;
7725         }
7726         else {
7727
7728             /* But if the first element is not zero, we unshift a 0 before the
7729              * array.  The data structure reserves a space for that 0 (which
7730              * should be a '1' right now), so physical shifting is unneeded,
7731              * but temporarily change that element to 0.  Before exiting the
7732              * routine, we must restore the element to '1' */
7733             array_b--;
7734             len_b++;
7735             array_b[0] = 0;
7736         }
7737     }
7738
7739     /* Size the intersection for the worst case: that the intersection ends up
7740      * fragmenting everything to be completely disjoint */
7741     r= _new_invlist(len_a + len_b);
7742
7743     /* Will contain U+0000 iff both components do */
7744     array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
7745                                      && len_b > 0 && array_b[0] == 0);
7746
7747     /* Go through each list item by item, stopping when exhausted one of
7748      * them */
7749     while (i_a < len_a && i_b < len_b) {
7750         UV cp;      /* The element to potentially add to the intersection's
7751                        array */
7752         bool cp_in_set; /* Is it in the input list's set or not */
7753
7754         /* We need to take one or the other of the two inputs for the
7755          * intersection.  Since we are merging two sorted lists, we take the
7756          * smaller of the next items.  In case of a tie, we take the one that
7757          * is not in its set first (a difference from the union algorithm).  If
7758          * we took one in the set first, it would increment the count, possibly
7759          * to 2 which would cause it to be output as starting a range in the
7760          * intersection, and the next time through we would take that same
7761          * number, and output it again as ending the set.  By doing it the
7762          * opposite of this, there is no possibility that the count will be
7763          * momentarily incremented to 2.  (In a tie and both are in the set or
7764          * both not in the set, it doesn't matter which we take first.) */
7765         if (array_a[i_a] < array_b[i_b]
7766             || (array_a[i_a] == array_b[i_b]
7767                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
7768         {
7769             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
7770             cp= array_a[i_a++];
7771         }
7772         else {
7773             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
7774             cp= array_b[i_b++];
7775         }
7776
7777         /* Here, have chosen which of the two inputs to look at.  Only output
7778          * if the running count changes to/from 2, which marks the
7779          * beginning/end of a range that's in the intersection */
7780         if (cp_in_set) {
7781             count++;
7782             if (count == 2) {
7783                 array_r[i_r++] = cp;
7784             }
7785         }
7786         else {
7787             if (count == 2) {
7788                 array_r[i_r++] = cp;
7789             }
7790             count--;
7791         }
7792     }
7793
7794     /* Here, we are finished going through at least one of the lists, which
7795      * means there is something remaining in at most one.  We check if the list
7796      * that has been exhausted is positioned such that we are in the middle
7797      * of a range in its set or not.  (i_a and i_b point to elements 1 beyond
7798      * the ones we care about.)  There are four cases:
7799      *  1) Both weren't in their sets, count is 0, and remains 0.  There's
7800      *     nothing left in the intersection.
7801      *  2) Both were in their sets, count is 2 and perhaps is incremented to
7802      *     above 2.  What should be output is exactly that which is in the
7803      *     non-exhausted set, as everything it has is also in the intersection
7804      *     set, and everything it doesn't have can't be in the intersection
7805      *  3) The exhausted was in its set, non-exhausted isn't, count is 1, and
7806      *     gets incremented to 2.  Like the previous case, the intersection is
7807      *     everything that remains in the non-exhausted set.
7808      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1, and
7809      *     remains 1.  And the intersection has nothing more. */
7810     if ((i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
7811         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
7812     {
7813         count++;
7814     }
7815
7816     /* The final length is what we've output so far plus what else is in the
7817      * intersection.  At most one of the subexpressions below will be non-zero */
7818     len_r = i_r;
7819     if (count >= 2) {
7820         len_r += (len_a - i_a) + (len_b - i_b);
7821     }
7822
7823     /* Set result to final length, which can change the pointer to array_r, so
7824      * re-find it */
7825     if (len_r != _invlist_len(r)) {
7826         invlist_set_len(r, len_r);
7827         invlist_trim(r);
7828         array_r = invlist_array(r);
7829     }
7830
7831     /* Finish outputting any remaining */
7832     if (count >= 2) { /* At most one will have a non-zero copy count */
7833         IV copy_count;
7834         if ((copy_count = len_a - i_a) > 0) {
7835             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
7836         }
7837         else if ((copy_count = len_b - i_b) > 0) {
7838             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
7839         }
7840     }
7841
7842     /*  We may be removing a reference to one of the inputs */
7843     if (a == *i || b == *i) {
7844         assert(! invlist_is_iterating(*i));
7845         SvREFCNT_dec_NN(*i);
7846     }
7847
7848     /* If we've changed b, restore it */
7849     if (complement_b) {
7850         array_b[0] = 1;
7851     }
7852
7853     *i = r;
7854     return;
7855 }
7856
7857 SV*
7858 Perl__add_range_to_invlist(pTHX_ SV* invlist, const UV start, const UV end)
7859 {
7860     /* Add the range from 'start' to 'end' inclusive to the inversion list's
7861      * set.  A pointer to the inversion list is returned.  This may actually be
7862      * a new list, in which case the passed in one has been destroyed.  The
7863      * passed in inversion list can be NULL, in which case a new one is created
7864      * with just the one range in it */
7865
7866     SV* range_invlist;
7867     UV len;
7868
7869     if (invlist == NULL) {
7870         invlist = _new_invlist(2);
7871         len = 0;
7872     }
7873     else {
7874         len = _invlist_len(invlist);
7875     }
7876
7877     /* If comes after the final entry, can just append it to the end */
7878     if (len == 0
7879         || start >= invlist_array(invlist)
7880                                     [_invlist_len(invlist) - 1])
7881     {
7882         _append_range_to_invlist(invlist, start, end);
7883         return invlist;
7884     }
7885
7886     /* Here, can't just append things, create and return a new inversion list
7887      * which is the union of this range and the existing inversion list */
7888     range_invlist = _new_invlist(2);
7889     _append_range_to_invlist(range_invlist, start, end);
7890
7891     _invlist_union(invlist, range_invlist, &invlist);
7892
7893     /* The temporary can be freed */
7894     SvREFCNT_dec_NN(range_invlist);
7895
7896     return invlist;
7897 }
7898
7899 #endif
7900
7901 PERL_STATIC_INLINE SV*
7902 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
7903     return _add_range_to_invlist(invlist, cp, cp);
7904 }
7905
7906 #ifndef PERL_IN_XSUB_RE
7907 void
7908 Perl__invlist_invert(pTHX_ SV* const invlist)
7909 {
7910     /* Complement the input inversion list.  This adds a 0 if the list didn't
7911      * have a zero; removes it otherwise.  As described above, the data
7912      * structure is set up so that this is very efficient */
7913
7914     UV* len_pos = _get_invlist_len_addr(invlist);
7915
7916     PERL_ARGS_ASSERT__INVLIST_INVERT;
7917
7918     assert(! invlist_is_iterating(invlist));
7919
7920     /* The inverse of matching nothing is matching everything */
7921     if (*len_pos == 0) {
7922         _append_range_to_invlist(invlist, 0, UV_MAX);
7923         return;
7924     }
7925
7926     /* The exclusive or complents 0 to 1; and 1 to 0.  If the result is 1, the
7927      * zero element was a 0, so it is being removed, so the length decrements
7928      * by 1; and vice-versa.  SvCUR is unaffected */
7929     if (*get_invlist_zero_addr(invlist) ^= 1) {
7930         (*len_pos)--;
7931     }
7932     else {
7933         (*len_pos)++;
7934     }
7935 }
7936
7937 void
7938 Perl__invlist_invert_prop(pTHX_ SV* const invlist)
7939 {
7940     /* Complement the input inversion list (which must be a Unicode property,
7941      * all of which don't match above the Unicode maximum code point.)  And
7942      * Perl has chosen to not have the inversion match above that either.  This
7943      * adds a 0x110000 if the list didn't end with it, and removes it if it did
7944      */
7945
7946     UV len;
7947     UV* array;
7948
7949     PERL_ARGS_ASSERT__INVLIST_INVERT_PROP;
7950
7951     _invlist_invert(invlist);
7952
7953     len = _invlist_len(invlist);
7954
7955     if (len != 0) { /* If empty do nothing */
7956         array = invlist_array(invlist);
7957         if (array[len - 1] != PERL_UNICODE_MAX + 1) {
7958             /* Add 0x110000.  First, grow if necessary */
7959             len++;
7960             if (invlist_max(invlist) < len) {
7961                 invlist_extend(invlist, len);
7962                 array = invlist_array(invlist);
7963             }
7964             invlist_set_len(invlist, len);
7965             array[len - 1] = PERL_UNICODE_MAX + 1;
7966         }
7967         else {  /* Remove the 0x110000 */
7968             invlist_set_len(invlist, len - 1);
7969         }
7970     }
7971
7972     return;
7973 }
7974 #endif
7975
7976 PERL_STATIC_INLINE SV*
7977 S_invlist_clone(pTHX_ SV* const invlist)
7978 {
7979
7980     /* Return a new inversion list that is a copy of the input one, which is
7981      * unchanged */
7982
7983     /* Need to allocate extra space to accommodate Perl's addition of a
7984      * trailing NUL to SvPV's, since it thinks they are always strings */
7985     SV* new_invlist = _new_invlist(_invlist_len(invlist) + 1);
7986     STRLEN length = SvCUR(invlist);
7987
7988     PERL_ARGS_ASSERT_INVLIST_CLONE;
7989
7990     SvCUR_set(new_invlist, length); /* This isn't done automatically */
7991     Copy(SvPVX(invlist), SvPVX(new_invlist), length, char);
7992
7993     return new_invlist;
7994 }
7995
7996 PERL_STATIC_INLINE UV*
7997 S_get_invlist_iter_addr(pTHX_ SV* invlist)
7998 {
7999     /* Return the address of the UV that contains the current iteration
8000      * position */
8001
8002     PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
8003
8004     return (UV *) (SvPVX(invlist) + (INVLIST_ITER_OFFSET * sizeof (UV)));
8005 }
8006
8007 PERL_STATIC_INLINE UV*
8008 S_get_invlist_version_id_addr(pTHX_ SV* invlist)
8009 {
8010     /* Return the address of the UV that contains the version id. */
8011
8012     PERL_ARGS_ASSERT_GET_INVLIST_VERSION_ID_ADDR;
8013
8014     return (UV *) (SvPVX(invlist) + (INVLIST_VERSION_ID_OFFSET * sizeof (UV)));
8015 }
8016
8017 PERL_STATIC_INLINE void
8018 S_invlist_iterinit(pTHX_ SV* invlist)   /* Initialize iterator for invlist */
8019 {
8020     PERL_ARGS_ASSERT_INVLIST_ITERINIT;
8021
8022     *get_invlist_iter_addr(invlist) = 0;
8023 }
8024
8025 PERL_STATIC_INLINE void
8026 S_invlist_iterfinish(pTHX_ SV* invlist)
8027 {
8028     /* Terminate iterator for invlist.  This is to catch development errors.
8029      * Any iteration that is interrupted before completed should call this
8030      * function.  Functions that add code points anywhere else but to the end
8031      * of an inversion list assert that they are not in the middle of an
8032      * iteration.  If they were, the addition would make the iteration
8033      * problematical: if the iteration hadn't reached the place where things
8034      * were being added, it would be ok */
8035
8036     PERL_ARGS_ASSERT_INVLIST_ITERFINISH;
8037
8038     *get_invlist_iter_addr(invlist) = UV_MAX;
8039 }
8040
8041 STATIC bool
8042 S_invlist_iternext(pTHX_ SV* invlist, UV* start, UV* end)
8043 {
8044     /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
8045      * This call sets in <*start> and <*end>, the next range in <invlist>.
8046      * Returns <TRUE> if successful and the next call will return the next
8047      * range; <FALSE> if was already at the end of the list.  If the latter,
8048      * <*start> and <*end> are unchanged, and the next call to this function
8049      * will start over at the beginning of the list */
8050
8051     UV* pos = get_invlist_iter_addr(invlist);
8052     UV len = _invlist_len(invlist);
8053     UV *array;
8054
8055     PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
8056
8057     if (*pos >= len) {
8058         *pos = UV_MAX;  /* Force iterinit() to be required next time */
8059         return FALSE;
8060     }
8061
8062     array = invlist_array(invlist);
8063
8064     *start = array[(*pos)++];
8065
8066     if (*pos >= len) {
8067         *end = UV_MAX;
8068     }
8069     else {
8070         *end = array[(*pos)++] - 1;
8071     }
8072
8073     return TRUE;
8074 }
8075
8076 PERL_STATIC_INLINE bool
8077 S_invlist_is_iterating(pTHX_ SV* const invlist)
8078 {
8079     PERL_ARGS_ASSERT_INVLIST_IS_ITERATING;
8080
8081     return *(get_invlist_iter_addr(invlist)) < UV_MAX;
8082 }
8083
8084 PERL_STATIC_INLINE UV
8085 S_invlist_highest(pTHX_ SV* const invlist)
8086 {
8087     /* Returns the highest code point that matches an inversion list.  This API
8088      * has an ambiguity, as it returns 0 under either the highest is actually
8089      * 0, or if the list is empty.  If this distinction matters to you, check
8090      * for emptiness before calling this function */
8091
8092     UV len = _invlist_len(invlist);
8093     UV *array;
8094
8095     PERL_ARGS_ASSERT_INVLIST_HIGHEST;
8096
8097     if (len == 0) {
8098         return 0;
8099     }
8100
8101     array = invlist_array(invlist);
8102
8103     /* The last element in the array in the inversion list always starts a
8104      * range that goes to infinity.  That range may be for code points that are
8105      * matched in the inversion list, or it may be for ones that aren't
8106      * matched.  In the latter case, the highest code point in the set is one
8107      * less than the beginning of this range; otherwise it is the final element
8108      * of this range: infinity */
8109     return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1))
8110            ? UV_MAX
8111            : array[len - 1] - 1;
8112 }
8113
8114 #ifndef PERL_IN_XSUB_RE
8115 SV *
8116 Perl__invlist_contents(pTHX_ SV* const invlist)
8117 {
8118     /* Get the contents of an inversion list into a string SV so that they can
8119      * be printed out.  It uses the format traditionally done for debug tracing
8120      */
8121
8122     UV start, end;
8123     SV* output = newSVpvs("\n");
8124
8125     PERL_ARGS_ASSERT__INVLIST_CONTENTS;
8126
8127     assert(! invlist_is_iterating(invlist));
8128
8129     invlist_iterinit(invlist);
8130     while (invlist_iternext(invlist, &start, &end)) {
8131         if (end == UV_MAX) {
8132             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\tINFINITY\n", start);
8133         }
8134         else if (end != start) {
8135             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\t%04"UVXf"\n",
8136                     start,       end);
8137         }
8138         else {
8139             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\n", start);
8140         }
8141     }
8142
8143     return output;
8144 }
8145 #endif
8146
8147 #ifdef PERL_ARGS_ASSERT__INVLIST_DUMP
8148 void
8149 Perl__invlist_dump(pTHX_ SV* const invlist, const char * const header)
8150 {
8151     /* Dumps out the ranges in an inversion list.  The string 'header'
8152      * if present is output on a line before the first range */
8153
8154     UV start, end;
8155
8156     PERL_ARGS_ASSERT__INVLIST_DUMP;
8157
8158     if (header && strlen(header)) {
8159         PerlIO_printf(Perl_debug_log, "%s\n", header);
8160     }
8161     if (invlist_is_iterating(invlist)) {
8162         PerlIO_printf(Perl_debug_log, "Can't dump because is in middle of iterating\n");
8163         return;
8164     }
8165
8166     invlist_iterinit(invlist);
8167     while (invlist_iternext(invlist, &start, &end)) {
8168         if (end == UV_MAX) {
8169             PerlIO_printf(Perl_debug_log, "0x%04"UVXf" .. INFINITY\n", start);
8170         }
8171         else if (end != start) {
8172             PerlIO_printf(Perl_debug_log, "0x%04"UVXf" .. 0x%04"UVXf"\n",
8173                                                  start,         end);
8174         }
8175         else {
8176             PerlIO_printf(Perl_debug_log, "0x%04"UVXf"\n", start);
8177         }
8178     }
8179 }
8180 #endif
8181
8182 #if 0
8183 bool
8184 S__invlistEQ(pTHX_ SV* const a, SV* const b, bool complement_b)
8185 {
8186     /* Return a boolean as to if the two passed in inversion lists are
8187      * identical.  The final argument, if TRUE, says to take the complement of
8188      * the second inversion list before doing the comparison */
8189
8190     UV* array_a = invlist_array(a);
8191     UV* array_b = invlist_array(b);
8192     UV len_a = _invlist_len(a);
8193     UV len_b = _invlist_len(b);
8194
8195     UV i = 0;               /* current index into the arrays */
8196     bool retval = TRUE;     /* Assume are identical until proven otherwise */
8197
8198     PERL_ARGS_ASSERT__INVLISTEQ;
8199
8200     /* If are to compare 'a' with the complement of b, set it
8201      * up so are looking at b's complement. */
8202     if (complement_b) {
8203
8204         /* The complement of nothing is everything, so <a> would have to have
8205          * just one element, starting at zero (ending at infinity) */
8206         if (len_b == 0) {
8207             return (len_a == 1 && array_a[0] == 0);
8208         }
8209         else if (array_b[0] == 0) {
8210
8211             /* Otherwise, to complement, we invert.  Here, the first element is
8212              * 0, just remove it.  To do this, we just pretend the array starts
8213              * one later, and clear the flag as we don't have to do anything
8214              * else later */
8215
8216             array_b++;
8217             len_b--;
8218             complement_b = FALSE;
8219         }
8220         else {
8221
8222             /* But if the first element is not zero, we unshift a 0 before the
8223              * array.  The data structure reserves a space for that 0 (which
8224              * should be a '1' right now), so physical shifting is unneeded,
8225              * but temporarily change that element to 0.  Before exiting the
8226              * routine, we must restore the element to '1' */
8227             array_b--;
8228             len_b++;
8229             array_b[0] = 0;
8230         }
8231     }
8232
8233     /* Make sure that the lengths are the same, as well as the final element
8234      * before looping through the remainder.  (Thus we test the length, final,
8235      * and first elements right off the bat) */
8236     if (len_a != len_b || array_a[len_a-1] != array_b[len_a-1]) {
8237         retval = FALSE;
8238     }
8239     else for (i = 0; i < len_a - 1; i++) {
8240         if (array_a[i] != array_b[i]) {
8241             retval = FALSE;
8242             break;
8243         }
8244     }
8245
8246     if (complement_b) {
8247         array_b[0] = 1;
8248     }
8249     return retval;
8250 }
8251 #endif
8252
8253 #undef HEADER_LENGTH
8254 #undef INVLIST_INITIAL_LENGTH
8255 #undef TO_INTERNAL_SIZE
8256 #undef FROM_INTERNAL_SIZE
8257 #undef INVLIST_LEN_OFFSET
8258 #undef INVLIST_ZERO_OFFSET
8259 #undef INVLIST_ITER_OFFSET
8260 #undef INVLIST_VERSION_ID
8261 #undef INVLIST_PREVIOUS_INDEX_OFFSET
8262
8263 /* End of inversion list object */
8264
8265 /*
8266  - reg - regular expression, i.e. main body or parenthesized thing
8267  *
8268  * Caller must absorb opening parenthesis.
8269  *
8270  * Combining parenthesis handling with the base level of regular expression
8271  * is a trifle forced, but the need to tie the tails of the branches to what
8272  * follows makes it hard to avoid.
8273  */
8274 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
8275 #ifdef DEBUGGING
8276 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
8277 #else
8278 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
8279 #endif
8280
8281 STATIC regnode *
8282 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
8283     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
8284 {
8285     dVAR;
8286     regnode *ret;               /* Will be the head of the group. */
8287     regnode *br;
8288     regnode *lastbr;
8289     regnode *ender = NULL;
8290     I32 parno = 0;
8291     I32 flags;
8292     U32 oregflags = RExC_flags;
8293     bool have_branch = 0;
8294     bool is_open = 0;
8295     I32 freeze_paren = 0;
8296     I32 after_freeze = 0;
8297
8298     /* for (?g), (?gc), and (?o) warnings; warning
8299        about (?c) will warn about (?g) -- japhy    */
8300
8301 #define WASTED_O  0x01
8302 #define WASTED_G  0x02
8303 #define WASTED_C  0x04
8304 #define WASTED_GC (0x02|0x04)
8305     I32 wastedflags = 0x00;
8306
8307     char * parse_start = RExC_parse; /* MJD */
8308     char * const oregcomp_parse = RExC_parse;
8309
8310     GET_RE_DEBUG_FLAGS_DECL;
8311
8312     PERL_ARGS_ASSERT_REG;
8313     DEBUG_PARSE("reg ");
8314
8315     *flagp = 0;                         /* Tentatively. */
8316
8317
8318     /* Make an OPEN node, if parenthesized. */
8319     if (paren) {
8320         if ( *RExC_parse == '*') { /* (*VERB:ARG) */
8321             char *start_verb = RExC_parse;
8322             STRLEN verb_len = 0;
8323             char *start_arg = NULL;
8324             unsigned char op = 0;
8325             int argok = 1;
8326             int internal_argval = 0; /* internal_argval is only useful if !argok */
8327             while ( *RExC_parse && *RExC_parse != ')' ) {
8328                 if ( *RExC_parse == ':' ) {
8329                     start_arg = RExC_parse + 1;
8330                     break;
8331                 }
8332                 RExC_parse++;
8333             }
8334             ++start_verb;
8335             verb_len = RExC_parse - start_verb;
8336             if ( start_arg ) {
8337                 RExC_parse++;
8338                 while ( *RExC_parse && *RExC_parse != ')' ) 
8339                     RExC_parse++;
8340                 if ( *RExC_parse != ')' ) 
8341                     vFAIL("Unterminated verb pattern argument");
8342                 if ( RExC_parse == start_arg )
8343                     start_arg = NULL;
8344             } else {
8345                 if ( *RExC_parse != ')' )
8346                     vFAIL("Unterminated verb pattern");
8347             }
8348             
8349             switch ( *start_verb ) {
8350             case 'A':  /* (*ACCEPT) */
8351                 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
8352                     op = ACCEPT;
8353                     internal_argval = RExC_nestroot;
8354                 }
8355                 break;
8356             case 'C':  /* (*COMMIT) */
8357                 if ( memEQs(start_verb,verb_len,"COMMIT") )
8358                     op = COMMIT;
8359                 break;
8360             case 'F':  /* (*FAIL) */
8361                 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
8362                     op = OPFAIL;
8363                     argok = 0;
8364                 }
8365                 break;
8366             case ':':  /* (*:NAME) */
8367             case 'M':  /* (*MARK:NAME) */
8368                 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
8369                     op = MARKPOINT;
8370                     argok = -1;
8371                 }
8372                 break;
8373             case 'P':  /* (*PRUNE) */
8374                 if ( memEQs(start_verb,verb_len,"PRUNE") )
8375                     op = PRUNE;
8376                 break;
8377             case 'S':   /* (*SKIP) */  
8378                 if ( memEQs(start_verb,verb_len,"SKIP") ) 
8379                     op = SKIP;
8380                 break;
8381             case 'T':  /* (*THEN) */
8382                 /* [19:06] <TimToady> :: is then */
8383                 if ( memEQs(start_verb,verb_len,"THEN") ) {
8384                     op = CUTGROUP;
8385                     RExC_seen |= REG_SEEN_CUTGROUP;
8386                 }
8387                 break;
8388             }
8389             if ( ! op ) {
8390                 RExC_parse++;
8391                 vFAIL3("Unknown verb pattern '%.*s'",
8392                     verb_len, start_verb);
8393             }
8394             if ( argok ) {
8395                 if ( start_arg && internal_argval ) {
8396                     vFAIL3("Verb pattern '%.*s' may not have an argument",
8397                         verb_len, start_verb); 
8398                 } else if ( argok < 0 && !start_arg ) {
8399                     vFAIL3("Verb pattern '%.*s' has a mandatory argument",
8400                         verb_len, start_verb);    
8401                 } else {
8402                     ret = reganode(pRExC_state, op, internal_argval);
8403                     if ( ! internal_argval && ! SIZE_ONLY ) {
8404                         if (start_arg) {
8405                             SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
8406                             ARG(ret) = add_data( pRExC_state, 1, "S" );
8407                             RExC_rxi->data->data[ARG(ret)]=(void*)sv;
8408                             ret->flags = 0;
8409                         } else {
8410                             ret->flags = 1; 
8411                         }
8412                     }               
8413                 }
8414                 if (!internal_argval)
8415                     RExC_seen |= REG_SEEN_VERBARG;
8416             } else if ( start_arg ) {
8417                 vFAIL3("Verb pattern '%.*s' may not have an argument",
8418                         verb_len, start_verb);    
8419             } else {
8420                 ret = reg_node(pRExC_state, op);
8421             }
8422             nextchar(pRExC_state);
8423             return ret;
8424         } else 
8425         if (*RExC_parse == '?') { /* (?...) */
8426             bool is_logical = 0;
8427             const char * const seqstart = RExC_parse;
8428             bool has_use_defaults = FALSE;
8429
8430             RExC_parse++;
8431             paren = *RExC_parse++;
8432             ret = NULL;                 /* For look-ahead/behind. */
8433             switch (paren) {
8434
8435             case 'P':   /* (?P...) variants for those used to PCRE/Python */
8436                 paren = *RExC_parse++;
8437                 if ( paren == '<')         /* (?P<...>) named capture */
8438                     goto named_capture;
8439                 else if (paren == '>') {   /* (?P>name) named recursion */
8440                     goto named_recursion;
8441                 }
8442                 else if (paren == '=') {   /* (?P=...)  named backref */
8443                     /* this pretty much dupes the code for \k<NAME> in regatom(), if
8444                        you change this make sure you change that */
8445                     char* name_start = RExC_parse;
8446                     U32 num = 0;
8447                     SV *sv_dat = reg_scan_name(pRExC_state,
8448                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8449                     if (RExC_parse == name_start || *RExC_parse != ')')
8450                         vFAIL2("Sequence %.3s... not terminated",parse_start);
8451
8452                     if (!SIZE_ONLY) {
8453                         num = add_data( pRExC_state, 1, "S" );
8454                         RExC_rxi->data->data[num]=(void*)sv_dat;
8455                         SvREFCNT_inc_simple_void(sv_dat);
8456                     }
8457                     RExC_sawback = 1;
8458                     ret = reganode(pRExC_state,
8459                                    ((! FOLD)
8460                                      ? NREF
8461                                      : (ASCII_FOLD_RESTRICTED)
8462                                        ? NREFFA
8463                                        : (AT_LEAST_UNI_SEMANTICS)
8464                                          ? NREFFU
8465                                          : (LOC)
8466                                            ? NREFFL
8467                                            : NREFF),
8468                                     num);
8469                     *flagp |= HASWIDTH;
8470
8471                     Set_Node_Offset(ret, parse_start+1);
8472                     Set_Node_Cur_Length(ret); /* MJD */
8473
8474                     nextchar(pRExC_state);
8475                     return ret;
8476                 }
8477                 RExC_parse++;
8478                 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8479                 /*NOTREACHED*/
8480             case '<':           /* (?<...) */
8481                 if (*RExC_parse == '!')
8482                     paren = ',';
8483                 else if (*RExC_parse != '=') 
8484               named_capture:
8485                 {               /* (?<...>) */
8486                     char *name_start;
8487                     SV *svname;
8488                     paren= '>';
8489             case '\'':          /* (?'...') */
8490                     name_start= RExC_parse;
8491                     svname = reg_scan_name(pRExC_state,
8492                         SIZE_ONLY ?  /* reverse test from the others */
8493                         REG_RSN_RETURN_NAME : 
8494                         REG_RSN_RETURN_NULL);
8495                     if (RExC_parse == name_start) {
8496                         RExC_parse++;
8497                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8498                         /*NOTREACHED*/
8499                     }
8500                     if (*RExC_parse != paren)
8501                         vFAIL2("Sequence (?%c... not terminated",
8502                             paren=='>' ? '<' : paren);
8503                     if (SIZE_ONLY) {
8504                         HE *he_str;
8505                         SV *sv_dat = NULL;
8506                         if (!svname) /* shouldn't happen */
8507                             Perl_croak(aTHX_
8508                                 "panic: reg_scan_name returned NULL");
8509                         if (!RExC_paren_names) {
8510                             RExC_paren_names= newHV();
8511                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
8512 #ifdef DEBUGGING
8513                             RExC_paren_name_list= newAV();
8514                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
8515 #endif
8516                         }
8517                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
8518                         if ( he_str )
8519                             sv_dat = HeVAL(he_str);
8520                         if ( ! sv_dat ) {
8521                             /* croak baby croak */
8522                             Perl_croak(aTHX_
8523                                 "panic: paren_name hash element allocation failed");
8524                         } else if ( SvPOK(sv_dat) ) {
8525                             /* (?|...) can mean we have dupes so scan to check
8526                                its already been stored. Maybe a flag indicating
8527                                we are inside such a construct would be useful,
8528                                but the arrays are likely to be quite small, so
8529                                for now we punt -- dmq */
8530                             IV count = SvIV(sv_dat);
8531                             I32 *pv = (I32*)SvPVX(sv_dat);
8532                             IV i;
8533                             for ( i = 0 ; i < count ; i++ ) {
8534                                 if ( pv[i] == RExC_npar ) {
8535                                     count = 0;
8536                                     break;
8537                                 }
8538                             }
8539                             if ( count ) {
8540                                 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
8541                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
8542                                 pv[count] = RExC_npar;
8543                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
8544                             }
8545                         } else {
8546                             (void)SvUPGRADE(sv_dat,SVt_PVNV);
8547                             sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
8548                             SvIOK_on(sv_dat);
8549                             SvIV_set(sv_dat, 1);
8550                         }
8551 #ifdef DEBUGGING
8552                         /* Yes this does cause a memory leak in debugging Perls */
8553                         if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
8554                             SvREFCNT_dec_NN(svname);
8555 #endif
8556
8557                         /*sv_dump(sv_dat);*/
8558                     }
8559                     nextchar(pRExC_state);
8560                     paren = 1;
8561                     goto capturing_parens;
8562                 }
8563                 RExC_seen |= REG_SEEN_LOOKBEHIND;
8564                 RExC_in_lookbehind++;
8565                 RExC_parse++;
8566             case '=':           /* (?=...) */
8567                 RExC_seen_zerolen++;
8568                 break;
8569             case '!':           /* (?!...) */
8570                 RExC_seen_zerolen++;
8571                 if (*RExC_parse == ')') {
8572                     ret=reg_node(pRExC_state, OPFAIL);
8573                     nextchar(pRExC_state);
8574                     return ret;
8575                 }
8576                 break;
8577             case '|':           /* (?|...) */
8578                 /* branch reset, behave like a (?:...) except that
8579                    buffers in alternations share the same numbers */
8580                 paren = ':'; 
8581                 after_freeze = freeze_paren = RExC_npar;
8582                 break;
8583             case ':':           /* (?:...) */
8584             case '>':           /* (?>...) */
8585                 break;
8586             case '$':           /* (?$...) */
8587             case '@':           /* (?@...) */
8588                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
8589                 break;
8590             case '#':           /* (?#...) */
8591                 while (*RExC_parse && *RExC_parse != ')')
8592                     RExC_parse++;
8593                 if (*RExC_parse != ')')
8594                     FAIL("Sequence (?#... not terminated");
8595                 nextchar(pRExC_state);
8596                 *flagp = TRYAGAIN;
8597                 return NULL;
8598             case '0' :           /* (?0) */
8599             case 'R' :           /* (?R) */
8600                 if (*RExC_parse != ')')
8601                     FAIL("Sequence (?R) not terminated");
8602                 ret = reg_node(pRExC_state, GOSTART);
8603                 *flagp |= POSTPONED;
8604                 nextchar(pRExC_state);
8605                 return ret;
8606                 /*notreached*/
8607             { /* named and numeric backreferences */
8608                 I32 num;
8609             case '&':            /* (?&NAME) */
8610                 parse_start = RExC_parse - 1;
8611               named_recursion:
8612                 {
8613                     SV *sv_dat = reg_scan_name(pRExC_state,
8614                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8615                      num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
8616                 }
8617                 goto gen_recurse_regop;
8618                 assert(0); /* NOT REACHED */
8619             case '+':
8620                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
8621                     RExC_parse++;
8622                     vFAIL("Illegal pattern");
8623                 }
8624                 goto parse_recursion;
8625                 /* NOT REACHED*/
8626             case '-': /* (?-1) */
8627                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
8628                     RExC_parse--; /* rewind to let it be handled later */
8629                     goto parse_flags;
8630                 } 
8631                 /*FALLTHROUGH */
8632             case '1': case '2': case '3': case '4': /* (?1) */
8633             case '5': case '6': case '7': case '8': case '9':
8634                 RExC_parse--;
8635               parse_recursion:
8636                 num = atoi(RExC_parse);
8637                 parse_start = RExC_parse - 1; /* MJD */
8638                 if (*RExC_parse == '-')
8639                     RExC_parse++;
8640                 while (isDIGIT(*RExC_parse))
8641                         RExC_parse++;
8642                 if (*RExC_parse!=')') 
8643                     vFAIL("Expecting close bracket");
8644
8645               gen_recurse_regop:
8646                 if ( paren == '-' ) {
8647                     /*
8648                     Diagram of capture buffer numbering.
8649                     Top line is the normal capture buffer numbers
8650                     Bottom line is the negative indexing as from
8651                     the X (the (?-2))
8652
8653                     +   1 2    3 4 5 X          6 7
8654                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
8655                     -   5 4    3 2 1 X          x x
8656
8657                     */
8658                     num = RExC_npar + num;
8659                     if (num < 1)  {
8660                         RExC_parse++;
8661                         vFAIL("Reference to nonexistent group");
8662                     }
8663                 } else if ( paren == '+' ) {
8664                     num = RExC_npar + num - 1;
8665                 }
8666
8667                 ret = reganode(pRExC_state, GOSUB, num);
8668                 if (!SIZE_ONLY) {
8669                     if (num > (I32)RExC_rx->nparens) {
8670                         RExC_parse++;
8671                         vFAIL("Reference to nonexistent group");
8672                     }
8673                     ARG2L_SET( ret, RExC_recurse_count++);
8674                     RExC_emit++;
8675                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
8676                         "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
8677                 } else {
8678                     RExC_size++;
8679                 }
8680                 RExC_seen |= REG_SEEN_RECURSE;
8681                 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
8682                 Set_Node_Offset(ret, parse_start); /* MJD */
8683
8684                 *flagp |= POSTPONED;
8685                 nextchar(pRExC_state);
8686                 return ret;
8687             } /* named and numeric backreferences */
8688             assert(0); /* NOT REACHED */
8689
8690             case '?':           /* (??...) */
8691                 is_logical = 1;
8692                 if (*RExC_parse != '{') {
8693                     RExC_parse++;
8694                     vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8695                     /*NOTREACHED*/
8696                 }
8697                 *flagp |= POSTPONED;
8698                 paren = *RExC_parse++;
8699                 /* FALL THROUGH */
8700             case '{':           /* (?{...}) */
8701             {
8702                 U32 n = 0;
8703                 struct reg_code_block *cb;
8704
8705                 RExC_seen_zerolen++;
8706
8707                 if (   !pRExC_state->num_code_blocks
8708                     || pRExC_state->code_index >= pRExC_state->num_code_blocks
8709                     || pRExC_state->code_blocks[pRExC_state->code_index].start
8710                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
8711                             - RExC_start)
8712                 ) {
8713                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
8714                         FAIL("panic: Sequence (?{...}): no code block found\n");
8715                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
8716                 }
8717                 /* this is a pre-compiled code block (?{...}) */
8718                 cb = &pRExC_state->code_blocks[pRExC_state->code_index];
8719                 RExC_parse = RExC_start + cb->end;
8720                 if (!SIZE_ONLY) {
8721                     OP *o = cb->block;
8722                     if (cb->src_regex) {
8723                         n = add_data(pRExC_state, 2, "rl");
8724                         RExC_rxi->data->data[n] =
8725                             (void*)SvREFCNT_inc((SV*)cb->src_regex);
8726                         RExC_rxi->data->data[n+1] = (void*)o;
8727                     }
8728                     else {
8729                         n = add_data(pRExC_state, 1,
8730                                (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l");
8731                         RExC_rxi->data->data[n] = (void*)o;
8732                     }
8733                 }
8734                 pRExC_state->code_index++;
8735                 nextchar(pRExC_state);
8736
8737                 if (is_logical) {
8738                     regnode *eval;
8739                     ret = reg_node(pRExC_state, LOGICAL);
8740                     eval = reganode(pRExC_state, EVAL, n);
8741                     if (!SIZE_ONLY) {
8742                         ret->flags = 2;
8743                         /* for later propagation into (??{}) return value */
8744                         eval->flags = (U8) (RExC_flags & RXf_PMf_COMPILETIME);
8745                     }
8746                     REGTAIL(pRExC_state, ret, eval);
8747                     /* deal with the length of this later - MJD */
8748                     return ret;
8749                 }
8750                 ret = reganode(pRExC_state, EVAL, n);
8751                 Set_Node_Length(ret, RExC_parse - parse_start + 1);
8752                 Set_Node_Offset(ret, parse_start);
8753                 return ret;
8754             }
8755             case '(':           /* (?(?{...})...) and (?(?=...)...) */
8756             {
8757                 int is_define= 0;
8758                 if (RExC_parse[0] == '?') {        /* (?(?...)) */
8759                     if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
8760                         || RExC_parse[1] == '<'
8761                         || RExC_parse[1] == '{') { /* Lookahead or eval. */
8762                         I32 flag;
8763
8764                         ret = reg_node(pRExC_state, LOGICAL);
8765                         if (!SIZE_ONLY)
8766                             ret->flags = 1;
8767                         REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
8768                         goto insert_if;
8769                     }
8770                 }
8771                 else if ( RExC_parse[0] == '<'     /* (?(<NAME>)...) */
8772                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
8773                 {
8774                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
8775                     char *name_start= RExC_parse++;
8776                     U32 num = 0;
8777                     SV *sv_dat=reg_scan_name(pRExC_state,
8778                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8779                     if (RExC_parse == name_start || *RExC_parse != ch)
8780                         vFAIL2("Sequence (?(%c... not terminated",
8781                             (ch == '>' ? '<' : ch));
8782                     RExC_parse++;
8783                     if (!SIZE_ONLY) {
8784                         num = add_data( pRExC_state, 1, "S" );
8785                         RExC_rxi->data->data[num]=(void*)sv_dat;
8786                         SvREFCNT_inc_simple_void(sv_dat);
8787                     }
8788                     ret = reganode(pRExC_state,NGROUPP,num);
8789                     goto insert_if_check_paren;
8790                 }
8791                 else if (RExC_parse[0] == 'D' &&
8792                          RExC_parse[1] == 'E' &&
8793                          RExC_parse[2] == 'F' &&
8794                          RExC_parse[3] == 'I' &&
8795                          RExC_parse[4] == 'N' &&
8796                          RExC_parse[5] == 'E')
8797                 {
8798                     ret = reganode(pRExC_state,DEFINEP,0);
8799                     RExC_parse +=6 ;
8800                     is_define = 1;
8801                     goto insert_if_check_paren;
8802                 }
8803                 else if (RExC_parse[0] == 'R') {
8804                     RExC_parse++;
8805                     parno = 0;
8806                     if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
8807                         parno = atoi(RExC_parse++);
8808                         while (isDIGIT(*RExC_parse))
8809                             RExC_parse++;
8810                     } else if (RExC_parse[0] == '&') {
8811                         SV *sv_dat;
8812                         RExC_parse++;
8813                         sv_dat = reg_scan_name(pRExC_state,
8814                             SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8815                         parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
8816                     }
8817                     ret = reganode(pRExC_state,INSUBP,parno); 
8818                     goto insert_if_check_paren;
8819                 }
8820                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
8821                     /* (?(1)...) */
8822                     char c;
8823                     parno = atoi(RExC_parse++);
8824
8825                     while (isDIGIT(*RExC_parse))
8826                         RExC_parse++;
8827                     ret = reganode(pRExC_state, GROUPP, parno);
8828
8829                  insert_if_check_paren:
8830                     if ((c = *nextchar(pRExC_state)) != ')')
8831                         vFAIL("Switch condition not recognized");
8832                   insert_if:
8833                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
8834                     br = regbranch(pRExC_state, &flags, 1,depth+1);
8835                     if (br == NULL)
8836                         br = reganode(pRExC_state, LONGJMP, 0);
8837                     else
8838                         REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
8839                     c = *nextchar(pRExC_state);
8840                     if (flags&HASWIDTH)
8841                         *flagp |= HASWIDTH;
8842                     if (c == '|') {
8843                         if (is_define) 
8844                             vFAIL("(?(DEFINE)....) does not allow branches");
8845                         lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
8846                         regbranch(pRExC_state, &flags, 1,depth+1);
8847                         REGTAIL(pRExC_state, ret, lastbr);
8848                         if (flags&HASWIDTH)
8849                             *flagp |= HASWIDTH;
8850                         c = *nextchar(pRExC_state);
8851                     }
8852                     else
8853                         lastbr = NULL;
8854                     if (c != ')')
8855                         vFAIL("Switch (?(condition)... contains too many branches");
8856                     ender = reg_node(pRExC_state, TAIL);
8857                     REGTAIL(pRExC_state, br, ender);
8858                     if (lastbr) {
8859                         REGTAIL(pRExC_state, lastbr, ender);
8860                         REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
8861                     }
8862                     else
8863                         REGTAIL(pRExC_state, ret, ender);
8864                     RExC_size++; /* XXX WHY do we need this?!!
8865                                     For large programs it seems to be required
8866                                     but I can't figure out why. -- dmq*/
8867                     return ret;
8868                 }
8869                 else {
8870                     vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
8871                 }
8872             }
8873             case 0:
8874                 RExC_parse--; /* for vFAIL to print correctly */
8875                 vFAIL("Sequence (? incomplete");
8876                 break;
8877             case DEFAULT_PAT_MOD:   /* Use default flags with the exceptions
8878                                        that follow */
8879                 has_use_defaults = TRUE;
8880                 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
8881                 set_regex_charset(&RExC_flags, (RExC_utf8 || RExC_uni_semantics)
8882                                                 ? REGEX_UNICODE_CHARSET
8883                                                 : REGEX_DEPENDS_CHARSET);
8884                 goto parse_flags;
8885             default:
8886                 --RExC_parse;
8887                 parse_flags:      /* (?i) */  
8888             {
8889                 U32 posflags = 0, negflags = 0;
8890                 U32 *flagsp = &posflags;
8891                 char has_charset_modifier = '\0';
8892                 regex_charset cs = get_regex_charset(RExC_flags);
8893                 if (cs == REGEX_DEPENDS_CHARSET
8894                     && (RExC_utf8 || RExC_uni_semantics))
8895                 {
8896                     cs = REGEX_UNICODE_CHARSET;
8897                 }
8898
8899                 while (*RExC_parse) {
8900                     /* && strchr("iogcmsx", *RExC_parse) */
8901                     /* (?g), (?gc) and (?o) are useless here
8902                        and must be globally applied -- japhy */
8903                     switch (*RExC_parse) {
8904                     CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
8905                     case LOCALE_PAT_MOD:
8906                         if (has_charset_modifier) {
8907                             goto excess_modifier;
8908                         }
8909                         else if (flagsp == &negflags) {
8910                             goto neg_modifier;
8911                         }
8912                         cs = REGEX_LOCALE_CHARSET;
8913                         has_charset_modifier = LOCALE_PAT_MOD;
8914                         RExC_contains_locale = 1;
8915                         break;
8916                     case UNICODE_PAT_MOD:
8917                         if (has_charset_modifier) {
8918                             goto excess_modifier;
8919                         }
8920                         else if (flagsp == &negflags) {
8921                             goto neg_modifier;
8922                         }
8923                         cs = REGEX_UNICODE_CHARSET;
8924                         has_charset_modifier = UNICODE_PAT_MOD;
8925                         break;
8926                     case ASCII_RESTRICT_PAT_MOD:
8927                         if (flagsp == &negflags) {
8928                             goto neg_modifier;
8929                         }
8930                         if (has_charset_modifier) {
8931                             if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
8932                                 goto excess_modifier;
8933                             }
8934                             /* Doubled modifier implies more restricted */
8935                             cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
8936                         }
8937                         else {
8938                             cs = REGEX_ASCII_RESTRICTED_CHARSET;
8939                         }
8940                         has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
8941                         break;
8942                     case DEPENDS_PAT_MOD:
8943                         if (has_use_defaults) {
8944                             goto fail_modifiers;
8945                         }
8946                         else if (flagsp == &negflags) {
8947                             goto neg_modifier;
8948                         }
8949                         else if (has_charset_modifier) {
8950                             goto excess_modifier;
8951                         }
8952
8953                         /* The dual charset means unicode semantics if the
8954                          * pattern (or target, not known until runtime) are
8955                          * utf8, or something in the pattern indicates unicode
8956                          * semantics */
8957                         cs = (RExC_utf8 || RExC_uni_semantics)
8958                              ? REGEX_UNICODE_CHARSET
8959                              : REGEX_DEPENDS_CHARSET;
8960                         has_charset_modifier = DEPENDS_PAT_MOD;
8961                         break;
8962                     excess_modifier:
8963                         RExC_parse++;
8964                         if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
8965                             vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
8966                         }
8967                         else if (has_charset_modifier == *(RExC_parse - 1)) {
8968                             vFAIL2("Regexp modifier \"%c\" may not appear twice", *(RExC_parse - 1));
8969                         }
8970                         else {
8971                             vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
8972                         }
8973                         /*NOTREACHED*/
8974                     neg_modifier:
8975                         RExC_parse++;
8976                         vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"", *(RExC_parse - 1));
8977                         /*NOTREACHED*/
8978                     case ONCE_PAT_MOD: /* 'o' */
8979                     case GLOBAL_PAT_MOD: /* 'g' */
8980                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
8981                             const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
8982                             if (! (wastedflags & wflagbit) ) {
8983                                 wastedflags |= wflagbit;
8984                                 vWARN5(
8985                                     RExC_parse + 1,
8986                                     "Useless (%s%c) - %suse /%c modifier",
8987                                     flagsp == &negflags ? "?-" : "?",
8988                                     *RExC_parse,
8989                                     flagsp == &negflags ? "don't " : "",
8990                                     *RExC_parse
8991                                 );
8992                             }
8993                         }
8994                         break;
8995                         
8996                     case CONTINUE_PAT_MOD: /* 'c' */
8997                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
8998                             if (! (wastedflags & WASTED_C) ) {
8999                                 wastedflags |= WASTED_GC;
9000                                 vWARN3(
9001                                     RExC_parse + 1,
9002                                     "Useless (%sc) - %suse /gc modifier",
9003                                     flagsp == &negflags ? "?-" : "?",
9004                                     flagsp == &negflags ? "don't " : ""
9005                                 );
9006                             }
9007                         }
9008                         break;
9009                     case KEEPCOPY_PAT_MOD: /* 'p' */
9010                         if (flagsp == &negflags) {
9011                             if (SIZE_ONLY)
9012                                 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
9013                         } else {
9014                             *flagsp |= RXf_PMf_KEEPCOPY;
9015                         }
9016                         break;
9017                     case '-':
9018                         /* A flag is a default iff it is following a minus, so
9019                          * if there is a minus, it means will be trying to
9020                          * re-specify a default which is an error */
9021                         if (has_use_defaults || flagsp == &negflags) {
9022             fail_modifiers:
9023                             RExC_parse++;
9024                             vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
9025                             /*NOTREACHED*/
9026                         }
9027                         flagsp = &negflags;
9028                         wastedflags = 0;  /* reset so (?g-c) warns twice */
9029                         break;
9030                     case ':':
9031                         paren = ':';
9032                         /*FALLTHROUGH*/
9033                     case ')':
9034                         RExC_flags |= posflags;
9035                         RExC_flags &= ~negflags;
9036                         set_regex_charset(&RExC_flags, cs);
9037                         if (paren != ':') {
9038                             oregflags |= posflags;
9039                             oregflags &= ~negflags;
9040                             set_regex_charset(&oregflags, cs);
9041                         }
9042                         nextchar(pRExC_state);
9043                         if (paren != ':') {
9044                             *flagp = TRYAGAIN;
9045                             return NULL;
9046                         } else {
9047                             ret = NULL;
9048                             goto parse_rest;
9049                         }
9050                         /*NOTREACHED*/
9051                     default:
9052                         RExC_parse++;
9053                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
9054                         /*NOTREACHED*/
9055                     }                           
9056                     ++RExC_parse;
9057                 }
9058             }} /* one for the default block, one for the switch */
9059         }
9060         else {                  /* (...) */
9061           capturing_parens:
9062             parno = RExC_npar;
9063             RExC_npar++;
9064             
9065             ret = reganode(pRExC_state, OPEN, parno);
9066             if (!SIZE_ONLY ){
9067                 if (!RExC_nestroot) 
9068                     RExC_nestroot = parno;
9069                 if (RExC_seen & REG_SEEN_RECURSE
9070                     && !RExC_open_parens[parno-1])
9071                 {
9072                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
9073                         "Setting open paren #%"IVdf" to %d\n", 
9074                         (IV)parno, REG_NODE_NUM(ret)));
9075                     RExC_open_parens[parno-1]= ret;
9076                 }
9077             }
9078             Set_Node_Length(ret, 1); /* MJD */
9079             Set_Node_Offset(ret, RExC_parse); /* MJD */
9080             is_open = 1;
9081         }
9082     }
9083     else                        /* ! paren */
9084         ret = NULL;
9085    
9086    parse_rest:
9087     /* Pick up the branches, linking them together. */
9088     parse_start = RExC_parse;   /* MJD */
9089     br = regbranch(pRExC_state, &flags, 1,depth+1);
9090
9091     /*     branch_len = (paren != 0); */
9092
9093     if (br == NULL)
9094         return(NULL);
9095     if (*RExC_parse == '|') {
9096         if (!SIZE_ONLY && RExC_extralen) {
9097             reginsert(pRExC_state, BRANCHJ, br, depth+1);
9098         }
9099         else {                  /* MJD */
9100             reginsert(pRExC_state, BRANCH, br, depth+1);
9101             Set_Node_Length(br, paren != 0);
9102             Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
9103         }
9104         have_branch = 1;
9105         if (SIZE_ONLY)
9106             RExC_extralen += 1;         /* For BRANCHJ-BRANCH. */
9107     }
9108     else if (paren == ':') {
9109         *flagp |= flags&SIMPLE;
9110     }
9111     if (is_open) {                              /* Starts with OPEN. */
9112         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
9113     }
9114     else if (paren != '?')              /* Not Conditional */
9115         ret = br;
9116     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
9117     lastbr = br;
9118     while (*RExC_parse == '|') {
9119         if (!SIZE_ONLY && RExC_extralen) {
9120             ender = reganode(pRExC_state, LONGJMP,0);
9121             REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
9122         }
9123         if (SIZE_ONLY)
9124             RExC_extralen += 2;         /* Account for LONGJMP. */
9125         nextchar(pRExC_state);
9126         if (freeze_paren) {
9127             if (RExC_npar > after_freeze)
9128                 after_freeze = RExC_npar;
9129             RExC_npar = freeze_paren;       
9130         }
9131         br = regbranch(pRExC_state, &flags, 0, depth+1);
9132
9133         if (br == NULL)
9134             return(NULL);
9135         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
9136         lastbr = br;
9137         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
9138     }
9139
9140     if (have_branch || paren != ':') {
9141         /* Make a closing node, and hook it on the end. */
9142         switch (paren) {
9143         case ':':
9144             ender = reg_node(pRExC_state, TAIL);
9145             break;
9146         case 1:
9147             ender = reganode(pRExC_state, CLOSE, parno);
9148             if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
9149                 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
9150                         "Setting close paren #%"IVdf" to %d\n", 
9151                         (IV)parno, REG_NODE_NUM(ender)));
9152                 RExC_close_parens[parno-1]= ender;
9153                 if (RExC_nestroot == parno) 
9154                     RExC_nestroot = 0;
9155             }       
9156             Set_Node_Offset(ender,RExC_parse+1); /* MJD */
9157             Set_Node_Length(ender,1); /* MJD */
9158             break;
9159         case '<':
9160         case ',':
9161         case '=':
9162         case '!':
9163             *flagp &= ~HASWIDTH;
9164             /* FALL THROUGH */
9165         case '>':
9166             ender = reg_node(pRExC_state, SUCCEED);
9167             break;
9168         case 0:
9169             ender = reg_node(pRExC_state, END);
9170             if (!SIZE_ONLY) {
9171                 assert(!RExC_opend); /* there can only be one! */
9172                 RExC_opend = ender;
9173             }
9174             break;
9175         }
9176         DEBUG_PARSE_r(if (!SIZE_ONLY) {
9177             SV * const mysv_val1=sv_newmortal();
9178             SV * const mysv_val2=sv_newmortal();
9179             DEBUG_PARSE_MSG("lsbr");
9180             regprop(RExC_rx, mysv_val1, lastbr);
9181             regprop(RExC_rx, mysv_val2, ender);
9182             PerlIO_printf(Perl_debug_log, "~ tying lastbr %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
9183                           SvPV_nolen_const(mysv_val1),
9184                           (IV)REG_NODE_NUM(lastbr),
9185                           SvPV_nolen_const(mysv_val2),
9186                           (IV)REG_NODE_NUM(ender),
9187                           (IV)(ender - lastbr)
9188             );
9189         });
9190         REGTAIL(pRExC_state, lastbr, ender);
9191
9192         if (have_branch && !SIZE_ONLY) {
9193             char is_nothing= 1;
9194             if (depth==1)
9195                 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
9196
9197             /* Hook the tails of the branches to the closing node. */
9198             for (br = ret; br; br = regnext(br)) {
9199                 const U8 op = PL_regkind[OP(br)];
9200                 if (op == BRANCH) {
9201                     REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
9202                     if (OP(NEXTOPER(br)) != NOTHING || regnext(NEXTOPER(br)) != ender)
9203                         is_nothing= 0;
9204                 }
9205                 else if (op == BRANCHJ) {
9206                     REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
9207                     /* for now we always disable this optimisation * /
9208                     if (OP(NEXTOPER(NEXTOPER(br))) != NOTHING || regnext(NEXTOPER(NEXTOPER(br))) != ender)
9209                     */
9210                         is_nothing= 0;
9211                 }
9212             }
9213             if (is_nothing) {
9214                 br= PL_regkind[OP(ret)] != BRANCH ? regnext(ret) : ret;
9215                 DEBUG_PARSE_r(if (!SIZE_ONLY) {
9216                     SV * const mysv_val1=sv_newmortal();
9217                     SV * const mysv_val2=sv_newmortal();
9218                     DEBUG_PARSE_MSG("NADA");
9219                     regprop(RExC_rx, mysv_val1, ret);
9220                     regprop(RExC_rx, mysv_val2, ender);
9221                     PerlIO_printf(Perl_debug_log, "~ converting ret %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
9222                                   SvPV_nolen_const(mysv_val1),
9223                                   (IV)REG_NODE_NUM(ret),
9224                                   SvPV_nolen_const(mysv_val2),
9225                                   (IV)REG_NODE_NUM(ender),
9226                                   (IV)(ender - ret)
9227                     );
9228                 });
9229                 OP(br)= NOTHING;
9230                 if (OP(ender) == TAIL) {
9231                     NEXT_OFF(br)= 0;
9232                     RExC_emit= br + 1;
9233                 } else {
9234                     regnode *opt;
9235                     for ( opt= br + 1; opt < ender ; opt++ )
9236                         OP(opt)= OPTIMIZED;
9237                     NEXT_OFF(br)= ender - br;
9238                 }
9239             }
9240         }
9241     }
9242
9243     {
9244         const char *p;
9245         static const char parens[] = "=!<,>";
9246
9247         if (paren && (p = strchr(parens, paren))) {
9248             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
9249             int flag = (p - parens) > 1;
9250
9251             if (paren == '>')
9252                 node = SUSPEND, flag = 0;
9253             reginsert(pRExC_state, node,ret, depth+1);
9254             Set_Node_Cur_Length(ret);
9255             Set_Node_Offset(ret, parse_start + 1);
9256             ret->flags = flag;
9257             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
9258         }
9259     }
9260
9261     /* Check for proper termination. */
9262     if (paren) {
9263         RExC_flags = oregflags;
9264         if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
9265             RExC_parse = oregcomp_parse;
9266             vFAIL("Unmatched (");
9267         }
9268     }
9269     else if (!paren && RExC_parse < RExC_end) {
9270         if (*RExC_parse == ')') {
9271             RExC_parse++;
9272             vFAIL("Unmatched )");
9273         }
9274         else
9275             FAIL("Junk on end of regexp");      /* "Can't happen". */
9276         assert(0); /* NOTREACHED */
9277     }
9278
9279     if (RExC_in_lookbehind) {
9280         RExC_in_lookbehind--;
9281     }
9282     if (after_freeze > RExC_npar)
9283         RExC_npar = after_freeze;
9284     return(ret);
9285 }
9286
9287 /*
9288  - regbranch - one alternative of an | operator
9289  *
9290  * Implements the concatenation operator.
9291  */
9292 STATIC regnode *
9293 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
9294 {
9295     dVAR;
9296     regnode *ret;
9297     regnode *chain = NULL;
9298     regnode *latest;
9299     I32 flags = 0, c = 0;
9300     GET_RE_DEBUG_FLAGS_DECL;
9301
9302     PERL_ARGS_ASSERT_REGBRANCH;
9303
9304     DEBUG_PARSE("brnc");
9305
9306     if (first)
9307         ret = NULL;
9308     else {
9309         if (!SIZE_ONLY && RExC_extralen)
9310             ret = reganode(pRExC_state, BRANCHJ,0);
9311         else {
9312             ret = reg_node(pRExC_state, BRANCH);
9313             Set_Node_Length(ret, 1);
9314         }
9315     }
9316
9317     if (!first && SIZE_ONLY)
9318         RExC_extralen += 1;                     /* BRANCHJ */
9319
9320     *flagp = WORST;                     /* Tentatively. */
9321
9322     RExC_parse--;
9323     nextchar(pRExC_state);
9324     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
9325         flags &= ~TRYAGAIN;
9326         latest = regpiece(pRExC_state, &flags,depth+1);
9327         if (latest == NULL) {
9328             if (flags & TRYAGAIN)
9329                 continue;
9330             return(NULL);
9331         }
9332         else if (ret == NULL)
9333             ret = latest;
9334         *flagp |= flags&(HASWIDTH|POSTPONED);
9335         if (chain == NULL)      /* First piece. */
9336             *flagp |= flags&SPSTART;
9337         else {
9338             RExC_naughty++;
9339             REGTAIL(pRExC_state, chain, latest);
9340         }
9341         chain = latest;
9342         c++;
9343     }
9344     if (chain == NULL) {        /* Loop ran zero times. */
9345         chain = reg_node(pRExC_state, NOTHING);
9346         if (ret == NULL)
9347             ret = chain;
9348     }
9349     if (c == 1) {
9350         *flagp |= flags&SIMPLE;
9351     }
9352
9353     return ret;
9354 }
9355
9356 /*
9357  - regpiece - something followed by possible [*+?]
9358  *
9359  * Note that the branching code sequences used for ? and the general cases
9360  * of * and + are somewhat optimized:  they use the same NOTHING node as
9361  * both the endmarker for their branch list and the body of the last branch.
9362  * It might seem that this node could be dispensed with entirely, but the
9363  * endmarker role is not redundant.
9364  */
9365 STATIC regnode *
9366 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
9367 {
9368     dVAR;
9369     regnode *ret;
9370     char op;
9371     char *next;
9372     I32 flags;
9373     const char * const origparse = RExC_parse;
9374     I32 min;
9375     I32 max = REG_INFTY;
9376 #ifdef RE_TRACK_PATTERN_OFFSETS
9377     char *parse_start;
9378 #endif
9379     const char *maxpos = NULL;
9380
9381     /* Save the original in case we change the emitted regop to a FAIL. */
9382     regnode * const orig_emit = RExC_emit;
9383
9384     GET_RE_DEBUG_FLAGS_DECL;
9385
9386     PERL_ARGS_ASSERT_REGPIECE;
9387
9388     DEBUG_PARSE("piec");
9389
9390     ret = regatom(pRExC_state, &flags,depth+1);
9391     if (ret == NULL) {
9392         if (flags & TRYAGAIN)
9393             *flagp |= TRYAGAIN;
9394         return(NULL);
9395     }
9396
9397     op = *RExC_parse;
9398
9399     if (op == '{' && regcurly(RExC_parse)) {
9400         maxpos = NULL;
9401 #ifdef RE_TRACK_PATTERN_OFFSETS
9402         parse_start = RExC_parse; /* MJD */
9403 #endif
9404         next = RExC_parse + 1;
9405         while (isDIGIT(*next) || *next == ',') {
9406             if (*next == ',') {
9407                 if (maxpos)
9408                     break;
9409                 else
9410                     maxpos = next;
9411             }
9412             next++;
9413         }
9414         if (*next == '}') {             /* got one */
9415             if (!maxpos)
9416                 maxpos = next;
9417             RExC_parse++;
9418             min = atoi(RExC_parse);
9419             if (*maxpos == ',')
9420                 maxpos++;
9421             else
9422                 maxpos = RExC_parse;
9423             max = atoi(maxpos);
9424             if (!max && *maxpos != '0')
9425                 max = REG_INFTY;                /* meaning "infinity" */
9426             else if (max >= REG_INFTY)
9427                 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
9428             RExC_parse = next;
9429             nextchar(pRExC_state);
9430             if (max < min) {    /* If can't match, warn and optimize to fail
9431                                    unconditionally */
9432                 if (SIZE_ONLY) {
9433                     ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match");
9434
9435                     /* We can't back off the size because we have to reserve
9436                      * enough space for all the things we are about to throw
9437                      * away, but we can shrink it by the ammount we are about
9438                      * to re-use here */
9439                     RExC_size = PREVOPER(RExC_size) - regarglen[(U8)OPFAIL];
9440                 }
9441                 else {
9442                     RExC_emit = orig_emit;
9443                 }
9444                 ret = reg_node(pRExC_state, OPFAIL);
9445                 return ret;
9446             }
9447             else if (max == 0) {    /* replace {0} with a nothing node */
9448                 if (SIZE_ONLY) {
9449                     RExC_size = PREVOPER(RExC_size) - regarglen[(U8)NOTHING];
9450                 }
9451                 else {
9452                     RExC_emit = orig_emit;
9453                 }
9454                 ret = reg_node(pRExC_state, NOTHING);
9455                 return ret;
9456             }
9457
9458         do_curly:
9459             if ((flags&SIMPLE)) {
9460                 RExC_naughty += 2 + RExC_naughty / 2;
9461                 reginsert(pRExC_state, CURLY, ret, depth+1);
9462                 Set_Node_Offset(ret, parse_start+1); /* MJD */
9463                 Set_Node_Cur_Length(ret);
9464             }
9465             else {
9466                 regnode * const w = reg_node(pRExC_state, WHILEM);
9467
9468                 w->flags = 0;
9469                 REGTAIL(pRExC_state, ret, w);
9470                 if (!SIZE_ONLY && RExC_extralen) {
9471                     reginsert(pRExC_state, LONGJMP,ret, depth+1);
9472                     reginsert(pRExC_state, NOTHING,ret, depth+1);
9473                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
9474                 }
9475                 reginsert(pRExC_state, CURLYX,ret, depth+1);
9476                                 /* MJD hk */
9477                 Set_Node_Offset(ret, parse_start+1);
9478                 Set_Node_Length(ret,
9479                                 op == '{' ? (RExC_parse - parse_start) : 1);
9480
9481                 if (!SIZE_ONLY && RExC_extralen)
9482                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
9483                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
9484                 if (SIZE_ONLY)
9485                     RExC_whilem_seen++, RExC_extralen += 3;
9486                 RExC_naughty += 4 + RExC_naughty;       /* compound interest */
9487             }
9488             ret->flags = 0;
9489
9490             if (min > 0)
9491                 *flagp = WORST;
9492             if (max > 0)
9493                 *flagp |= HASWIDTH;
9494             if (!SIZE_ONLY) {
9495                 ARG1_SET(ret, (U16)min);
9496                 ARG2_SET(ret, (U16)max);
9497             }
9498
9499             goto nest_check;
9500         }
9501     }
9502
9503     if (!ISMULT1(op)) {
9504         *flagp = flags;
9505         return(ret);
9506     }
9507
9508 #if 0                           /* Now runtime fix should be reliable. */
9509
9510     /* if this is reinstated, don't forget to put this back into perldiag:
9511
9512             =item Regexp *+ operand could be empty at {#} in regex m/%s/
9513
9514            (F) The part of the regexp subject to either the * or + quantifier
9515            could match an empty string. The {#} shows in the regular
9516            expression about where the problem was discovered.
9517
9518     */
9519
9520     if (!(flags&HASWIDTH) && op != '?')
9521       vFAIL("Regexp *+ operand could be empty");
9522 #endif
9523
9524 #ifdef RE_TRACK_PATTERN_OFFSETS
9525     parse_start = RExC_parse;
9526 #endif
9527     nextchar(pRExC_state);
9528
9529     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
9530
9531     if (op == '*' && (flags&SIMPLE)) {
9532         reginsert(pRExC_state, STAR, ret, depth+1);
9533         ret->flags = 0;
9534         RExC_naughty += 4;
9535     }
9536     else if (op == '*') {
9537         min = 0;
9538         goto do_curly;
9539     }
9540     else if (op == '+' && (flags&SIMPLE)) {
9541         reginsert(pRExC_state, PLUS, ret, depth+1);
9542         ret->flags = 0;
9543         RExC_naughty += 3;
9544     }
9545     else if (op == '+') {
9546         min = 1;
9547         goto do_curly;
9548     }
9549     else if (op == '?') {
9550         min = 0; max = 1;
9551         goto do_curly;
9552     }
9553   nest_check:
9554     if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
9555         SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
9556         ckWARN3reg(RExC_parse,
9557                    "%.*s matches null string many times",
9558                    (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
9559                    origparse);
9560         (void)ReREFCNT_inc(RExC_rx_sv);
9561     }
9562
9563     if (RExC_parse < RExC_end && *RExC_parse == '?') {
9564         nextchar(pRExC_state);
9565         reginsert(pRExC_state, MINMOD, ret, depth+1);
9566         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
9567     }
9568 #ifndef REG_ALLOW_MINMOD_SUSPEND
9569     else
9570 #endif
9571     if (RExC_parse < RExC_end && *RExC_parse == '+') {
9572         regnode *ender;
9573         nextchar(pRExC_state);
9574         ender = reg_node(pRExC_state, SUCCEED);
9575         REGTAIL(pRExC_state, ret, ender);
9576         reginsert(pRExC_state, SUSPEND, ret, depth+1);
9577         ret->flags = 0;
9578         ender = reg_node(pRExC_state, TAIL);
9579         REGTAIL(pRExC_state, ret, ender);
9580         /*ret= ender;*/
9581     }
9582
9583     if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
9584         RExC_parse++;
9585         vFAIL("Nested quantifiers");
9586     }
9587
9588     return(ret);
9589 }
9590
9591 STATIC bool
9592 S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state, regnode** node_p, UV *valuep, I32 *flagp, U32 depth, bool in_char_class)
9593 {
9594    
9595  /* This is expected to be called by a parser routine that has recognized '\N'
9596    and needs to handle the rest. RExC_parse is expected to point at the first
9597    char following the N at the time of the call.  On successful return,
9598    RExC_parse has been updated to point to just after the sequence identified
9599    by this routine, and <*flagp> has been updated.
9600
9601    The \N may be inside (indicated by the boolean <in_char_class>) or outside a
9602    character class.
9603
9604    \N may begin either a named sequence, or if outside a character class, mean
9605    to match a non-newline.  For non single-quoted regexes, the tokenizer has
9606    attempted to decide which, and in the case of a named sequence, converted it
9607    into one of the forms: \N{} (if the sequence is null), or \N{U+c1.c2...},
9608    where c1... are the characters in the sequence.  For single-quoted regexes,
9609    the tokenizer passes the \N sequence through unchanged; this code will not
9610    attempt to determine this nor expand those, instead raising a syntax error.
9611    The net effect is that if the beginning of the passed-in pattern isn't '{U+'
9612    or there is no '}', it signals that this \N occurrence means to match a
9613    non-newline.
9614
9615    Only the \N{U+...} form should occur in a character class, for the same
9616    reason that '.' inside a character class means to just match a period: it
9617    just doesn't make sense.
9618
9619    The function raises an error (via vFAIL), and doesn't return for various
9620    syntax errors.  Otherwise it returns TRUE and sets <node_p> or <valuep> on
9621    success; it returns FALSE otherwise.
9622
9623    If <valuep> is non-null, it means the caller can accept an input sequence
9624    consisting of a just a single code point; <*valuep> is set to that value
9625    if the input is such.
9626
9627    If <node_p> is non-null it signifies that the caller can accept any other
9628    legal sequence (i.e., one that isn't just a single code point).  <*node_p>
9629    is set as follows:
9630     1) \N means not-a-NL: points to a newly created REG_ANY node;
9631     2) \N{}:              points to a new NOTHING node;
9632     3) otherwise:         points to a new EXACT node containing the resolved
9633                           string.
9634    Note that FALSE is returned for single code point sequences if <valuep> is
9635    null.
9636  */
9637
9638     char * endbrace;    /* '}' following the name */
9639     char* p;
9640     char *endchar;      /* Points to '.' or '}' ending cur char in the input
9641                            stream */
9642     bool has_multiple_chars; /* true if the input stream contains a sequence of
9643                                 more than one character */
9644
9645     GET_RE_DEBUG_FLAGS_DECL;
9646  
9647     PERL_ARGS_ASSERT_GROK_BSLASH_N;
9648
9649     GET_RE_DEBUG_FLAGS;
9650
9651     assert(cBOOL(node_p) ^ cBOOL(valuep));  /* Exactly one should be set */
9652
9653     /* The [^\n] meaning of \N ignores spaces and comments under the /x
9654      * modifier.  The other meaning does not */
9655     p = (RExC_flags & RXf_PMf_EXTENDED)
9656         ? regwhite( pRExC_state, RExC_parse )
9657         : RExC_parse;
9658
9659     /* Disambiguate between \N meaning a named character versus \N meaning
9660      * [^\n].  The former is assumed when it can't be the latter. */
9661     if (*p != '{' || regcurly(p)) {
9662         RExC_parse = p;
9663         if (! node_p) {
9664             /* no bare \N in a charclass */
9665             if (in_char_class) {
9666                 vFAIL("\\N in a character class must be a named character: \\N{...}");
9667             }
9668             return FALSE;
9669         }
9670         nextchar(pRExC_state);
9671         *node_p = reg_node(pRExC_state, REG_ANY);
9672         *flagp |= HASWIDTH|SIMPLE;
9673         RExC_naughty++;
9674         RExC_parse--;
9675         Set_Node_Length(*node_p, 1); /* MJD */
9676         return TRUE;
9677     }
9678
9679     /* Here, we have decided it should be a named character or sequence */
9680
9681     /* The test above made sure that the next real character is a '{', but
9682      * under the /x modifier, it could be separated by space (or a comment and
9683      * \n) and this is not allowed (for consistency with \x{...} and the
9684      * tokenizer handling of \N{NAME}). */
9685     if (*RExC_parse != '{') {
9686         vFAIL("Missing braces on \\N{}");
9687     }
9688
9689     RExC_parse++;       /* Skip past the '{' */
9690
9691     if (! (endbrace = strchr(RExC_parse, '}')) /* no trailing brace */
9692         || ! (endbrace == RExC_parse            /* nothing between the {} */
9693               || (endbrace - RExC_parse >= 2    /* U+ (bad hex is checked below */
9694                   && strnEQ(RExC_parse, "U+", 2)))) /* for a better error msg) */
9695     {
9696         if (endbrace) RExC_parse = endbrace;    /* position msg's '<--HERE' */
9697         vFAIL("\\N{NAME} must be resolved by the lexer");
9698     }
9699
9700     if (endbrace == RExC_parse) {   /* empty: \N{} */
9701         bool ret = TRUE;
9702         if (node_p) {
9703             *node_p = reg_node(pRExC_state,NOTHING);
9704         }
9705         else if (in_char_class) {
9706             if (SIZE_ONLY && in_char_class) {
9707                 ckWARNreg(RExC_parse,
9708                         "Ignoring zero length \\N{} in character class"
9709                 );
9710             }
9711             ret = FALSE;
9712         }
9713         else {
9714             return FALSE;
9715         }
9716         nextchar(pRExC_state);
9717         return ret;
9718     }
9719
9720     RExC_uni_semantics = 1; /* Unicode named chars imply Unicode semantics */
9721     RExC_parse += 2;    /* Skip past the 'U+' */
9722
9723     endchar = RExC_parse + strcspn(RExC_parse, ".}");
9724
9725     /* Code points are separated by dots.  If none, there is only one code
9726      * point, and is terminated by the brace */
9727     has_multiple_chars = (endchar < endbrace);
9728
9729     if (valuep && (! has_multiple_chars || in_char_class)) {
9730         /* We only pay attention to the first char of
9731         multichar strings being returned in char classes. I kinda wonder
9732         if this makes sense as it does change the behaviour
9733         from earlier versions, OTOH that behaviour was broken
9734         as well. XXX Solution is to recharacterize as
9735         [rest-of-class]|multi1|multi2... */
9736
9737         STRLEN length_of_hex = (STRLEN)(endchar - RExC_parse);
9738         I32 grok_hex_flags = PERL_SCAN_ALLOW_UNDERSCORES
9739             | PERL_SCAN_DISALLOW_PREFIX
9740             | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
9741
9742         *valuep = grok_hex(RExC_parse, &length_of_hex, &grok_hex_flags, NULL);
9743
9744         /* The tokenizer should have guaranteed validity, but it's possible to
9745          * bypass it by using single quoting, so check */
9746         if (length_of_hex == 0
9747             || length_of_hex != (STRLEN)(endchar - RExC_parse) )
9748         {
9749             RExC_parse += length_of_hex;        /* Includes all the valid */
9750             RExC_parse += (RExC_orig_utf8)      /* point to after 1st invalid */
9751                             ? UTF8SKIP(RExC_parse)
9752                             : 1;
9753             /* Guard against malformed utf8 */
9754             if (RExC_parse >= endchar) {
9755                 RExC_parse = endchar;
9756             }
9757             vFAIL("Invalid hexadecimal number in \\N{U+...}");
9758         }
9759
9760         if (in_char_class && has_multiple_chars) {
9761             ckWARNreg(endchar, "Using just the first character returned by \\N{} in character class");
9762         }
9763
9764         RExC_parse = endbrace + 1;
9765     }
9766     else if (! node_p || ! has_multiple_chars) {
9767
9768         /* Here, the input is legal, but not according to the caller's
9769          * options.  We fail without advancing the parse, so that the
9770          * caller can try again */
9771         RExC_parse = p;
9772         return FALSE;
9773     }
9774     else {
9775
9776         /* What is done here is to convert this to a sub-pattern of the form
9777          * (?:\x{char1}\x{char2}...)
9778          * and then call reg recursively.  That way, it retains its atomicness,
9779          * while not having to worry about special handling that some code
9780          * points may have.  toke.c has converted the original Unicode values
9781          * to native, so that we can just pass on the hex values unchanged.  We
9782          * do have to set a flag to keep recoding from happening in the
9783          * recursion */
9784
9785         SV * substitute_parse = newSVpvn_flags("?:", 2, SVf_UTF8|SVs_TEMP);
9786         STRLEN len;
9787         char *orig_end = RExC_end;
9788         I32 flags;
9789
9790         while (RExC_parse < endbrace) {
9791
9792             /* Convert to notation the rest of the code understands */
9793             sv_catpv(substitute_parse, "\\x{");
9794             sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse);
9795             sv_catpv(substitute_parse, "}");
9796
9797             /* Point to the beginning of the next character in the sequence. */
9798             RExC_parse = endchar + 1;
9799             endchar = RExC_parse + strcspn(RExC_parse, ".}");
9800         }
9801         sv_catpv(substitute_parse, ")");
9802
9803         RExC_parse = SvPV(substitute_parse, len);
9804
9805         /* Don't allow empty number */
9806         if (len < 8) {
9807             vFAIL("Invalid hexadecimal number in \\N{U+...}");
9808         }
9809         RExC_end = RExC_parse + len;
9810
9811         /* The values are Unicode, and therefore not subject to recoding */
9812         RExC_override_recoding = 1;
9813
9814         *node_p = reg(pRExC_state, 1, &flags, depth+1);
9815         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
9816
9817         RExC_parse = endbrace;
9818         RExC_end = orig_end;
9819         RExC_override_recoding = 0;
9820
9821         nextchar(pRExC_state);
9822     }
9823
9824     return TRUE;
9825 }
9826
9827
9828 /*
9829  * reg_recode
9830  *
9831  * It returns the code point in utf8 for the value in *encp.
9832  *    value: a code value in the source encoding
9833  *    encp:  a pointer to an Encode object
9834  *
9835  * If the result from Encode is not a single character,
9836  * it returns U+FFFD (Replacement character) and sets *encp to NULL.
9837  */
9838 STATIC UV
9839 S_reg_recode(pTHX_ const char value, SV **encp)
9840 {
9841     STRLEN numlen = 1;
9842     SV * const sv = newSVpvn_flags(&value, numlen, SVs_TEMP);
9843     const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
9844     const STRLEN newlen = SvCUR(sv);
9845     UV uv = UNICODE_REPLACEMENT;
9846
9847     PERL_ARGS_ASSERT_REG_RECODE;
9848
9849     if (newlen)
9850         uv = SvUTF8(sv)
9851              ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
9852              : *(U8*)s;
9853
9854     if (!newlen || numlen != newlen) {
9855         uv = UNICODE_REPLACEMENT;
9856         *encp = NULL;
9857     }
9858     return uv;
9859 }
9860
9861 PERL_STATIC_INLINE U8
9862 S_compute_EXACTish(pTHX_ RExC_state_t *pRExC_state)
9863 {
9864     U8 op;
9865
9866     PERL_ARGS_ASSERT_COMPUTE_EXACTISH;
9867
9868     if (! FOLD) {
9869         return EXACT;
9870     }
9871
9872     op = get_regex_charset(RExC_flags);
9873     if (op >= REGEX_ASCII_RESTRICTED_CHARSET) {
9874         op--; /* /a is same as /u, and map /aa's offset to what /a's would have
9875                  been, so there is no hole */
9876     }
9877
9878     return op + EXACTF;
9879 }
9880
9881 PERL_STATIC_INLINE void
9882 S_alloc_maybe_populate_EXACT(pTHX_ RExC_state_t *pRExC_state, regnode *node, I32* flagp, STRLEN len, UV code_point)
9883 {
9884     /* This knows the details about sizing an EXACTish node, setting flags for
9885      * it (by setting <*flagp>, and potentially populating it with a single
9886      * character.
9887      *
9888      * If <len> (the length in bytes) is non-zero, this function assumes that
9889      * the node has already been populated, and just does the sizing.  In this
9890      * case <code_point> should be the final code point that has already been
9891      * placed into the node.  This value will be ignored except that under some
9892      * circumstances <*flagp> is set based on it.
9893      *
9894      * If <len> is zero, the function assumes that the node is to contain only
9895      * the single character given by <code_point> and calculates what <len>
9896      * should be.  In pass 1, it sizes the node appropriately.  In pass 2, it
9897      * additionally will populate the node's STRING with <code_point>, if <len>
9898      * is 0.  In both cases <*flagp> is appropriately set
9899      *
9900      * It knows that under FOLD, UTF characters and the Latin Sharp S must be
9901      * folded (the latter only when the rules indicate it can match 'ss') */
9902
9903     bool len_passed_in = cBOOL(len != 0);
9904     U8 character[UTF8_MAXBYTES_CASE+1];
9905
9906     PERL_ARGS_ASSERT_ALLOC_MAYBE_POPULATE_EXACT;
9907
9908     if (! len_passed_in) {
9909         if (UTF) {
9910             if (FOLD) {
9911                 to_uni_fold(NATIVE_TO_UNI(code_point), character, &len);
9912             }
9913             else {
9914                 uvchr_to_utf8( character, code_point);
9915                 len = UTF8SKIP(character);
9916             }
9917         }
9918         else if (! FOLD
9919                  || code_point != LATIN_SMALL_LETTER_SHARP_S
9920                  || ASCII_FOLD_RESTRICTED
9921                  || ! AT_LEAST_UNI_SEMANTICS)
9922         {
9923             *character = (U8) code_point;
9924             len = 1;
9925         }
9926         else {
9927             *character = 's';
9928             *(character + 1) = 's';
9929             len = 2;
9930         }
9931     }
9932
9933     if (SIZE_ONLY) {
9934         RExC_size += STR_SZ(len);
9935     }
9936     else {
9937         RExC_emit += STR_SZ(len);
9938         STR_LEN(node) = len;
9939         if (! len_passed_in) {
9940             Copy((char *) character, STRING(node), len, char);
9941         }
9942     }
9943
9944     *flagp |= HASWIDTH;
9945
9946     /* A single character node is SIMPLE, except for the special-cased SHARP S
9947      * under /di. */
9948     if ((len == 1 || (UTF && len == UNISKIP(code_point)))
9949         && (code_point != LATIN_SMALL_LETTER_SHARP_S
9950             || ! FOLD || ! DEPENDS_SEMANTICS))
9951     {
9952         *flagp |= SIMPLE;
9953     }
9954 }
9955
9956 /*
9957  - regatom - the lowest level
9958
9959    Try to identify anything special at the start of the pattern. If there
9960    is, then handle it as required. This may involve generating a single regop,
9961    such as for an assertion; or it may involve recursing, such as to
9962    handle a () structure.
9963
9964    If the string doesn't start with something special then we gobble up
9965    as much literal text as we can.
9966
9967    Once we have been able to handle whatever type of thing started the
9968    sequence, we return.
9969
9970    Note: we have to be careful with escapes, as they can be both literal
9971    and special, and in the case of \10 and friends, context determines which.
9972
9973    A summary of the code structure is:
9974
9975    switch (first_byte) {
9976         cases for each special:
9977             handle this special;
9978             break;
9979         case '\\':
9980             switch (2nd byte) {
9981                 cases for each unambiguous special:
9982                     handle this special;
9983                     break;
9984                 cases for each ambigous special/literal:
9985                     disambiguate;
9986                     if (special)  handle here
9987                     else goto defchar;
9988                 default: // unambiguously literal:
9989                     goto defchar;
9990             }
9991         default:  // is a literal char
9992             // FALL THROUGH
9993         defchar:
9994             create EXACTish node for literal;
9995             while (more input and node isn't full) {
9996                 switch (input_byte) {
9997                    cases for each special;
9998                        make sure parse pointer is set so that the next call to
9999                            regatom will see this special first
10000                        goto loopdone; // EXACTish node terminated by prev. char
10001                    default:
10002                        append char to EXACTISH node;
10003                 }
10004                 get next input byte;
10005             }
10006         loopdone:
10007    }
10008    return the generated node;
10009
10010    Specifically there are two separate switches for handling
10011    escape sequences, with the one for handling literal escapes requiring
10012    a dummy entry for all of the special escapes that are actually handled
10013    by the other.
10014 */
10015
10016 STATIC regnode *
10017 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
10018 {
10019     dVAR;
10020     regnode *ret = NULL;
10021     I32 flags;
10022     char *parse_start = RExC_parse;
10023     U8 op;
10024     int invert = 0;
10025
10026     GET_RE_DEBUG_FLAGS_DECL;
10027
10028     *flagp = WORST;             /* Tentatively. */
10029
10030     DEBUG_PARSE("atom");
10031
10032     PERL_ARGS_ASSERT_REGATOM;
10033
10034 tryagain:
10035     switch ((U8)*RExC_parse) {
10036     case '^':
10037         RExC_seen_zerolen++;
10038         nextchar(pRExC_state);
10039         if (RExC_flags & RXf_PMf_MULTILINE)
10040             ret = reg_node(pRExC_state, MBOL);
10041         else if (RExC_flags & RXf_PMf_SINGLELINE)
10042             ret = reg_node(pRExC_state, SBOL);
10043         else
10044             ret = reg_node(pRExC_state, BOL);
10045         Set_Node_Length(ret, 1); /* MJD */
10046         break;
10047     case '$':
10048         nextchar(pRExC_state);
10049         if (*RExC_parse)
10050             RExC_seen_zerolen++;
10051         if (RExC_flags & RXf_PMf_MULTILINE)
10052             ret = reg_node(pRExC_state, MEOL);
10053         else if (RExC_flags & RXf_PMf_SINGLELINE)
10054             ret = reg_node(pRExC_state, SEOL);
10055         else
10056             ret = reg_node(pRExC_state, EOL);
10057         Set_Node_Length(ret, 1); /* MJD */
10058         break;
10059     case '.':
10060         nextchar(pRExC_state);
10061         if (RExC_flags & RXf_PMf_SINGLELINE)
10062             ret = reg_node(pRExC_state, SANY);
10063         else
10064             ret = reg_node(pRExC_state, REG_ANY);
10065         *flagp |= HASWIDTH|SIMPLE;
10066         RExC_naughty++;
10067         Set_Node_Length(ret, 1); /* MJD */
10068         break;
10069     case '[':
10070     {
10071         char * const oregcomp_parse = ++RExC_parse;
10072         ret = regclass(pRExC_state, flagp,depth+1);
10073         if (*RExC_parse != ']') {
10074             RExC_parse = oregcomp_parse;
10075             vFAIL("Unmatched [");
10076         }
10077         nextchar(pRExC_state);
10078         Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
10079         break;
10080     }
10081     case '(':
10082         nextchar(pRExC_state);
10083         ret = reg(pRExC_state, 1, &flags,depth+1);
10084         if (ret == NULL) {
10085                 if (flags & TRYAGAIN) {
10086                     if (RExC_parse == RExC_end) {
10087                          /* Make parent create an empty node if needed. */
10088                         *flagp |= TRYAGAIN;
10089                         return(NULL);
10090                     }
10091                     goto tryagain;
10092                 }
10093                 return(NULL);
10094         }
10095         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
10096         break;
10097     case '|':
10098     case ')':
10099         if (flags & TRYAGAIN) {
10100             *flagp |= TRYAGAIN;
10101             return NULL;
10102         }
10103         vFAIL("Internal urp");
10104                                 /* Supposed to be caught earlier. */
10105         break;
10106     case '?':
10107     case '+':
10108     case '*':
10109         RExC_parse++;
10110         vFAIL("Quantifier follows nothing");
10111         break;
10112     case '\\':
10113         /* Special Escapes
10114
10115            This switch handles escape sequences that resolve to some kind
10116            of special regop and not to literal text. Escape sequnces that
10117            resolve to literal text are handled below in the switch marked
10118            "Literal Escapes".
10119
10120            Every entry in this switch *must* have a corresponding entry
10121            in the literal escape switch. However, the opposite is not
10122            required, as the default for this switch is to jump to the
10123            literal text handling code.
10124         */
10125         switch ((U8)*++RExC_parse) {
10126             U8 arg;
10127         /* Special Escapes */
10128         case 'A':
10129             RExC_seen_zerolen++;
10130             ret = reg_node(pRExC_state, SBOL);
10131             *flagp |= SIMPLE;
10132             goto finish_meta_pat;
10133         case 'G':
10134             ret = reg_node(pRExC_state, GPOS);
10135             RExC_seen |= REG_SEEN_GPOS;
10136             *flagp |= SIMPLE;
10137             goto finish_meta_pat;
10138         case 'K':
10139             RExC_seen_zerolen++;
10140             ret = reg_node(pRExC_state, KEEPS);
10141             *flagp |= SIMPLE;
10142             /* XXX:dmq : disabling in-place substitution seems to
10143              * be necessary here to avoid cases of memory corruption, as
10144              * with: C<$_="x" x 80; s/x\K/y/> -- rgs
10145              */
10146             RExC_seen |= REG_SEEN_LOOKBEHIND;
10147             goto finish_meta_pat;
10148         case 'Z':
10149             ret = reg_node(pRExC_state, SEOL);
10150             *flagp |= SIMPLE;
10151             RExC_seen_zerolen++;                /* Do not optimize RE away */
10152             goto finish_meta_pat;
10153         case 'z':
10154             ret = reg_node(pRExC_state, EOS);
10155             *flagp |= SIMPLE;
10156             RExC_seen_zerolen++;                /* Do not optimize RE away */
10157             goto finish_meta_pat;
10158         case 'C':
10159             ret = reg_node(pRExC_state, CANY);
10160             RExC_seen |= REG_SEEN_CANY;
10161             *flagp |= HASWIDTH|SIMPLE;
10162             goto finish_meta_pat;
10163         case 'X':
10164             ret = reg_node(pRExC_state, CLUMP);
10165             *flagp |= HASWIDTH;
10166             goto finish_meta_pat;
10167
10168         case 'W':
10169             invert = 1;
10170             /* FALLTHROUGH */
10171         case 'w':
10172             arg = ANYOF_WORDCHAR;
10173             goto join_posix;
10174
10175         case 'b':
10176             RExC_seen_zerolen++;
10177             RExC_seen |= REG_SEEN_LOOKBEHIND;
10178             op = BOUND + get_regex_charset(RExC_flags);
10179             if (op > BOUNDA) {  /* /aa is same as /a */
10180                 op = BOUNDA;
10181             }
10182             ret = reg_node(pRExC_state, op);
10183             FLAGS(ret) = get_regex_charset(RExC_flags);
10184             *flagp |= SIMPLE;
10185             goto finish_meta_pat;
10186         case 'B':
10187             RExC_seen_zerolen++;
10188             RExC_seen |= REG_SEEN_LOOKBEHIND;
10189             op = NBOUND + get_regex_charset(RExC_flags);
10190             if (op > NBOUNDA) { /* /aa is same as /a */
10191                 op = NBOUNDA;
10192             }
10193             ret = reg_node(pRExC_state, op);
10194             FLAGS(ret) = get_regex_charset(RExC_flags);
10195             *flagp |= SIMPLE;
10196             goto finish_meta_pat;
10197
10198         case 'D':
10199             invert = 1;
10200             /* FALLTHROUGH */
10201         case 'd':
10202             arg = ANYOF_DIGIT;
10203             goto join_posix;
10204
10205         case 'R':
10206             ret = reg_node(pRExC_state, LNBREAK);
10207             *flagp |= HASWIDTH|SIMPLE;
10208             goto finish_meta_pat;
10209
10210         case 'H':
10211             invert = 1;
10212             /* FALLTHROUGH */
10213         case 'h':
10214             arg = ANYOF_BLANK;
10215             op = POSIXU;
10216             goto join_posix_op_known;
10217
10218         case 'V':
10219             invert = 1;
10220             /* FALLTHROUGH */
10221         case 'v':
10222             arg = ANYOF_VERTWS;
10223             op = POSIXU;
10224             goto join_posix_op_known;
10225
10226         case 'S':
10227             invert = 1;
10228             /* FALLTHROUGH */
10229         case 's':
10230             arg = ANYOF_SPACE;
10231
10232         join_posix:
10233
10234             op = POSIXD + get_regex_charset(RExC_flags);
10235             if (op > POSIXA) {  /* /aa is same as /a */
10236                 op = POSIXA;
10237             }
10238
10239         join_posix_op_known:
10240
10241             if (invert) {
10242                 op += NPOSIXD - POSIXD;
10243             }
10244
10245             ret = reg_node(pRExC_state, op);
10246             if (! SIZE_ONLY) {
10247                 FLAGS(ret) = namedclass_to_classnum(arg);
10248             }
10249
10250             *flagp |= HASWIDTH|SIMPLE;
10251             /* FALL THROUGH */
10252
10253          finish_meta_pat:           
10254             nextchar(pRExC_state);
10255             Set_Node_Length(ret, 2); /* MJD */
10256             break;          
10257         case 'p':
10258         case 'P':
10259             {
10260                 char* const oldregxend = RExC_end;
10261 #ifdef DEBUGGING
10262                 char* parse_start = RExC_parse - 2;
10263 #endif
10264
10265                 if (RExC_parse[1] == '{') {
10266                   /* a lovely hack--pretend we saw [\pX] instead */
10267                     RExC_end = strchr(RExC_parse, '}');
10268                     if (!RExC_end) {
10269                         const U8 c = (U8)*RExC_parse;
10270                         RExC_parse += 2;
10271                         RExC_end = oldregxend;
10272                         vFAIL2("Missing right brace on \\%c{}", c);
10273                     }
10274                     RExC_end++;
10275                 }
10276                 else {
10277                     RExC_end = RExC_parse + 2;
10278                     if (RExC_end > oldregxend)
10279                         RExC_end = oldregxend;
10280                 }
10281                 RExC_parse--;
10282
10283                 ret = regclass(pRExC_state, flagp,depth+1);
10284
10285                 RExC_end = oldregxend;
10286                 RExC_parse--;
10287
10288                 Set_Node_Offset(ret, parse_start + 2);
10289                 Set_Node_Cur_Length(ret);
10290                 nextchar(pRExC_state);
10291             }
10292             break;
10293         case 'N': 
10294             /* Handle \N and \N{NAME} with multiple code points here and not
10295              * below because it can be multicharacter. join_exact() will join
10296              * them up later on.  Also this makes sure that things like
10297              * /\N{BLAH}+/ and \N{BLAH} being multi char Just Happen. dmq.
10298              * The options to the grok function call causes it to fail if the
10299              * sequence is just a single code point.  We then go treat it as
10300              * just another character in the current EXACT node, and hence it
10301              * gets uniform treatment with all the other characters.  The
10302              * special treatment for quantifiers is not needed for such single
10303              * character sequences */
10304             ++RExC_parse;
10305             if (! grok_bslash_N(pRExC_state, &ret, NULL, flagp, depth, FALSE)) {
10306                 RExC_parse--;
10307                 goto defchar;
10308             }
10309             break;
10310         case 'k':    /* Handle \k<NAME> and \k'NAME' */
10311         parse_named_seq:
10312         {   
10313             char ch= RExC_parse[1];         
10314             if (ch != '<' && ch != '\'' && ch != '{') {
10315                 RExC_parse++;
10316                 vFAIL2("Sequence %.2s... not terminated",parse_start);
10317             } else {
10318                 /* this pretty much dupes the code for (?P=...) in reg(), if
10319                    you change this make sure you change that */
10320                 char* name_start = (RExC_parse += 2);
10321                 U32 num = 0;
10322                 SV *sv_dat = reg_scan_name(pRExC_state,
10323                     SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
10324                 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
10325                 if (RExC_parse == name_start || *RExC_parse != ch)
10326                     vFAIL2("Sequence %.3s... not terminated",parse_start);
10327
10328                 if (!SIZE_ONLY) {
10329                     num = add_data( pRExC_state, 1, "S" );
10330                     RExC_rxi->data->data[num]=(void*)sv_dat;
10331                     SvREFCNT_inc_simple_void(sv_dat);
10332                 }
10333
10334                 RExC_sawback = 1;
10335                 ret = reganode(pRExC_state,
10336                                ((! FOLD)
10337                                  ? NREF
10338                                  : (ASCII_FOLD_RESTRICTED)
10339                                    ? NREFFA
10340                                    : (AT_LEAST_UNI_SEMANTICS)
10341                                      ? NREFFU
10342                                      : (LOC)
10343                                        ? NREFFL
10344                                        : NREFF),
10345                                 num);
10346                 *flagp |= HASWIDTH;
10347
10348                 /* override incorrect value set in reganode MJD */
10349                 Set_Node_Offset(ret, parse_start+1);
10350                 Set_Node_Cur_Length(ret); /* MJD */
10351                 nextchar(pRExC_state);
10352
10353             }
10354             break;
10355         }
10356         case 'g': 
10357         case '1': case '2': case '3': case '4':
10358         case '5': case '6': case '7': case '8': case '9':
10359             {
10360                 I32 num;
10361                 bool isg = *RExC_parse == 'g';
10362                 bool isrel = 0; 
10363                 bool hasbrace = 0;
10364                 if (isg) {
10365                     RExC_parse++;
10366                     if (*RExC_parse == '{') {
10367                         RExC_parse++;
10368                         hasbrace = 1;
10369                     }
10370                     if (*RExC_parse == '-') {
10371                         RExC_parse++;
10372                         isrel = 1;
10373                     }
10374                     if (hasbrace && !isDIGIT(*RExC_parse)) {
10375                         if (isrel) RExC_parse--;
10376                         RExC_parse -= 2;                            
10377                         goto parse_named_seq;
10378                 }   }
10379                 num = atoi(RExC_parse);
10380                 if (isg && num == 0)
10381                     vFAIL("Reference to invalid group 0");
10382                 if (isrel) {
10383                     num = RExC_npar - num;
10384                     if (num < 1)
10385                         vFAIL("Reference to nonexistent or unclosed group");
10386                 }
10387                 if (!isg && num > 9 && num >= RExC_npar)
10388                     /* Probably a character specified in octal, e.g. \35 */
10389                     goto defchar;
10390                 else {
10391                     char * const parse_start = RExC_parse - 1; /* MJD */
10392                     while (isDIGIT(*RExC_parse))
10393                         RExC_parse++;
10394                     if (parse_start == RExC_parse - 1) 
10395                         vFAIL("Unterminated \\g... pattern");
10396                     if (hasbrace) {
10397                         if (*RExC_parse != '}') 
10398                             vFAIL("Unterminated \\g{...} pattern");
10399                         RExC_parse++;
10400                     }    
10401                     if (!SIZE_ONLY) {
10402                         if (num > (I32)RExC_rx->nparens)
10403                             vFAIL("Reference to nonexistent group");
10404                     }
10405                     RExC_sawback = 1;
10406                     ret = reganode(pRExC_state,
10407                                    ((! FOLD)
10408                                      ? REF
10409                                      : (ASCII_FOLD_RESTRICTED)
10410                                        ? REFFA
10411                                        : (AT_LEAST_UNI_SEMANTICS)
10412                                          ? REFFU
10413                                          : (LOC)
10414                                            ? REFFL
10415                                            : REFF),
10416                                     num);
10417                     *flagp |= HASWIDTH;
10418
10419                     /* override incorrect value set in reganode MJD */
10420                     Set_Node_Offset(ret, parse_start+1);
10421                     Set_Node_Cur_Length(ret); /* MJD */
10422                     RExC_parse--;
10423                     nextchar(pRExC_state);
10424                 }
10425             }
10426             break;
10427         case '\0':
10428             if (RExC_parse >= RExC_end)
10429                 FAIL("Trailing \\");
10430             /* FALL THROUGH */
10431         default:
10432             /* Do not generate "unrecognized" warnings here, we fall
10433                back into the quick-grab loop below */
10434             parse_start--;
10435             goto defchar;
10436         }
10437         break;
10438
10439     case '#':
10440         if (RExC_flags & RXf_PMf_EXTENDED) {
10441             if ( reg_skipcomment( pRExC_state ) )
10442                 goto tryagain;
10443         }
10444         /* FALL THROUGH */
10445
10446     default:
10447
10448             parse_start = RExC_parse - 1;
10449
10450             RExC_parse++;
10451
10452         defchar: {
10453             STRLEN len = 0;
10454             UV ender;
10455             char *p;
10456             char *s;
10457 #define MAX_NODE_STRING_SIZE 127
10458             char foldbuf[MAX_NODE_STRING_SIZE+UTF8_MAXBYTES_CASE];
10459             char *s0;
10460             U8 upper_parse = MAX_NODE_STRING_SIZE;
10461             STRLEN foldlen;
10462             U8 node_type;
10463             bool next_is_quantifier;
10464             char * oldp = NULL;
10465
10466             /* If a folding node contains only code points that don't
10467              * participate in folds, it can be changed into an EXACT node,
10468              * which allows the optimizer more things to look for */
10469             bool maybe_exact;
10470
10471             ender = 0;
10472             node_type = compute_EXACTish(pRExC_state);
10473             ret = reg_node(pRExC_state, node_type);
10474
10475             /* In pass1, folded, we use a temporary buffer instead of the
10476              * actual node, as the node doesn't exist yet */
10477             s = (SIZE_ONLY && FOLD) ? foldbuf : STRING(ret);
10478
10479             s0 = s;
10480
10481         reparse:
10482
10483             /* We do the EXACTFish to EXACT node only if folding, and not if in
10484              * locale, as whether a character folds or not isn't known until
10485              * runtime */
10486             maybe_exact = FOLD && ! LOC;
10487
10488             /* XXX The node can hold up to 255 bytes, yet this only goes to
10489              * 127.  I (khw) do not know why.  Keeping it somewhat less than
10490              * 255 allows us to not have to worry about overflow due to
10491              * converting to utf8 and fold expansion, but that value is
10492              * 255-UTF8_MAXBYTES_CASE.  join_exact() may join adjacent nodes
10493              * split up by this limit into a single one using the real max of
10494              * 255.  Even at 127, this breaks under rare circumstances.  If
10495              * folding, we do not want to split a node at a character that is a
10496              * non-final in a multi-char fold, as an input string could just
10497              * happen to want to match across the node boundary.  The join
10498              * would solve that problem if the join actually happens.  But a
10499              * series of more than two nodes in a row each of 127 would cause
10500              * the first join to succeed to get to 254, but then there wouldn't
10501              * be room for the next one, which could at be one of those split
10502              * multi-char folds.  I don't know of any fool-proof solution.  One
10503              * could back off to end with only a code point that isn't such a
10504              * non-final, but it is possible for there not to be any in the
10505              * entire node. */
10506             for (p = RExC_parse - 1;
10507                  len < upper_parse && p < RExC_end;
10508                  len++)
10509             {
10510                 oldp = p;
10511
10512                 if (RExC_flags & RXf_PMf_EXTENDED)
10513                     p = regwhite( pRExC_state, p );
10514                 switch ((U8)*p) {
10515                 case '^':
10516                 case '$':
10517                 case '.':
10518                 case '[':
10519                 case '(':
10520                 case ')':
10521                 case '|':
10522                     goto loopdone;
10523                 case '\\':
10524                     /* Literal Escapes Switch
10525
10526                        This switch is meant to handle escape sequences that
10527                        resolve to a literal character.
10528
10529                        Every escape sequence that represents something
10530                        else, like an assertion or a char class, is handled
10531                        in the switch marked 'Special Escapes' above in this
10532                        routine, but also has an entry here as anything that
10533                        isn't explicitly mentioned here will be treated as
10534                        an unescaped equivalent literal.
10535                     */
10536
10537                     switch ((U8)*++p) {
10538                     /* These are all the special escapes. */
10539                     case 'A':             /* Start assertion */
10540                     case 'b': case 'B':   /* Word-boundary assertion*/
10541                     case 'C':             /* Single char !DANGEROUS! */
10542                     case 'd': case 'D':   /* digit class */
10543                     case 'g': case 'G':   /* generic-backref, pos assertion */
10544                     case 'h': case 'H':   /* HORIZWS */
10545                     case 'k': case 'K':   /* named backref, keep marker */
10546                     case 'p': case 'P':   /* Unicode property */
10547                               case 'R':   /* LNBREAK */
10548                     case 's': case 'S':   /* space class */
10549                     case 'v': case 'V':   /* VERTWS */
10550                     case 'w': case 'W':   /* word class */
10551                     case 'X':             /* eXtended Unicode "combining character sequence" */
10552                     case 'z': case 'Z':   /* End of line/string assertion */
10553                         --p;
10554                         goto loopdone;
10555
10556                     /* Anything after here is an escape that resolves to a
10557                        literal. (Except digits, which may or may not)
10558                      */
10559                     case 'n':
10560                         ender = '\n';
10561                         p++;
10562                         break;
10563                     case 'N': /* Handle a single-code point named character. */
10564                         /* The options cause it to fail if a multiple code
10565                          * point sequence.  Handle those in the switch() above
10566                          * */
10567                         RExC_parse = p + 1;
10568                         if (! grok_bslash_N(pRExC_state, NULL, &ender,
10569                                             flagp, depth, FALSE))
10570                         {
10571                             RExC_parse = p = oldp;
10572                             goto loopdone;
10573                         }
10574                         p = RExC_parse;
10575                         if (ender > 0xff) {
10576                             REQUIRE_UTF8;
10577                         }
10578                         break;
10579                     case 'r':
10580                         ender = '\r';
10581                         p++;
10582                         break;
10583                     case 't':
10584                         ender = '\t';
10585                         p++;
10586                         break;
10587                     case 'f':
10588                         ender = '\f';
10589                         p++;
10590                         break;
10591                     case 'e':
10592                           ender = ASCII_TO_NATIVE('\033');
10593                         p++;
10594                         break;
10595                     case 'a':
10596                           ender = ASCII_TO_NATIVE('\007');
10597                         p++;
10598                         break;
10599                     case 'o':
10600                         {
10601                             STRLEN brace_len = len;
10602                             UV result;
10603                             const char* error_msg;
10604
10605                             bool valid = grok_bslash_o(p,
10606                                                        &result,
10607                                                        &brace_len,
10608                                                        &error_msg,
10609                                                        1);
10610                             p += brace_len;
10611                             if (! valid) {
10612                                 RExC_parse = p; /* going to die anyway; point
10613                                                    to exact spot of failure */
10614                                 vFAIL(error_msg);
10615                             }
10616                             else
10617                             {
10618                                 ender = result;
10619                             }
10620                             if (PL_encoding && ender < 0x100) {
10621                                 goto recode_encoding;
10622                             }
10623                             if (ender > 0xff) {
10624                                 REQUIRE_UTF8;
10625                             }
10626                             break;
10627                         }
10628                     case 'x':
10629                         {
10630                             STRLEN brace_len = len;
10631                             UV result;
10632                             const char* error_msg;
10633
10634                             bool valid = grok_bslash_x(p,
10635                                                        &result,
10636                                                        &brace_len,
10637                                                        &error_msg,
10638                                                        1);
10639                             p += brace_len;
10640                             if (! valid) {
10641                                 RExC_parse = p; /* going to die anyway; point
10642                                                    to exact spot of failure */
10643                                 vFAIL(error_msg);
10644                             }
10645                             else {
10646                                 ender = result;
10647                             }
10648                             if (PL_encoding && ender < 0x100) {
10649                                 goto recode_encoding;
10650                             }
10651                             if (ender > 0xff) {
10652                                 REQUIRE_UTF8;
10653                             }
10654                             break;
10655                         }
10656                     case 'c':
10657                         p++;
10658                         ender = grok_bslash_c(*p++, UTF, SIZE_ONLY);
10659                         break;
10660                     case '0': case '1': case '2': case '3':case '4':
10661                     case '5': case '6': case '7':
10662                         if (*p == '0' ||
10663                             (isDIGIT(p[1]) && atoi(p) >= RExC_npar))
10664                         {
10665                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
10666                             STRLEN numlen = 3;
10667                             ender = grok_oct(p, &numlen, &flags, NULL);
10668                             if (ender > 0xff) {
10669                                 REQUIRE_UTF8;
10670                             }
10671                             p += numlen;
10672                         }
10673                         else {
10674                             --p;
10675                             goto loopdone;
10676                         }
10677                         if (PL_encoding && ender < 0x100)
10678                             goto recode_encoding;
10679                         break;
10680                     recode_encoding:
10681                         if (! RExC_override_recoding) {
10682                             SV* enc = PL_encoding;
10683                             ender = reg_recode((const char)(U8)ender, &enc);
10684                             if (!enc && SIZE_ONLY)
10685                                 ckWARNreg(p, "Invalid escape in the specified encoding");
10686                             REQUIRE_UTF8;
10687                         }
10688                         break;
10689                     case '\0':
10690                         if (p >= RExC_end)
10691                             FAIL("Trailing \\");
10692                         /* FALL THROUGH */
10693                     default:
10694                         if (!SIZE_ONLY&& isALPHANUMERIC(*p)) {
10695                             ckWARN2reg(p + 1, "Unrecognized escape \\%.1s passed through", p);
10696                         }
10697                         goto normal_default;
10698                     }
10699                     break;
10700                 case '{':
10701                     /* Currently we don't warn when the lbrace is at the start
10702                      * of a construct.  This catches it in the middle of a
10703                      * literal string, or when its the first thing after
10704                      * something like "\b" */
10705                     if (! SIZE_ONLY
10706                         && (len || (p > RExC_start && isALPHA_A(*(p -1)))))
10707                     {
10708                         ckWARNregdep(p + 1, "Unescaped left brace in regex is deprecated, passed through");
10709                     }
10710                     /*FALLTHROUGH*/
10711                 default:
10712                   normal_default:
10713                     if (UTF8_IS_START(*p) && UTF) {
10714                         STRLEN numlen;
10715                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
10716                                                &numlen, UTF8_ALLOW_DEFAULT);
10717                         p += numlen;
10718                     }
10719                     else
10720                         ender = (U8) *p++;
10721                     break;
10722                 } /* End of switch on the literal */
10723
10724                 /* Here, have looked at the literal character and <ender>
10725                  * contains its ordinal, <p> points to the character after it
10726                  */
10727
10728                 if ( RExC_flags & RXf_PMf_EXTENDED)
10729                     p = regwhite( pRExC_state, p );
10730
10731                 /* If the next thing is a quantifier, it applies to this
10732                  * character only, which means that this character has to be in
10733                  * its own node and can't just be appended to the string in an
10734                  * existing node, so if there are already other characters in
10735                  * the node, close the node with just them, and set up to do
10736                  * this character again next time through, when it will be the
10737                  * only thing in its new node */
10738                 if ((next_is_quantifier = (p < RExC_end && ISMULT2(p))) && len)
10739                 {
10740                     p = oldp;
10741                     goto loopdone;
10742                 }
10743
10744                 if (FOLD) {
10745                     if (UTF
10746                             /* See comments for join_exact() as to why we fold
10747                              * this non-UTF at compile time */
10748                         || (node_type == EXACTFU
10749                             && ender == LATIN_SMALL_LETTER_SHARP_S))
10750                     {
10751
10752
10753                         /* Prime the casefolded buffer.  Locale rules, which
10754                          * apply only to code points < 256, aren't known until
10755                          * execution, so for them, just output the original
10756                          * character using utf8.  If we start to fold non-UTF
10757                          * patterns, be sure to update join_exact() */
10758                         if (LOC && ender < 256) {
10759                             if (UNI_IS_INVARIANT(ender)) {
10760                                 *s = (U8) ender;
10761                                 foldlen = 1;
10762                             } else {
10763                                 *s = UTF8_TWO_BYTE_HI(ender);
10764                                 *(s + 1) = UTF8_TWO_BYTE_LO(ender);
10765                                 foldlen = 2;
10766                             }
10767                         }
10768                         else {
10769                             UV folded = _to_uni_fold_flags(
10770                                            ender,
10771                                            (U8 *) s,
10772                                            &foldlen,
10773                                            FOLD_FLAGS_FULL
10774                                            | ((LOC) ?  FOLD_FLAGS_LOCALE
10775                                                     : (ASCII_FOLD_RESTRICTED)
10776                                                       ? FOLD_FLAGS_NOMIX_ASCII
10777                                                       : 0)
10778                                             );
10779
10780                             /* If this node only contains non-folding code
10781                              * points so far, see if this new one is also
10782                              * non-folding */
10783                             if (maybe_exact) {
10784                                 if (folded != ender) {
10785                                     maybe_exact = FALSE;
10786                                 }
10787                                 else {
10788                                     /* Here the fold is the original; we have
10789                                      * to check further to see if anything
10790                                      * folds to it */
10791                                     if (! PL_utf8_foldable) {
10792                                         SV* swash = swash_init("utf8",
10793                                                            "_Perl_Any_Folds",
10794                                                            &PL_sv_undef, 1, 0);
10795                                         PL_utf8_foldable =
10796                                                     _get_swash_invlist(swash);
10797                                         SvREFCNT_dec_NN(swash);
10798                                     }
10799                                     if (_invlist_contains_cp(PL_utf8_foldable,
10800                                                              ender))
10801                                     {
10802                                         maybe_exact = FALSE;
10803                                     }
10804                                 }
10805                             }
10806                             ender = folded;
10807                         }
10808                         s += foldlen;
10809
10810                         /* The loop increments <len> each time, as all but this
10811                          * path (and the one just below for UTF) through it add
10812                          * a single byte to the EXACTish node.  But this one
10813                          * has changed len to be the correct final value, so
10814                          * subtract one to cancel out the increment that
10815                          * follows */
10816                         len += foldlen - 1;
10817                     }
10818                     else {
10819                         *(s++) = ender;
10820                         maybe_exact &= ! IS_IN_SOME_FOLD_L1(ender);
10821                     }
10822                 }
10823                 else if (UTF) {
10824                     const STRLEN unilen = reguni(pRExC_state, ender, s);
10825                     if (unilen > 0) {
10826                        s   += unilen;
10827                        len += unilen;
10828                     }
10829
10830                     /* See comment just above for - 1 */
10831                     len--;
10832                 }
10833                 else {
10834                     REGC((char)ender, s++);
10835                 }
10836
10837                 if (next_is_quantifier) {
10838
10839                     /* Here, the next input is a quantifier, and to get here,
10840                      * the current character is the only one in the node.
10841                      * Also, here <len> doesn't include the final byte for this
10842                      * character */
10843                     len++;
10844                     goto loopdone;
10845                 }
10846
10847             } /* End of loop through literal characters */
10848
10849             /* Here we have either exhausted the input or ran out of room in
10850              * the node.  (If we encountered a character that can't be in the
10851              * node, transfer is made directly to <loopdone>, and so we
10852              * wouldn't have fallen off the end of the loop.)  In the latter
10853              * case, we artificially have to split the node into two, because
10854              * we just don't have enough space to hold everything.  This
10855              * creates a problem if the final character participates in a
10856              * multi-character fold in the non-final position, as a match that
10857              * should have occurred won't, due to the way nodes are matched,
10858              * and our artificial boundary.  So back off until we find a non-
10859              * problematic character -- one that isn't at the beginning or
10860              * middle of such a fold.  (Either it doesn't participate in any
10861              * folds, or appears only in the final position of all the folds it
10862              * does participate in.)  A better solution with far fewer false
10863              * positives, and that would fill the nodes more completely, would
10864              * be to actually have available all the multi-character folds to
10865              * test against, and to back-off only far enough to be sure that
10866              * this node isn't ending with a partial one.  <upper_parse> is set
10867              * further below (if we need to reparse the node) to include just
10868              * up through that final non-problematic character that this code
10869              * identifies, so when it is set to less than the full node, we can
10870              * skip the rest of this */
10871             if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) {
10872
10873                 const STRLEN full_len = len;
10874
10875                 assert(len >= MAX_NODE_STRING_SIZE);
10876
10877                 /* Here, <s> points to the final byte of the final character.
10878                  * Look backwards through the string until find a non-
10879                  * problematic character */
10880
10881                 if (! UTF) {
10882
10883                     /* These two have no multi-char folds to non-UTF characters
10884                      */
10885                     if (ASCII_FOLD_RESTRICTED || LOC) {
10886                         goto loopdone;
10887                     }
10888
10889                     while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { }
10890                     len = s - s0 + 1;
10891                 }
10892                 else {
10893                     if (!  PL_NonL1NonFinalFold) {
10894                         PL_NonL1NonFinalFold = _new_invlist_C_array(
10895                                         NonL1_Perl_Non_Final_Folds_invlist);
10896                     }
10897
10898                     /* Point to the first byte of the final character */
10899                     s = (char *) utf8_hop((U8 *) s, -1);
10900
10901                     while (s >= s0) {   /* Search backwards until find
10902                                            non-problematic char */
10903                         if (UTF8_IS_INVARIANT(*s)) {
10904
10905                             /* There are no ascii characters that participate
10906                              * in multi-char folds under /aa.  In EBCDIC, the
10907                              * non-ascii invariants are all control characters,
10908                              * so don't ever participate in any folds. */
10909                             if (ASCII_FOLD_RESTRICTED
10910                                 || ! IS_NON_FINAL_FOLD(*s))
10911                             {
10912                                 break;
10913                             }
10914                         }
10915                         else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
10916
10917                             /* No Latin1 characters participate in multi-char
10918                              * folds under /l */
10919                             if (LOC
10920                                 || ! IS_NON_FINAL_FOLD(TWO_BYTE_UTF8_TO_UNI(
10921                                                                 *s, *(s+1))))
10922                             {
10923                                 break;
10924                             }
10925                         }
10926                         else if (! _invlist_contains_cp(
10927                                         PL_NonL1NonFinalFold,
10928                                         valid_utf8_to_uvchr((U8 *) s, NULL)))
10929                         {
10930                             break;
10931                         }
10932
10933                         /* Here, the current character is problematic in that
10934                          * it does occur in the non-final position of some
10935                          * fold, so try the character before it, but have to
10936                          * special case the very first byte in the string, so
10937                          * we don't read outside the string */
10938                         s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1);
10939                     } /* End of loop backwards through the string */
10940
10941                     /* If there were only problematic characters in the string,
10942                      * <s> will point to before s0, in which case the length
10943                      * should be 0, otherwise include the length of the
10944                      * non-problematic character just found */
10945                     len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s);
10946                 }
10947
10948                 /* Here, have found the final character, if any, that is
10949                  * non-problematic as far as ending the node without splitting
10950                  * it across a potential multi-char fold.  <len> contains the
10951                  * number of bytes in the node up-to and including that
10952                  * character, or is 0 if there is no such character, meaning
10953                  * the whole node contains only problematic characters.  In
10954                  * this case, give up and just take the node as-is.  We can't
10955                  * do any better */
10956                 if (len == 0) {
10957                     len = full_len;
10958                 } else {
10959
10960                     /* Here, the node does contain some characters that aren't
10961                      * problematic.  If one such is the final character in the
10962                      * node, we are done */
10963                     if (len == full_len) {
10964                         goto loopdone;
10965                     }
10966                     else if (len + ((UTF) ? UTF8SKIP(s) : 1) == full_len) {
10967
10968                         /* If the final character is problematic, but the
10969                          * penultimate is not, back-off that last character to
10970                          * later start a new node with it */
10971                         p = oldp;
10972                         goto loopdone;
10973                     }
10974
10975                     /* Here, the final non-problematic character is earlier
10976                      * in the input than the penultimate character.  What we do
10977                      * is reparse from the beginning, going up only as far as
10978                      * this final ok one, thus guaranteeing that the node ends
10979                      * in an acceptable character.  The reason we reparse is
10980                      * that we know how far in the character is, but we don't
10981                      * know how to correlate its position with the input parse.
10982                      * An alternate implementation would be to build that
10983                      * correlation as we go along during the original parse,
10984                      * but that would entail extra work for every node, whereas
10985                      * this code gets executed only when the string is too
10986                      * large for the node, and the final two characters are
10987                      * problematic, an infrequent occurrence.  Yet another
10988                      * possible strategy would be to save the tail of the
10989                      * string, and the next time regatom is called, initialize
10990                      * with that.  The problem with this is that unless you
10991                      * back off one more character, you won't be guaranteed
10992                      * regatom will get called again, unless regbranch,
10993                      * regpiece ... are also changed.  If you do back off that
10994                      * extra character, so that there is input guaranteed to
10995                      * force calling regatom, you can't handle the case where
10996                      * just the first character in the node is acceptable.  I
10997                      * (khw) decided to try this method which doesn't have that
10998                      * pitfall; if performance issues are found, we can do a
10999                      * combination of the current approach plus that one */
11000                     upper_parse = len;
11001                     len = 0;
11002                     s = s0;
11003                     goto reparse;
11004                 }
11005             }   /* End of verifying node ends with an appropriate char */
11006
11007         loopdone:   /* Jumped to when encounters something that shouldn't be in
11008                        the node */
11009
11010             /* If 'maybe_exact' is still set here, means there are no
11011              * code points in the node that participate in folds */
11012             if (FOLD && maybe_exact) {
11013                 OP(ret) = EXACT;
11014             }
11015
11016             /* I (khw) don't know if you can get here with zero length, but the
11017              * old code handled this situation by creating a zero-length EXACT
11018              * node.  Might as well be NOTHING instead */
11019             if (len == 0) {
11020                 OP(ret) = NOTHING;
11021             }
11022             else{
11023                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, len, ender);
11024             }
11025
11026             RExC_parse = p - 1;
11027             Set_Node_Cur_Length(ret); /* MJD */
11028             nextchar(pRExC_state);
11029             {
11030                 /* len is STRLEN which is unsigned, need to copy to signed */
11031                 IV iv = len;
11032                 if (iv < 0)
11033                     vFAIL("Internal disaster");
11034             }
11035
11036         } /* End of label 'defchar:' */
11037         break;
11038     } /* End of giant switch on input character */
11039
11040     return(ret);
11041 }
11042
11043 STATIC char *
11044 S_regwhite( RExC_state_t *pRExC_state, char *p )
11045 {
11046     const char *e = RExC_end;
11047
11048     PERL_ARGS_ASSERT_REGWHITE;
11049
11050     while (p < e) {
11051         if (isSPACE(*p))
11052             ++p;
11053         else if (*p == '#') {
11054             bool ended = 0;
11055             do {
11056                 if (*p++ == '\n') {
11057                     ended = 1;
11058                     break;
11059                 }
11060             } while (p < e);
11061             if (!ended)
11062                 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
11063         }
11064         else
11065             break;
11066     }
11067     return p;
11068 }
11069
11070 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
11071    Character classes ([:foo:]) can also be negated ([:^foo:]).
11072    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
11073    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
11074    but trigger failures because they are currently unimplemented. */
11075
11076 #define POSIXCC_DONE(c)   ((c) == ':')
11077 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
11078 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
11079
11080 PERL_STATIC_INLINE I32
11081 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value, SV *free_me)
11082 {
11083     dVAR;
11084     I32 namedclass = OOB_NAMEDCLASS;
11085
11086     PERL_ARGS_ASSERT_REGPPOSIXCC;
11087
11088     if (value == '[' && RExC_parse + 1 < RExC_end &&
11089         /* I smell either [: or [= or [. -- POSIX has been here, right? */
11090         POSIXCC(UCHARAT(RExC_parse))) {
11091         const char c = UCHARAT(RExC_parse);
11092         char* const s = RExC_parse++;
11093
11094         while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
11095             RExC_parse++;
11096         if (RExC_parse == RExC_end)
11097             /* Grandfather lone [:, [=, [. */
11098             RExC_parse = s;
11099         else {
11100             const char* const t = RExC_parse++; /* skip over the c */
11101             assert(*t == c);
11102
11103             if (UCHARAT(RExC_parse) == ']') {
11104                 const char *posixcc = s + 1;
11105                 RExC_parse++; /* skip over the ending ] */
11106
11107                 if (*s == ':') {
11108                     const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
11109                     const I32 skip = t - posixcc;
11110
11111                     /* Initially switch on the length of the name.  */
11112                     switch (skip) {
11113                     case 4:
11114                         if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
11115                             namedclass = ANYOF_WORDCHAR;
11116                         break;
11117                     case 5:
11118                         /* Names all of length 5.  */
11119                         /* alnum alpha ascii blank cntrl digit graph lower
11120                            print punct space upper  */
11121                         /* Offset 4 gives the best switch position.  */
11122                         switch (posixcc[4]) {
11123                         case 'a':
11124                             if (memEQ(posixcc, "alph", 4)) /* alpha */
11125                                 namedclass = ANYOF_ALPHA;
11126                             break;
11127                         case 'e':
11128                             if (memEQ(posixcc, "spac", 4)) /* space */
11129                                 namedclass = ANYOF_PSXSPC;
11130                             break;
11131                         case 'h':
11132                             if (memEQ(posixcc, "grap", 4)) /* graph */
11133                                 namedclass = ANYOF_GRAPH;
11134                             break;
11135                         case 'i':
11136                             if (memEQ(posixcc, "asci", 4)) /* ascii */
11137                                 namedclass = ANYOF_ASCII;
11138                             break;
11139                         case 'k':
11140                             if (memEQ(posixcc, "blan", 4)) /* blank */
11141                                 namedclass = ANYOF_BLANK;
11142                             break;
11143                         case 'l':
11144                             if (memEQ(posixcc, "cntr", 4)) /* cntrl */
11145                                 namedclass = ANYOF_CNTRL;
11146                             break;
11147                         case 'm':
11148                             if (memEQ(posixcc, "alnu", 4)) /* alnum */
11149                                 namedclass = ANYOF_ALPHANUMERIC;
11150                             break;
11151                         case 'r':
11152                             if (memEQ(posixcc, "lowe", 4)) /* lower */
11153                                 namedclass = ANYOF_LOWER;
11154                             else if (memEQ(posixcc, "uppe", 4)) /* upper */
11155                                 namedclass = ANYOF_UPPER;
11156                             break;
11157                         case 't':
11158                             if (memEQ(posixcc, "digi", 4)) /* digit */
11159                                 namedclass = ANYOF_DIGIT;
11160                             else if (memEQ(posixcc, "prin", 4)) /* print */
11161                                 namedclass = ANYOF_PRINT;
11162                             else if (memEQ(posixcc, "punc", 4)) /* punct */
11163                                 namedclass = ANYOF_PUNCT;
11164                             break;
11165                         }
11166                         break;
11167                     case 6:
11168                         if (memEQ(posixcc, "xdigit", 6))
11169                             namedclass = ANYOF_XDIGIT;
11170                         break;
11171                     }
11172
11173                     if (namedclass == OOB_NAMEDCLASS)
11174                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
11175                                       t - s - 1, s + 1);
11176
11177                     /* The #defines are structured so each complement is +1 to
11178                      * the normal one */
11179                     if (complement) {
11180                         namedclass++;
11181                     }
11182                     assert (posixcc[skip] == ':');
11183                     assert (posixcc[skip+1] == ']');
11184                 } else if (!SIZE_ONLY) {
11185                     /* [[=foo=]] and [[.foo.]] are still future. */
11186
11187                     /* adjust RExC_parse so the warning shows after
11188                        the class closes */
11189                     while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
11190                         RExC_parse++;
11191                     SvREFCNT_dec(free_me);
11192                     vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
11193                 }
11194             } else {
11195                 /* Maternal grandfather:
11196                  * "[:" ending in ":" but not in ":]" */
11197                 RExC_parse = s;
11198             }
11199         }
11200     }
11201
11202     return namedclass;
11203 }
11204
11205
11206 /* The names of properties whose definitions are not known at compile time are
11207  * stored in this SV, after a constant heading.  So if the length has been
11208  * changed since initialization, then there is a run-time definition. */
11209 #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION (SvCUR(listsv) != initial_listsv_len)
11210
11211 STATIC regnode *
11212 S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
11213 {
11214     /* parse a bracketed class specification.  Most of these will produce an ANYOF node;
11215      * but something like [a] will produce an EXACT node; [aA], an EXACTFish
11216      * node; [[:ascii:]], a POSIXA node; etc.  It is more complex under /i with
11217      * multi-character folds: it will be rewritten following the paradigm of
11218      * this example, where the <multi-fold>s are characters which fold to
11219      * multiple character sequences:
11220      *      /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i
11221      * gets effectively rewritten as:
11222      *      /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i
11223      * reg() gets called (recursively) on the rewritten version, and this
11224      * function will return what it constructs.  (Actually the <multi-fold>s
11225      * aren't physically removed from the [abcdefghi], it's just that they are
11226      * ignored in the recursion by means of a flag:
11227      * <RExC_in_multi_char_class>.)
11228      *
11229      * ANYOF nodes contain a bit map for the first 256 characters, with the
11230      * corresponding bit set if that character is in the list.  For characters
11231      * above 255, a range list or swash is used.  There are extra bits for \w,
11232      * etc. in locale ANYOFs, as what these match is not determinable at
11233      * compile time */
11234
11235     dVAR;
11236     UV nextvalue;
11237     UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE;
11238     IV range = 0;
11239     UV value = OOB_UNICODE, save_value = OOB_UNICODE;
11240     regnode *ret;
11241     STRLEN numlen;
11242     IV namedclass = OOB_NAMEDCLASS;
11243     char *rangebegin = NULL;
11244     bool need_class = 0;
11245     SV *listsv = NULL;
11246     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
11247                                       than just initialized.  */
11248     SV* properties = NULL;    /* Code points that match \p{} \P{} */
11249     SV* posixes = NULL;     /* Code points that match classes like, [:word:],
11250                                extended beyond the Latin1 range */
11251     UV element_count = 0;   /* Number of distinct elements in the class.
11252                                Optimizations may be possible if this is tiny */
11253     AV * multi_char_matches = NULL; /* Code points that fold to more than one
11254                                        character; used under /i */
11255     UV n;
11256
11257     /* Unicode properties are stored in a swash; this holds the current one
11258      * being parsed.  If this swash is the only above-latin1 component of the
11259      * character class, an optimization is to pass it directly on to the
11260      * execution engine.  Otherwise, it is set to NULL to indicate that there
11261      * are other things in the class that have to be dealt with at execution
11262      * time */
11263     SV* swash = NULL;           /* Code points that match \p{} \P{} */
11264
11265     /* Set if a component of this character class is user-defined; just passed
11266      * on to the engine */
11267     bool has_user_defined_property = FALSE;
11268
11269     /* inversion list of code points this node matches only when the target
11270      * string is in UTF-8.  (Because is under /d) */
11271     SV* depends_list = NULL;
11272
11273     /* inversion list of code points this node matches.  For much of the
11274      * function, it includes only those that match regardless of the utf8ness
11275      * of the target string */
11276     SV* cp_list = NULL;
11277
11278 #ifdef EBCDIC
11279     /* In a range, counts how many 0-2 of the ends of it came from literals,
11280      * not escapes.  Thus we can tell if 'A' was input vs \x{C1} */
11281     UV literal_endpoint = 0;
11282 #endif
11283     bool invert = FALSE;    /* Is this class to be complemented */
11284
11285     /* Is there any thing like \W or [:^digit:] that matches above the legal
11286      * Unicode range? */
11287     bool runtime_posix_matches_above_Unicode = FALSE;
11288
11289     regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
11290         case we need to change the emitted regop to an EXACT. */
11291     const char * orig_parse = RExC_parse;
11292     const I32 orig_size = RExC_size;
11293     GET_RE_DEBUG_FLAGS_DECL;
11294
11295     PERL_ARGS_ASSERT_REGCLASS;
11296 #ifndef DEBUGGING
11297     PERL_UNUSED_ARG(depth);
11298 #endif
11299
11300     DEBUG_PARSE("clas");
11301
11302     /* Assume we are going to generate an ANYOF node. */
11303     ret = reganode(pRExC_state, ANYOF, 0);
11304
11305     if (!SIZE_ONLY) {
11306         ANYOF_FLAGS(ret) = 0;
11307     }
11308
11309     if (UCHARAT(RExC_parse) == '^') {   /* Complement of range. */
11310         RExC_parse++;
11311         invert = TRUE;
11312         RExC_naughty++;
11313     }
11314
11315     if (SIZE_ONLY) {
11316         RExC_size += ANYOF_SKIP;
11317         listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
11318     }
11319     else {
11320         RExC_emit += ANYOF_SKIP;
11321         if (LOC) {
11322             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
11323         }
11324         listsv = newSVpvs("# comment\n");
11325         initial_listsv_len = SvCUR(listsv);
11326     }
11327
11328     nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
11329
11330     if (!SIZE_ONLY && POSIXCC(nextvalue))
11331     {
11332         const char *s = RExC_parse;
11333         const char  c = *s++;
11334
11335         while (isALNUM(*s))
11336             s++;
11337         if (*s && c == *s && s[1] == ']') {
11338             SAVEFREESV(RExC_rx_sv);
11339             SAVEFREESV(listsv);
11340             ckWARN3reg(s+2,
11341                        "POSIX syntax [%c %c] belongs inside character classes",
11342                        c, c);
11343             (void)ReREFCNT_inc(RExC_rx_sv);
11344             SvREFCNT_inc_simple_void_NN(listsv);
11345         }
11346     }
11347
11348     /* allow 1st char to be ] (allowing it to be - is dealt with later) */
11349     if (UCHARAT(RExC_parse) == ']')
11350         goto charclassloop;
11351
11352 parseit:
11353     while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
11354
11355     charclassloop:
11356
11357         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
11358         save_value = value;
11359         save_prevvalue = prevvalue;
11360
11361         if (!range) {
11362             rangebegin = RExC_parse;
11363             element_count++;
11364         }
11365         if (UTF) {
11366             value = utf8n_to_uvchr((U8*)RExC_parse,
11367                                    RExC_end - RExC_parse,
11368                                    &numlen, UTF8_ALLOW_DEFAULT);
11369             RExC_parse += numlen;
11370         }
11371         else
11372             value = UCHARAT(RExC_parse++);
11373
11374         nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
11375         if (value == '[' && POSIXCC(nextvalue))
11376             namedclass = regpposixcc(pRExC_state, value, listsv);
11377         else if (value == '\\') {
11378             if (UTF) {
11379                 value = utf8n_to_uvchr((U8*)RExC_parse,
11380                                    RExC_end - RExC_parse,
11381                                    &numlen, UTF8_ALLOW_DEFAULT);
11382                 RExC_parse += numlen;
11383             }
11384             else
11385                 value = UCHARAT(RExC_parse++);
11386             /* Some compilers cannot handle switching on 64-bit integer
11387              * values, therefore value cannot be an UV.  Yes, this will
11388              * be a problem later if we want switch on Unicode.
11389              * A similar issue a little bit later when switching on
11390              * namedclass. --jhi */
11391             switch ((I32)value) {
11392             case 'w':   namedclass = ANYOF_WORDCHAR;    break;
11393             case 'W':   namedclass = ANYOF_NWORDCHAR;   break;
11394             case 's':   namedclass = ANYOF_SPACE;       break;
11395             case 'S':   namedclass = ANYOF_NSPACE;      break;
11396             case 'd':   namedclass = ANYOF_DIGIT;       break;
11397             case 'D':   namedclass = ANYOF_NDIGIT;      break;
11398             case 'v':   namedclass = ANYOF_VERTWS;      break;
11399             case 'V':   namedclass = ANYOF_NVERTWS;     break;
11400             case 'h':   namedclass = ANYOF_HORIZWS;     break;
11401             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
11402             case 'N':  /* Handle \N{NAME} in class */
11403                 {
11404                     /* We only pay attention to the first char of 
11405                     multichar strings being returned. I kinda wonder
11406                     if this makes sense as it does change the behaviour
11407                     from earlier versions, OTOH that behaviour was broken
11408                     as well. */
11409                     if (! grok_bslash_N(pRExC_state, NULL, &value, flagp, depth,
11410                                       TRUE /* => charclass */))
11411                     {
11412                         goto parseit;
11413                     }
11414                 }
11415                 break;
11416             case 'p':
11417             case 'P':
11418                 {
11419                 char *e;
11420
11421                 /* This routine will handle any undefined properties */
11422                 U8 swash_init_flags = _CORE_SWASH_INIT_RETURN_IF_UNDEF;
11423
11424                 if (RExC_parse >= RExC_end)
11425                     vFAIL2("Empty \\%c{}", (U8)value);
11426                 if (*RExC_parse == '{') {
11427                     const U8 c = (U8)value;
11428                     e = strchr(RExC_parse++, '}');
11429                     if (!e)
11430                         vFAIL2("Missing right brace on \\%c{}", c);
11431                     while (isSPACE(UCHARAT(RExC_parse)))
11432                         RExC_parse++;
11433                     if (e == RExC_parse)
11434                         vFAIL2("Empty \\%c{}", c);
11435                     n = e - RExC_parse;
11436                     while (isSPACE(UCHARAT(RExC_parse + n - 1)))
11437                         n--;
11438                 }
11439                 else {
11440                     e = RExC_parse;
11441                     n = 1;
11442                 }
11443                 if (!SIZE_ONLY) {
11444                     SV* invlist;
11445                     char* name;
11446
11447                     if (UCHARAT(RExC_parse) == '^') {
11448                          RExC_parse++;
11449                          n--;
11450                          value = value == 'p' ? 'P' : 'p'; /* toggle */
11451                          while (isSPACE(UCHARAT(RExC_parse))) {
11452                               RExC_parse++;
11453                               n--;
11454                          }
11455                     }
11456                     /* Try to get the definition of the property into
11457                      * <invlist>.  If /i is in effect, the effective property
11458                      * will have its name be <__NAME_i>.  The design is
11459                      * discussed in commit
11460                      * 2f833f5208e26b208886e51e09e2c072b5eabb46 */
11461                     Newx(name, n + sizeof("_i__\n"), char);
11462
11463                     sprintf(name, "%s%.*s%s\n",
11464                                     (FOLD) ? "__" : "",
11465                                     (int)n,
11466                                     RExC_parse,
11467                                     (FOLD) ? "_i" : ""
11468                     );
11469
11470                     /* Look up the property name, and get its swash and
11471                      * inversion list, if the property is found  */
11472                     if (swash) {
11473                         SvREFCNT_dec_NN(swash);
11474                     }
11475                     swash = _core_swash_init("utf8", name, &PL_sv_undef,
11476                                              1, /* binary */
11477                                              0, /* not tr/// */
11478                                              NULL, /* No inversion list */
11479                                              &swash_init_flags
11480                                             );
11481                     if (! swash || ! (invlist = _get_swash_invlist(swash))) {
11482                         if (swash) {
11483                             SvREFCNT_dec_NN(swash);
11484                             swash = NULL;
11485                         }
11486
11487                         /* Here didn't find it.  It could be a user-defined
11488                          * property that will be available at run-time.  Add it
11489                          * to the list to look up then */
11490                         Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%s\n",
11491                                         (value == 'p' ? '+' : '!'),
11492                                         name);
11493                         has_user_defined_property = TRUE;
11494
11495                         /* We don't know yet, so have to assume that the
11496                          * property could match something in the Latin1 range,
11497                          * hence something that isn't utf8.  Note that this
11498                          * would cause things in <depends_list> to match
11499                          * inappropriately, except that any \p{}, including
11500                          * this one forces Unicode semantics, which means there
11501                          * is <no depends_list> */
11502                         ANYOF_FLAGS(ret) |= ANYOF_NONBITMAP_NON_UTF8;
11503                     }
11504                     else {
11505
11506                         /* Here, did get the swash and its inversion list.  If
11507                          * the swash is from a user-defined property, then this
11508                          * whole character class should be regarded as such */
11509                         has_user_defined_property =
11510                                     (swash_init_flags
11511                                      & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY);
11512
11513                         /* Invert if asking for the complement */
11514                         if (value == 'P') {
11515                             _invlist_union_complement_2nd(properties,
11516                                                           invlist,
11517                                                           &properties);
11518
11519                             /* The swash can't be used as-is, because we've
11520                              * inverted things; delay removing it to here after
11521                              * have copied its invlist above */
11522                             SvREFCNT_dec_NN(swash);
11523                             swash = NULL;
11524                         }
11525                         else {
11526                             _invlist_union(properties, invlist, &properties);
11527                         }
11528                     }
11529                     Safefree(name);
11530                 }
11531                 RExC_parse = e + 1;
11532                 namedclass = ANYOF_UNIPROP;  /* no official name, but it's named */
11533
11534                 /* \p means they want Unicode semantics */
11535                 RExC_uni_semantics = 1;
11536                 }
11537                 break;
11538             case 'n':   value = '\n';                   break;
11539             case 'r':   value = '\r';                   break;
11540             case 't':   value = '\t';                   break;
11541             case 'f':   value = '\f';                   break;
11542             case 'b':   value = '\b';                   break;
11543             case 'e':   value = ASCII_TO_NATIVE('\033');break;
11544             case 'a':   value = ASCII_TO_NATIVE('\007');break;
11545             case 'o':
11546                 RExC_parse--;   /* function expects to be pointed at the 'o' */
11547                 {
11548                     const char* error_msg;
11549                     bool valid = grok_bslash_o(RExC_parse,
11550                                                &value,
11551                                                &numlen,
11552                                                &error_msg,
11553                                                SIZE_ONLY);
11554                     RExC_parse += numlen;
11555                     if (! valid) {
11556                         vFAIL(error_msg);
11557                     }
11558                 }
11559                 if (PL_encoding && value < 0x100) {
11560                     goto recode_encoding;
11561                 }
11562                 break;
11563             case 'x':
11564                 RExC_parse--;   /* function expects to be pointed at the 'x' */
11565                 {
11566                     const char* error_msg;
11567                     bool valid = grok_bslash_x(RExC_parse,
11568                                                &value,
11569                                                &numlen,
11570                                                &error_msg,
11571                                                1);
11572                     RExC_parse += numlen;
11573                     if (! valid) {
11574                         vFAIL(error_msg);
11575                     }
11576                 }
11577                 if (PL_encoding && value < 0x100)
11578                     goto recode_encoding;
11579                 break;
11580             case 'c':
11581                 value = grok_bslash_c(*RExC_parse++, UTF, SIZE_ONLY);
11582                 break;
11583             case '0': case '1': case '2': case '3': case '4':
11584             case '5': case '6': case '7':
11585                 {
11586                     /* Take 1-3 octal digits */
11587                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
11588                     numlen = 3;
11589                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
11590                     RExC_parse += numlen;
11591                     if (PL_encoding && value < 0x100)
11592                         goto recode_encoding;
11593                     break;
11594                 }
11595             recode_encoding:
11596                 if (! RExC_override_recoding) {
11597                     SV* enc = PL_encoding;
11598                     value = reg_recode((const char)(U8)value, &enc);
11599                     if (!enc && SIZE_ONLY)
11600                         ckWARNreg(RExC_parse,
11601                                   "Invalid escape in the specified encoding");
11602                     break;
11603                 }
11604             default:
11605                 /* Allow \_ to not give an error */
11606                 if (!SIZE_ONLY && isALNUM(value) && value != '_') {
11607                     SAVEFREESV(RExC_rx_sv);
11608                     SAVEFREESV(listsv);
11609                     ckWARN2reg(RExC_parse,
11610                                "Unrecognized escape \\%c in character class passed through",
11611                                (int)value);
11612                     (void)ReREFCNT_inc(RExC_rx_sv);
11613                     SvREFCNT_inc_simple_void_NN(listsv);
11614                 }
11615                 break;
11616             }
11617         } /* end of \blah */
11618 #ifdef EBCDIC
11619         else
11620             literal_endpoint++;
11621 #endif
11622
11623             /* What matches in a locale is not known until runtime.  This
11624              * includes what the Posix classes (like \w, [:space:]) match.
11625              * Room must be reserved (one time per class) to store such
11626              * classes, either if Perl is compiled so that locale nodes always
11627              * should have this space, or if there is such class info to be
11628              * stored.  The space will contain a bit for each named class that
11629              * is to be matched against.  This isn't needed for \p{} and
11630              * pseudo-classes, as they are not affected by locale, and hence
11631              * are dealt with separately */
11632             if (LOC
11633                 && ! need_class
11634                 && (ANYOF_LOCALE == ANYOF_CLASS
11635                     || (namedclass > OOB_NAMEDCLASS && namedclass < ANYOF_MAX)))
11636             {
11637                 need_class = 1;
11638                 if (SIZE_ONLY) {
11639                     RExC_size += ANYOF_CLASS_SKIP - ANYOF_SKIP;
11640                 }
11641                 else {
11642                     RExC_emit += ANYOF_CLASS_SKIP - ANYOF_SKIP;
11643                     ANYOF_CLASS_ZERO(ret);
11644                 }
11645                 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
11646             }
11647
11648         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
11649
11650             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
11651              * literal, as is the character that began the false range, i.e.
11652              * the 'a' in the examples */
11653             if (range) {
11654                 if (!SIZE_ONLY) {
11655                     const int w =
11656                         RExC_parse >= rangebegin ?
11657                         RExC_parse - rangebegin : 0;
11658                     SAVEFREESV(RExC_rx_sv); /* in case of fatal warnings */
11659                     SAVEFREESV(listsv);
11660                     ckWARN4reg(RExC_parse,
11661                                "False [] range \"%*.*s\"",
11662                                w, w, rangebegin);
11663                     (void)ReREFCNT_inc(RExC_rx_sv);
11664                     SvREFCNT_inc_simple_void_NN(listsv);
11665                     cp_list = add_cp_to_invlist(cp_list, '-');
11666                     cp_list = add_cp_to_invlist(cp_list, prevvalue);
11667                 }
11668
11669                 range = 0; /* this was not a true range */
11670                 element_count += 2; /* So counts for three values */
11671             }
11672
11673             if (! SIZE_ONLY) {
11674                 U8 classnum = namedclass_to_classnum(namedclass);
11675
11676                 /* The ascii range inversion list */
11677                 SV* ascii_source = PL_Posix_ptrs[classnum];
11678
11679                 /* The full Latin1 range inversion list */
11680                 SV* l1_source = PL_L1Posix_ptrs[classnum];
11681
11682                 /* The name of the property to use to match the full eXtended
11683                  * Unicode range swash fo this character class */
11684                 const char *Xname = swash_property_names[classnum];
11685
11686                 /* LOWER and UPPER under fold match ALPHA in the ASCII range,
11687                  * and Cased outside it */
11688                 if (FOLD && ! LOC
11689                     && (classnum == _CC_LOWER || classnum == _CC_UPPER))
11690                 {
11691                     ascii_source = PL_Posix_ptrs[_CC_ALPHA];
11692                     l1_source = PL_L1Cased;
11693                     Xname = "Cased";
11694                 }
11695
11696                 switch ((I32)namedclass) {
11697
11698                 case ANYOF_DIGIT:
11699                     l1_source = ascii_source;
11700                     /* FALL THROUGH */
11701
11702                 case ANYOF_ALPHANUMERIC: /* C's alnum, in contrast to \w */
11703                 case ANYOF_ALPHA:
11704                 case ANYOF_GRAPH:
11705                 case ANYOF_LOWER:
11706                 case ANYOF_PRINT:
11707                 case ANYOF_PUNCT:
11708                 case ANYOF_UPPER:
11709                 case ANYOF_WORDCHAR:
11710                     if ( !  PL_utf8_swash_ptrs[classnum]) {
11711
11712                         /* If not /a matching, there are code points we don't
11713                          * know at compile time.  Arrange for the unknown
11714                          * matches to be loaded at run-time, if needed */
11715                         if (! AT_LEAST_ASCII_RESTRICTED) {
11716                             Perl_sv_catpvf(aTHX_ listsv, "+utf8::%s\n", Xname);
11717                         }
11718                         if (LOC) {  /* Under locale, set run-time lookup */
11719                             ANYOF_CLASS_SET(ret, namedclass);
11720                         }
11721                         else {
11722                             /* Add the current class's code points to the
11723                              * running total */
11724                             _invlist_union(posixes,
11725                                            (AT_LEAST_ASCII_RESTRICTED)
11726                                                 ? ascii_source
11727                                                 : l1_source,
11728                                            &posixes);
11729                         }
11730                         break;
11731                     }
11732                     if (! PL_XPosix_ptrs[classnum]) {
11733                         PL_XPosix_ptrs[classnum]
11734                             = _swash_to_invlist(PL_utf8_swash_ptrs[classnum]);
11735                     }
11736                     /* FALL THROUGH */
11737
11738                 case ANYOF_BLANK:
11739                 case ANYOF_CNTRL:
11740                 case ANYOF_PSXSPC:
11741                 case ANYOF_SPACE:
11742                 case ANYOF_XDIGIT:
11743                     if (! LOC) {
11744                         /* For non-locale, just add it to any existing list */
11745                         _invlist_union(posixes,
11746                                        (AT_LEAST_ASCII_RESTRICTED)
11747                                            ? ascii_source
11748                                            : PL_XPosix_ptrs[classnum],
11749                                        &posixes);
11750                     }
11751                     else {  /* Locale */
11752                         SV* scratch_list = NULL;
11753
11754                         /* For above Latin1 code points, we use the full
11755                          * Unicode range */
11756                         _invlist_intersection(PL_AboveLatin1,
11757                                               PL_XPosix_ptrs[classnum],
11758                                               &scratch_list);
11759                         /* And set the output to it, adding instead if there
11760                          * already is an output.  Checking if 'posixes' is NULL
11761                          * first saves an extra clone.  Its reference count
11762                          * will be decremented at the next union, etc, or if
11763                          * this is the only instance, at the end of the routine
11764                          * */
11765                         if (! posixes) {
11766                             posixes = scratch_list;
11767                         }
11768                         else {
11769                             _invlist_union(posixes, scratch_list, &posixes);
11770                             SvREFCNT_dec_NN(scratch_list);
11771                         }
11772
11773 #ifndef HAS_ISBLANK
11774                         if (namedclass != ANYOF_BLANK) {
11775 #endif
11776                             /* Set this class in the node for runtime
11777                              * matching */
11778                             ANYOF_CLASS_SET(ret, namedclass);
11779 #ifndef HAS_ISBLANK
11780                         }
11781                         else {
11782                             /* No isblank(), use the hard-coded ASCII-range
11783                              * blanks, adding them to the running total. */
11784
11785                             _invlist_union(posixes, ascii_source, &posixes);
11786                         }
11787 #endif
11788                     }
11789                     break;
11790
11791                 case ANYOF_NDIGIT:
11792                     l1_source = ascii_source;
11793                     /* FALL THROUGH */
11794
11795                 case ANYOF_NALPHANUMERIC:
11796                 case ANYOF_NALPHA:
11797                 case ANYOF_NGRAPH:
11798                 case ANYOF_NLOWER:
11799                 case ANYOF_NPRINT:
11800                 case ANYOF_NPUNCT:
11801                 case ANYOF_NUPPER:
11802                 case ANYOF_NWORDCHAR:
11803                     if ( !  PL_utf8_swash_ptrs[classnum]) {
11804                         if (AT_LEAST_ASCII_RESTRICTED) {
11805                             /* Under /a should match everything above ASCII,
11806                              * and the complement of the set's ASCII matches */
11807                             _invlist_union_complement_2nd(posixes, ascii_source,
11808                                                           &posixes);
11809                         }
11810                         else {
11811                             /* Arrange for the unknown matches to be loaded at
11812                              * run-time, if needed */
11813                             Perl_sv_catpvf(aTHX_ listsv, "!utf8::%s\n", Xname);
11814                             runtime_posix_matches_above_Unicode = TRUE;
11815                             if (LOC) {
11816                                 ANYOF_CLASS_SET(ret, namedclass);
11817                             }
11818                             else {
11819
11820                                 /* We want to match everything in Latin1,
11821                                  * except those things that l1_source matches
11822                                  * */
11823                                 SV* scratch_list = NULL;
11824                                 _invlist_subtract(PL_Latin1, l1_source,
11825                                                   &scratch_list);
11826
11827                                 /* Add the list from this class to the running
11828                                  * total */
11829                                 if (! posixes) {
11830                                     posixes = scratch_list;
11831                                 }
11832                                 else {
11833                                     _invlist_union(posixes, scratch_list,
11834                                                    &posixes);
11835                                     SvREFCNT_dec_NN(scratch_list);
11836                                 }
11837                                 if (DEPENDS_SEMANTICS) {
11838                                     ANYOF_FLAGS(ret)
11839                                                 |= ANYOF_NON_UTF8_LATIN1_ALL;
11840                                 }
11841                             }
11842                         }
11843                         break;
11844                     }
11845                     if (! PL_XPosix_ptrs[classnum]) {
11846                         PL_XPosix_ptrs[classnum]
11847                             = _swash_to_invlist(PL_utf8_swash_ptrs[classnum]);
11848                     }
11849                     /* FALL THROUGH */
11850
11851                 case ANYOF_NBLANK:
11852                 case ANYOF_NCNTRL:
11853                 case ANYOF_NPSXSPC:
11854                 case ANYOF_NSPACE:
11855                 case ANYOF_NXDIGIT:
11856                     if (! LOC) {
11857                         _invlist_union_complement_2nd(
11858                                                 posixes,
11859                                                 (AT_LEAST_ASCII_RESTRICTED)
11860                                                     ? ascii_source
11861                                                     : PL_XPosix_ptrs[classnum],
11862                                                 &posixes);
11863                         /* Under /d, everything in the upper half of the Latin1
11864                          * range matches this complement */
11865                         if (DEPENDS_SEMANTICS) {
11866                             ANYOF_FLAGS(ret) |= ANYOF_NON_UTF8_LATIN1_ALL;
11867                         }
11868                     }
11869                     else {  /* Locale */
11870                         SV* scratch_list = NULL;
11871                         _invlist_subtract(PL_AboveLatin1,
11872                                           PL_XPosix_ptrs[classnum],
11873                                           &scratch_list);
11874                         if (! posixes) {
11875                             posixes = scratch_list;
11876                         }
11877                         else {
11878                             _invlist_union(posixes, scratch_list, &posixes);
11879                             SvREFCNT_dec_NN(scratch_list);
11880                         }
11881 #ifndef HAS_ISBLANK
11882                         if (namedclass != ANYOF_NBLANK) {
11883 #endif
11884                             ANYOF_CLASS_SET(ret, namedclass);
11885 #ifndef HAS_ISBLANK
11886                         }
11887                         else {
11888                             /* Get the list of all code points in Latin1 that
11889                              * are not ASCII blanks, and add them to the
11890                              * running total */
11891                             _invlist_subtract(PL_Latin1, ascii_source,
11892                                               &scratch_list);
11893                             _invlist_union(posixes, scratch_list, &posixes);
11894                             SvREFCNT_dec_NN(scratch_list);
11895                         }
11896 #endif
11897                     }
11898                     break;
11899
11900                 case ANYOF_ASCII:
11901 #ifdef HAS_ISASCII
11902                     if (LOC) {
11903                         ANYOF_CLASS_SET(ret, namedclass);
11904                     }
11905                     else
11906 #endif  /* Not isascii(); just use the hard-coded definition for it */
11907                         _invlist_union(posixes, PL_ASCII, &posixes);
11908                     break;
11909                 case ANYOF_NASCII:
11910 #ifdef HAS_ISASCII
11911                     if (LOC) {
11912                         ANYOF_CLASS_SET(ret, namedclass);
11913                     }
11914                     else {
11915 #endif
11916                         _invlist_union_complement_2nd(posixes,
11917                                                     PL_ASCII, &posixes);
11918                         if (DEPENDS_SEMANTICS) {
11919                             ANYOF_FLAGS(ret) |= ANYOF_NON_UTF8_LATIN1_ALL;
11920                         }
11921 #ifdef HAS_ISASCII
11922                     }
11923 #endif
11924                     break;
11925
11926                 case ANYOF_HORIZWS:
11927                     /* For these, we use the cp_list, as neither /d nor /l make
11928                      * a difference in what these match.  There would be
11929                      * problems if these characters had folds other than
11930                      * themselves, as cp_list is subject to folding.
11931                      *
11932                      * It turns out that \h is just a synonym for XPosixBlank */
11933                     classnum = _CC_BLANK;
11934                     /* FALL THROUGH */
11935
11936                 case ANYOF_VERTWS:
11937                     _invlist_union(cp_list, PL_XPosix_ptrs[classnum], &cp_list);
11938                     break;
11939
11940                 case ANYOF_NHORIZWS:
11941                     classnum = _CC_BLANK;
11942                     /* FALL THROUGH */
11943
11944                 case ANYOF_NVERTWS:
11945                     _invlist_union_complement_2nd(cp_list,
11946                                                   PL_XPosix_ptrs[classnum],
11947                                                   &cp_list);
11948                     break;
11949
11950                 case ANYOF_UNIPROP: /* this is to handle \p and \P */
11951                     break;
11952
11953                 default:
11954                     vFAIL("Invalid [::] class");
11955                     break;
11956                 }
11957
11958                 continue;   /* Go get next character */
11959             }
11960         } /* end of namedclass \blah */
11961
11962         if (range) {
11963             if (prevvalue > value) /* b-a */ {
11964                 const int w = RExC_parse - rangebegin;
11965                 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
11966                 range = 0; /* not a valid range */
11967             }
11968         }
11969         else {
11970             prevvalue = value; /* save the beginning of the potential range */
11971             if (RExC_parse+1 < RExC_end
11972                 && *RExC_parse == '-'
11973                 && RExC_parse[1] != ']')
11974             {
11975                 RExC_parse++;
11976
11977                 /* a bad range like \w-, [:word:]- ? */
11978                 if (namedclass > OOB_NAMEDCLASS) {
11979                     if (ckWARN(WARN_REGEXP)) {
11980                         const int w =
11981                             RExC_parse >= rangebegin ?
11982                             RExC_parse - rangebegin : 0;
11983                         vWARN4(RExC_parse,
11984                                "False [] range \"%*.*s\"",
11985                                w, w, rangebegin);
11986                     }
11987                     if (!SIZE_ONLY) {
11988                         cp_list = add_cp_to_invlist(cp_list, '-');
11989                     }
11990                     element_count++;
11991                 } else
11992                     range = 1;  /* yeah, it's a range! */
11993                 continue;       /* but do it the next time */
11994             }
11995         }
11996
11997         /* Here, <prevvalue> is the beginning of the range, if any; or <value>
11998          * if not */
11999
12000         /* non-Latin1 code point implies unicode semantics.  Must be set in
12001          * pass1 so is there for the whole of pass 2 */
12002         if (value > 255) {
12003             RExC_uni_semantics = 1;
12004         }
12005
12006         /* Ready to process either the single value, or the completed range.
12007          * For single-valued non-inverted ranges, we consider the possibility
12008          * of multi-char folds.  (We made a conscious decision to not do this
12009          * for the other cases because it can often lead to non-intuitive
12010          * results.  For example, you have the peculiar case that:
12011          *  "s s" =~ /^[^\xDF]+$/i => Y
12012          *  "ss"  =~ /^[^\xDF]+$/i => N
12013          *
12014          * See [perl #89750] */
12015         if (FOLD && ! invert && value == prevvalue) {
12016             if (value == LATIN_SMALL_LETTER_SHARP_S
12017                 || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold,
12018                                                         value)))
12019             {
12020                 /* Here <value> is indeed a multi-char fold.  Get what it is */
12021
12022                 U8 foldbuf[UTF8_MAXBYTES_CASE];
12023                 STRLEN foldlen;
12024
12025                 UV folded = _to_uni_fold_flags(
12026                                 value,
12027                                 foldbuf,
12028                                 &foldlen,
12029                                 FOLD_FLAGS_FULL
12030                                 | ((LOC) ?  FOLD_FLAGS_LOCALE
12031                                             : (ASCII_FOLD_RESTRICTED)
12032                                               ? FOLD_FLAGS_NOMIX_ASCII
12033                                               : 0)
12034                                 );
12035
12036                 /* Here, <folded> should be the first character of the
12037                  * multi-char fold of <value>, with <foldbuf> containing the
12038                  * whole thing.  But, if this fold is not allowed (because of
12039                  * the flags), <fold> will be the same as <value>, and should
12040                  * be processed like any other character, so skip the special
12041                  * handling */
12042                 if (folded != value) {
12043
12044                     /* Skip if we are recursed, currently parsing the class
12045                      * again.  Otherwise add this character to the list of
12046                      * multi-char folds. */
12047                     if (! RExC_in_multi_char_class) {
12048                         AV** this_array_ptr;
12049                         AV* this_array;
12050                         STRLEN cp_count = utf8_length(foldbuf,
12051                                                       foldbuf + foldlen);
12052                         SV* multi_fold = sv_2mortal(newSVpvn("", 0));
12053
12054                         Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%"UVXf"}", value);
12055
12056
12057                         if (! multi_char_matches) {
12058                             multi_char_matches = newAV();
12059                         }
12060
12061                         /* <multi_char_matches> is actually an array of arrays.
12062                          * There will be one or two top-level elements: [2],
12063                          * and/or [3].  The [2] element is an array, each
12064                          * element thereof is a character which folds to two
12065                          * characters; likewise for [3].  (Unicode guarantees a
12066                          * maximum of 3 characters in any fold.)  When we
12067                          * rewrite the character class below, we will do so
12068                          * such that the longest folds are written first, so
12069                          * that it prefers the longest matching strings first.
12070                          * This is done even if it turns out that any
12071                          * quantifier is non-greedy, out of programmer
12072                          * laziness.  Tom Christiansen has agreed that this is
12073                          * ok.  This makes the test for the ligature 'ffi' come
12074                          * before the test for 'ff' */
12075                         if (av_exists(multi_char_matches, cp_count)) {
12076                             this_array_ptr = (AV**) av_fetch(multi_char_matches,
12077                                                              cp_count, FALSE);
12078                             this_array = *this_array_ptr;
12079                         }
12080                         else {
12081                             this_array = newAV();
12082                             av_store(multi_char_matches, cp_count,
12083                                      (SV*) this_array);
12084                         }
12085                         av_push(this_array, multi_fold);
12086                     }
12087
12088                     /* This element should not be processed further in this
12089                      * class */
12090                     element_count--;
12091                     value = save_value;
12092                     prevvalue = save_prevvalue;
12093                     continue;
12094                 }
12095             }
12096         }
12097
12098         /* Deal with this element of the class */
12099         if (! SIZE_ONLY) {
12100 #ifndef EBCDIC
12101             cp_list = _add_range_to_invlist(cp_list, prevvalue, value);
12102 #else
12103             UV* this_range = _new_invlist(1);
12104             _append_range_to_invlist(this_range, prevvalue, value);
12105
12106             /* In EBCDIC, the ranges 'A-Z' and 'a-z' are each not contiguous.
12107              * If this range was specified using something like 'i-j', we want
12108              * to include only the 'i' and the 'j', and not anything in
12109              * between, so exclude non-ASCII, non-alphabetics from it.
12110              * However, if the range was specified with something like
12111              * [\x89-\x91] or [\x89-j], all code points within it should be
12112              * included.  literal_endpoint==2 means both ends of the range used
12113              * a literal character, not \x{foo} */
12114             if (literal_endpoint == 2
12115                 && (prevvalue >= 'a' && value <= 'z')
12116                     || (prevvalue >= 'A' && value <= 'Z'))
12117             {
12118                 _invlist_intersection(this_range, PL_ASCII, &this_range, );
12119                 _invlist_intersection(this_range, PL_Alpha, &this_range, );
12120             }
12121             _invlist_union(cp_list, this_range, &cp_list);
12122             literal_endpoint = 0;
12123 #endif
12124         }
12125
12126         range = 0; /* this range (if it was one) is done now */
12127     } /* End of loop through all the text within the brackets */
12128
12129     /* If anything in the class expands to more than one character, we have to
12130      * deal with them by building up a substitute parse string, and recursively
12131      * calling reg() on it, instead of proceeding */
12132     if (multi_char_matches) {
12133         SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP);
12134         I32 cp_count;
12135         STRLEN len;
12136         char *save_end = RExC_end;
12137         char *save_parse = RExC_parse;
12138         bool first_time = TRUE;     /* First multi-char occurrence doesn't get
12139                                        a "|" */
12140         I32 reg_flags;
12141
12142         assert(! invert);
12143 #if 0   /* Have decided not to deal with multi-char folds in inverted classes,
12144            because too confusing */
12145         if (invert) {
12146             sv_catpv(substitute_parse, "(?:");
12147         }
12148 #endif
12149
12150         /* Look at the longest folds first */
12151         for (cp_count = av_len(multi_char_matches); cp_count > 0; cp_count--) {
12152
12153             if (av_exists(multi_char_matches, cp_count)) {
12154                 AV** this_array_ptr;
12155                 SV* this_sequence;
12156
12157                 this_array_ptr = (AV**) av_fetch(multi_char_matches,
12158                                                  cp_count, FALSE);
12159                 while ((this_sequence = av_pop(*this_array_ptr)) !=
12160                                                                 &PL_sv_undef)
12161                 {
12162                     if (! first_time) {
12163                         sv_catpv(substitute_parse, "|");
12164                     }
12165                     first_time = FALSE;
12166
12167                     sv_catpv(substitute_parse, SvPVX(this_sequence));
12168                 }
12169             }
12170         }
12171
12172         /* If the character class contains anything else besides these
12173          * multi-character folds, have to include it in recursive parsing */
12174         if (element_count) {
12175             sv_catpv(substitute_parse, "|[");
12176             sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse);
12177             sv_catpv(substitute_parse, "]");
12178         }
12179
12180         sv_catpv(substitute_parse, ")");
12181 #if 0
12182         if (invert) {
12183             /* This is a way to get the parse to skip forward a whole named
12184              * sequence instead of matching the 2nd character when it fails the
12185              * first */
12186             sv_catpv(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)");
12187         }
12188 #endif
12189
12190         RExC_parse = SvPV(substitute_parse, len);
12191         RExC_end = RExC_parse + len;
12192         RExC_in_multi_char_class = 1;
12193         RExC_emit = (regnode *)orig_emit;
12194
12195         ret = reg(pRExC_state, 1, &reg_flags, depth+1);
12196
12197         *flagp |= reg_flags&(HASWIDTH|SIMPLE|SPSTART|POSTPONED);
12198
12199         RExC_parse = save_parse;
12200         RExC_end = save_end;
12201         RExC_in_multi_char_class = 0;
12202         SvREFCNT_dec_NN(multi_char_matches);
12203         SvREFCNT_dec_NN(listsv);
12204         return ret;
12205     }
12206
12207     /* If the character class contains only a single element, it may be
12208      * optimizable into another node type which is smaller and runs faster.
12209      * Check if this is the case for this class */
12210     if (element_count == 1) {
12211         U8 op = END;
12212         U8 arg = 0;
12213
12214         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class, like \w or
12215                                               [:digit:] or \p{foo} */
12216
12217             /* All named classes are mapped into POSIXish nodes, with its FLAG
12218              * argument giving which class it is */
12219             switch ((I32)namedclass) {
12220                 case ANYOF_UNIPROP:
12221                     break;
12222
12223                 /* These don't depend on the charset modifiers.  They always
12224                  * match under /u rules */
12225                 case ANYOF_NHORIZWS:
12226                 case ANYOF_HORIZWS:
12227                     namedclass = ANYOF_BLANK + namedclass - ANYOF_HORIZWS;
12228                     /* FALLTHROUGH */
12229
12230                 case ANYOF_NVERTWS:
12231                 case ANYOF_VERTWS:
12232                     op = POSIXU;
12233                     goto join_posix;
12234
12235                 /* The actual POSIXish node for all the rest depends on the
12236                  * charset modifier.  The ones in the first set depend only on
12237                  * ASCII or, if available on this platform, locale */
12238                 case ANYOF_ASCII:
12239                 case ANYOF_NASCII:
12240 #ifdef HAS_ISASCII
12241                     op = (LOC) ? POSIXL : POSIXA;
12242 #else
12243                     op = POSIXA;
12244 #endif
12245                     goto join_posix;
12246
12247                 case ANYOF_LOWER:
12248                 case ANYOF_NLOWER:
12249                 case ANYOF_UPPER:
12250                 case ANYOF_NUPPER:
12251                     /* under /a could be alpha */
12252                     if (FOLD) {
12253                         if (ASCII_RESTRICTED) {
12254                             namedclass = ANYOF_ALPHA + (namedclass % 2);
12255                         }
12256                         else if (! LOC) {
12257                             break;
12258                         }
12259                     }
12260                     /* FALLTHROUGH */
12261
12262                 /* The rest have more possibilities depending on the charset.  We
12263                  * take advantage of the enum ordering of the charset modifiers to
12264                  * get the exact node type, */
12265                 default:
12266                     op = POSIXD + get_regex_charset(RExC_flags);
12267                     if (op > POSIXA) { /* /aa is same as /a */
12268                         op = POSIXA;
12269                     }
12270 #ifndef HAS_ISBLANK
12271                     if (op == POSIXL
12272                         && (namedclass == ANYOF_BLANK
12273                             || namedclass == ANYOF_NBLANK))
12274                     {
12275                         op = POSIXA;
12276                     }
12277 #endif
12278
12279                 join_posix:
12280                     /* The odd numbered ones are the complements of the
12281                      * next-lower even number one */
12282                     if (namedclass % 2 == 1) {
12283                         invert = ! invert;
12284                         namedclass--;
12285                     }
12286                     arg = namedclass_to_classnum(namedclass);
12287                     break;
12288             }
12289         }
12290         else if (value == prevvalue) {
12291
12292             /* Here, the class consists of just a single code point */
12293
12294             if (invert) {
12295                 if (! LOC && value == '\n') {
12296                     op = REG_ANY; /* Optimize [^\n] */
12297                     *flagp |= HASWIDTH|SIMPLE;
12298                     RExC_naughty++;
12299                 }
12300             }
12301             else if (value < 256 || UTF) {
12302
12303                 /* Optimize a single value into an EXACTish node, but not if it
12304                  * would require converting the pattern to UTF-8. */
12305                 op = compute_EXACTish(pRExC_state);
12306             }
12307         } /* Otherwise is a range */
12308         else if (! LOC) {   /* locale could vary these */
12309             if (prevvalue == '0') {
12310                 if (value == '9') {
12311                     arg = _CC_DIGIT;
12312                     op = POSIXA;
12313                 }
12314             }
12315         }
12316
12317         /* Here, we have changed <op> away from its initial value iff we found
12318          * an optimization */
12319         if (op != END) {
12320
12321             /* Throw away this ANYOF regnode, and emit the calculated one,
12322              * which should correspond to the beginning, not current, state of
12323              * the parse */
12324             const char * cur_parse = RExC_parse;
12325             RExC_parse = (char *)orig_parse;
12326             if ( SIZE_ONLY) {
12327                 if (! LOC) {
12328
12329                     /* To get locale nodes to not use the full ANYOF size would
12330                      * require moving the code above that writes the portions
12331                      * of it that aren't in other nodes to after this point.
12332                      * e.g.  ANYOF_CLASS_SET */
12333                     RExC_size = orig_size;
12334                 }
12335             }
12336             else {
12337                 RExC_emit = (regnode *)orig_emit;
12338                 if (PL_regkind[op] == POSIXD) {
12339                     if (invert) {
12340                         op += NPOSIXD - POSIXD;
12341                     }
12342                 }
12343             }
12344
12345             ret = reg_node(pRExC_state, op);
12346
12347             if (PL_regkind[op] == POSIXD || PL_regkind[op] == NPOSIXD) {
12348                 if (! SIZE_ONLY) {
12349                     FLAGS(ret) = arg;
12350                 }
12351                 *flagp |= HASWIDTH|SIMPLE;
12352             }
12353             else if (PL_regkind[op] == EXACT) {
12354                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value);
12355             }
12356
12357             RExC_parse = (char *) cur_parse;
12358
12359             SvREFCNT_dec(posixes);
12360             SvREFCNT_dec_NN(listsv);
12361             SvREFCNT_dec(cp_list);
12362             return ret;
12363         }
12364     }
12365
12366     if (SIZE_ONLY)
12367         return ret;
12368     /****** !SIZE_ONLY (Pass 2) AFTER HERE *********/
12369
12370     /* If folding, we calculate all characters that could fold to or from the
12371      * ones already on the list */
12372     if (FOLD && cp_list) {
12373         UV start, end;  /* End points of code point ranges */
12374
12375         SV* fold_intersection = NULL;
12376
12377         /* If the highest code point is within Latin1, we can use the
12378          * compiled-in Alphas list, and not have to go out to disk.  This
12379          * yields two false positives, the masculine and feminine ordinal
12380          * indicators, which are weeded out below using the
12381          * IS_IN_SOME_FOLD_L1() macro */
12382         if (invlist_highest(cp_list) < 256) {
12383             _invlist_intersection(PL_L1Posix_ptrs[_CC_ALPHA], cp_list, &fold_intersection);
12384         }
12385         else {
12386
12387             /* Here, there are non-Latin1 code points, so we will have to go
12388              * fetch the list of all the characters that participate in folds
12389              */
12390             if (! PL_utf8_foldable) {
12391                 SV* swash = swash_init("utf8", "_Perl_Any_Folds",
12392                                        &PL_sv_undef, 1, 0);
12393                 PL_utf8_foldable = _get_swash_invlist(swash);
12394                 SvREFCNT_dec_NN(swash);
12395             }
12396
12397             /* This is a hash that for a particular fold gives all characters
12398              * that are involved in it */
12399             if (! PL_utf8_foldclosures) {
12400
12401                 /* If we were unable to find any folds, then we likely won't be
12402                  * able to find the closures.  So just create an empty list.
12403                  * Folding will effectively be restricted to the non-Unicode
12404                  * rules hard-coded into Perl.  (This case happens legitimately
12405                  * during compilation of Perl itself before the Unicode tables
12406                  * are generated) */
12407                 if (_invlist_len(PL_utf8_foldable) == 0) {
12408                     PL_utf8_foldclosures = newHV();
12409                 }
12410                 else {
12411                     /* If the folds haven't been read in, call a fold function
12412                      * to force that */
12413                     if (! PL_utf8_tofold) {
12414                         U8 dummy[UTF8_MAXBYTES+1];
12415
12416                         /* This string is just a short named one above \xff */
12417                         to_utf8_fold((U8*) HYPHEN_UTF8, dummy, NULL);
12418                         assert(PL_utf8_tofold); /* Verify that worked */
12419                     }
12420                     PL_utf8_foldclosures =
12421                                     _swash_inversion_hash(PL_utf8_tofold);
12422                 }
12423             }
12424
12425             /* Only the characters in this class that participate in folds need
12426              * be checked.  Get the intersection of this class and all the
12427              * possible characters that are foldable.  This can quickly narrow
12428              * down a large class */
12429             _invlist_intersection(PL_utf8_foldable, cp_list,
12430                                   &fold_intersection);
12431         }
12432
12433         /* Now look at the foldable characters in this class individually */
12434         invlist_iterinit(fold_intersection);
12435         while (invlist_iternext(fold_intersection, &start, &end)) {
12436             UV j;
12437
12438             /* Locale folding for Latin1 characters is deferred until runtime */
12439             if (LOC && start < 256) {
12440                 start = 256;
12441             }
12442
12443             /* Look at every character in the range */
12444             for (j = start; j <= end; j++) {
12445
12446                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
12447                 STRLEN foldlen;
12448                 SV** listp;
12449
12450                 if (j < 256) {
12451
12452                     /* We have the latin1 folding rules hard-coded here so that
12453                      * an innocent-looking character class, like /[ks]/i won't
12454                      * have to go out to disk to find the possible matches.
12455                      * XXX It would be better to generate these via regen, in
12456                      * case a new version of the Unicode standard adds new
12457                      * mappings, though that is not really likely, and may be
12458                      * caught by the default: case of the switch below. */
12459
12460                     if (IS_IN_SOME_FOLD_L1(j)) {
12461
12462                         /* ASCII is always matched; non-ASCII is matched only
12463                          * under Unicode rules */
12464                         if (isASCII(j) || AT_LEAST_UNI_SEMANTICS) {
12465                             cp_list =
12466                                 add_cp_to_invlist(cp_list, PL_fold_latin1[j]);
12467                         }
12468                         else {
12469                             depends_list =
12470                              add_cp_to_invlist(depends_list, PL_fold_latin1[j]);
12471                         }
12472                     }
12473
12474                     if (HAS_NONLATIN1_FOLD_CLOSURE(j)
12475                         && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED))
12476                     {
12477                         /* Certain Latin1 characters have matches outside
12478                          * Latin1.  To get here, <j> is one of those
12479                          * characters.   None of these matches is valid for
12480                          * ASCII characters under /aa, which is why the 'if'
12481                          * just above excludes those.  These matches only
12482                          * happen when the target string is utf8.  The code
12483                          * below adds the single fold closures for <j> to the
12484                          * inversion list. */
12485                         switch (j) {
12486                             case 'k':
12487                             case 'K':
12488                                 cp_list =
12489                                     add_cp_to_invlist(cp_list, KELVIN_SIGN);
12490                                 break;
12491                             case 's':
12492                             case 'S':
12493                                 cp_list = add_cp_to_invlist(cp_list,
12494                                                     LATIN_SMALL_LETTER_LONG_S);
12495                                 break;
12496                             case MICRO_SIGN:
12497                                 cp_list = add_cp_to_invlist(cp_list,
12498                                                     GREEK_CAPITAL_LETTER_MU);
12499                                 cp_list = add_cp_to_invlist(cp_list,
12500                                                     GREEK_SMALL_LETTER_MU);
12501                                 break;
12502                             case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
12503                             case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
12504                                 cp_list =
12505                                     add_cp_to_invlist(cp_list, ANGSTROM_SIGN);
12506                                 break;
12507                             case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
12508                                 cp_list = add_cp_to_invlist(cp_list,
12509                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
12510                                 break;
12511                             case LATIN_SMALL_LETTER_SHARP_S:
12512                                 cp_list = add_cp_to_invlist(cp_list,
12513                                                 LATIN_CAPITAL_LETTER_SHARP_S);
12514                                 break;
12515                             case 'F': case 'f':
12516                             case 'I': case 'i':
12517                             case 'L': case 'l':
12518                             case 'T': case 't':
12519                             case 'A': case 'a':
12520                             case 'H': case 'h':
12521                             case 'J': case 'j':
12522                             case 'N': case 'n':
12523                             case 'W': case 'w':
12524                             case 'Y': case 'y':
12525                                 /* These all are targets of multi-character
12526                                  * folds from code points that require UTF8 to
12527                                  * express, so they can't match unless the
12528                                  * target string is in UTF-8, so no action here
12529                                  * is necessary, as regexec.c properly handles
12530                                  * the general case for UTF-8 matching and
12531                                  * multi-char folds */
12532                                 break;
12533                             default:
12534                                 /* Use deprecated warning to increase the
12535                                  * chances of this being output */
12536                                 ckWARN2regdep(RExC_parse, "Perl folding rules are not up-to-date for 0x%"UVXf"; please use the perlbug utility to report;", j);
12537                                 break;
12538                         }
12539                     }
12540                     continue;
12541                 }
12542
12543                 /* Here is an above Latin1 character.  We don't have the rules
12544                  * hard-coded for it.  First, get its fold.  This is the simple
12545                  * fold, as the multi-character folds have been handled earlier
12546                  * and separated out */
12547                 _to_uni_fold_flags(j, foldbuf, &foldlen,
12548                                                ((LOC)
12549                                                ? FOLD_FLAGS_LOCALE
12550                                                : (ASCII_FOLD_RESTRICTED)
12551                                                   ? FOLD_FLAGS_NOMIX_ASCII
12552                                                   : 0));
12553
12554                 /* Single character fold of above Latin1.  Add everything in
12555                  * its fold closure to the list that this node should match.
12556                  * The fold closures data structure is a hash with the keys
12557                  * being the UTF-8 of every character that is folded to, like
12558                  * 'k', and the values each an array of all code points that
12559                  * fold to its key.  e.g. [ 'k', 'K', KELVIN_SIGN ].
12560                  * Multi-character folds are not included */
12561                 if ((listp = hv_fetch(PL_utf8_foldclosures,
12562                                       (char *) foldbuf, foldlen, FALSE)))
12563                 {
12564                     AV* list = (AV*) *listp;
12565                     IV k;
12566                     for (k = 0; k <= av_len(list); k++) {
12567                         SV** c_p = av_fetch(list, k, FALSE);
12568                         UV c;
12569                         if (c_p == NULL) {
12570                             Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
12571                         }
12572                         c = SvUV(*c_p);
12573
12574                         /* /aa doesn't allow folds between ASCII and non-; /l
12575                          * doesn't allow them between above and below 256 */
12576                         if ((ASCII_FOLD_RESTRICTED
12577                                   && (isASCII(c) != isASCII(j)))
12578                             || (LOC && ((c < 256) != (j < 256))))
12579                         {
12580                             continue;
12581                         }
12582
12583                         /* Folds involving non-ascii Latin1 characters
12584                          * under /d are added to a separate list */
12585                         if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS)
12586                         {
12587                             cp_list = add_cp_to_invlist(cp_list, c);
12588                         }
12589                         else {
12590                           depends_list = add_cp_to_invlist(depends_list, c);
12591                         }
12592                     }
12593                 }
12594             }
12595         }
12596         SvREFCNT_dec_NN(fold_intersection);
12597     }
12598
12599     /* And combine the result (if any) with any inversion list from posix
12600      * classes.  The lists are kept separate up to now because we don't want to
12601      * fold the classes (folding of those is automatically handled by the swash
12602      * fetching code) */
12603     if (posixes) {
12604         if (! DEPENDS_SEMANTICS) {
12605             if (cp_list) {
12606                 _invlist_union(cp_list, posixes, &cp_list);
12607                 SvREFCNT_dec_NN(posixes);
12608             }
12609             else {
12610                 cp_list = posixes;
12611             }
12612         }
12613         else {
12614             /* Under /d, we put into a separate list the Latin1 things that
12615              * match only when the target string is utf8 */
12616             SV* nonascii_but_latin1_properties = NULL;
12617             _invlist_intersection(posixes, PL_Latin1,
12618                                   &nonascii_but_latin1_properties);
12619             _invlist_subtract(nonascii_but_latin1_properties, PL_ASCII,
12620                               &nonascii_but_latin1_properties);
12621             _invlist_subtract(posixes, nonascii_but_latin1_properties,
12622                               &posixes);
12623             if (cp_list) {
12624                 _invlist_union(cp_list, posixes, &cp_list);
12625                 SvREFCNT_dec_NN(posixes);
12626             }
12627             else {
12628                 cp_list = posixes;
12629             }
12630
12631             if (depends_list) {
12632                 _invlist_union(depends_list, nonascii_but_latin1_properties,
12633                                &depends_list);
12634                 SvREFCNT_dec_NN(nonascii_but_latin1_properties);
12635             }
12636             else {
12637                 depends_list = nonascii_but_latin1_properties;
12638             }
12639         }
12640     }
12641
12642     /* And combine the result (if any) with any inversion list from properties.
12643      * The lists are kept separate up to now so that we can distinguish the two
12644      * in regards to matching above-Unicode.  A run-time warning is generated
12645      * if a Unicode property is matched against a non-Unicode code point. But,
12646      * we allow user-defined properties to match anything, without any warning,
12647      * and we also suppress the warning if there is a portion of the character
12648      * class that isn't a Unicode property, and which matches above Unicode, \W
12649      * or [\x{110000}] for example.
12650      * (Note that in this case, unlike the Posix one above, there is no
12651      * <depends_list>, because having a Unicode property forces Unicode
12652      * semantics */
12653     if (properties) {
12654         bool warn_super = ! has_user_defined_property;
12655         if (cp_list) {
12656
12657             /* If it matters to the final outcome, see if a non-property
12658              * component of the class matches above Unicode.  If so, the
12659              * warning gets suppressed.  This is true even if just a single
12660              * such code point is specified, as though not strictly correct if
12661              * another such code point is matched against, the fact that they
12662              * are using above-Unicode code points indicates they should know
12663              * the issues involved */
12664             if (warn_super) {
12665                 bool non_prop_matches_above_Unicode =
12666                             runtime_posix_matches_above_Unicode
12667                             | (invlist_highest(cp_list) > PERL_UNICODE_MAX);
12668                 if (invert) {
12669                     non_prop_matches_above_Unicode =
12670                                             !  non_prop_matches_above_Unicode;
12671                 }
12672                 warn_super = ! non_prop_matches_above_Unicode;
12673             }
12674
12675             _invlist_union(properties, cp_list, &cp_list);
12676             SvREFCNT_dec_NN(properties);
12677         }
12678         else {
12679             cp_list = properties;
12680         }
12681
12682         if (warn_super) {
12683             OP(ret) = ANYOF_WARN_SUPER;
12684         }
12685     }
12686
12687     /* Here, we have calculated what code points should be in the character
12688      * class.
12689      *
12690      * Now we can see about various optimizations.  Fold calculation (which we
12691      * did above) needs to take place before inversion.  Otherwise /[^k]/i
12692      * would invert to include K, which under /i would match k, which it
12693      * shouldn't.  Therefore we can't invert folded locale now, as it won't be
12694      * folded until runtime */
12695
12696     /* Optimize inverted simple patterns (e.g. [^a-z]) when everything is known
12697      * at compile time.  Besides not inverting folded locale now, we can't
12698      * invert if there are things such as \w, which aren't known until runtime
12699      * */
12700     if (invert
12701         && ! (LOC && (FOLD || (ANYOF_FLAGS(ret) & ANYOF_CLASS)))
12702         && ! depends_list
12703         && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
12704     {
12705         _invlist_invert(cp_list);
12706
12707         /* Any swash can't be used as-is, because we've inverted things */
12708         if (swash) {
12709             SvREFCNT_dec_NN(swash);
12710             swash = NULL;
12711         }
12712
12713         /* Clear the invert flag since have just done it here */
12714         invert = FALSE;
12715     }
12716
12717     /* If we didn't do folding, it's because some information isn't available
12718      * until runtime; set the run-time fold flag for these.  (We don't have to
12719      * worry about properties folding, as that is taken care of by the swash
12720      * fetching) */
12721     if (FOLD && LOC)
12722     {
12723        ANYOF_FLAGS(ret) |= ANYOF_LOC_FOLD;
12724     }
12725
12726     /* Some character classes are equivalent to other nodes.  Such nodes take
12727      * up less room and generally fewer operations to execute than ANYOF nodes.
12728      * Above, we checked for and optimized into some such equivalents for
12729      * certain common classes that are easy to test.  Getting to this point in
12730      * the code means that the class didn't get optimized there.  Since this
12731      * code is only executed in Pass 2, it is too late to save space--it has
12732      * been allocated in Pass 1, and currently isn't given back.  But turning
12733      * things into an EXACTish node can allow the optimizer to join it to any
12734      * adjacent such nodes.  And if the class is equivalent to things like /./,
12735      * expensive run-time swashes can be avoided.  Now that we have more
12736      * complete information, we can find things necessarily missed by the
12737      * earlier code.  I (khw) am not sure how much to look for here.  It would
12738      * be easy, but perhaps too slow, to check any candidates against all the
12739      * node types they could possibly match using _invlistEQ(). */
12740
12741     if (cp_list
12742         && ! invert
12743         && ! depends_list
12744         && ! (ANYOF_FLAGS(ret) & ANYOF_CLASS)
12745         && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
12746     {
12747         UV start, end;
12748         U8 op = END;  /* The optimzation node-type */
12749         const char * cur_parse= RExC_parse;
12750
12751         invlist_iterinit(cp_list);
12752         if (! invlist_iternext(cp_list, &start, &end)) {
12753
12754             /* Here, the list is empty.  This happens, for example, when a
12755              * Unicode property is the only thing in the character class, and
12756              * it doesn't match anything.  (perluniprops.pod notes such
12757              * properties) */
12758             op = OPFAIL;
12759             *flagp |= HASWIDTH|SIMPLE;
12760         }
12761         else if (start == end) {    /* The range is a single code point */
12762             if (! invlist_iternext(cp_list, &start, &end)
12763
12764                     /* Don't do this optimization if it would require changing
12765                      * the pattern to UTF-8 */
12766                 && (start < 256 || UTF))
12767             {
12768                 /* Here, the list contains a single code point.  Can optimize
12769                  * into an EXACT node */
12770
12771                 value = start;
12772
12773                 if (! FOLD) {
12774                     op = EXACT;
12775                 }
12776                 else if (LOC) {
12777
12778                     /* A locale node under folding with one code point can be
12779                      * an EXACTFL, as its fold won't be calculated until
12780                      * runtime */
12781                     op = EXACTFL;
12782                 }
12783                 else {
12784
12785                     /* Here, we are generally folding, but there is only one
12786                      * code point to match.  If we have to, we use an EXACT
12787                      * node, but it would be better for joining with adjacent
12788                      * nodes in the optimization pass if we used the same
12789                      * EXACTFish node that any such are likely to be.  We can
12790                      * do this iff the code point doesn't participate in any
12791                      * folds.  For example, an EXACTF of a colon is the same as
12792                      * an EXACT one, since nothing folds to or from a colon. */
12793                     if (value < 256) {
12794                         if (IS_IN_SOME_FOLD_L1(value)) {
12795                             op = EXACT;
12796                         }
12797                     }
12798                     else {
12799                         if (! PL_utf8_foldable) {
12800                             SV* swash = swash_init("utf8", "_Perl_Any_Folds",
12801                                                 &PL_sv_undef, 1, 0);
12802                             PL_utf8_foldable = _get_swash_invlist(swash);
12803                             SvREFCNT_dec_NN(swash);
12804                         }
12805                         if (_invlist_contains_cp(PL_utf8_foldable, value)) {
12806                             op = EXACT;
12807                         }
12808                     }
12809
12810                     /* If we haven't found the node type, above, it means we
12811                      * can use the prevailing one */
12812                     if (op == END) {
12813                         op = compute_EXACTish(pRExC_state);
12814                     }
12815                 }
12816             }
12817         }
12818         else if (start == 0) {
12819             if (end == UV_MAX) {
12820                 op = SANY;
12821                 *flagp |= HASWIDTH|SIMPLE;
12822                 RExC_naughty++;
12823             }
12824             else if (end == '\n' - 1
12825                     && invlist_iternext(cp_list, &start, &end)
12826                     && start == '\n' + 1 && end == UV_MAX)
12827             {
12828                 op = REG_ANY;
12829                 *flagp |= HASWIDTH|SIMPLE;
12830                 RExC_naughty++;
12831             }
12832         }
12833         invlist_iterfinish(cp_list);
12834
12835         if (op != END) {
12836             RExC_parse = (char *)orig_parse;
12837             RExC_emit = (regnode *)orig_emit;
12838
12839             ret = reg_node(pRExC_state, op);
12840
12841             RExC_parse = (char *)cur_parse;
12842
12843             if (PL_regkind[op] == EXACT) {
12844                 alloc_maybe_populate_EXACT(pRExC_state, ret, flagp, 0, value);
12845             }
12846
12847             SvREFCNT_dec_NN(cp_list);
12848             SvREFCNT_dec_NN(listsv);
12849             return ret;
12850         }
12851     }
12852
12853     /* Here, <cp_list> contains all the code points we can determine at
12854      * compile time that match under all conditions.  Go through it, and
12855      * for things that belong in the bitmap, put them there, and delete from
12856      * <cp_list>.  While we are at it, see if everything above 255 is in the
12857      * list, and if so, set a flag to speed up execution */
12858     ANYOF_BITMAP_ZERO(ret);
12859     if (cp_list) {
12860
12861         /* This gets set if we actually need to modify things */
12862         bool change_invlist = FALSE;
12863
12864         UV start, end;
12865
12866         /* Start looking through <cp_list> */
12867         invlist_iterinit(cp_list);
12868         while (invlist_iternext(cp_list, &start, &end)) {
12869             UV high;
12870             int i;
12871
12872             if (end == UV_MAX && start <= 256) {
12873                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE_ALL;
12874             }
12875
12876             /* Quit if are above what we should change */
12877             if (start > 255) {
12878                 break;
12879             }
12880
12881             change_invlist = TRUE;
12882
12883             /* Set all the bits in the range, up to the max that we are doing */
12884             high = (end < 255) ? end : 255;
12885             for (i = start; i <= (int) high; i++) {
12886                 if (! ANYOF_BITMAP_TEST(ret, i)) {
12887                     ANYOF_BITMAP_SET(ret, i);
12888                     prevvalue = value;
12889                     value = i;
12890                 }
12891             }
12892         }
12893         invlist_iterfinish(cp_list);
12894
12895         /* Done with loop; remove any code points that are in the bitmap from
12896          * <cp_list> */
12897         if (change_invlist) {
12898             _invlist_subtract(cp_list, PL_Latin1, &cp_list);
12899         }
12900
12901         /* If have completely emptied it, remove it completely */
12902         if (_invlist_len(cp_list) == 0) {
12903             SvREFCNT_dec_NN(cp_list);
12904             cp_list = NULL;
12905         }
12906     }
12907
12908     if (invert) {
12909         ANYOF_FLAGS(ret) |= ANYOF_INVERT;
12910     }
12911
12912     /* Here, the bitmap has been populated with all the Latin1 code points that
12913      * always match.  Can now add to the overall list those that match only
12914      * when the target string is UTF-8 (<depends_list>). */
12915     if (depends_list) {
12916         if (cp_list) {
12917             _invlist_union(cp_list, depends_list, &cp_list);
12918             SvREFCNT_dec_NN(depends_list);
12919         }
12920         else {
12921             cp_list = depends_list;
12922         }
12923     }
12924
12925     /* If there is a swash and more than one element, we can't use the swash in
12926      * the optimization below. */
12927     if (swash && element_count > 1) {
12928         SvREFCNT_dec_NN(swash);
12929         swash = NULL;
12930     }
12931
12932     if (! cp_list
12933         && ! HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
12934     {
12935         ARG_SET(ret, ANYOF_NONBITMAP_EMPTY);
12936         SvREFCNT_dec_NN(listsv);
12937     }
12938     else {
12939         /* av[0] stores the character class description in its textual form:
12940          *       used later (regexec.c:Perl_regclass_swash()) to initialize the
12941          *       appropriate swash, and is also useful for dumping the regnode.
12942          * av[1] if NULL, is a placeholder to later contain the swash computed
12943          *       from av[0].  But if no further computation need be done, the
12944          *       swash is stored there now.
12945          * av[2] stores the cp_list inversion list for use in addition or
12946          *       instead of av[0]; used only if av[1] is NULL
12947          * av[3] is set if any component of the class is from a user-defined
12948          *       property; used only if av[1] is NULL */
12949         AV * const av = newAV();
12950         SV *rv;
12951
12952         av_store(av, 0, (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION)
12953                         ? listsv
12954                         : (SvREFCNT_dec_NN(listsv), &PL_sv_undef));
12955         if (swash) {
12956             av_store(av, 1, swash);
12957             SvREFCNT_dec_NN(cp_list);
12958         }
12959         else {
12960             av_store(av, 1, NULL);
12961             if (cp_list) {
12962                 av_store(av, 2, cp_list);
12963                 av_store(av, 3, newSVuv(has_user_defined_property));
12964             }
12965         }
12966
12967         rv = newRV_noinc(MUTABLE_SV(av));
12968         n = add_data(pRExC_state, 1, "s");
12969         RExC_rxi->data->data[n] = (void*)rv;
12970         ARG_SET(ret, n);
12971     }
12972
12973     *flagp |= HASWIDTH|SIMPLE;
12974     return ret;
12975 }
12976 #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION
12977
12978
12979 /* reg_skipcomment()
12980
12981    Absorbs an /x style # comments from the input stream.
12982    Returns true if there is more text remaining in the stream.
12983    Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
12984    terminates the pattern without including a newline.
12985
12986    Note its the callers responsibility to ensure that we are
12987    actually in /x mode
12988
12989 */
12990
12991 STATIC bool
12992 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
12993 {
12994     bool ended = 0;
12995
12996     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
12997
12998     while (RExC_parse < RExC_end)
12999         if (*RExC_parse++ == '\n') {
13000             ended = 1;
13001             break;
13002         }
13003     if (!ended) {
13004         /* we ran off the end of the pattern without ending
13005            the comment, so we have to add an \n when wrapping */
13006         RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
13007         return 0;
13008     } else
13009         return 1;
13010 }
13011
13012 /* nextchar()
13013
13014    Advances the parse position, and optionally absorbs
13015    "whitespace" from the inputstream.
13016
13017    Without /x "whitespace" means (?#...) style comments only,
13018    with /x this means (?#...) and # comments and whitespace proper.
13019
13020    Returns the RExC_parse point from BEFORE the scan occurs.
13021
13022    This is the /x friendly way of saying RExC_parse++.
13023 */
13024
13025 STATIC char*
13026 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
13027 {
13028     char* const retval = RExC_parse++;
13029
13030     PERL_ARGS_ASSERT_NEXTCHAR;
13031
13032     for (;;) {
13033         if (RExC_end - RExC_parse >= 3
13034             && *RExC_parse == '('
13035             && RExC_parse[1] == '?'
13036             && RExC_parse[2] == '#')
13037         {
13038             while (*RExC_parse != ')') {
13039                 if (RExC_parse == RExC_end)
13040                     FAIL("Sequence (?#... not terminated");
13041                 RExC_parse++;
13042             }
13043             RExC_parse++;
13044             continue;
13045         }
13046         if (RExC_flags & RXf_PMf_EXTENDED) {
13047             if (isSPACE(*RExC_parse)) {
13048                 RExC_parse++;
13049                 continue;
13050             }
13051             else if (*RExC_parse == '#') {
13052                 if ( reg_skipcomment( pRExC_state ) )
13053                     continue;
13054             }
13055         }
13056         return retval;
13057     }
13058 }
13059
13060 /*
13061 - reg_node - emit a node
13062 */
13063 STATIC regnode *                        /* Location. */
13064 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
13065 {
13066     dVAR;
13067     regnode *ptr;
13068     regnode * const ret = RExC_emit;
13069     GET_RE_DEBUG_FLAGS_DECL;
13070
13071     PERL_ARGS_ASSERT_REG_NODE;
13072
13073     if (SIZE_ONLY) {
13074         SIZE_ALIGN(RExC_size);
13075         RExC_size += 1;
13076         return(ret);
13077     }
13078     if (RExC_emit >= RExC_emit_bound)
13079         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
13080                    op, RExC_emit, RExC_emit_bound);
13081
13082     NODE_ALIGN_FILL(ret);
13083     ptr = ret;
13084     FILL_ADVANCE_NODE(ptr, op);
13085 #ifdef RE_TRACK_PATTERN_OFFSETS
13086     if (RExC_offsets) {         /* MJD */
13087         MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n", 
13088               "reg_node", __LINE__, 
13089               PL_reg_name[op],
13090               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] 
13091                 ? "Overwriting end of array!\n" : "OK",
13092               (UV)(RExC_emit - RExC_emit_start),
13093               (UV)(RExC_parse - RExC_start),
13094               (UV)RExC_offsets[0])); 
13095         Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
13096     }
13097 #endif
13098     RExC_emit = ptr;
13099     return(ret);
13100 }
13101
13102 /*
13103 - reganode - emit a node with an argument
13104 */
13105 STATIC regnode *                        /* Location. */
13106 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
13107 {
13108     dVAR;
13109     regnode *ptr;
13110     regnode * const ret = RExC_emit;
13111     GET_RE_DEBUG_FLAGS_DECL;
13112
13113     PERL_ARGS_ASSERT_REGANODE;
13114
13115     if (SIZE_ONLY) {
13116         SIZE_ALIGN(RExC_size);
13117         RExC_size += 2;
13118         /* 
13119            We can't do this:
13120            
13121            assert(2==regarglen[op]+1); 
13122
13123            Anything larger than this has to allocate the extra amount.
13124            If we changed this to be:
13125            
13126            RExC_size += (1 + regarglen[op]);
13127            
13128            then it wouldn't matter. Its not clear what side effect
13129            might come from that so its not done so far.
13130            -- dmq
13131         */
13132         return(ret);
13133     }
13134     if (RExC_emit >= RExC_emit_bound)
13135         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
13136                    op, RExC_emit, RExC_emit_bound);
13137
13138     NODE_ALIGN_FILL(ret);
13139     ptr = ret;
13140     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
13141 #ifdef RE_TRACK_PATTERN_OFFSETS
13142     if (RExC_offsets) {         /* MJD */
13143         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
13144               "reganode",
13145               __LINE__,
13146               PL_reg_name[op],
13147               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ? 
13148               "Overwriting end of array!\n" : "OK",
13149               (UV)(RExC_emit - RExC_emit_start),
13150               (UV)(RExC_parse - RExC_start),
13151               (UV)RExC_offsets[0])); 
13152         Set_Cur_Node_Offset;
13153     }
13154 #endif            
13155     RExC_emit = ptr;
13156     return(ret);
13157 }
13158
13159 /*
13160 - reguni - emit (if appropriate) a Unicode character
13161 */
13162 STATIC STRLEN
13163 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
13164 {
13165     dVAR;
13166
13167     PERL_ARGS_ASSERT_REGUNI;
13168
13169     return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
13170 }
13171
13172 /*
13173 - reginsert - insert an operator in front of already-emitted operand
13174 *
13175 * Means relocating the operand.
13176 */
13177 STATIC void
13178 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
13179 {
13180     dVAR;
13181     regnode *src;
13182     regnode *dst;
13183     regnode *place;
13184     const int offset = regarglen[(U8)op];
13185     const int size = NODE_STEP_REGNODE + offset;
13186     GET_RE_DEBUG_FLAGS_DECL;
13187
13188     PERL_ARGS_ASSERT_REGINSERT;
13189     PERL_UNUSED_ARG(depth);
13190 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
13191     DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
13192     if (SIZE_ONLY) {
13193         RExC_size += size;
13194         return;
13195     }
13196
13197     src = RExC_emit;
13198     RExC_emit += size;
13199     dst = RExC_emit;
13200     if (RExC_open_parens) {
13201         int paren;
13202         /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
13203         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
13204             if ( RExC_open_parens[paren] >= opnd ) {
13205                 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
13206                 RExC_open_parens[paren] += size;
13207             } else {
13208                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
13209             }
13210             if ( RExC_close_parens[paren] >= opnd ) {
13211                 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
13212                 RExC_close_parens[paren] += size;
13213             } else {
13214                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
13215             }
13216         }
13217     }
13218
13219     while (src > opnd) {
13220         StructCopy(--src, --dst, regnode);
13221 #ifdef RE_TRACK_PATTERN_OFFSETS
13222         if (RExC_offsets) {     /* MJD 20010112 */
13223             MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
13224                   "reg_insert",
13225                   __LINE__,
13226                   PL_reg_name[op],
13227                   (UV)(dst - RExC_emit_start) > RExC_offsets[0] 
13228                     ? "Overwriting end of array!\n" : "OK",
13229                   (UV)(src - RExC_emit_start),
13230                   (UV)(dst - RExC_emit_start),
13231                   (UV)RExC_offsets[0])); 
13232             Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
13233             Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
13234         }
13235 #endif
13236     }
13237     
13238
13239     place = opnd;               /* Op node, where operand used to be. */
13240 #ifdef RE_TRACK_PATTERN_OFFSETS
13241     if (RExC_offsets) {         /* MJD */
13242         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
13243               "reginsert",
13244               __LINE__,
13245               PL_reg_name[op],
13246               (UV)(place - RExC_emit_start) > RExC_offsets[0] 
13247               ? "Overwriting end of array!\n" : "OK",
13248               (UV)(place - RExC_emit_start),
13249               (UV)(RExC_parse - RExC_start),
13250               (UV)RExC_offsets[0]));
13251         Set_Node_Offset(place, RExC_parse);
13252         Set_Node_Length(place, 1);
13253     }
13254 #endif    
13255     src = NEXTOPER(place);
13256     FILL_ADVANCE_NODE(place, op);
13257     Zero(src, offset, regnode);
13258 }
13259
13260 /*
13261 - regtail - set the next-pointer at the end of a node chain of p to val.
13262 - SEE ALSO: regtail_study
13263 */
13264 /* TODO: All three parms should be const */
13265 STATIC void
13266 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
13267 {
13268     dVAR;
13269     regnode *scan;
13270     GET_RE_DEBUG_FLAGS_DECL;
13271
13272     PERL_ARGS_ASSERT_REGTAIL;
13273 #ifndef DEBUGGING
13274     PERL_UNUSED_ARG(depth);
13275 #endif
13276
13277     if (SIZE_ONLY)
13278         return;
13279
13280     /* Find last node. */
13281     scan = p;
13282     for (;;) {
13283         regnode * const temp = regnext(scan);
13284         DEBUG_PARSE_r({
13285             SV * const mysv=sv_newmortal();
13286             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
13287             regprop(RExC_rx, mysv, scan);
13288             PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
13289                 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
13290                     (temp == NULL ? "->" : ""),
13291                     (temp == NULL ? PL_reg_name[OP(val)] : "")
13292             );
13293         });
13294         if (temp == NULL)
13295             break;
13296         scan = temp;
13297     }
13298
13299     if (reg_off_by_arg[OP(scan)]) {
13300         ARG_SET(scan, val - scan);
13301     }
13302     else {
13303         NEXT_OFF(scan) = val - scan;
13304     }
13305 }
13306
13307 #ifdef DEBUGGING
13308 /*
13309 - regtail_study - set the next-pointer at the end of a node chain of p to val.
13310 - Look for optimizable sequences at the same time.
13311 - currently only looks for EXACT chains.
13312
13313 This is experimental code. The idea is to use this routine to perform 
13314 in place optimizations on branches and groups as they are constructed,
13315 with the long term intention of removing optimization from study_chunk so
13316 that it is purely analytical.
13317
13318 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
13319 to control which is which.
13320
13321 */
13322 /* TODO: All four parms should be const */
13323
13324 STATIC U8
13325 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
13326 {
13327     dVAR;
13328     regnode *scan;
13329     U8 exact = PSEUDO;
13330 #ifdef EXPERIMENTAL_INPLACESCAN
13331     I32 min = 0;
13332 #endif
13333     GET_RE_DEBUG_FLAGS_DECL;
13334
13335     PERL_ARGS_ASSERT_REGTAIL_STUDY;
13336
13337
13338     if (SIZE_ONLY)
13339         return exact;
13340
13341     /* Find last node. */
13342
13343     scan = p;
13344     for (;;) {
13345         regnode * const temp = regnext(scan);
13346 #ifdef EXPERIMENTAL_INPLACESCAN
13347         if (PL_regkind[OP(scan)] == EXACT) {
13348             bool has_exactf_sharp_s;    /* Unexamined in this routine */
13349             if (join_exact(pRExC_state,scan,&min, &has_exactf_sharp_s, 1,val,depth+1))
13350                 return EXACT;
13351         }
13352 #endif
13353         if ( exact ) {
13354             switch (OP(scan)) {
13355                 case EXACT:
13356                 case EXACTF:
13357                 case EXACTFA:
13358                 case EXACTFU:
13359                 case EXACTFU_SS:
13360                 case EXACTFU_TRICKYFOLD:
13361                 case EXACTFL:
13362                         if( exact == PSEUDO )
13363                             exact= OP(scan);
13364                         else if ( exact != OP(scan) )
13365                             exact= 0;
13366                 case NOTHING:
13367                     break;
13368                 default:
13369                     exact= 0;
13370             }
13371         }
13372         DEBUG_PARSE_r({
13373             SV * const mysv=sv_newmortal();
13374             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
13375             regprop(RExC_rx, mysv, scan);
13376             PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
13377                 SvPV_nolen_const(mysv),
13378                 REG_NODE_NUM(scan),
13379                 PL_reg_name[exact]);
13380         });
13381         if (temp == NULL)
13382             break;
13383         scan = temp;
13384     }
13385     DEBUG_PARSE_r({
13386         SV * const mysv_val=sv_newmortal();
13387         DEBUG_PARSE_MSG("");
13388         regprop(RExC_rx, mysv_val, val);
13389         PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
13390                       SvPV_nolen_const(mysv_val),
13391                       (IV)REG_NODE_NUM(val),
13392                       (IV)(val - scan)
13393         );
13394     });
13395     if (reg_off_by_arg[OP(scan)]) {
13396         ARG_SET(scan, val - scan);
13397     }
13398     else {
13399         NEXT_OFF(scan) = val - scan;
13400     }
13401
13402     return exact;
13403 }
13404 #endif
13405
13406 /*
13407  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
13408  */
13409 #ifdef DEBUGGING
13410 static void 
13411 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
13412 {
13413     int bit;
13414     int set=0;
13415     regex_charset cs;
13416
13417     for (bit=0; bit<32; bit++) {
13418         if (flags & (1<<bit)) {
13419             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
13420                 continue;
13421             }
13422             if (!set++ && lead) 
13423                 PerlIO_printf(Perl_debug_log, "%s",lead);
13424             PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
13425         }               
13426     }      
13427     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
13428             if (!set++ && lead) {
13429                 PerlIO_printf(Perl_debug_log, "%s",lead);
13430             }
13431             switch (cs) {
13432                 case REGEX_UNICODE_CHARSET:
13433                     PerlIO_printf(Perl_debug_log, "UNICODE");
13434                     break;
13435                 case REGEX_LOCALE_CHARSET:
13436                     PerlIO_printf(Perl_debug_log, "LOCALE");
13437                     break;
13438                 case REGEX_ASCII_RESTRICTED_CHARSET:
13439                     PerlIO_printf(Perl_debug_log, "ASCII-RESTRICTED");
13440                     break;
13441                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
13442                     PerlIO_printf(Perl_debug_log, "ASCII-MORE_RESTRICTED");
13443                     break;
13444                 default:
13445                     PerlIO_printf(Perl_debug_log, "UNKNOWN CHARACTER SET");
13446                     break;
13447             }
13448     }
13449     if (lead)  {
13450         if (set) 
13451             PerlIO_printf(Perl_debug_log, "\n");
13452         else 
13453             PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
13454     }            
13455 }   
13456 #endif
13457
13458 void
13459 Perl_regdump(pTHX_ const regexp *r)
13460 {
13461 #ifdef DEBUGGING
13462     dVAR;
13463     SV * const sv = sv_newmortal();
13464     SV *dsv= sv_newmortal();
13465     RXi_GET_DECL(r,ri);
13466     GET_RE_DEBUG_FLAGS_DECL;
13467
13468     PERL_ARGS_ASSERT_REGDUMP;
13469
13470     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
13471
13472     /* Header fields of interest. */
13473     if (r->anchored_substr) {
13474         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr), 
13475             RE_SV_DUMPLEN(r->anchored_substr), 30);
13476         PerlIO_printf(Perl_debug_log,
13477                       "anchored %s%s at %"IVdf" ",
13478                       s, RE_SV_TAIL(r->anchored_substr),
13479                       (IV)r->anchored_offset);
13480     } else if (r->anchored_utf8) {
13481         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8), 
13482             RE_SV_DUMPLEN(r->anchored_utf8), 30);
13483         PerlIO_printf(Perl_debug_log,
13484                       "anchored utf8 %s%s at %"IVdf" ",
13485                       s, RE_SV_TAIL(r->anchored_utf8),
13486                       (IV)r->anchored_offset);
13487     }                 
13488     if (r->float_substr) {
13489         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr), 
13490             RE_SV_DUMPLEN(r->float_substr), 30);
13491         PerlIO_printf(Perl_debug_log,
13492                       "floating %s%s at %"IVdf"..%"UVuf" ",
13493                       s, RE_SV_TAIL(r->float_substr),
13494                       (IV)r->float_min_offset, (UV)r->float_max_offset);
13495     } else if (r->float_utf8) {
13496         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8), 
13497             RE_SV_DUMPLEN(r->float_utf8), 30);
13498         PerlIO_printf(Perl_debug_log,
13499                       "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
13500                       s, RE_SV_TAIL(r->float_utf8),
13501                       (IV)r->float_min_offset, (UV)r->float_max_offset);
13502     }
13503     if (r->check_substr || r->check_utf8)
13504         PerlIO_printf(Perl_debug_log,
13505                       (const char *)
13506                       (r->check_substr == r->float_substr
13507                        && r->check_utf8 == r->float_utf8
13508                        ? "(checking floating" : "(checking anchored"));
13509     if (r->extflags & RXf_NOSCAN)
13510         PerlIO_printf(Perl_debug_log, " noscan");
13511     if (r->extflags & RXf_CHECK_ALL)
13512         PerlIO_printf(Perl_debug_log, " isall");
13513     if (r->check_substr || r->check_utf8)
13514         PerlIO_printf(Perl_debug_log, ") ");
13515
13516     if (ri->regstclass) {
13517         regprop(r, sv, ri->regstclass);
13518         PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
13519     }
13520     if (r->extflags & RXf_ANCH) {
13521         PerlIO_printf(Perl_debug_log, "anchored");
13522         if (r->extflags & RXf_ANCH_BOL)
13523             PerlIO_printf(Perl_debug_log, "(BOL)");
13524         if (r->extflags & RXf_ANCH_MBOL)
13525             PerlIO_printf(Perl_debug_log, "(MBOL)");
13526         if (r->extflags & RXf_ANCH_SBOL)
13527             PerlIO_printf(Perl_debug_log, "(SBOL)");
13528         if (r->extflags & RXf_ANCH_GPOS)
13529             PerlIO_printf(Perl_debug_log, "(GPOS)");
13530         PerlIO_putc(Perl_debug_log, ' ');
13531     }
13532     if (r->extflags & RXf_GPOS_SEEN)
13533         PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
13534     if (r->intflags & PREGf_SKIP)
13535         PerlIO_printf(Perl_debug_log, "plus ");
13536     if (r->intflags & PREGf_IMPLICIT)
13537         PerlIO_printf(Perl_debug_log, "implicit ");
13538     PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
13539     if (r->extflags & RXf_EVAL_SEEN)
13540         PerlIO_printf(Perl_debug_log, "with eval ");
13541     PerlIO_printf(Perl_debug_log, "\n");
13542     DEBUG_FLAGS_r(regdump_extflags("r->extflags: ",r->extflags));            
13543 #else
13544     PERL_ARGS_ASSERT_REGDUMP;
13545     PERL_UNUSED_CONTEXT;
13546     PERL_UNUSED_ARG(r);
13547 #endif  /* DEBUGGING */
13548 }
13549
13550 /*
13551 - regprop - printable representation of opcode
13552 */
13553 #define EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags) \
13554 STMT_START { \
13555         if (do_sep) {                           \
13556             Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]); \
13557             if (flags & ANYOF_INVERT)           \
13558                 /*make sure the invert info is in each */ \
13559                 sv_catpvs(sv, "^");             \
13560             do_sep = 0;                         \
13561         }                                       \
13562 } STMT_END
13563
13564 void
13565 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
13566 {
13567 #ifdef DEBUGGING
13568     dVAR;
13569     int k;
13570
13571     /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
13572     static const char * const anyofs[] = {
13573 #if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 || _CC_LOWER != 3 \
13574     || _CC_UPPER != 4 || _CC_PUNCT != 5 || _CC_PRINT != 6 \
13575     || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 || _CC_SPACE != 9 \
13576     || _CC_BLANK != 10 || _CC_XDIGIT != 11 || _CC_PSXSPC != 12 \
13577     || _CC_CNTRL != 13 || _CC_ASCII != 14 || _CC_VERTSPACE != 15
13578   #error Need to adjust order of anyofs[]
13579 #endif
13580         "[\\w]",
13581         "[\\W]",
13582         "[\\d]",
13583         "[\\D]",
13584         "[:alpha:]",
13585         "[:^alpha:]",
13586         "[:lower:]",
13587         "[:^lower:]",
13588         "[:upper:]",
13589         "[:^upper:]",
13590         "[:punct:]",
13591         "[:^punct:]",
13592         "[:print:]",
13593         "[:^print:]",
13594         "[:alnum:]",
13595         "[:^alnum:]",
13596         "[:graph:]",
13597         "[:^graph:]",
13598         "[\\s]",
13599         "[\\S]",
13600         "[:blank:]",
13601         "[:^blank:]",
13602         "[:xdigit:]",
13603         "[:^xdigit:]",
13604         "[:space:]",
13605         "[:^space:]",
13606         "[:cntrl:]",
13607         "[:^cntrl:]",
13608         "[:ascii:]",
13609         "[:^ascii:]",
13610         "[\\v]",
13611         "[\\V]"
13612     };
13613     RXi_GET_DECL(prog,progi);
13614     GET_RE_DEBUG_FLAGS_DECL;
13615     
13616     PERL_ARGS_ASSERT_REGPROP;
13617
13618     sv_setpvs(sv, "");
13619
13620     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
13621         /* It would be nice to FAIL() here, but this may be called from
13622            regexec.c, and it would be hard to supply pRExC_state. */
13623         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
13624     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
13625
13626     k = PL_regkind[OP(o)];
13627
13628     if (k == EXACT) {
13629         sv_catpvs(sv, " ");
13630         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT) 
13631          * is a crude hack but it may be the best for now since 
13632          * we have no flag "this EXACTish node was UTF-8" 
13633          * --jhi */
13634         pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
13635                   PERL_PV_ESCAPE_UNI_DETECT |
13636                   PERL_PV_ESCAPE_NONASCII   |
13637                   PERL_PV_PRETTY_ELLIPSES   |
13638                   PERL_PV_PRETTY_LTGT       |
13639                   PERL_PV_PRETTY_NOCLEAR
13640                   );
13641     } else if (k == TRIE) {
13642         /* print the details of the trie in dumpuntil instead, as
13643          * progi->data isn't available here */
13644         const char op = OP(o);
13645         const U32 n = ARG(o);
13646         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
13647                (reg_ac_data *)progi->data->data[n] :
13648                NULL;
13649         const reg_trie_data * const trie
13650             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
13651         
13652         Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
13653         DEBUG_TRIE_COMPILE_r(
13654             Perl_sv_catpvf(aTHX_ sv,
13655                 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
13656                 (UV)trie->startstate,
13657                 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
13658                 (UV)trie->wordcount,
13659                 (UV)trie->minlen,
13660                 (UV)trie->maxlen,
13661                 (UV)TRIE_CHARCOUNT(trie),
13662                 (UV)trie->uniquecharcount
13663             )
13664         );
13665         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
13666             int i;
13667             int rangestart = -1;
13668             U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
13669             sv_catpvs(sv, "[");
13670             for (i = 0; i <= 256; i++) {
13671                 if (i < 256 && BITMAP_TEST(bitmap,i)) {
13672                     if (rangestart == -1)
13673                         rangestart = i;
13674                 } else if (rangestart != -1) {
13675                     if (i <= rangestart + 3)
13676                         for (; rangestart < i; rangestart++)
13677                             put_byte(sv, rangestart);
13678                     else {
13679                         put_byte(sv, rangestart);
13680                         sv_catpvs(sv, "-");
13681                         put_byte(sv, i - 1);
13682                     }
13683                     rangestart = -1;
13684                 }
13685             }
13686             sv_catpvs(sv, "]");
13687         } 
13688          
13689     } else if (k == CURLY) {
13690         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
13691             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
13692         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
13693     }
13694     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
13695         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
13696     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
13697         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
13698         if ( RXp_PAREN_NAMES(prog) ) {
13699             if ( k != REF || (OP(o) < NREF)) {
13700                 AV *list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
13701                 SV **name= av_fetch(list, ARG(o), 0 );
13702                 if (name)
13703                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
13704             }       
13705             else {
13706                 AV *list= MUTABLE_AV(progi->data->data[ progi->name_list_idx ]);
13707                 SV *sv_dat= MUTABLE_SV(progi->data->data[ ARG( o ) ]);
13708                 I32 *nums=(I32*)SvPVX(sv_dat);
13709                 SV **name= av_fetch(list, nums[0], 0 );
13710                 I32 n;
13711                 if (name) {
13712                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
13713                         Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
13714                                     (n ? "," : ""), (IV)nums[n]);
13715                     }
13716                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
13717                 }
13718             }
13719         }            
13720     } else if (k == GOSUB) 
13721         Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
13722     else if (k == VERB) {
13723         if (!o->flags) 
13724             Perl_sv_catpvf(aTHX_ sv, ":%"SVf, 
13725                            SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
13726     } else if (k == LOGICAL)
13727         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
13728     else if (k == ANYOF) {
13729         int i, rangestart = -1;
13730         const U8 flags = ANYOF_FLAGS(o);
13731         int do_sep = 0;
13732
13733
13734         if (flags & ANYOF_LOCALE)
13735             sv_catpvs(sv, "{loc}");
13736         if (flags & ANYOF_LOC_FOLD)
13737             sv_catpvs(sv, "{i}");
13738         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
13739         if (flags & ANYOF_INVERT)
13740             sv_catpvs(sv, "^");
13741
13742         /* output what the standard cp 0-255 bitmap matches */
13743         for (i = 0; i <= 256; i++) {
13744             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
13745                 if (rangestart == -1)
13746                     rangestart = i;
13747             } else if (rangestart != -1) {
13748                 if (i <= rangestart + 3)
13749                     for (; rangestart < i; rangestart++)
13750                         put_byte(sv, rangestart);
13751                 else {
13752                     put_byte(sv, rangestart);
13753                     sv_catpvs(sv, "-");
13754                     put_byte(sv, i - 1);
13755                 }
13756                 do_sep = 1;
13757                 rangestart = -1;
13758             }
13759         }
13760         
13761         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
13762         /* output any special charclass tests (used entirely under use locale) */
13763         if (ANYOF_CLASS_TEST_ANY_SET(o))
13764             for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
13765                 if (ANYOF_CLASS_TEST(o,i)) {
13766                     sv_catpv(sv, anyofs[i]);
13767                     do_sep = 1;
13768                 }
13769         
13770         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
13771         
13772         if (flags & ANYOF_NON_UTF8_LATIN1_ALL) {
13773             sv_catpvs(sv, "{non-utf8-latin1-all}");
13774         }
13775
13776         /* output information about the unicode matching */
13777         if (flags & ANYOF_UNICODE_ALL)
13778             sv_catpvs(sv, "{unicode_all}");
13779         else if (ANYOF_NONBITMAP(o))
13780             sv_catpvs(sv, "{unicode}");
13781         if (flags & ANYOF_NONBITMAP_NON_UTF8)
13782             sv_catpvs(sv, "{outside bitmap}");
13783
13784         if (ANYOF_NONBITMAP(o)) {
13785             SV *lv; /* Set if there is something outside the bit map */
13786             SV * const sw = regclass_swash(prog, o, FALSE, &lv, NULL);
13787             bool byte_output = FALSE;   /* If something in the bitmap has been
13788                                            output */
13789
13790             if (lv && lv != &PL_sv_undef) {
13791                 if (sw) {
13792                     U8 s[UTF8_MAXBYTES_CASE+1];
13793
13794                     for (i = 0; i <= 256; i++) { /* Look at chars in bitmap */
13795                         uvchr_to_utf8(s, i);
13796
13797                         if (i < 256
13798                             && ! ANYOF_BITMAP_TEST(o, i)    /* Don't duplicate
13799                                                                things already
13800                                                                output as part
13801                                                                of the bitmap */
13802                             && swash_fetch(sw, s, TRUE))
13803                         {
13804                             if (rangestart == -1)
13805                                 rangestart = i;
13806                         } else if (rangestart != -1) {
13807                             byte_output = TRUE;
13808                             if (i <= rangestart + 3)
13809                                 for (; rangestart < i; rangestart++) {
13810                                     put_byte(sv, rangestart);
13811                                 }
13812                             else {
13813                                 put_byte(sv, rangestart);
13814                                 sv_catpvs(sv, "-");
13815                                 put_byte(sv, i-1);
13816                             }
13817                             rangestart = -1;
13818                         }
13819                     }
13820                 }
13821
13822                 {
13823                     char *s = savesvpv(lv);
13824                     char * const origs = s;
13825
13826                     while (*s && *s != '\n')
13827                         s++;
13828
13829                     if (*s == '\n') {
13830                         const char * const t = ++s;
13831
13832                         if (byte_output) {
13833                             sv_catpvs(sv, " ");
13834                         }
13835
13836                         while (*s) {
13837                             if (*s == '\n') {
13838
13839                                 /* Truncate very long output */
13840                                 if (s - origs > 256) {
13841                                     Perl_sv_catpvf(aTHX_ sv,
13842                                                    "%.*s...",
13843                                                    (int) (s - origs - 1),
13844                                                    t);
13845                                     goto out_dump;
13846                                 }
13847                                 *s = ' ';
13848                             }
13849                             else if (*s == '\t') {
13850                                 *s = '-';
13851                             }
13852                             s++;
13853                         }
13854                         if (s[-1] == ' ')
13855                             s[-1] = 0;
13856
13857                         sv_catpv(sv, t);
13858                     }
13859
13860                 out_dump:
13861
13862                     Safefree(origs);
13863                 }
13864                 SvREFCNT_dec_NN(lv);
13865             }
13866         }
13867
13868         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
13869     }
13870     else if (k == POSIXD || k == NPOSIXD) {
13871         U8 index = FLAGS(o) * 2;
13872         if (index > (sizeof(anyofs) / sizeof(anyofs[0]))) {
13873             Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index);
13874         }
13875         else {
13876             sv_catpv(sv, anyofs[index]);
13877         }
13878     }
13879     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
13880         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
13881 #else
13882     PERL_UNUSED_CONTEXT;
13883     PERL_UNUSED_ARG(sv);
13884     PERL_UNUSED_ARG(o);
13885     PERL_UNUSED_ARG(prog);
13886 #endif  /* DEBUGGING */
13887 }
13888
13889 SV *
13890 Perl_re_intuit_string(pTHX_ REGEXP * const r)
13891 {                               /* Assume that RE_INTUIT is set */
13892     dVAR;
13893     struct regexp *const prog = ReANY(r);
13894     GET_RE_DEBUG_FLAGS_DECL;
13895
13896     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
13897     PERL_UNUSED_CONTEXT;
13898
13899     DEBUG_COMPILE_r(
13900         {
13901             const char * const s = SvPV_nolen_const(prog->check_substr
13902                       ? prog->check_substr : prog->check_utf8);
13903
13904             if (!PL_colorset) reginitcolors();
13905             PerlIO_printf(Perl_debug_log,
13906                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
13907                       PL_colors[4],
13908                       prog->check_substr ? "" : "utf8 ",
13909                       PL_colors[5],PL_colors[0],
13910                       s,
13911                       PL_colors[1],
13912                       (strlen(s) > 60 ? "..." : ""));
13913         } );
13914
13915     return prog->check_substr ? prog->check_substr : prog->check_utf8;
13916 }
13917
13918 /* 
13919    pregfree() 
13920    
13921    handles refcounting and freeing the perl core regexp structure. When 
13922    it is necessary to actually free the structure the first thing it 
13923    does is call the 'free' method of the regexp_engine associated to
13924    the regexp, allowing the handling of the void *pprivate; member 
13925    first. (This routine is not overridable by extensions, which is why 
13926    the extensions free is called first.)
13927    
13928    See regdupe and regdupe_internal if you change anything here. 
13929 */
13930 #ifndef PERL_IN_XSUB_RE
13931 void
13932 Perl_pregfree(pTHX_ REGEXP *r)
13933 {
13934     SvREFCNT_dec(r);
13935 }
13936
13937 void
13938 Perl_pregfree2(pTHX_ REGEXP *rx)
13939 {
13940     dVAR;
13941     struct regexp *const r = ReANY(rx);
13942     GET_RE_DEBUG_FLAGS_DECL;
13943
13944     PERL_ARGS_ASSERT_PREGFREE2;
13945
13946     if (r->mother_re) {
13947         ReREFCNT_dec(r->mother_re);
13948     } else {
13949         CALLREGFREE_PVT(rx); /* free the private data */
13950         SvREFCNT_dec(RXp_PAREN_NAMES(r));
13951         Safefree(r->xpv_len_u.xpvlenu_pv);
13952     }        
13953     if (r->substrs) {
13954         SvREFCNT_dec(r->anchored_substr);
13955         SvREFCNT_dec(r->anchored_utf8);
13956         SvREFCNT_dec(r->float_substr);
13957         SvREFCNT_dec(r->float_utf8);
13958         Safefree(r->substrs);
13959     }
13960     RX_MATCH_COPY_FREE(rx);
13961 #ifdef PERL_ANY_COW
13962     SvREFCNT_dec(r->saved_copy);
13963 #endif
13964     Safefree(r->offs);
13965     SvREFCNT_dec(r->qr_anoncv);
13966     rx->sv_u.svu_rx = 0;
13967 }
13968
13969 /*  reg_temp_copy()
13970     
13971     This is a hacky workaround to the structural issue of match results
13972     being stored in the regexp structure which is in turn stored in
13973     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
13974     could be PL_curpm in multiple contexts, and could require multiple
13975     result sets being associated with the pattern simultaneously, such
13976     as when doing a recursive match with (??{$qr})
13977     
13978     The solution is to make a lightweight copy of the regexp structure 
13979     when a qr// is returned from the code executed by (??{$qr}) this
13980     lightweight copy doesn't actually own any of its data except for
13981     the starp/end and the actual regexp structure itself. 
13982     
13983 */    
13984     
13985     
13986 REGEXP *
13987 Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
13988 {
13989     struct regexp *ret;
13990     struct regexp *const r = ReANY(rx);
13991     const bool islv = ret_x && SvTYPE(ret_x) == SVt_PVLV;
13992
13993     PERL_ARGS_ASSERT_REG_TEMP_COPY;
13994
13995     if (!ret_x)
13996         ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
13997     else {
13998         SvOK_off((SV *)ret_x);
13999         if (islv) {
14000             /* For PVLVs, SvANY points to the xpvlv body while sv_u points
14001                to the regexp.  (For SVt_REGEXPs, sv_upgrade has already
14002                made both spots point to the same regexp body.) */
14003             REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP);
14004             assert(!SvPVX(ret_x));
14005             ret_x->sv_u.svu_rx = temp->sv_any;
14006             temp->sv_any = NULL;
14007             SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL;
14008             SvREFCNT_dec_NN(temp);
14009             /* SvCUR still resides in the xpvlv struct, so the regexp copy-
14010                ing below will not set it. */
14011             SvCUR_set(ret_x, SvCUR(rx));
14012         }
14013     }
14014     /* This ensures that SvTHINKFIRST(sv) is true, and hence that
14015        sv_force_normal(sv) is called.  */
14016     SvFAKE_on(ret_x);
14017     ret = ReANY(ret_x);
14018     
14019     SvFLAGS(ret_x) |= SvUTF8(rx);
14020     /* We share the same string buffer as the original regexp, on which we
14021        hold a reference count, incremented when mother_re is set below.
14022        The string pointer is copied here, being part of the regexp struct.
14023      */
14024     memcpy(&(ret->xpv_cur), &(r->xpv_cur),
14025            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
14026     if (r->offs) {
14027         const I32 npar = r->nparens+1;
14028         Newx(ret->offs, npar, regexp_paren_pair);
14029         Copy(r->offs, ret->offs, npar, regexp_paren_pair);
14030     }
14031     if (r->substrs) {
14032         Newx(ret->substrs, 1, struct reg_substr_data);
14033         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
14034
14035         SvREFCNT_inc_void(ret->anchored_substr);
14036         SvREFCNT_inc_void(ret->anchored_utf8);
14037         SvREFCNT_inc_void(ret->float_substr);
14038         SvREFCNT_inc_void(ret->float_utf8);
14039
14040         /* check_substr and check_utf8, if non-NULL, point to either their
14041            anchored or float namesakes, and don't hold a second reference.  */
14042     }
14043     RX_MATCH_COPIED_off(ret_x);
14044 #ifdef PERL_ANY_COW
14045     ret->saved_copy = NULL;
14046 #endif
14047     ret->mother_re = ReREFCNT_inc(r->mother_re ? r->mother_re : rx);
14048     SvREFCNT_inc_void(ret->qr_anoncv);
14049     
14050     return ret_x;
14051 }
14052 #endif
14053
14054 /* regfree_internal() 
14055
14056    Free the private data in a regexp. This is overloadable by 
14057    extensions. Perl takes care of the regexp structure in pregfree(), 
14058    this covers the *pprivate pointer which technically perl doesn't 
14059    know about, however of course we have to handle the 
14060    regexp_internal structure when no extension is in use. 
14061    
14062    Note this is called before freeing anything in the regexp 
14063    structure. 
14064  */
14065  
14066 void
14067 Perl_regfree_internal(pTHX_ REGEXP * const rx)
14068 {
14069     dVAR;
14070     struct regexp *const r = ReANY(rx);
14071     RXi_GET_DECL(r,ri);
14072     GET_RE_DEBUG_FLAGS_DECL;
14073
14074     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
14075
14076     DEBUG_COMPILE_r({
14077         if (!PL_colorset)
14078             reginitcolors();
14079         {
14080             SV *dsv= sv_newmortal();
14081             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
14082                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
14083             PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n", 
14084                 PL_colors[4],PL_colors[5],s);
14085         }
14086     });
14087 #ifdef RE_TRACK_PATTERN_OFFSETS
14088     if (ri->u.offsets)
14089         Safefree(ri->u.offsets);             /* 20010421 MJD */
14090 #endif
14091     if (ri->code_blocks) {
14092         int n;
14093         for (n = 0; n < ri->num_code_blocks; n++)
14094             SvREFCNT_dec(ri->code_blocks[n].src_regex);
14095         Safefree(ri->code_blocks);
14096     }
14097
14098     if (ri->data) {
14099         int n = ri->data->count;
14100
14101         while (--n >= 0) {
14102           /* If you add a ->what type here, update the comment in regcomp.h */
14103             switch (ri->data->what[n]) {
14104             case 'a':
14105             case 'r':
14106             case 's':
14107             case 'S':
14108             case 'u':
14109                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
14110                 break;
14111             case 'f':
14112                 Safefree(ri->data->data[n]);
14113                 break;
14114             case 'l':
14115             case 'L':
14116                 break;
14117             case 'T':           
14118                 { /* Aho Corasick add-on structure for a trie node.
14119                      Used in stclass optimization only */
14120                     U32 refcount;
14121                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
14122                     OP_REFCNT_LOCK;
14123                     refcount = --aho->refcount;
14124                     OP_REFCNT_UNLOCK;
14125                     if ( !refcount ) {
14126                         PerlMemShared_free(aho->states);
14127                         PerlMemShared_free(aho->fail);
14128                          /* do this last!!!! */
14129                         PerlMemShared_free(ri->data->data[n]);
14130                         PerlMemShared_free(ri->regstclass);
14131                     }
14132                 }
14133                 break;
14134             case 't':
14135                 {
14136                     /* trie structure. */
14137                     U32 refcount;
14138                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
14139                     OP_REFCNT_LOCK;
14140                     refcount = --trie->refcount;
14141                     OP_REFCNT_UNLOCK;
14142                     if ( !refcount ) {
14143                         PerlMemShared_free(trie->charmap);
14144                         PerlMemShared_free(trie->states);
14145                         PerlMemShared_free(trie->trans);
14146                         if (trie->bitmap)
14147                             PerlMemShared_free(trie->bitmap);
14148                         if (trie->jump)
14149                             PerlMemShared_free(trie->jump);
14150                         PerlMemShared_free(trie->wordinfo);
14151                         /* do this last!!!! */
14152                         PerlMemShared_free(ri->data->data[n]);
14153                     }
14154                 }
14155                 break;
14156             default:
14157                 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
14158             }
14159         }
14160         Safefree(ri->data->what);
14161         Safefree(ri->data);
14162     }
14163
14164     Safefree(ri);
14165 }
14166
14167 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
14168 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
14169 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
14170
14171 /* 
14172    re_dup - duplicate a regexp. 
14173    
14174    This routine is expected to clone a given regexp structure. It is only
14175    compiled under USE_ITHREADS.
14176
14177    After all of the core data stored in struct regexp is duplicated
14178    the regexp_engine.dupe method is used to copy any private data
14179    stored in the *pprivate pointer. This allows extensions to handle
14180    any duplication it needs to do.
14181
14182    See pregfree() and regfree_internal() if you change anything here. 
14183 */
14184 #if defined(USE_ITHREADS)
14185 #ifndef PERL_IN_XSUB_RE
14186 void
14187 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
14188 {
14189     dVAR;
14190     I32 npar;
14191     const struct regexp *r = ReANY(sstr);
14192     struct regexp *ret = ReANY(dstr);
14193     
14194     PERL_ARGS_ASSERT_RE_DUP_GUTS;
14195
14196     npar = r->nparens+1;
14197     Newx(ret->offs, npar, regexp_paren_pair);
14198     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
14199     if(ret->swap) {
14200         /* no need to copy these */
14201         Newx(ret->swap, npar, regexp_paren_pair);
14202     }
14203
14204     if (ret->substrs) {
14205         /* Do it this way to avoid reading from *r after the StructCopy().
14206            That way, if any of the sv_dup_inc()s dislodge *r from the L1
14207            cache, it doesn't matter.  */
14208         const bool anchored = r->check_substr
14209             ? r->check_substr == r->anchored_substr
14210             : r->check_utf8 == r->anchored_utf8;
14211         Newx(ret->substrs, 1, struct reg_substr_data);
14212         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
14213
14214         ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
14215         ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
14216         ret->float_substr = sv_dup_inc(ret->float_substr, param);
14217         ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
14218
14219         /* check_substr and check_utf8, if non-NULL, point to either their
14220            anchored or float namesakes, and don't hold a second reference.  */
14221
14222         if (ret->check_substr) {
14223             if (anchored) {
14224                 assert(r->check_utf8 == r->anchored_utf8);
14225                 ret->check_substr = ret->anchored_substr;
14226                 ret->check_utf8 = ret->anchored_utf8;
14227             } else {
14228                 assert(r->check_substr == r->float_substr);
14229                 assert(r->check_utf8 == r->float_utf8);
14230                 ret->check_substr = ret->float_substr;
14231                 ret->check_utf8 = ret->float_utf8;
14232             }
14233         } else if (ret->check_utf8) {
14234             if (anchored) {
14235                 ret->check_utf8 = ret->anchored_utf8;
14236             } else {
14237                 ret->check_utf8 = ret->float_utf8;
14238             }
14239         }
14240     }
14241
14242     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
14243     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
14244
14245     if (ret->pprivate)
14246         RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
14247
14248     if (RX_MATCH_COPIED(dstr))
14249         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
14250     else
14251         ret->subbeg = NULL;
14252 #ifdef PERL_ANY_COW
14253     ret->saved_copy = NULL;
14254 #endif
14255
14256     /* Whether mother_re be set or no, we need to copy the string.  We
14257        cannot refrain from copying it when the storage points directly to
14258        our mother regexp, because that's
14259                1: a buffer in a different thread
14260                2: something we no longer hold a reference on
14261                so we need to copy it locally.  */
14262     RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED(sstr), SvCUR(sstr)+1);
14263     ret->mother_re   = NULL;
14264     ret->gofs = 0;
14265 }
14266 #endif /* PERL_IN_XSUB_RE */
14267
14268 /*
14269    regdupe_internal()
14270    
14271    This is the internal complement to regdupe() which is used to copy
14272    the structure pointed to by the *pprivate pointer in the regexp.
14273    This is the core version of the extension overridable cloning hook.
14274    The regexp structure being duplicated will be copied by perl prior
14275    to this and will be provided as the regexp *r argument, however 
14276    with the /old/ structures pprivate pointer value. Thus this routine
14277    may override any copying normally done by perl.
14278    
14279    It returns a pointer to the new regexp_internal structure.
14280 */
14281
14282 void *
14283 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
14284 {
14285     dVAR;
14286     struct regexp *const r = ReANY(rx);
14287     regexp_internal *reti;
14288     int len;
14289     RXi_GET_DECL(r,ri);
14290
14291     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
14292     
14293     len = ProgLen(ri);
14294     
14295     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal);
14296     Copy(ri->program, reti->program, len+1, regnode);
14297
14298     reti->num_code_blocks = ri->num_code_blocks;
14299     if (ri->code_blocks) {
14300         int n;
14301         Newxc(reti->code_blocks, ri->num_code_blocks, struct reg_code_block,
14302                 struct reg_code_block);
14303         Copy(ri->code_blocks, reti->code_blocks, ri->num_code_blocks,
14304                 struct reg_code_block);
14305         for (n = 0; n < ri->num_code_blocks; n++)
14306              reti->code_blocks[n].src_regex = (REGEXP*)
14307                     sv_dup_inc((SV*)(ri->code_blocks[n].src_regex), param);
14308     }
14309     else
14310         reti->code_blocks = NULL;
14311
14312     reti->regstclass = NULL;
14313
14314     if (ri->data) {
14315         struct reg_data *d;
14316         const int count = ri->data->count;
14317         int i;
14318
14319         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
14320                 char, struct reg_data);
14321         Newx(d->what, count, U8);
14322
14323         d->count = count;
14324         for (i = 0; i < count; i++) {
14325             d->what[i] = ri->data->what[i];
14326             switch (d->what[i]) {
14327                 /* see also regcomp.h and regfree_internal() */
14328             case 'a': /* actually an AV, but the dup function is identical.  */
14329             case 'r':
14330             case 's':
14331             case 'S':
14332             case 'u': /* actually an HV, but the dup function is identical.  */
14333                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
14334                 break;
14335             case 'f':
14336                 /* This is cheating. */
14337                 Newx(d->data[i], 1, struct regnode_charclass_class);
14338                 StructCopy(ri->data->data[i], d->data[i],
14339                             struct regnode_charclass_class);
14340                 reti->regstclass = (regnode*)d->data[i];
14341                 break;
14342             case 'T':
14343                 /* Trie stclasses are readonly and can thus be shared
14344                  * without duplication. We free the stclass in pregfree
14345                  * when the corresponding reg_ac_data struct is freed.
14346                  */
14347                 reti->regstclass= ri->regstclass;
14348                 /* Fall through */
14349             case 't':
14350                 OP_REFCNT_LOCK;
14351                 ((reg_trie_data*)ri->data->data[i])->refcount++;
14352                 OP_REFCNT_UNLOCK;
14353                 /* Fall through */
14354             case 'l':
14355             case 'L':
14356                 d->data[i] = ri->data->data[i];
14357                 break;
14358             default:
14359                 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
14360             }
14361         }
14362
14363         reti->data = d;
14364     }
14365     else
14366         reti->data = NULL;
14367
14368     reti->name_list_idx = ri->name_list_idx;
14369
14370 #ifdef RE_TRACK_PATTERN_OFFSETS
14371     if (ri->u.offsets) {
14372         Newx(reti->u.offsets, 2*len+1, U32);
14373         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
14374     }
14375 #else
14376     SetProgLen(reti,len);
14377 #endif
14378
14379     return (void*)reti;
14380 }
14381
14382 #endif    /* USE_ITHREADS */
14383
14384 #ifndef PERL_IN_XSUB_RE
14385
14386 /*
14387  - regnext - dig the "next" pointer out of a node
14388  */
14389 regnode *
14390 Perl_regnext(pTHX_ regnode *p)
14391 {
14392     dVAR;
14393     I32 offset;
14394
14395     if (!p)
14396         return(NULL);
14397
14398     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
14399         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(p), (int)REGNODE_MAX);
14400     }
14401
14402     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
14403     if (offset == 0)
14404         return(NULL);
14405
14406     return(p+offset);
14407 }
14408 #endif
14409
14410 STATIC void
14411 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
14412 {
14413     va_list args;
14414     STRLEN l1 = strlen(pat1);
14415     STRLEN l2 = strlen(pat2);
14416     char buf[512];
14417     SV *msv;
14418     const char *message;
14419
14420     PERL_ARGS_ASSERT_RE_CROAK2;
14421
14422     if (l1 > 510)
14423         l1 = 510;
14424     if (l1 + l2 > 510)
14425         l2 = 510 - l1;
14426     Copy(pat1, buf, l1 , char);
14427     Copy(pat2, buf + l1, l2 , char);
14428     buf[l1 + l2] = '\n';
14429     buf[l1 + l2 + 1] = '\0';
14430 #ifdef I_STDARG
14431     /* ANSI variant takes additional second argument */
14432     va_start(args, pat2);
14433 #else
14434     va_start(args);
14435 #endif
14436     msv = vmess(buf, &args);
14437     va_end(args);
14438     message = SvPV_const(msv,l1);
14439     if (l1 > 512)
14440         l1 = 512;
14441     Copy(message, buf, l1 , char);
14442     buf[l1-1] = '\0';                   /* Overwrite \n */
14443     Perl_croak(aTHX_ "%s", buf);
14444 }
14445
14446 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
14447
14448 #ifndef PERL_IN_XSUB_RE
14449 void
14450 Perl_save_re_context(pTHX)
14451 {
14452     dVAR;
14453
14454     struct re_save_state *state;
14455
14456     SAVEVPTR(PL_curcop);
14457     SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
14458
14459     state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
14460     PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
14461     SSPUSHUV(SAVEt_RE_STATE);
14462
14463     Copy(&PL_reg_state, state, 1, struct re_save_state);
14464
14465     PL_reg_oldsaved = NULL;
14466     PL_reg_oldsavedlen = 0;
14467     PL_reg_oldsavedoffset = 0;
14468     PL_reg_oldsavedcoffset = 0;
14469     PL_reg_maxiter = 0;
14470     PL_reg_leftiter = 0;
14471     PL_reg_poscache = NULL;
14472     PL_reg_poscache_size = 0;
14473 #ifdef PERL_ANY_COW
14474     PL_nrs = NULL;
14475 #endif
14476
14477     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
14478     if (PL_curpm) {
14479         const REGEXP * const rx = PM_GETRE(PL_curpm);
14480         if (rx) {
14481             U32 i;
14482             for (i = 1; i <= RX_NPARENS(rx); i++) {
14483                 char digits[TYPE_CHARS(long)];
14484                 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
14485                 GV *const *const gvp
14486                     = (GV**)hv_fetch(PL_defstash, digits, len, 0);
14487
14488                 if (gvp) {
14489                     GV * const gv = *gvp;
14490                     if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
14491                         save_scalar(gv);
14492                 }
14493             }
14494         }
14495     }
14496 }
14497 #endif
14498
14499 #ifdef DEBUGGING
14500
14501 STATIC void
14502 S_put_byte(pTHX_ SV *sv, int c)
14503 {
14504     PERL_ARGS_ASSERT_PUT_BYTE;
14505
14506     /* Our definition of isPRINT() ignores locales, so only bytes that are
14507        not part of UTF-8 are considered printable. I assume that the same
14508        holds for UTF-EBCDIC.
14509        Also, code point 255 is not printable in either (it's E0 in EBCDIC,
14510        which Wikipedia says:
14511
14512        EO, or Eight Ones, is an 8-bit EBCDIC character code represented as all
14513        ones (binary 1111 1111, hexadecimal FF). It is similar, but not
14514        identical, to the ASCII delete (DEL) or rubout control character.
14515        ) So the old condition can be simplified to !isPRINT(c)  */
14516     if (!isPRINT(c)) {
14517         if (c < 256) {
14518             Perl_sv_catpvf(aTHX_ sv, "\\x%02x", c);
14519         }
14520         else {
14521             Perl_sv_catpvf(aTHX_ sv, "\\x{%x}", c);
14522         }
14523     }
14524     else {
14525         const char string = c;
14526         if (c == '-' || c == ']' || c == '\\' || c == '^')
14527             sv_catpvs(sv, "\\");
14528         sv_catpvn(sv, &string, 1);
14529     }
14530 }
14531
14532
14533 #define CLEAR_OPTSTART \
14534     if (optstart) STMT_START { \
14535             DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
14536             optstart=NULL; \
14537     } STMT_END
14538
14539 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
14540
14541 STATIC const regnode *
14542 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
14543             const regnode *last, const regnode *plast, 
14544             SV* sv, I32 indent, U32 depth)
14545 {
14546     dVAR;
14547     U8 op = PSEUDO;     /* Arbitrary non-END op. */
14548     const regnode *next;
14549     const regnode *optstart= NULL;
14550     
14551     RXi_GET_DECL(r,ri);
14552     GET_RE_DEBUG_FLAGS_DECL;
14553
14554     PERL_ARGS_ASSERT_DUMPUNTIL;
14555
14556 #ifdef DEBUG_DUMPUNTIL
14557     PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
14558         last ? last-start : 0,plast ? plast-start : 0);
14559 #endif
14560             
14561     if (plast && plast < last) 
14562         last= plast;
14563
14564     while (PL_regkind[op] != END && (!last || node < last)) {
14565         /* While that wasn't END last time... */
14566         NODE_ALIGN(node);
14567         op = OP(node);
14568         if (op == CLOSE || op == WHILEM)
14569             indent--;
14570         next = regnext((regnode *)node);
14571
14572         /* Where, what. */
14573         if (OP(node) == OPTIMIZED) {
14574             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
14575                 optstart = node;
14576             else
14577                 goto after_print;
14578         } else
14579             CLEAR_OPTSTART;
14580
14581         regprop(r, sv, node);
14582         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
14583                       (int)(2*indent + 1), "", SvPVX_const(sv));
14584         
14585         if (OP(node) != OPTIMIZED) {                  
14586             if (next == NULL)           /* Next ptr. */
14587                 PerlIO_printf(Perl_debug_log, " (0)");
14588             else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
14589                 PerlIO_printf(Perl_debug_log, " (FAIL)");
14590             else 
14591                 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
14592             (void)PerlIO_putc(Perl_debug_log, '\n'); 
14593         }
14594         
14595       after_print:
14596         if (PL_regkind[(U8)op] == BRANCHJ) {
14597             assert(next);
14598             {
14599                 const regnode *nnode = (OP(next) == LONGJMP
14600                                        ? regnext((regnode *)next)
14601                                        : next);
14602                 if (last && nnode > last)
14603                     nnode = last;
14604                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
14605             }
14606         }
14607         else if (PL_regkind[(U8)op] == BRANCH) {
14608             assert(next);
14609             DUMPUNTIL(NEXTOPER(node), next);
14610         }
14611         else if ( PL_regkind[(U8)op]  == TRIE ) {
14612             const regnode *this_trie = node;
14613             const char op = OP(node);
14614             const U32 n = ARG(node);
14615             const reg_ac_data * const ac = op>=AHOCORASICK ?
14616                (reg_ac_data *)ri->data->data[n] :
14617                NULL;
14618             const reg_trie_data * const trie =
14619                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
14620 #ifdef DEBUGGING
14621             AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
14622 #endif
14623             const regnode *nextbranch= NULL;
14624             I32 word_idx;
14625             sv_setpvs(sv, "");
14626             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
14627                 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
14628
14629                 PerlIO_printf(Perl_debug_log, "%*s%s ",
14630                    (int)(2*(indent+3)), "",
14631                     elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
14632                             PL_colors[0], PL_colors[1],
14633                             (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
14634                             PERL_PV_PRETTY_ELLIPSES    |
14635                             PERL_PV_PRETTY_LTGT
14636                             )
14637                             : "???"
14638                 );
14639                 if (trie->jump) {
14640                     U16 dist= trie->jump[word_idx+1];
14641                     PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
14642                                   (UV)((dist ? this_trie + dist : next) - start));
14643                     if (dist) {
14644                         if (!nextbranch)
14645                             nextbranch= this_trie + trie->jump[0];    
14646                         DUMPUNTIL(this_trie + dist, nextbranch);
14647                     }
14648                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
14649                         nextbranch= regnext((regnode *)nextbranch);
14650                 } else {
14651                     PerlIO_printf(Perl_debug_log, "\n");
14652                 }
14653             }
14654             if (last && next > last)
14655                 node= last;
14656             else
14657                 node= next;
14658         }
14659         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
14660             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
14661                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
14662         }
14663         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
14664             assert(next);
14665             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
14666         }
14667         else if ( op == PLUS || op == STAR) {
14668             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
14669         }
14670         else if (PL_regkind[(U8)op] == ANYOF) {
14671             /* arglen 1 + class block */
14672             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_CLASS)
14673                     ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
14674             node = NEXTOPER(node);
14675         }
14676         else if (PL_regkind[(U8)op] == EXACT) {
14677             /* Literal string, where present. */
14678             node += NODE_SZ_STR(node) - 1;
14679             node = NEXTOPER(node);
14680         }
14681         else {
14682             node = NEXTOPER(node);
14683             node += regarglen[(U8)op];
14684         }
14685         if (op == CURLYX || op == OPEN)
14686             indent++;
14687     }
14688     CLEAR_OPTSTART;
14689 #ifdef DEBUG_DUMPUNTIL    
14690     PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
14691 #endif
14692     return node;
14693 }
14694
14695 #endif  /* DEBUGGING */
14696
14697 /*
14698  * Local variables:
14699  * c-indentation-style: bsd
14700  * c-basic-offset: 4
14701  * indent-tabs-mode: nil
14702  * End:
14703  *
14704  * ex: set ts=8 sts=4 sw=4 et:
14705  */