This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fix small Pod error introduced by commit c5e3e317152223ae.
[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 #else
85 #  include "regcomp.h"
86 #endif
87
88 #include "dquote_static.c"
89 #ifndef PERL_IN_XSUB_RE
90 #  include "charclass_invlists.h"
91 #endif
92
93 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
94
95 #ifdef op
96 #undef op
97 #endif /* op */
98
99 #ifdef MSDOS
100 #  if defined(BUGGY_MSC6)
101  /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
102 #    pragma optimize("a",off)
103  /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
104 #    pragma optimize("w",on )
105 #  endif /* BUGGY_MSC6 */
106 #endif /* MSDOS */
107
108 #ifndef STATIC
109 #define STATIC  static
110 #endif
111
112
113 typedef struct RExC_state_t {
114     U32         flags;                  /* RXf_* are we folding, multilining? */
115     U32         pm_flags;               /* PMf_* stuff from the calling PMOP */
116     char        *precomp;               /* uncompiled string. */
117     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
118     regexp      *rx;                    /* perl core regexp structure */
119     regexp_internal     *rxi;           /* internal data for regexp object pprivate field */        
120     char        *start;                 /* Start of input for compile */
121     char        *end;                   /* End of input for compile */
122     char        *parse;                 /* Input-scan pointer. */
123     I32         whilem_seen;            /* number of WHILEM in this expr */
124     regnode     *emit_start;            /* Start of emitted-code area */
125     regnode     *emit_bound;            /* First regnode outside of the allocated space */
126     regnode     *emit;                  /* Code-emit pointer; &regdummy = don't = compiling */
127     I32         naughty;                /* How bad is this pattern? */
128     I32         sawback;                /* Did we see \1, ...? */
129     U32         seen;
130     I32         size;                   /* Code size. */
131     I32         npar;                   /* Capture buffer count, (OPEN). */
132     I32         cpar;                   /* Capture buffer count, (CLOSE). */
133     I32         nestroot;               /* root parens we are in - used by accept */
134     I32         extralen;
135     I32         seen_zerolen;
136     regnode     **open_parens;          /* pointers to open parens */
137     regnode     **close_parens;         /* pointers to close parens */
138     regnode     *opend;                 /* END node in program */
139     I32         utf8;           /* whether the pattern is utf8 or not */
140     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
141                                 /* XXX use this for future optimisation of case
142                                  * where pattern must be upgraded to utf8. */
143     I32         uni_semantics;  /* If a d charset modifier should use unicode
144                                    rules, even if the pattern is not in
145                                    utf8 */
146     HV          *paren_names;           /* Paren names */
147     
148     regnode     **recurse;              /* Recurse regops */
149     I32         recurse_count;          /* Number of recurse regops */
150     I32         in_lookbehind;
151     I32         contains_locale;
152     I32         override_recoding;
153     struct reg_code_block *code_blocks; /* positions of literal (?{})
154                                             within pattern */
155     int         num_code_blocks;        /* size of code_blocks[] */
156     int         code_index;             /* next code_blocks[] slot */
157 #if ADD_TO_REGEXEC
158     char        *starttry;              /* -Dr: where regtry was called. */
159 #define RExC_starttry   (pRExC_state->starttry)
160 #endif
161     SV          *runtime_code_qr;       /* qr with the runtime code blocks */
162 #ifdef DEBUGGING
163     const char  *lastparse;
164     I32         lastnum;
165     AV          *paren_name_list;       /* idx -> name */
166 #define RExC_lastparse  (pRExC_state->lastparse)
167 #define RExC_lastnum    (pRExC_state->lastnum)
168 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
169 #endif
170 } RExC_state_t;
171
172 #define RExC_flags      (pRExC_state->flags)
173 #define RExC_pm_flags   (pRExC_state->pm_flags)
174 #define RExC_precomp    (pRExC_state->precomp)
175 #define RExC_rx_sv      (pRExC_state->rx_sv)
176 #define RExC_rx         (pRExC_state->rx)
177 #define RExC_rxi        (pRExC_state->rxi)
178 #define RExC_start      (pRExC_state->start)
179 #define RExC_end        (pRExC_state->end)
180 #define RExC_parse      (pRExC_state->parse)
181 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
182 #ifdef RE_TRACK_PATTERN_OFFSETS
183 #define RExC_offsets    (pRExC_state->rxi->u.offsets) /* I am not like the others */
184 #endif
185 #define RExC_emit       (pRExC_state->emit)
186 #define RExC_emit_start (pRExC_state->emit_start)
187 #define RExC_emit_bound (pRExC_state->emit_bound)
188 #define RExC_naughty    (pRExC_state->naughty)
189 #define RExC_sawback    (pRExC_state->sawback)
190 #define RExC_seen       (pRExC_state->seen)
191 #define RExC_size       (pRExC_state->size)
192 #define RExC_npar       (pRExC_state->npar)
193 #define RExC_nestroot   (pRExC_state->nestroot)
194 #define RExC_extralen   (pRExC_state->extralen)
195 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
196 #define RExC_utf8       (pRExC_state->utf8)
197 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
198 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
199 #define RExC_open_parens        (pRExC_state->open_parens)
200 #define RExC_close_parens       (pRExC_state->close_parens)
201 #define RExC_opend      (pRExC_state->opend)
202 #define RExC_paren_names        (pRExC_state->paren_names)
203 #define RExC_recurse    (pRExC_state->recurse)
204 #define RExC_recurse_count      (pRExC_state->recurse_count)
205 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
206 #define RExC_contains_locale    (pRExC_state->contains_locale)
207 #define RExC_override_recoding  (pRExC_state->override_recoding)
208
209
210 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
211 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
212         ((*s) == '{' && regcurly(s)))
213
214 #ifdef SPSTART
215 #undef SPSTART          /* dratted cpp namespace... */
216 #endif
217 /*
218  * Flags to be passed up and down.
219  */
220 #define WORST           0       /* Worst case. */
221 #define HASWIDTH        0x01    /* Known to match non-null strings. */
222
223 /* Simple enough to be STAR/PLUS operand, in an EXACT node must be a single
224  * character, and if utf8, must be invariant.  Note that this is not the same
225  * thing as REGNODE_SIMPLE */
226 #define SIMPLE          0x02
227 #define SPSTART         0x04    /* Starts with * or +. */
228 #define TRYAGAIN        0x08    /* Weeded out a declaration. */
229 #define POSTPONED       0x10    /* (?1),(?&name), (??{...}) or similar */
230
231 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
232
233 /* whether trie related optimizations are enabled */
234 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
235 #define TRIE_STUDY_OPT
236 #define FULL_TRIE_STUDY
237 #define TRIE_STCLASS
238 #endif
239
240
241
242 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
243 #define PBITVAL(paren) (1 << ((paren) & 7))
244 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
245 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
246 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
247
248 /* If not already in utf8, do a longjmp back to the beginning */
249 #define UTF8_LONGJMP 42 /* Choose a value not likely to ever conflict */
250 #define REQUIRE_UTF8    STMT_START {                                       \
251                                      if (! UTF) JMPENV_JUMP(UTF8_LONGJMP); \
252                         } STMT_END
253
254 /* About scan_data_t.
255
256   During optimisation we recurse through the regexp program performing
257   various inplace (keyhole style) optimisations. In addition study_chunk
258   and scan_commit populate this data structure with information about
259   what strings MUST appear in the pattern. We look for the longest 
260   string that must appear at a fixed location, and we look for the
261   longest string that may appear at a floating location. So for instance
262   in the pattern:
263   
264     /FOO[xX]A.*B[xX]BAR/
265     
266   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
267   strings (because they follow a .* construct). study_chunk will identify
268   both FOO and BAR as being the longest fixed and floating strings respectively.
269   
270   The strings can be composites, for instance
271   
272      /(f)(o)(o)/
273      
274   will result in a composite fixed substring 'foo'.
275   
276   For each string some basic information is maintained:
277   
278   - offset or min_offset
279     This is the position the string must appear at, or not before.
280     It also implicitly (when combined with minlenp) tells us how many
281     characters must match before the string we are searching for.
282     Likewise when combined with minlenp and the length of the string it
283     tells us how many characters must appear after the string we have 
284     found.
285   
286   - max_offset
287     Only used for floating strings. This is the rightmost point that
288     the string can appear at. If set to I32 max it indicates that the
289     string can occur infinitely far to the right.
290   
291   - minlenp
292     A pointer to the minimum length of the pattern that the string 
293     was found inside. This is important as in the case of positive 
294     lookahead or positive lookbehind we can have multiple patterns 
295     involved. Consider
296     
297     /(?=FOO).*F/
298     
299     The minimum length of the pattern overall is 3, the minimum length
300     of the lookahead part is 3, but the minimum length of the part that
301     will actually match is 1. So 'FOO's minimum length is 3, but the 
302     minimum length for the F is 1. This is important as the minimum length
303     is used to determine offsets in front of and behind the string being 
304     looked for.  Since strings can be composites this is the length of the
305     pattern at the time it was committed with a scan_commit. Note that
306     the length is calculated by study_chunk, so that the minimum lengths
307     are not known until the full pattern has been compiled, thus the 
308     pointer to the value.
309   
310   - lookbehind
311   
312     In the case of lookbehind the string being searched for can be
313     offset past the start point of the final matching string. 
314     If this value was just blithely removed from the min_offset it would
315     invalidate some of the calculations for how many chars must match
316     before or after (as they are derived from min_offset and minlen and
317     the length of the string being searched for). 
318     When the final pattern is compiled and the data is moved from the
319     scan_data_t structure into the regexp structure the information
320     about lookbehind is factored in, with the information that would 
321     have been lost precalculated in the end_shift field for the 
322     associated string.
323
324   The fields pos_min and pos_delta are used to store the minimum offset
325   and the delta to the maximum offset at the current point in the pattern.    
326
327 */
328
329 typedef struct scan_data_t {
330     /*I32 len_min;      unused */
331     /*I32 len_delta;    unused */
332     I32 pos_min;
333     I32 pos_delta;
334     SV *last_found;
335     I32 last_end;           /* min value, <0 unless valid. */
336     I32 last_start_min;
337     I32 last_start_max;
338     SV **longest;           /* Either &l_fixed, or &l_float. */
339     SV *longest_fixed;      /* longest fixed string found in pattern */
340     I32 offset_fixed;       /* offset where it starts */
341     I32 *minlen_fixed;      /* pointer to the minlen relevant to the string */
342     I32 lookbehind_fixed;   /* is the position of the string modfied by LB */
343     SV *longest_float;      /* longest floating string found in pattern */
344     I32 offset_float_min;   /* earliest point in string it can appear */
345     I32 offset_float_max;   /* latest point in string it can appear */
346     I32 *minlen_float;      /* pointer to the minlen relevant to the string */
347     I32 lookbehind_float;   /* is the position of the string modified by LB */
348     I32 flags;
349     I32 whilem_c;
350     I32 *last_closep;
351     struct regnode_charclass_class *start_class;
352 } scan_data_t;
353
354 /*
355  * Forward declarations for pregcomp()'s friends.
356  */
357
358 static const scan_data_t zero_scan_data =
359   { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
360
361 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
362 #define SF_BEFORE_SEOL          0x0001
363 #define SF_BEFORE_MEOL          0x0002
364 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
365 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
366
367 #ifdef NO_UNARY_PLUS
368 #  define SF_FIX_SHIFT_EOL      (0+2)
369 #  define SF_FL_SHIFT_EOL               (0+4)
370 #else
371 #  define SF_FIX_SHIFT_EOL      (+2)
372 #  define SF_FL_SHIFT_EOL               (+4)
373 #endif
374
375 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
376 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
377
378 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
379 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
380 #define SF_IS_INF               0x0040
381 #define SF_HAS_PAR              0x0080
382 #define SF_IN_PAR               0x0100
383 #define SF_HAS_EVAL             0x0200
384 #define SCF_DO_SUBSTR           0x0400
385 #define SCF_DO_STCLASS_AND      0x0800
386 #define SCF_DO_STCLASS_OR       0x1000
387 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
388 #define SCF_WHILEM_VISITED_POS  0x2000
389
390 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
391 #define SCF_SEEN_ACCEPT         0x8000 
392
393 #define UTF cBOOL(RExC_utf8)
394
395 /* The enums for all these are ordered so things work out correctly */
396 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
397 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_DEPENDS_CHARSET)
398 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
399 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) >= REGEX_UNICODE_CHARSET)
400 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_RESTRICTED_CHARSET)
401 #define MORE_ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
402 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) >= REGEX_ASCII_RESTRICTED_CHARSET)
403
404 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
405
406 #define OOB_UNICODE             12345678
407 #define OOB_NAMEDCLASS          -1
408
409 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
410 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
411
412
413 /* length of regex to show in messages that don't mark a position within */
414 #define RegexLengthToShowInErrorMessages 127
415
416 /*
417  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
418  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
419  * op/pragma/warn/regcomp.
420  */
421 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
422 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
423
424 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
425
426 /*
427  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
428  * arg. Show regex, up to a maximum length. If it's too long, chop and add
429  * "...".
430  */
431 #define _FAIL(code) STMT_START {                                        \
432     const char *ellipses = "";                                          \
433     IV len = RExC_end - RExC_precomp;                                   \
434                                                                         \
435     if (!SIZE_ONLY)                                                     \
436         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv);                   \
437     if (len > RegexLengthToShowInErrorMessages) {                       \
438         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
439         len = RegexLengthToShowInErrorMessages - 10;                    \
440         ellipses = "...";                                               \
441     }                                                                   \
442     code;                                                               \
443 } STMT_END
444
445 #define FAIL(msg) _FAIL(                            \
446     Perl_croak(aTHX_ "%s in regex m/%.*s%s/",       \
447             msg, (int)len, RExC_precomp, ellipses))
448
449 #define FAIL2(msg,arg) _FAIL(                       \
450     Perl_croak(aTHX_ msg " in regex m/%.*s%s/",     \
451             arg, (int)len, RExC_precomp, ellipses))
452
453 /*
454  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
455  */
456 #define Simple_vFAIL(m) STMT_START {                                    \
457     const IV offset = RExC_parse - RExC_precomp;                        \
458     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
459             m, (int)offset, RExC_precomp, RExC_precomp + offset);       \
460 } STMT_END
461
462 /*
463  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
464  */
465 #define vFAIL(m) STMT_START {                           \
466     if (!SIZE_ONLY)                                     \
467         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv);   \
468     Simple_vFAIL(m);                                    \
469 } STMT_END
470
471 /*
472  * Like Simple_vFAIL(), but accepts two arguments.
473  */
474 #define Simple_vFAIL2(m,a1) STMT_START {                        \
475     const IV offset = RExC_parse - RExC_precomp;                        \
476     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1,                   \
477             (int)offset, RExC_precomp, RExC_precomp + offset);  \
478 } STMT_END
479
480 /*
481  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
482  */
483 #define vFAIL2(m,a1) STMT_START {                       \
484     if (!SIZE_ONLY)                                     \
485         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv);   \
486     Simple_vFAIL2(m, a1);                               \
487 } STMT_END
488
489
490 /*
491  * Like Simple_vFAIL(), but accepts three arguments.
492  */
493 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
494     const IV offset = RExC_parse - RExC_precomp;                \
495     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2,               \
496             (int)offset, RExC_precomp, RExC_precomp + offset);  \
497 } STMT_END
498
499 /*
500  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
501  */
502 #define vFAIL3(m,a1,a2) STMT_START {                    \
503     if (!SIZE_ONLY)                                     \
504         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv);   \
505     Simple_vFAIL3(m, a1, a2);                           \
506 } STMT_END
507
508 /*
509  * Like Simple_vFAIL(), but accepts four arguments.
510  */
511 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
512     const IV offset = RExC_parse - RExC_precomp;                \
513     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,           \
514             (int)offset, RExC_precomp, RExC_precomp + offset);  \
515 } STMT_END
516
517 #define ckWARNreg(loc,m) STMT_START {                                   \
518     const IV offset = loc - RExC_precomp;                               \
519     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
520             (int)offset, RExC_precomp, RExC_precomp + offset);          \
521 } STMT_END
522
523 #define ckWARNregdep(loc,m) STMT_START {                                \
524     const IV offset = loc - RExC_precomp;                               \
525     Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP),     \
526             m REPORT_LOCATION,                                          \
527             (int)offset, RExC_precomp, RExC_precomp + offset);          \
528 } STMT_END
529
530 #define ckWARN2regdep(loc,m, a1) STMT_START {                           \
531     const IV offset = loc - RExC_precomp;                               \
532     Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP),     \
533             m REPORT_LOCATION,                                          \
534             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
535 } STMT_END
536
537 #define ckWARN2reg(loc, m, a1) STMT_START {                             \
538     const IV offset = loc - RExC_precomp;                               \
539     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
540             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
541 } STMT_END
542
543 #define vWARN3(loc, m, a1, a2) STMT_START {                             \
544     const IV offset = loc - RExC_precomp;                               \
545     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
546             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
547 } STMT_END
548
549 #define ckWARN3reg(loc, m, a1, a2) STMT_START {                         \
550     const IV offset = loc - RExC_precomp;                               \
551     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
552             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
553 } STMT_END
554
555 #define vWARN4(loc, m, a1, a2, a3) STMT_START {                         \
556     const IV offset = loc - RExC_precomp;                               \
557     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
558             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
559 } STMT_END
560
561 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START {                     \
562     const IV offset = loc - RExC_precomp;                               \
563     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
564             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
565 } STMT_END
566
567 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START {                     \
568     const IV offset = loc - RExC_precomp;                               \
569     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
570             a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
571 } STMT_END
572
573
574 /* Allow for side effects in s */
575 #define REGC(c,s) STMT_START {                  \
576     if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
577 } STMT_END
578
579 /* Macros for recording node offsets.   20001227 mjd@plover.com 
580  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
581  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
582  * Element 0 holds the number n.
583  * Position is 1 indexed.
584  */
585 #ifndef RE_TRACK_PATTERN_OFFSETS
586 #define Set_Node_Offset_To_R(node,byte)
587 #define Set_Node_Offset(node,byte)
588 #define Set_Cur_Node_Offset
589 #define Set_Node_Length_To_R(node,len)
590 #define Set_Node_Length(node,len)
591 #define Set_Node_Cur_Length(node)
592 #define Node_Offset(n) 
593 #define Node_Length(n) 
594 #define Set_Node_Offset_Length(node,offset,len)
595 #define ProgLen(ri) ri->u.proglen
596 #define SetProgLen(ri,x) ri->u.proglen = x
597 #else
598 #define ProgLen(ri) ri->u.offsets[0]
599 #define SetProgLen(ri,x) ri->u.offsets[0] = x
600 #define Set_Node_Offset_To_R(node,byte) STMT_START {                    \
601     if (! SIZE_ONLY) {                                                  \
602         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
603                     __LINE__, (int)(node), (int)(byte)));               \
604         if((node) < 0) {                                                \
605             Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
606         } else {                                                        \
607             RExC_offsets[2*(node)-1] = (byte);                          \
608         }                                                               \
609     }                                                                   \
610 } STMT_END
611
612 #define Set_Node_Offset(node,byte) \
613     Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
614 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
615
616 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
617     if (! SIZE_ONLY) {                                                  \
618         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
619                 __LINE__, (int)(node), (int)(len)));                    \
620         if((node) < 0) {                                                \
621             Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
622         } else {                                                        \
623             RExC_offsets[2*(node)] = (len);                             \
624         }                                                               \
625     }                                                                   \
626 } STMT_END
627
628 #define Set_Node_Length(node,len) \
629     Set_Node_Length_To_R((node)-RExC_emit_start, len)
630 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
631 #define Set_Node_Cur_Length(node) \
632     Set_Node_Length(node, RExC_parse - parse_start)
633
634 /* Get offsets and lengths */
635 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
636 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
637
638 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
639     Set_Node_Offset_To_R((node)-RExC_emit_start, (offset));     \
640     Set_Node_Length_To_R((node)-RExC_emit_start, (len));        \
641 } STMT_END
642 #endif
643
644 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
645 #define EXPERIMENTAL_INPLACESCAN
646 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
647
648 #define DEBUG_STUDYDATA(str,data,depth)                              \
649 DEBUG_OPTIMISE_MORE_r(if(data){                                      \
650     PerlIO_printf(Perl_debug_log,                                    \
651         "%*s" str "Pos:%"IVdf"/%"IVdf                                \
652         " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s",       \
653         (int)(depth)*2, "",                                          \
654         (IV)((data)->pos_min),                                       \
655         (IV)((data)->pos_delta),                                     \
656         (UV)((data)->flags),                                         \
657         (IV)((data)->whilem_c),                                      \
658         (IV)((data)->last_closep ? *((data)->last_closep) : -1),     \
659         is_inf ? "INF " : ""                                         \
660     );                                                               \
661     if ((data)->last_found)                                          \
662         PerlIO_printf(Perl_debug_log,                                \
663             "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
664             " %sFloat: '%s' @ %"IVdf"/%"IVdf"",                      \
665             SvPVX_const((data)->last_found),                         \
666             (IV)((data)->last_end),                                  \
667             (IV)((data)->last_start_min),                            \
668             (IV)((data)->last_start_max),                            \
669             ((data)->longest &&                                      \
670              (data)->longest==&((data)->longest_fixed)) ? "*" : "",  \
671             SvPVX_const((data)->longest_fixed),                      \
672             (IV)((data)->offset_fixed),                              \
673             ((data)->longest &&                                      \
674              (data)->longest==&((data)->longest_float)) ? "*" : "",  \
675             SvPVX_const((data)->longest_float),                      \
676             (IV)((data)->offset_float_min),                          \
677             (IV)((data)->offset_float_max)                           \
678         );                                                           \
679     PerlIO_printf(Perl_debug_log,"\n");                              \
680 });
681
682 static void clear_re(pTHX_ void *r);
683
684 /* Mark that we cannot extend a found fixed substring at this point.
685    Update the longest found anchored substring and the longest found
686    floating substrings if needed. */
687
688 STATIC void
689 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
690 {
691     const STRLEN l = CHR_SVLEN(data->last_found);
692     const STRLEN old_l = CHR_SVLEN(*data->longest);
693     GET_RE_DEBUG_FLAGS_DECL;
694
695     PERL_ARGS_ASSERT_SCAN_COMMIT;
696
697     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
698         SvSetMagicSV(*data->longest, data->last_found);
699         if (*data->longest == data->longest_fixed) {
700             data->offset_fixed = l ? data->last_start_min : data->pos_min;
701             if (data->flags & SF_BEFORE_EOL)
702                 data->flags
703                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
704             else
705                 data->flags &= ~SF_FIX_BEFORE_EOL;
706             data->minlen_fixed=minlenp;
707             data->lookbehind_fixed=0;
708         }
709         else { /* *data->longest == data->longest_float */
710             data->offset_float_min = l ? data->last_start_min : data->pos_min;
711             data->offset_float_max = (l
712                                       ? data->last_start_max
713                                       : data->pos_min + data->pos_delta);
714             if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
715                 data->offset_float_max = I32_MAX;
716             if (data->flags & SF_BEFORE_EOL)
717                 data->flags
718                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
719             else
720                 data->flags &= ~SF_FL_BEFORE_EOL;
721             data->minlen_float=minlenp;
722             data->lookbehind_float=0;
723         }
724     }
725     SvCUR_set(data->last_found, 0);
726     {
727         SV * const sv = data->last_found;
728         if (SvUTF8(sv) && SvMAGICAL(sv)) {
729             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
730             if (mg)
731                 mg->mg_len = 0;
732         }
733     }
734     data->last_end = -1;
735     data->flags &= ~SF_BEFORE_EOL;
736     DEBUG_STUDYDATA("commit: ",data,0);
737 }
738
739 /* Can match anything (initialization) */
740 STATIC void
741 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
742 {
743     PERL_ARGS_ASSERT_CL_ANYTHING;
744
745     ANYOF_BITMAP_SETALL(cl);
746     cl->flags = ANYOF_CLASS|ANYOF_EOS|ANYOF_UNICODE_ALL
747                 |ANYOF_LOC_NONBITMAP_FOLD|ANYOF_NON_UTF8_LATIN1_ALL;
748
749     /* If any portion of the regex is to operate under locale rules,
750      * initialization includes it.  The reason this isn't done for all regexes
751      * is that the optimizer was written under the assumption that locale was
752      * all-or-nothing.  Given the complexity and lack of documentation in the
753      * optimizer, and that there are inadequate test cases for locale, so many
754      * parts of it may not work properly, it is safest to avoid locale unless
755      * necessary. */
756     if (RExC_contains_locale) {
757         ANYOF_CLASS_SETALL(cl);     /* /l uses class */
758         cl->flags |= ANYOF_LOCALE;
759     }
760     else {
761         ANYOF_CLASS_ZERO(cl);       /* Only /l uses class now */
762     }
763 }
764
765 /* Can match anything (initialization) */
766 STATIC int
767 S_cl_is_anything(const struct regnode_charclass_class *cl)
768 {
769     int value;
770
771     PERL_ARGS_ASSERT_CL_IS_ANYTHING;
772
773     for (value = 0; value <= ANYOF_MAX; value += 2)
774         if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
775             return 1;
776     if (!(cl->flags & ANYOF_UNICODE_ALL))
777         return 0;
778     if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
779         return 0;
780     return 1;
781 }
782
783 /* Can match anything (initialization) */
784 STATIC void
785 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
786 {
787     PERL_ARGS_ASSERT_CL_INIT;
788
789     Zero(cl, 1, struct regnode_charclass_class);
790     cl->type = ANYOF;
791     cl_anything(pRExC_state, cl);
792     ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
793 }
794
795 /* These two functions currently do the exact same thing */
796 #define cl_init_zero            S_cl_init
797
798 /* 'AND' a given class with another one.  Can create false positives.  'cl'
799  * should not be inverted.  'and_with->flags & ANYOF_CLASS' should be 0 if
800  * 'and_with' is a regnode_charclass instead of a regnode_charclass_class. */
801 STATIC void
802 S_cl_and(struct regnode_charclass_class *cl,
803         const struct regnode_charclass_class *and_with)
804 {
805     PERL_ARGS_ASSERT_CL_AND;
806
807     assert(and_with->type == ANYOF);
808
809     /* I (khw) am not sure all these restrictions are necessary XXX */
810     if (!(ANYOF_CLASS_TEST_ANY_SET(and_with))
811         && !(ANYOF_CLASS_TEST_ANY_SET(cl))
812         && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
813         && !(and_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
814         && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) {
815         int i;
816
817         if (and_with->flags & ANYOF_INVERT)
818             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
819                 cl->bitmap[i] &= ~and_with->bitmap[i];
820         else
821             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
822                 cl->bitmap[i] &= and_with->bitmap[i];
823     } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
824
825     if (and_with->flags & ANYOF_INVERT) {
826
827         /* Here, the and'ed node is inverted.  Get the AND of the flags that
828          * aren't affected by the inversion.  Those that are affected are
829          * handled individually below */
830         U8 affected_flags = cl->flags & ~INVERSION_UNAFFECTED_FLAGS;
831         cl->flags &= (and_with->flags & INVERSION_UNAFFECTED_FLAGS);
832         cl->flags |= affected_flags;
833
834         /* We currently don't know how to deal with things that aren't in the
835          * bitmap, but we know that the intersection is no greater than what
836          * is already in cl, so let there be false positives that get sorted
837          * out after the synthetic start class succeeds, and the node is
838          * matched for real. */
839
840         /* The inversion of these two flags indicate that the resulting
841          * intersection doesn't have them */
842         if (and_with->flags & ANYOF_UNICODE_ALL) {
843             cl->flags &= ~ANYOF_UNICODE_ALL;
844         }
845         if (and_with->flags & ANYOF_NON_UTF8_LATIN1_ALL) {
846             cl->flags &= ~ANYOF_NON_UTF8_LATIN1_ALL;
847         }
848     }
849     else {   /* and'd node is not inverted */
850         U8 outside_bitmap_but_not_utf8; /* Temp variable */
851
852         if (! ANYOF_NONBITMAP(and_with)) {
853
854             /* Here 'and_with' doesn't match anything outside the bitmap
855              * (except possibly ANYOF_UNICODE_ALL), which means the
856              * intersection can't either, except for ANYOF_UNICODE_ALL, in
857              * which case we don't know what the intersection is, but it's no
858              * greater than what cl already has, so can just leave it alone,
859              * with possible false positives */
860             if (! (and_with->flags & ANYOF_UNICODE_ALL)) {
861                 ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
862                 cl->flags &= ~ANYOF_NONBITMAP_NON_UTF8;
863             }
864         }
865         else if (! ANYOF_NONBITMAP(cl)) {
866
867             /* Here, 'and_with' does match something outside the bitmap, and cl
868              * doesn't have a list of things to match outside the bitmap.  If
869              * cl can match all code points above 255, the intersection will
870              * be those above-255 code points that 'and_with' matches.  If cl
871              * can't match all Unicode code points, it means that it can't
872              * match anything outside the bitmap (since the 'if' that got us
873              * into this block tested for that), so we leave the bitmap empty.
874              */
875             if (cl->flags & ANYOF_UNICODE_ALL) {
876                 ARG_SET(cl, ARG(and_with));
877
878                 /* and_with's ARG may match things that don't require UTF8.
879                  * And now cl's will too, in spite of this being an 'and'.  See
880                  * the comments below about the kludge */
881                 cl->flags |= and_with->flags & ANYOF_NONBITMAP_NON_UTF8;
882             }
883         }
884         else {
885             /* Here, both 'and_with' and cl match something outside the
886              * bitmap.  Currently we do not do the intersection, so just match
887              * whatever cl had at the beginning.  */
888         }
889
890
891         /* Take the intersection of the two sets of flags.  However, the
892          * ANYOF_NONBITMAP_NON_UTF8 flag is treated as an 'or'.  This is a
893          * kludge around the fact that this flag is not treated like the others
894          * which are initialized in cl_anything().  The way the optimizer works
895          * is that the synthetic start class (SSC) is initialized to match
896          * anything, and then the first time a real node is encountered, its
897          * values are AND'd with the SSC's with the result being the values of
898          * the real node.  However, there are paths through the optimizer where
899          * the AND never gets called, so those initialized bits are set
900          * inappropriately, which is not usually a big deal, as they just cause
901          * false positives in the SSC, which will just mean a probably
902          * imperceptible slow down in execution.  However this bit has a
903          * higher false positive consequence in that it can cause utf8.pm,
904          * utf8_heavy.pl ... to be loaded when not necessary, which is a much
905          * bigger slowdown and also causes significant extra memory to be used.
906          * In order to prevent this, the code now takes a different tack.  The
907          * bit isn't set unless some part of the regular expression needs it,
908          * but once set it won't get cleared.  This means that these extra
909          * modules won't get loaded unless there was some path through the
910          * pattern that would have required them anyway, and  so any false
911          * positives that occur by not ANDing them out when they could be
912          * aren't as severe as they would be if we treated this bit like all
913          * the others */
914         outside_bitmap_but_not_utf8 = (cl->flags | and_with->flags)
915                                       & ANYOF_NONBITMAP_NON_UTF8;
916         cl->flags &= and_with->flags;
917         cl->flags |= outside_bitmap_but_not_utf8;
918     }
919 }
920
921 /* 'OR' a given class with another one.  Can create false positives.  'cl'
922  * should not be inverted.  'or_with->flags & ANYOF_CLASS' should be 0 if
923  * 'or_with' is a regnode_charclass instead of a regnode_charclass_class. */
924 STATIC void
925 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
926 {
927     PERL_ARGS_ASSERT_CL_OR;
928
929     if (or_with->flags & ANYOF_INVERT) {
930
931         /* Here, the or'd node is to be inverted.  This means we take the
932          * complement of everything not in the bitmap, but currently we don't
933          * know what that is, so give up and match anything */
934         if (ANYOF_NONBITMAP(or_with)) {
935             cl_anything(pRExC_state, cl);
936         }
937         /* We do not use
938          * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
939          *   <= (B1 | !B2) | (CL1 | !CL2)
940          * which is wasteful if CL2 is small, but we ignore CL2:
941          *   (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
942          * XXXX Can we handle case-fold?  Unclear:
943          *   (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
944          *   (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
945          */
946         else if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
947              && !(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
948              && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD) ) {
949             int i;
950
951             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
952                 cl->bitmap[i] |= ~or_with->bitmap[i];
953         } /* XXXX: logic is complicated otherwise */
954         else {
955             cl_anything(pRExC_state, cl);
956         }
957
958         /* And, we can just take the union of the flags that aren't affected
959          * by the inversion */
960         cl->flags |= or_with->flags & INVERSION_UNAFFECTED_FLAGS;
961
962         /* For the remaining flags:
963             ANYOF_UNICODE_ALL and inverted means to not match anything above
964                     255, which means that the union with cl should just be
965                     what cl has in it, so can ignore this flag
966             ANYOF_NON_UTF8_LATIN1_ALL and inverted means if not utf8 and ord
967                     is 127-255 to match them, but then invert that, so the
968                     union with cl should just be what cl has in it, so can
969                     ignore this flag
970          */
971     } else {    /* 'or_with' is not inverted */
972         /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
973         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
974              && (!(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
975                  || (cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) ) {
976             int i;
977
978             /* OR char bitmap and class bitmap separately */
979             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
980                 cl->bitmap[i] |= or_with->bitmap[i];
981             if (ANYOF_CLASS_TEST_ANY_SET(or_with)) {
982                 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
983                     cl->classflags[i] |= or_with->classflags[i];
984                 cl->flags |= ANYOF_CLASS;
985             }
986         }
987         else { /* XXXX: logic is complicated, leave it along for a moment. */
988             cl_anything(pRExC_state, cl);
989         }
990
991         if (ANYOF_NONBITMAP(or_with)) {
992
993             /* Use the added node's outside-the-bit-map match if there isn't a
994              * conflict.  If there is a conflict (both nodes match something
995              * outside the bitmap, but what they match outside is not the same
996              * pointer, and hence not easily compared until XXX we extend
997              * inversion lists this far), give up and allow the start class to
998              * match everything outside the bitmap.  If that stuff is all above
999              * 255, can just set UNICODE_ALL, otherwise caould be anything. */
1000             if (! ANYOF_NONBITMAP(cl)) {
1001                 ARG_SET(cl, ARG(or_with));
1002             }
1003             else if (ARG(cl) != ARG(or_with)) {
1004
1005                 if ((or_with->flags & ANYOF_NONBITMAP_NON_UTF8)) {
1006                     cl_anything(pRExC_state, cl);
1007                 }
1008                 else {
1009                     cl->flags |= ANYOF_UNICODE_ALL;
1010                 }
1011             }
1012         }
1013
1014         /* Take the union */
1015         cl->flags |= or_with->flags;
1016     }
1017 }
1018
1019 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1020 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
1021 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1022 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
1023
1024
1025 #ifdef DEBUGGING
1026 /*
1027    dump_trie(trie,widecharmap,revcharmap)
1028    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1029    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1030
1031    These routines dump out a trie in a somewhat readable format.
1032    The _interim_ variants are used for debugging the interim
1033    tables that are used to generate the final compressed
1034    representation which is what dump_trie expects.
1035
1036    Part of the reason for their existence is to provide a form
1037    of documentation as to how the different representations function.
1038
1039 */
1040
1041 /*
1042   Dumps the final compressed table form of the trie to Perl_debug_log.
1043   Used for debugging make_trie().
1044 */
1045
1046 STATIC void
1047 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1048             AV *revcharmap, U32 depth)
1049 {
1050     U32 state;
1051     SV *sv=sv_newmortal();
1052     int colwidth= widecharmap ? 6 : 4;
1053     U16 word;
1054     GET_RE_DEBUG_FLAGS_DECL;
1055
1056     PERL_ARGS_ASSERT_DUMP_TRIE;
1057
1058     PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1059         (int)depth * 2 + 2,"",
1060         "Match","Base","Ofs" );
1061
1062     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1063         SV ** const tmp = av_fetch( revcharmap, state, 0);
1064         if ( tmp ) {
1065             PerlIO_printf( Perl_debug_log, "%*s", 
1066                 colwidth,
1067                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1068                             PL_colors[0], PL_colors[1],
1069                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1070                             PERL_PV_ESCAPE_FIRSTCHAR 
1071                 ) 
1072             );
1073         }
1074     }
1075     PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1076         (int)depth * 2 + 2,"");
1077
1078     for( state = 0 ; state < trie->uniquecharcount ; state++ )
1079         PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1080     PerlIO_printf( Perl_debug_log, "\n");
1081
1082     for( state = 1 ; state < trie->statecount ; state++ ) {
1083         const U32 base = trie->states[ state ].trans.base;
1084
1085         PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
1086
1087         if ( trie->states[ state ].wordnum ) {
1088             PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
1089         } else {
1090             PerlIO_printf( Perl_debug_log, "%6s", "" );
1091         }
1092
1093         PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1094
1095         if ( base ) {
1096             U32 ofs = 0;
1097
1098             while( ( base + ofs  < trie->uniquecharcount ) ||
1099                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
1100                      && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
1101                     ofs++;
1102
1103             PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1104
1105             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1106                 if ( ( base + ofs >= trie->uniquecharcount ) &&
1107                      ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1108                      trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1109                 {
1110                    PerlIO_printf( Perl_debug_log, "%*"UVXf,
1111                     colwidth,
1112                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
1113                 } else {
1114                     PerlIO_printf( Perl_debug_log, "%*s",colwidth,"   ." );
1115                 }
1116             }
1117
1118             PerlIO_printf( Perl_debug_log, "]");
1119
1120         }
1121         PerlIO_printf( Perl_debug_log, "\n" );
1122     }
1123     PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=", (int)depth*2, "");
1124     for (word=1; word <= trie->wordcount; word++) {
1125         PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
1126             (int)word, (int)(trie->wordinfo[word].prev),
1127             (int)(trie->wordinfo[word].len));
1128     }
1129     PerlIO_printf(Perl_debug_log, "\n" );
1130 }    
1131 /*
1132   Dumps a fully constructed but uncompressed trie in list form.
1133   List tries normally only are used for construction when the number of 
1134   possible chars (trie->uniquecharcount) is very high.
1135   Used for debugging make_trie().
1136 */
1137 STATIC void
1138 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
1139                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
1140                          U32 depth)
1141 {
1142     U32 state;
1143     SV *sv=sv_newmortal();
1144     int colwidth= widecharmap ? 6 : 4;
1145     GET_RE_DEBUG_FLAGS_DECL;
1146
1147     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1148
1149     /* print out the table precompression.  */
1150     PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1151         (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1152         "------:-----+-----------------\n" );
1153     
1154     for( state=1 ; state < next_alloc ; state ++ ) {
1155         U16 charid;
1156     
1157         PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
1158             (int)depth * 2 + 2,"", (UV)state  );
1159         if ( ! trie->states[ state ].wordnum ) {
1160             PerlIO_printf( Perl_debug_log, "%5s| ","");
1161         } else {
1162             PerlIO_printf( Perl_debug_log, "W%4x| ",
1163                 trie->states[ state ].wordnum
1164             );
1165         }
1166         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
1167             SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
1168             if ( tmp ) {
1169                 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1170                     colwidth,
1171                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1172                             PL_colors[0], PL_colors[1],
1173                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1174                             PERL_PV_ESCAPE_FIRSTCHAR 
1175                     ) ,
1176                     TRIE_LIST_ITEM(state,charid).forid,
1177                     (UV)TRIE_LIST_ITEM(state,charid).newstate
1178                 );
1179                 if (!(charid % 10)) 
1180                     PerlIO_printf(Perl_debug_log, "\n%*s| ",
1181                         (int)((depth * 2) + 14), "");
1182             }
1183         }
1184         PerlIO_printf( Perl_debug_log, "\n");
1185     }
1186 }    
1187
1188 /*
1189   Dumps a fully constructed but uncompressed trie in table form.
1190   This is the normal DFA style state transition table, with a few 
1191   twists to facilitate compression later. 
1192   Used for debugging make_trie().
1193 */
1194 STATIC void
1195 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
1196                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
1197                           U32 depth)
1198 {
1199     U32 state;
1200     U16 charid;
1201     SV *sv=sv_newmortal();
1202     int colwidth= widecharmap ? 6 : 4;
1203     GET_RE_DEBUG_FLAGS_DECL;
1204
1205     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
1206     
1207     /*
1208        print out the table precompression so that we can do a visual check
1209        that they are identical.
1210      */
1211     
1212     PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1213
1214     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1215         SV ** const tmp = av_fetch( revcharmap, charid, 0);
1216         if ( tmp ) {
1217             PerlIO_printf( Perl_debug_log, "%*s", 
1218                 colwidth,
1219                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1220                             PL_colors[0], PL_colors[1],
1221                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1222                             PERL_PV_ESCAPE_FIRSTCHAR 
1223                 ) 
1224             );
1225         }
1226     }
1227
1228     PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1229
1230     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1231         PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1232     }
1233
1234     PerlIO_printf( Perl_debug_log, "\n" );
1235
1236     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1237
1238         PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ", 
1239             (int)depth * 2 + 2,"",
1240             (UV)TRIE_NODENUM( state ) );
1241
1242         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1243             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1244             if (v)
1245                 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1246             else
1247                 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1248         }
1249         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1250             PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1251         } else {
1252             PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1253             trie->states[ TRIE_NODENUM( state ) ].wordnum );
1254         }
1255     }
1256 }
1257
1258 #endif
1259
1260
1261 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1262   startbranch: the first branch in the whole branch sequence
1263   first      : start branch of sequence of branch-exact nodes.
1264                May be the same as startbranch
1265   last       : Thing following the last branch.
1266                May be the same as tail.
1267   tail       : item following the branch sequence
1268   count      : words in the sequence
1269   flags      : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1270   depth      : indent depth
1271
1272 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1273
1274 A trie is an N'ary tree where the branches are determined by digital
1275 decomposition of the key. IE, at the root node you look up the 1st character and
1276 follow that branch repeat until you find the end of the branches. Nodes can be
1277 marked as "accepting" meaning they represent a complete word. Eg:
1278
1279   /he|she|his|hers/
1280
1281 would convert into the following structure. Numbers represent states, letters
1282 following numbers represent valid transitions on the letter from that state, if
1283 the number is in square brackets it represents an accepting state, otherwise it
1284 will be in parenthesis.
1285
1286       +-h->+-e->[3]-+-r->(8)-+-s->[9]
1287       |    |
1288       |   (2)
1289       |    |
1290      (1)   +-i->(6)-+-s->[7]
1291       |
1292       +-s->(3)-+-h->(4)-+-e->[5]
1293
1294       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1295
1296 This shows that when matching against the string 'hers' we will begin at state 1
1297 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1298 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1299 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1300 single traverse. We store a mapping from accepting to state to which word was
1301 matched, and then when we have multiple possibilities we try to complete the
1302 rest of the regex in the order in which they occured in the alternation.
1303
1304 The only prior NFA like behaviour that would be changed by the TRIE support is
1305 the silent ignoring of duplicate alternations which are of the form:
1306
1307  / (DUPE|DUPE) X? (?{ ... }) Y /x
1308
1309 Thus EVAL blocks following a trie may be called a different number of times with
1310 and without the optimisation. With the optimisations dupes will be silently
1311 ignored. This inconsistent behaviour of EVAL type nodes is well established as
1312 the following demonstrates:
1313
1314  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1315
1316 which prints out 'word' three times, but
1317
1318  'words'=~/(word|word|word)(?{ print $1 })S/
1319
1320 which doesnt print it out at all. This is due to other optimisations kicking in.
1321
1322 Example of what happens on a structural level:
1323
1324 The regexp /(ac|ad|ab)+/ will produce the following debug output:
1325
1326    1: CURLYM[1] {1,32767}(18)
1327    5:   BRANCH(8)
1328    6:     EXACT <ac>(16)
1329    8:   BRANCH(11)
1330    9:     EXACT <ad>(16)
1331   11:   BRANCH(14)
1332   12:     EXACT <ab>(16)
1333   16:   SUCCEED(0)
1334   17:   NOTHING(18)
1335   18: END(0)
1336
1337 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1338 and should turn into:
1339
1340    1: CURLYM[1] {1,32767}(18)
1341    5:   TRIE(16)
1342         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1343           <ac>
1344           <ad>
1345           <ab>
1346   16:   SUCCEED(0)
1347   17:   NOTHING(18)
1348   18: END(0)
1349
1350 Cases where tail != last would be like /(?foo|bar)baz/:
1351
1352    1: BRANCH(4)
1353    2:   EXACT <foo>(8)
1354    4: BRANCH(7)
1355    5:   EXACT <bar>(8)
1356    7: TAIL(8)
1357    8: EXACT <baz>(10)
1358   10: END(0)
1359
1360 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1361 and would end up looking like:
1362
1363     1: TRIE(8)
1364       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1365         <foo>
1366         <bar>
1367    7: TAIL(8)
1368    8: EXACT <baz>(10)
1369   10: END(0)
1370
1371     d = uvuni_to_utf8_flags(d, uv, 0);
1372
1373 is the recommended Unicode-aware way of saying
1374
1375     *(d++) = uv;
1376 */
1377
1378 #define TRIE_STORE_REVCHAR(val)                                            \
1379     STMT_START {                                                           \
1380         if (UTF) {                                                         \
1381             SV *zlopp = newSV(7); /* XXX: optimize me */                   \
1382             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
1383             unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, val); \
1384             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
1385             SvPOK_on(zlopp);                                               \
1386             SvUTF8_on(zlopp);                                              \
1387             av_push(revcharmap, zlopp);                                    \
1388         } else {                                                           \
1389             char ooooff = (char)val;                                           \
1390             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
1391         }                                                                  \
1392         } STMT_END
1393
1394 #define TRIE_READ_CHAR STMT_START {                                                     \
1395     wordlen++;                                                                          \
1396     if ( UTF ) {                                                                        \
1397         /* if it is UTF then it is either already folded, or does not need folding */   \
1398         uvc = utf8n_to_uvuni( (const U8*) uc, UTF8_MAXLEN, &len, uniflags);             \
1399     }                                                                                   \
1400     else if (folder == PL_fold_latin1) {                                                \
1401         /* if we use this folder we have to obey unicode rules on latin-1 data */       \
1402         if ( foldlen > 0 ) {                                                            \
1403            uvc = utf8n_to_uvuni( (const U8*) scan, UTF8_MAXLEN, &len, uniflags );       \
1404            foldlen -= len;                                                              \
1405            scan += len;                                                                 \
1406            len = 0;                                                                     \
1407         } else {                                                                        \
1408             len = 1;                                                                    \
1409             uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, 1);                     \
1410             skiplen = UNISKIP(uvc);                                                     \
1411             foldlen -= skiplen;                                                         \
1412             scan = foldbuf + skiplen;                                                   \
1413         }                                                                               \
1414     } else {                                                                            \
1415         /* raw data, will be folded later if needed */                                  \
1416         uvc = (U32)*uc;                                                                 \
1417         len = 1;                                                                        \
1418     }                                                                                   \
1419 } STMT_END
1420
1421
1422
1423 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
1424     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
1425         U32 ging = TRIE_LIST_LEN( state ) *= 2;                 \
1426         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1427     }                                                           \
1428     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
1429     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
1430     TRIE_LIST_CUR( state )++;                                   \
1431 } STMT_END
1432
1433 #define TRIE_LIST_NEW(state) STMT_START {                       \
1434     Newxz( trie->states[ state ].trans.list,               \
1435         4, reg_trie_trans_le );                                 \
1436      TRIE_LIST_CUR( state ) = 1;                                \
1437      TRIE_LIST_LEN( state ) = 4;                                \
1438 } STMT_END
1439
1440 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
1441     U16 dupe= trie->states[ state ].wordnum;                    \
1442     regnode * const noper_next = regnext( noper );              \
1443                                                                 \
1444     DEBUG_r({                                                   \
1445         /* store the word for dumping */                        \
1446         SV* tmp;                                                \
1447         if (OP(noper) != NOTHING)                               \
1448             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
1449         else                                                    \
1450             tmp = newSVpvn_utf8( "", 0, UTF );                  \
1451         av_push( trie_words, tmp );                             \
1452     });                                                         \
1453                                                                 \
1454     curword++;                                                  \
1455     trie->wordinfo[curword].prev   = 0;                         \
1456     trie->wordinfo[curword].len    = wordlen;                   \
1457     trie->wordinfo[curword].accept = state;                     \
1458                                                                 \
1459     if ( noper_next < tail ) {                                  \
1460         if (!trie->jump)                                        \
1461             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1462         trie->jump[curword] = (U16)(noper_next - convert);      \
1463         if (!jumper)                                            \
1464             jumper = noper_next;                                \
1465         if (!nextbranch)                                        \
1466             nextbranch= regnext(cur);                           \
1467     }                                                           \
1468                                                                 \
1469     if ( dupe ) {                                               \
1470         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
1471         /* chain, so that when the bits of chain are later    */\
1472         /* linked together, the dups appear in the chain      */\
1473         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1474         trie->wordinfo[dupe].prev = curword;                    \
1475     } else {                                                    \
1476         /* we haven't inserted this word yet.                */ \
1477         trie->states[ state ].wordnum = curword;                \
1478     }                                                           \
1479 } STMT_END
1480
1481
1482 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
1483      ( ( base + charid >=  ucharcount                                   \
1484          && base + charid < ubound                                      \
1485          && state == trie->trans[ base - ucharcount + charid ].check    \
1486          && trie->trans[ base - ucharcount + charid ].next )            \
1487            ? trie->trans[ base - ucharcount + charid ].next             \
1488            : ( state==1 ? special : 0 )                                 \
1489       )
1490
1491 #define MADE_TRIE       1
1492 #define MADE_JUMP_TRIE  2
1493 #define MADE_EXACT_TRIE 4
1494
1495 STATIC I32
1496 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1497 {
1498     dVAR;
1499     /* first pass, loop through and scan words */
1500     reg_trie_data *trie;
1501     HV *widecharmap = NULL;
1502     AV *revcharmap = newAV();
1503     regnode *cur;
1504     const U32 uniflags = UTF8_ALLOW_DEFAULT;
1505     STRLEN len = 0;
1506     UV uvc = 0;
1507     U16 curword = 0;
1508     U32 next_alloc = 0;
1509     regnode *jumper = NULL;
1510     regnode *nextbranch = NULL;
1511     regnode *convert = NULL;
1512     U32 *prev_states; /* temp array mapping each state to previous one */
1513     /* we just use folder as a flag in utf8 */
1514     const U8 * folder = NULL;
1515
1516 #ifdef DEBUGGING
1517     const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1518     AV *trie_words = NULL;
1519     /* along with revcharmap, this only used during construction but both are
1520      * useful during debugging so we store them in the struct when debugging.
1521      */
1522 #else
1523     const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1524     STRLEN trie_charcount=0;
1525 #endif
1526     SV *re_trie_maxbuff;
1527     GET_RE_DEBUG_FLAGS_DECL;
1528
1529     PERL_ARGS_ASSERT_MAKE_TRIE;
1530 #ifndef DEBUGGING
1531     PERL_UNUSED_ARG(depth);
1532 #endif
1533
1534     switch (flags) {
1535         case EXACT: break;
1536         case EXACTFA:
1537         case EXACTFU_SS:
1538         case EXACTFU_TRICKYFOLD:
1539         case EXACTFU: folder = PL_fold_latin1; break;
1540         case EXACTF:  folder = PL_fold; break;
1541         case EXACTFL: folder = PL_fold_locale; break;
1542         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] );
1543     }
1544
1545     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1546     trie->refcount = 1;
1547     trie->startstate = 1;
1548     trie->wordcount = word_count;
1549     RExC_rxi->data->data[ data_slot ] = (void*)trie;
1550     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1551     if (flags == EXACT)
1552         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1553     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
1554                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
1555
1556     DEBUG_r({
1557         trie_words = newAV();
1558     });
1559
1560     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1561     if (!SvIOK(re_trie_maxbuff)) {
1562         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1563     }
1564     DEBUG_TRIE_COMPILE_r({
1565                 PerlIO_printf( Perl_debug_log,
1566                   "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1567                   (int)depth * 2 + 2, "", 
1568                   REG_NODE_NUM(startbranch),REG_NODE_NUM(first), 
1569                   REG_NODE_NUM(last), REG_NODE_NUM(tail),
1570                   (int)depth);
1571     });
1572    
1573    /* Find the node we are going to overwrite */
1574     if ( first == startbranch && OP( last ) != BRANCH ) {
1575         /* whole branch chain */
1576         convert = first;
1577     } else {
1578         /* branch sub-chain */
1579         convert = NEXTOPER( first );
1580     }
1581         
1582     /*  -- First loop and Setup --
1583
1584        We first traverse the branches and scan each word to determine if it
1585        contains widechars, and how many unique chars there are, this is
1586        important as we have to build a table with at least as many columns as we
1587        have unique chars.
1588
1589        We use an array of integers to represent the character codes 0..255
1590        (trie->charmap) and we use a an HV* to store Unicode characters. We use the
1591        native representation of the character value as the key and IV's for the
1592        coded index.
1593
1594        *TODO* If we keep track of how many times each character is used we can
1595        remap the columns so that the table compression later on is more
1596        efficient in terms of memory by ensuring the most common value is in the
1597        middle and the least common are on the outside.  IMO this would be better
1598        than a most to least common mapping as theres a decent chance the most
1599        common letter will share a node with the least common, meaning the node
1600        will not be compressible. With a middle is most common approach the worst
1601        case is when we have the least common nodes twice.
1602
1603      */
1604
1605     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1606         regnode *noper = NEXTOPER( cur );
1607         const U8 *uc = (U8*)STRING( noper );
1608         const U8 *e  = uc + STR_LEN( noper );
1609         STRLEN foldlen = 0;
1610         U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1611         STRLEN skiplen = 0;
1612         const U8 *scan = (U8*)NULL;
1613         U32 wordlen      = 0;         /* required init */
1614         STRLEN chars = 0;
1615         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
1616
1617         if (OP(noper) == NOTHING) {
1618             regnode *noper_next= regnext(noper);
1619             if (noper_next != tail && OP(noper_next) == flags) {
1620                 noper = noper_next;
1621                 uc= (U8*)STRING(noper);
1622                 e= uc + STR_LEN(noper);
1623                 trie->minlen= STR_LEN(noper);
1624             } else {
1625                 trie->minlen= 0;
1626                 continue;
1627             }
1628         }
1629
1630         if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */
1631             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1632                                           regardless of encoding */
1633             if (OP( noper ) == EXACTFU_SS) {
1634                 /* false positives are ok, so just set this */
1635                 TRIE_BITMAP_SET(trie,0xDF);
1636             }
1637         }
1638         for ( ; uc < e ; uc += len ) {
1639             TRIE_CHARCOUNT(trie)++;
1640             TRIE_READ_CHAR;
1641             chars++;
1642             if ( uvc < 256 ) {
1643                 if ( folder ) {
1644                     U8 folded= folder[ (U8) uvc ];
1645                     if ( !trie->charmap[ folded ] ) {
1646                         trie->charmap[ folded ]=( ++trie->uniquecharcount );
1647                         TRIE_STORE_REVCHAR( folded );
1648                     }
1649                 }
1650                 if ( !trie->charmap[ uvc ] ) {
1651                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1652                     TRIE_STORE_REVCHAR( uvc );
1653                 }
1654                 if ( set_bit ) {
1655                     /* store the codepoint in the bitmap, and its folded
1656                      * equivalent. */
1657                     TRIE_BITMAP_SET(trie, uvc);
1658
1659                     /* store the folded codepoint */
1660                     if ( folder ) TRIE_BITMAP_SET(trie, folder[(U8) uvc ]);
1661
1662                     if ( !UTF ) {
1663                         /* store first byte of utf8 representation of
1664                            variant codepoints */
1665                         if (! UNI_IS_INVARIANT(uvc)) {
1666                             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
1667                         }
1668                     }
1669                     set_bit = 0; /* We've done our bit :-) */
1670                 }
1671             } else {
1672                 SV** svpp;
1673                 if ( !widecharmap )
1674                     widecharmap = newHV();
1675
1676                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1677
1678                 if ( !svpp )
1679                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1680
1681                 if ( !SvTRUE( *svpp ) ) {
1682                     sv_setiv( *svpp, ++trie->uniquecharcount );
1683                     TRIE_STORE_REVCHAR(uvc);
1684                 }
1685             }
1686         }
1687         if( cur == first ) {
1688             trie->minlen = chars;
1689             trie->maxlen = chars;
1690         } else if (chars < trie->minlen) {
1691             trie->minlen = chars;
1692         } else if (chars > trie->maxlen) {
1693             trie->maxlen = chars;
1694         }
1695         if (OP( noper ) == EXACTFU_SS) {
1696             /* XXX: workaround - 'ss' could match "\x{DF}" so minlen could be 1 and not 2*/
1697             if (trie->minlen > 1)
1698                 trie->minlen= 1;
1699         }
1700         if (OP( noper ) == EXACTFU_TRICKYFOLD) {
1701             /* XXX: workround - things like "\x{1FBE}\x{0308}\x{0301}" can match "\x{0390}" 
1702              *                - We assume that any such sequence might match a 2 byte string */
1703             if (trie->minlen > 2 )
1704                 trie->minlen= 2;
1705         }
1706
1707     } /* end first pass */
1708     DEBUG_TRIE_COMPILE_r(
1709         PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1710                 (int)depth * 2 + 2,"",
1711                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1712                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1713                 (int)trie->minlen, (int)trie->maxlen )
1714     );
1715
1716     /*
1717         We now know what we are dealing with in terms of unique chars and
1718         string sizes so we can calculate how much memory a naive
1719         representation using a flat table  will take. If it's over a reasonable
1720         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1721         conservative but potentially much slower representation using an array
1722         of lists.
1723
1724         At the end we convert both representations into the same compressed
1725         form that will be used in regexec.c for matching with. The latter
1726         is a form that cannot be used to construct with but has memory
1727         properties similar to the list form and access properties similar
1728         to the table form making it both suitable for fast searches and
1729         small enough that its feasable to store for the duration of a program.
1730
1731         See the comment in the code where the compressed table is produced
1732         inplace from the flat tabe representation for an explanation of how
1733         the compression works.
1734
1735     */
1736
1737
1738     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
1739     prev_states[1] = 0;
1740
1741     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1742         /*
1743             Second Pass -- Array Of Lists Representation
1744
1745             Each state will be represented by a list of charid:state records
1746             (reg_trie_trans_le) the first such element holds the CUR and LEN
1747             points of the allocated array. (See defines above).
1748
1749             We build the initial structure using the lists, and then convert
1750             it into the compressed table form which allows faster lookups
1751             (but cant be modified once converted).
1752         */
1753
1754         STRLEN transcount = 1;
1755
1756         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1757             "%*sCompiling trie using list compiler\n",
1758             (int)depth * 2 + 2, ""));
1759
1760         trie->states = (reg_trie_state *)
1761             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1762                                   sizeof(reg_trie_state) );
1763         TRIE_LIST_NEW(1);
1764         next_alloc = 2;
1765
1766         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1767
1768             regnode *noper   = NEXTOPER( cur );
1769             U8 *uc           = (U8*)STRING( noper );
1770             const U8 *e      = uc + STR_LEN( noper );
1771             U32 state        = 1;         /* required init */
1772             U16 charid       = 0;         /* sanity init */
1773             U8 *scan         = (U8*)NULL; /* sanity init */
1774             STRLEN foldlen   = 0;         /* required init */
1775             U32 wordlen      = 0;         /* required init */
1776             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1777             STRLEN skiplen   = 0;
1778
1779             if (OP(noper) == NOTHING) {
1780                 regnode *noper_next= regnext(noper);
1781                 if (noper_next != tail && OP(noper_next) == flags) {
1782                     noper = noper_next;
1783                     uc= (U8*)STRING(noper);
1784                     e= uc + STR_LEN(noper);
1785                 }
1786             }
1787
1788             if (OP(noper) != NOTHING) {
1789                 for ( ; uc < e ; uc += len ) {
1790
1791                     TRIE_READ_CHAR;
1792
1793                     if ( uvc < 256 ) {
1794                         charid = trie->charmap[ uvc ];
1795                     } else {
1796                         SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1797                         if ( !svpp ) {
1798                             charid = 0;
1799                         } else {
1800                             charid=(U16)SvIV( *svpp );
1801                         }
1802                     }
1803                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
1804                     if ( charid ) {
1805
1806                         U16 check;
1807                         U32 newstate = 0;
1808
1809                         charid--;
1810                         if ( !trie->states[ state ].trans.list ) {
1811                             TRIE_LIST_NEW( state );
1812                         }
1813                         for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1814                             if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1815                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1816                                 break;
1817                             }
1818                         }
1819                         if ( ! newstate ) {
1820                             newstate = next_alloc++;
1821                             prev_states[newstate] = state;
1822                             TRIE_LIST_PUSH( state, charid, newstate );
1823                             transcount++;
1824                         }
1825                         state = newstate;
1826                     } else {
1827                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1828                     }
1829                 }
1830             }
1831             TRIE_HANDLE_WORD(state);
1832
1833         } /* end second pass */
1834
1835         /* next alloc is the NEXT state to be allocated */
1836         trie->statecount = next_alloc; 
1837         trie->states = (reg_trie_state *)
1838             PerlMemShared_realloc( trie->states,
1839                                    next_alloc
1840                                    * sizeof(reg_trie_state) );
1841
1842         /* and now dump it out before we compress it */
1843         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1844                                                          revcharmap, next_alloc,
1845                                                          depth+1)
1846         );
1847
1848         trie->trans = (reg_trie_trans *)
1849             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1850         {
1851             U32 state;
1852             U32 tp = 0;
1853             U32 zp = 0;
1854
1855
1856             for( state=1 ; state < next_alloc ; state ++ ) {
1857                 U32 base=0;
1858
1859                 /*
1860                 DEBUG_TRIE_COMPILE_MORE_r(
1861                     PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1862                 );
1863                 */
1864
1865                 if (trie->states[state].trans.list) {
1866                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1867                     U16 maxid=minid;
1868                     U16 idx;
1869
1870                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1871                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1872                         if ( forid < minid ) {
1873                             minid=forid;
1874                         } else if ( forid > maxid ) {
1875                             maxid=forid;
1876                         }
1877                     }
1878                     if ( transcount < tp + maxid - minid + 1) {
1879                         transcount *= 2;
1880                         trie->trans = (reg_trie_trans *)
1881                             PerlMemShared_realloc( trie->trans,
1882                                                      transcount
1883                                                      * sizeof(reg_trie_trans) );
1884                         Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1885                     }
1886                     base = trie->uniquecharcount + tp - minid;
1887                     if ( maxid == minid ) {
1888                         U32 set = 0;
1889                         for ( ; zp < tp ; zp++ ) {
1890                             if ( ! trie->trans[ zp ].next ) {
1891                                 base = trie->uniquecharcount + zp - minid;
1892                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1893                                 trie->trans[ zp ].check = state;
1894                                 set = 1;
1895                                 break;
1896                             }
1897                         }
1898                         if ( !set ) {
1899                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1900                             trie->trans[ tp ].check = state;
1901                             tp++;
1902                             zp = tp;
1903                         }
1904                     } else {
1905                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1906                             const U32 tid = base -  trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1907                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1908                             trie->trans[ tid ].check = state;
1909                         }
1910                         tp += ( maxid - minid + 1 );
1911                     }
1912                     Safefree(trie->states[ state ].trans.list);
1913                 }
1914                 /*
1915                 DEBUG_TRIE_COMPILE_MORE_r(
1916                     PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1917                 );
1918                 */
1919                 trie->states[ state ].trans.base=base;
1920             }
1921             trie->lasttrans = tp + 1;
1922         }
1923     } else {
1924         /*
1925            Second Pass -- Flat Table Representation.
1926
1927            we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1928            We know that we will need Charcount+1 trans at most to store the data
1929            (one row per char at worst case) So we preallocate both structures
1930            assuming worst case.
1931
1932            We then construct the trie using only the .next slots of the entry
1933            structs.
1934
1935            We use the .check field of the first entry of the node temporarily to
1936            make compression both faster and easier by keeping track of how many non
1937            zero fields are in the node.
1938
1939            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1940            transition.
1941
1942            There are two terms at use here: state as a TRIE_NODEIDX() which is a
1943            number representing the first entry of the node, and state as a
1944            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1945            TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1946            are 2 entrys per node. eg:
1947
1948              A B       A B
1949           1. 2 4    1. 3 7
1950           2. 0 3    3. 0 5
1951           3. 0 0    5. 0 0
1952           4. 0 0    7. 0 0
1953
1954            The table is internally in the right hand, idx form. However as we also
1955            have to deal with the states array which is indexed by nodenum we have to
1956            use TRIE_NODENUM() to convert.
1957
1958         */
1959         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1960             "%*sCompiling trie using table compiler\n",
1961             (int)depth * 2 + 2, ""));
1962
1963         trie->trans = (reg_trie_trans *)
1964             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1965                                   * trie->uniquecharcount + 1,
1966                                   sizeof(reg_trie_trans) );
1967         trie->states = (reg_trie_state *)
1968             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1969                                   sizeof(reg_trie_state) );
1970         next_alloc = trie->uniquecharcount + 1;
1971
1972
1973         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1974
1975             regnode *noper   = NEXTOPER( cur );
1976             const U8 *uc     = (U8*)STRING( noper );
1977             const U8 *e      = uc + STR_LEN( noper );
1978
1979             U32 state        = 1;         /* required init */
1980
1981             U16 charid       = 0;         /* sanity init */
1982             U32 accept_state = 0;         /* sanity init */
1983             U8 *scan         = (U8*)NULL; /* sanity init */
1984
1985             STRLEN foldlen   = 0;         /* required init */
1986             U32 wordlen      = 0;         /* required init */
1987             STRLEN skiplen   = 0;
1988             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1989
1990             if (OP(noper) == NOTHING) {
1991                 regnode *noper_next= regnext(noper);
1992                 if (noper_next != tail && OP(noper_next) == flags) {
1993                     noper = noper_next;
1994                     uc= (U8*)STRING(noper);
1995                     e= uc + STR_LEN(noper);
1996                 }
1997             }
1998
1999             if ( OP(noper) != NOTHING ) {
2000                 for ( ; uc < e ; uc += len ) {
2001
2002                     TRIE_READ_CHAR;
2003
2004                     if ( uvc < 256 ) {
2005                         charid = trie->charmap[ uvc ];
2006                     } else {
2007                         SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
2008                         charid = svpp ? (U16)SvIV(*svpp) : 0;
2009                     }
2010                     if ( charid ) {
2011                         charid--;
2012                         if ( !trie->trans[ state + charid ].next ) {
2013                             trie->trans[ state + charid ].next = next_alloc;
2014                             trie->trans[ state ].check++;
2015                             prev_states[TRIE_NODENUM(next_alloc)]
2016                                     = TRIE_NODENUM(state);
2017                             next_alloc += trie->uniquecharcount;
2018                         }
2019                         state = trie->trans[ state + charid ].next;
2020                     } else {
2021                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
2022                     }
2023                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
2024                 }
2025             }
2026             accept_state = TRIE_NODENUM( state );
2027             TRIE_HANDLE_WORD(accept_state);
2028
2029         } /* end second pass */
2030
2031         /* and now dump it out before we compress it */
2032         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
2033                                                           revcharmap,
2034                                                           next_alloc, depth+1));
2035
2036         {
2037         /*
2038            * Inplace compress the table.*
2039
2040            For sparse data sets the table constructed by the trie algorithm will
2041            be mostly 0/FAIL transitions or to put it another way mostly empty.
2042            (Note that leaf nodes will not contain any transitions.)
2043
2044            This algorithm compresses the tables by eliminating most such
2045            transitions, at the cost of a modest bit of extra work during lookup:
2046
2047            - Each states[] entry contains a .base field which indicates the
2048            index in the state[] array wheres its transition data is stored.
2049
2050            - If .base is 0 there are no valid transitions from that node.
2051
2052            - If .base is nonzero then charid is added to it to find an entry in
2053            the trans array.
2054
2055            -If trans[states[state].base+charid].check!=state then the
2056            transition is taken to be a 0/Fail transition. Thus if there are fail
2057            transitions at the front of the node then the .base offset will point
2058            somewhere inside the previous nodes data (or maybe even into a node
2059            even earlier), but the .check field determines if the transition is
2060            valid.
2061
2062            XXX - wrong maybe?
2063            The following process inplace converts the table to the compressed
2064            table: We first do not compress the root node 1,and mark all its
2065            .check pointers as 1 and set its .base pointer as 1 as well. This
2066            allows us to do a DFA construction from the compressed table later,
2067            and ensures that any .base pointers we calculate later are greater
2068            than 0.
2069
2070            - We set 'pos' to indicate the first entry of the second node.
2071
2072            - We then iterate over the columns of the node, finding the first and
2073            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
2074            and set the .check pointers accordingly, and advance pos
2075            appropriately and repreat for the next node. Note that when we copy
2076            the next pointers we have to convert them from the original
2077            NODEIDX form to NODENUM form as the former is not valid post
2078            compression.
2079
2080            - If a node has no transitions used we mark its base as 0 and do not
2081            advance the pos pointer.
2082
2083            - If a node only has one transition we use a second pointer into the
2084            structure to fill in allocated fail transitions from other states.
2085            This pointer is independent of the main pointer and scans forward
2086            looking for null transitions that are allocated to a state. When it
2087            finds one it writes the single transition into the "hole".  If the
2088            pointer doesnt find one the single transition is appended as normal.
2089
2090            - Once compressed we can Renew/realloc the structures to release the
2091            excess space.
2092
2093            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
2094            specifically Fig 3.47 and the associated pseudocode.
2095
2096            demq
2097         */
2098         const U32 laststate = TRIE_NODENUM( next_alloc );
2099         U32 state, charid;
2100         U32 pos = 0, zp=0;
2101         trie->statecount = laststate;
2102
2103         for ( state = 1 ; state < laststate ; state++ ) {
2104             U8 flag = 0;
2105             const U32 stateidx = TRIE_NODEIDX( state );
2106             const U32 o_used = trie->trans[ stateidx ].check;
2107             U32 used = trie->trans[ stateidx ].check;
2108             trie->trans[ stateidx ].check = 0;
2109
2110             for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
2111                 if ( flag || trie->trans[ stateidx + charid ].next ) {
2112                     if ( trie->trans[ stateidx + charid ].next ) {
2113                         if (o_used == 1) {
2114                             for ( ; zp < pos ; zp++ ) {
2115                                 if ( ! trie->trans[ zp ].next ) {
2116                                     break;
2117                                 }
2118                             }
2119                             trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
2120                             trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2121                             trie->trans[ zp ].check = state;
2122                             if ( ++zp > pos ) pos = zp;
2123                             break;
2124                         }
2125                         used--;
2126                     }
2127                     if ( !flag ) {
2128                         flag = 1;
2129                         trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
2130                     }
2131                     trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2132                     trie->trans[ pos ].check = state;
2133                     pos++;
2134                 }
2135             }
2136         }
2137         trie->lasttrans = pos + 1;
2138         trie->states = (reg_trie_state *)
2139             PerlMemShared_realloc( trie->states, laststate
2140                                    * sizeof(reg_trie_state) );
2141         DEBUG_TRIE_COMPILE_MORE_r(
2142                 PerlIO_printf( Perl_debug_log,
2143                     "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
2144                     (int)depth * 2 + 2,"",
2145                     (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
2146                     (IV)next_alloc,
2147                     (IV)pos,
2148                     ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
2149             );
2150
2151         } /* end table compress */
2152     }
2153     DEBUG_TRIE_COMPILE_MORE_r(
2154             PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
2155                 (int)depth * 2 + 2, "",
2156                 (UV)trie->statecount,
2157                 (UV)trie->lasttrans)
2158     );
2159     /* resize the trans array to remove unused space */
2160     trie->trans = (reg_trie_trans *)
2161         PerlMemShared_realloc( trie->trans, trie->lasttrans
2162                                * sizeof(reg_trie_trans) );
2163
2164     {   /* Modify the program and insert the new TRIE node */ 
2165         U8 nodetype =(U8)(flags & 0xFF);
2166         char *str=NULL;
2167         
2168 #ifdef DEBUGGING
2169         regnode *optimize = NULL;
2170 #ifdef RE_TRACK_PATTERN_OFFSETS
2171
2172         U32 mjd_offset = 0;
2173         U32 mjd_nodelen = 0;
2174 #endif /* RE_TRACK_PATTERN_OFFSETS */
2175 #endif /* DEBUGGING */
2176         /*
2177            This means we convert either the first branch or the first Exact,
2178            depending on whether the thing following (in 'last') is a branch
2179            or not and whther first is the startbranch (ie is it a sub part of
2180            the alternation or is it the whole thing.)
2181            Assuming its a sub part we convert the EXACT otherwise we convert
2182            the whole branch sequence, including the first.
2183          */
2184         /* Find the node we are going to overwrite */
2185         if ( first != startbranch || OP( last ) == BRANCH ) {
2186             /* branch sub-chain */
2187             NEXT_OFF( first ) = (U16)(last - first);
2188 #ifdef RE_TRACK_PATTERN_OFFSETS
2189             DEBUG_r({
2190                 mjd_offset= Node_Offset((convert));
2191                 mjd_nodelen= Node_Length((convert));
2192             });
2193 #endif
2194             /* whole branch chain */
2195         }
2196 #ifdef RE_TRACK_PATTERN_OFFSETS
2197         else {
2198             DEBUG_r({
2199                 const  regnode *nop = NEXTOPER( convert );
2200                 mjd_offset= Node_Offset((nop));
2201                 mjd_nodelen= Node_Length((nop));
2202             });
2203         }
2204         DEBUG_OPTIMISE_r(
2205             PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
2206                 (int)depth * 2 + 2, "",
2207                 (UV)mjd_offset, (UV)mjd_nodelen)
2208         );
2209 #endif
2210         /* But first we check to see if there is a common prefix we can 
2211            split out as an EXACT and put in front of the TRIE node.  */
2212         trie->startstate= 1;
2213         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
2214             U32 state;
2215             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
2216                 U32 ofs = 0;
2217                 I32 idx = -1;
2218                 U32 count = 0;
2219                 const U32 base = trie->states[ state ].trans.base;
2220
2221                 if ( trie->states[state].wordnum )
2222                         count = 1;
2223
2224                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2225                     if ( ( base + ofs >= trie->uniquecharcount ) &&
2226                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
2227                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2228                     {
2229                         if ( ++count > 1 ) {
2230                             SV **tmp = av_fetch( revcharmap, ofs, 0);
2231                             const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
2232                             if ( state == 1 ) break;
2233                             if ( count == 2 ) {
2234                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2235                                 DEBUG_OPTIMISE_r(
2236                                     PerlIO_printf(Perl_debug_log,
2237                                         "%*sNew Start State=%"UVuf" Class: [",
2238                                         (int)depth * 2 + 2, "",
2239                                         (UV)state));
2240                                 if (idx >= 0) {
2241                                     SV ** const tmp = av_fetch( revcharmap, idx, 0);
2242                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
2243
2244                                     TRIE_BITMAP_SET(trie,*ch);
2245                                     if ( folder )
2246                                         TRIE_BITMAP_SET(trie, folder[ *ch ]);
2247                                     DEBUG_OPTIMISE_r(
2248                                         PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
2249                                     );
2250                                 }
2251                             }
2252                             TRIE_BITMAP_SET(trie,*ch);
2253                             if ( folder )
2254                                 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2255                             DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2256                         }
2257                         idx = ofs;
2258                     }
2259                 }
2260                 if ( count == 1 ) {
2261                     SV **tmp = av_fetch( revcharmap, idx, 0);
2262                     STRLEN len;
2263                     char *ch = SvPV( *tmp, len );
2264                     DEBUG_OPTIMISE_r({
2265                         SV *sv=sv_newmortal();
2266                         PerlIO_printf( Perl_debug_log,
2267                             "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2268                             (int)depth * 2 + 2, "",
2269                             (UV)state, (UV)idx, 
2270                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6, 
2271                                 PL_colors[0], PL_colors[1],
2272                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2273                                 PERL_PV_ESCAPE_FIRSTCHAR 
2274                             )
2275                         );
2276                     });
2277                     if ( state==1 ) {
2278                         OP( convert ) = nodetype;
2279                         str=STRING(convert);
2280                         STR_LEN(convert)=0;
2281                     }
2282                     STR_LEN(convert) += len;
2283                     while (len--)
2284                         *str++ = *ch++;
2285                 } else {
2286 #ifdef DEBUGGING            
2287                     if (state>1)
2288                         DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
2289 #endif
2290                     break;
2291                 }
2292             }
2293             trie->prefixlen = (state-1);
2294             if (str) {
2295                 regnode *n = convert+NODE_SZ_STR(convert);
2296                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
2297                 trie->startstate = state;
2298                 trie->minlen -= (state - 1);
2299                 trie->maxlen -= (state - 1);
2300 #ifdef DEBUGGING
2301                /* At least the UNICOS C compiler choked on this
2302                 * being argument to DEBUG_r(), so let's just have
2303                 * it right here. */
2304                if (
2305 #ifdef PERL_EXT_RE_BUILD
2306                    1
2307 #else
2308                    DEBUG_r_TEST
2309 #endif
2310                    ) {
2311                    regnode *fix = convert;
2312                    U32 word = trie->wordcount;
2313                    mjd_nodelen++;
2314                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2315                    while( ++fix < n ) {
2316                        Set_Node_Offset_Length(fix, 0, 0);
2317                    }
2318                    while (word--) {
2319                        SV ** const tmp = av_fetch( trie_words, word, 0 );
2320                        if (tmp) {
2321                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
2322                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2323                            else
2324                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2325                        }
2326                    }
2327                }
2328 #endif
2329                 if (trie->maxlen) {
2330                     convert = n;
2331                 } else {
2332                     NEXT_OFF(convert) = (U16)(tail - convert);
2333                     DEBUG_r(optimize= n);
2334                 }
2335             }
2336         }
2337         if (!jumper) 
2338             jumper = last; 
2339         if ( trie->maxlen ) {
2340             NEXT_OFF( convert ) = (U16)(tail - convert);
2341             ARG_SET( convert, data_slot );
2342             /* Store the offset to the first unabsorbed branch in 
2343                jump[0], which is otherwise unused by the jump logic. 
2344                We use this when dumping a trie and during optimisation. */
2345             if (trie->jump) 
2346                 trie->jump[0] = (U16)(nextbranch - convert);
2347             
2348             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
2349              *   and there is a bitmap
2350              *   and the first "jump target" node we found leaves enough room
2351              * then convert the TRIE node into a TRIEC node, with the bitmap
2352              * embedded inline in the opcode - this is hypothetically faster.
2353              */
2354             if ( !trie->states[trie->startstate].wordnum
2355                  && trie->bitmap
2356                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2357             {
2358                 OP( convert ) = TRIEC;
2359                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2360                 PerlMemShared_free(trie->bitmap);
2361                 trie->bitmap= NULL;
2362             } else 
2363                 OP( convert ) = TRIE;
2364
2365             /* store the type in the flags */
2366             convert->flags = nodetype;
2367             DEBUG_r({
2368             optimize = convert 
2369                       + NODE_STEP_REGNODE 
2370                       + regarglen[ OP( convert ) ];
2371             });
2372             /* XXX We really should free up the resource in trie now, 
2373                    as we won't use them - (which resources?) dmq */
2374         }
2375         /* needed for dumping*/
2376         DEBUG_r(if (optimize) {
2377             regnode *opt = convert;
2378
2379             while ( ++opt < optimize) {
2380                 Set_Node_Offset_Length(opt,0,0);
2381             }
2382             /* 
2383                 Try to clean up some of the debris left after the 
2384                 optimisation.
2385              */
2386             while( optimize < jumper ) {
2387                 mjd_nodelen += Node_Length((optimize));
2388                 OP( optimize ) = OPTIMIZED;
2389                 Set_Node_Offset_Length(optimize,0,0);
2390                 optimize++;
2391             }
2392             Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2393         });
2394     } /* end node insert */
2395
2396     /*  Finish populating the prev field of the wordinfo array.  Walk back
2397      *  from each accept state until we find another accept state, and if
2398      *  so, point the first word's .prev field at the second word. If the
2399      *  second already has a .prev field set, stop now. This will be the
2400      *  case either if we've already processed that word's accept state,
2401      *  or that state had multiple words, and the overspill words were
2402      *  already linked up earlier.
2403      */
2404     {
2405         U16 word;
2406         U32 state;
2407         U16 prev;
2408
2409         for (word=1; word <= trie->wordcount; word++) {
2410             prev = 0;
2411             if (trie->wordinfo[word].prev)
2412                 continue;
2413             state = trie->wordinfo[word].accept;
2414             while (state) {
2415                 state = prev_states[state];
2416                 if (!state)
2417                     break;
2418                 prev = trie->states[state].wordnum;
2419                 if (prev)
2420                     break;
2421             }
2422             trie->wordinfo[word].prev = prev;
2423         }
2424         Safefree(prev_states);
2425     }
2426
2427
2428     /* and now dump out the compressed format */
2429     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2430
2431     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2432 #ifdef DEBUGGING
2433     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2434     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2435 #else
2436     SvREFCNT_dec(revcharmap);
2437 #endif
2438     return trie->jump 
2439            ? MADE_JUMP_TRIE 
2440            : trie->startstate>1 
2441              ? MADE_EXACT_TRIE 
2442              : MADE_TRIE;
2443 }
2444
2445 STATIC void
2446 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source,  regnode *stclass, U32 depth)
2447 {
2448 /* The Trie is constructed and compressed now so we can build a fail array if it's needed
2449
2450    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2451    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2452    ISBN 0-201-10088-6
2453
2454    We find the fail state for each state in the trie, this state is the longest proper
2455    suffix of the current state's 'word' that is also a proper prefix of another word in our
2456    trie. State 1 represents the word '' and is thus the default fail state. This allows
2457    the DFA not to have to restart after its tried and failed a word at a given point, it
2458    simply continues as though it had been matching the other word in the first place.
2459    Consider
2460       'abcdgu'=~/abcdefg|cdgu/
2461    When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2462    fail, which would bring us to the state representing 'd' in the second word where we would
2463    try 'g' and succeed, proceeding to match 'cdgu'.
2464  */
2465  /* add a fail transition */
2466     const U32 trie_offset = ARG(source);
2467     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2468     U32 *q;
2469     const U32 ucharcount = trie->uniquecharcount;
2470     const U32 numstates = trie->statecount;
2471     const U32 ubound = trie->lasttrans + ucharcount;
2472     U32 q_read = 0;
2473     U32 q_write = 0;
2474     U32 charid;
2475     U32 base = trie->states[ 1 ].trans.base;
2476     U32 *fail;
2477     reg_ac_data *aho;
2478     const U32 data_slot = add_data( pRExC_state, 1, "T" );
2479     GET_RE_DEBUG_FLAGS_DECL;
2480
2481     PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
2482 #ifndef DEBUGGING
2483     PERL_UNUSED_ARG(depth);
2484 #endif
2485
2486
2487     ARG_SET( stclass, data_slot );
2488     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2489     RExC_rxi->data->data[ data_slot ] = (void*)aho;
2490     aho->trie=trie_offset;
2491     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2492     Copy( trie->states, aho->states, numstates, reg_trie_state );
2493     Newxz( q, numstates, U32);
2494     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2495     aho->refcount = 1;
2496     fail = aho->fail;
2497     /* initialize fail[0..1] to be 1 so that we always have
2498        a valid final fail state */
2499     fail[ 0 ] = fail[ 1 ] = 1;
2500
2501     for ( charid = 0; charid < ucharcount ; charid++ ) {
2502         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2503         if ( newstate ) {
2504             q[ q_write ] = newstate;
2505             /* set to point at the root */
2506             fail[ q[ q_write++ ] ]=1;
2507         }
2508     }
2509     while ( q_read < q_write) {
2510         const U32 cur = q[ q_read++ % numstates ];
2511         base = trie->states[ cur ].trans.base;
2512
2513         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2514             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2515             if (ch_state) {
2516                 U32 fail_state = cur;
2517                 U32 fail_base;
2518                 do {
2519                     fail_state = fail[ fail_state ];
2520                     fail_base = aho->states[ fail_state ].trans.base;
2521                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2522
2523                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2524                 fail[ ch_state ] = fail_state;
2525                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2526                 {
2527                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
2528                 }
2529                 q[ q_write++ % numstates] = ch_state;
2530             }
2531         }
2532     }
2533     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2534        when we fail in state 1, this allows us to use the
2535        charclass scan to find a valid start char. This is based on the principle
2536        that theres a good chance the string being searched contains lots of stuff
2537        that cant be a start char.
2538      */
2539     fail[ 0 ] = fail[ 1 ] = 0;
2540     DEBUG_TRIE_COMPILE_r({
2541         PerlIO_printf(Perl_debug_log,
2542                       "%*sStclass Failtable (%"UVuf" states): 0", 
2543                       (int)(depth * 2), "", (UV)numstates
2544         );
2545         for( q_read=1; q_read<numstates; q_read++ ) {
2546             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2547         }
2548         PerlIO_printf(Perl_debug_log, "\n");
2549     });
2550     Safefree(q);
2551     /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2552 }
2553
2554
2555 /*
2556  * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2557  * These need to be revisited when a newer toolchain becomes available.
2558  */
2559 #if defined(__sparc64__) && defined(__GNUC__)
2560 #   if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2561 #       undef  SPARC64_GCC_WORKAROUND
2562 #       define SPARC64_GCC_WORKAROUND 1
2563 #   endif
2564 #endif
2565
2566 #define DEBUG_PEEP(str,scan,depth) \
2567     DEBUG_OPTIMISE_r({if (scan){ \
2568        SV * const mysv=sv_newmortal(); \
2569        regnode *Next = regnext(scan); \
2570        regprop(RExC_rx, mysv, scan); \
2571        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2572        (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2573        Next ? (REG_NODE_NUM(Next)) : 0 ); \
2574    }});
2575
2576
2577 /* The below joins as many adjacent EXACTish nodes as possible into a single
2578  * one, and looks for problematic sequences of characters whose folds vs.
2579  * non-folds have sufficiently different lengths, that the optimizer would be
2580  * fooled into rejecting legitimate matches of them, and the trie construction
2581  * code can't cope with them.  The joining is only done if:
2582  * 1) there is room in the current conglomerated node to entirely contain the
2583  *    next one.
2584  * 2) they are the exact same node type
2585  *
2586  * The adjacent nodes actually may be separated by NOTHING kind nodes, and
2587  * these get optimized out
2588  *
2589  * If there are problematic code sequences, *min_subtract is set to the delta
2590  * that the minimum size of the node can be less than its actual size.  And,
2591  * the node type of the result is changed to reflect that it contains these
2592  * sequences.
2593  *
2594  * And *has_exactf_sharp_s is set to indicate whether or not the node is EXACTF
2595  * and contains LATIN SMALL LETTER SHARP S
2596  *
2597  * This is as good a place as any to discuss the design of handling these
2598  * problematic sequences.  It's been wrong in Perl for a very long time.  There
2599  * are three code points in Unicode whose folded lengths differ so much from
2600  * the un-folded lengths that it causes problems for the optimizer and trie
2601  * construction.  Why only these are problematic, and not others where lengths
2602  * also differ is something I (khw) do not understand.  New versions of Unicode
2603  * might add more such code points.  Hopefully the logic in fold_grind.t that
2604  * figures out what to test (in part by verifying that each size-combination
2605  * gets tested) will catch any that do come along, so they can be added to the
2606  * special handling below.  The chances of new ones are actually rather small,
2607  * as most, if not all, of the world's scripts that have casefolding have
2608  * already been encoded by Unicode.  Also, a number of Unicode's decisions were
2609  * made to allow compatibility with pre-existing standards, and almost all of
2610  * those have already been dealt with.  These would otherwise be the most
2611  * likely candidates for generating further tricky sequences.  In other words,
2612  * Unicode by itself is unlikely to add new ones unless it is for compatibility
2613  * with pre-existing standards, and there aren't many of those left.
2614  *
2615  * The previous designs for dealing with these involved assigning a special
2616  * node for them.  This approach doesn't work, as evidenced by this example:
2617  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
2618  * Both these fold to "sss", but if the pattern is parsed to create a node of
2619  * that would match just the \xDF, it won't be able to handle the case where a
2620  * successful match would have to cross the node's boundary.  The new approach
2621  * that hopefully generally solves the problem generates an EXACTFU_SS node
2622  * that is "sss".
2623  *
2624  * There are a number of components to the approach (a lot of work for just
2625  * three code points!):
2626  * 1)   This routine examines each EXACTFish node that could contain the
2627  *      problematic sequences.  It returns in *min_subtract how much to
2628  *      subtract from the the actual length of the string to get a real minimum
2629  *      for one that could match it.  This number is usually 0 except for the
2630  *      problematic sequences.  This delta is used by the caller to adjust the
2631  *      min length of the match, and the delta between min and max, so that the
2632  *      optimizer doesn't reject these possibilities based on size constraints.
2633  * 2)   These sequences are not currently correctly handled by the trie code
2634  *      either, so it changes the joined node type to ops that are not handled
2635  *      by trie's, those new ops being EXACTFU_SS and EXACTFU_TRICKYFOLD.
2636  * 3)   This is sufficient for the two Greek sequences (described below), but
2637  *      the one involving the Sharp s (\xDF) needs more.  The node type
2638  *      EXACTFU_SS is used for an EXACTFU node that contains at least one "ss"
2639  *      sequence in it.  For non-UTF-8 patterns and strings, this is the only
2640  *      case where there is a possible fold length change.  That means that a
2641  *      regular EXACTFU node without UTF-8 involvement doesn't have to concern
2642  *      itself with length changes, and so can be processed faster.  regexec.c
2643  *      takes advantage of this.  Generally, an EXACTFish node that is in UTF-8
2644  *      is pre-folded by regcomp.c.  This saves effort in regex matching.
2645  *      However, probably mostly for historical reasons, the pre-folding isn't
2646  *      done for non-UTF8 patterns (and it can't be for EXACTF and EXACTFL
2647  *      nodes, as what they fold to isn't known until runtime.)  The fold
2648  *      possibilities for the non-UTF8 patterns are quite simple, except for
2649  *      the sharp s.  All the ones that don't involve a UTF-8 target string
2650  *      are members of a fold-pair, and arrays are set up for all of them
2651  *      that quickly find the other member of the pair.  It might actually
2652  *      be faster to pre-fold these, but it isn't currently done, except for
2653  *      the sharp s.  Code elsewhere in this file makes sure that it gets
2654  *      folded to 'ss', even if the pattern isn't UTF-8.  This avoids the
2655  *      issues described in the next item.
2656  * 4)   A problem remains for the sharp s in EXACTF nodes.  Whether it matches
2657  *      'ss' or not is not knowable at compile time.  It will match iff the
2658  *      target string is in UTF-8, unlike the EXACTFU nodes, where it always
2659  *      matches; and the EXACTFL and EXACTFA nodes where it never does.  Thus
2660  *      it can't be folded to "ss" at compile time, unlike EXACTFU does as
2661  *      described in item 3).  An assumption that the optimizer part of
2662  *      regexec.c (probably unwittingly) makes is that a character in the
2663  *      pattern corresponds to at most a single character in the target string.
2664  *      (And I do mean character, and not byte here, unlike other parts of the
2665  *      documentation that have never been updated to account for multibyte
2666  *      Unicode.)  This assumption is wrong only in this case, as all other
2667  *      cases are either 1-1 folds when no UTF-8 is involved; or is true by
2668  *      virtue of having this file pre-fold UTF-8 patterns.   I'm
2669  *      reluctant to try to change this assumption, so instead the code punts.
2670  *      This routine examines EXACTF nodes for the sharp s, and returns a
2671  *      boolean indicating whether or not the node is an EXACTF node that
2672  *      contains a sharp s.  When it is true, the caller sets a flag that later
2673  *      causes the optimizer in this file to not set values for the floating
2674  *      and fixed string lengths, and thus avoids the optimizer code in
2675  *      regexec.c that makes the invalid assumption.  Thus, there is no
2676  *      optimization based on string lengths for EXACTF nodes that contain the
2677  *      sharp s.  This only happens for /id rules (which means the pattern
2678  *      isn't in UTF-8).
2679  */
2680
2681 #define JOIN_EXACT(scan,min_subtract,has_exactf_sharp_s, flags) \
2682     if (PL_regkind[OP(scan)] == EXACT) \
2683         join_exact(pRExC_state,(scan),(min_subtract),has_exactf_sharp_s, (flags),NULL,depth+1)
2684
2685 STATIC U32
2686 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) {
2687     /* Merge several consecutive EXACTish nodes into one. */
2688     regnode *n = regnext(scan);
2689     U32 stringok = 1;
2690     regnode *next = scan + NODE_SZ_STR(scan);
2691     U32 merged = 0;
2692     U32 stopnow = 0;
2693 #ifdef DEBUGGING
2694     regnode *stop = scan;
2695     GET_RE_DEBUG_FLAGS_DECL;
2696 #else
2697     PERL_UNUSED_ARG(depth);
2698 #endif
2699
2700     PERL_ARGS_ASSERT_JOIN_EXACT;
2701 #ifndef EXPERIMENTAL_INPLACESCAN
2702     PERL_UNUSED_ARG(flags);
2703     PERL_UNUSED_ARG(val);
2704 #endif
2705     DEBUG_PEEP("join",scan,depth);
2706
2707     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
2708      * EXACT ones that are mergeable to the current one. */
2709     while (n
2710            && (PL_regkind[OP(n)] == NOTHING
2711                || (stringok && OP(n) == OP(scan)))
2712            && NEXT_OFF(n)
2713            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
2714     {
2715         
2716         if (OP(n) == TAIL || n > next)
2717             stringok = 0;
2718         if (PL_regkind[OP(n)] == NOTHING) {
2719             DEBUG_PEEP("skip:",n,depth);
2720             NEXT_OFF(scan) += NEXT_OFF(n);
2721             next = n + NODE_STEP_REGNODE;
2722 #ifdef DEBUGGING
2723             if (stringok)
2724                 stop = n;
2725 #endif
2726             n = regnext(n);
2727         }
2728         else if (stringok) {
2729             const unsigned int oldl = STR_LEN(scan);
2730             regnode * const nnext = regnext(n);
2731
2732             if (oldl + STR_LEN(n) > U8_MAX)
2733                 break;
2734             
2735             DEBUG_PEEP("merg",n,depth);
2736             merged++;
2737
2738             NEXT_OFF(scan) += NEXT_OFF(n);
2739             STR_LEN(scan) += STR_LEN(n);
2740             next = n + NODE_SZ_STR(n);
2741             /* Now we can overwrite *n : */
2742             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2743 #ifdef DEBUGGING
2744             stop = next - 1;
2745 #endif
2746             n = nnext;
2747             if (stopnow) break;
2748         }
2749
2750 #ifdef EXPERIMENTAL_INPLACESCAN
2751         if (flags && !NEXT_OFF(n)) {
2752             DEBUG_PEEP("atch", val, depth);
2753             if (reg_off_by_arg[OP(n)]) {
2754                 ARG_SET(n, val - n);
2755             }
2756             else {
2757                 NEXT_OFF(n) = val - n;
2758             }
2759             stopnow = 1;
2760         }
2761 #endif
2762     }
2763
2764     *min_subtract = 0;
2765     *has_exactf_sharp_s = FALSE;
2766
2767     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
2768      * can now analyze for sequences of problematic code points.  (Prior to
2769      * this final joining, sequences could have been split over boundaries, and
2770      * hence missed).  The sequences only happen in folding, hence for any
2771      * non-EXACT EXACTish node */
2772     if (OP(scan) != EXACT) {
2773         U8 *s;
2774         U8 * s0 = (U8*) STRING(scan);
2775         U8 * const s_end = s0 + STR_LEN(scan);
2776
2777         /* The below is perhaps overboard, but this allows us to save a test
2778          * each time through the loop at the expense of a mask.  This is
2779          * because on both EBCDIC and ASCII machines, 'S' and 's' differ by a
2780          * single bit.  On ASCII they are 32 apart; on EBCDIC, they are 64.
2781          * This uses an exclusive 'or' to find that bit and then inverts it to
2782          * form a mask, with just a single 0, in the bit position where 'S' and
2783          * 's' differ. */
2784         const U8 S_or_s_mask = (U8) ~ ('S' ^ 's');
2785         const U8 s_masked = 's' & S_or_s_mask;
2786
2787         /* One pass is made over the node's string looking for all the
2788          * possibilities.  to avoid some tests in the loop, there are two main
2789          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
2790          * non-UTF-8 */
2791         if (UTF) {
2792
2793             /* There are two problematic Greek code points in Unicode
2794              * casefolding
2795              *
2796              * U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2797              * U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2798              *
2799              * which casefold to
2800              *
2801              * Unicode                      UTF-8
2802              *
2803              * U+03B9 U+0308 U+0301         0xCE 0xB9 0xCC 0x88 0xCC 0x81
2804              * U+03C5 U+0308 U+0301         0xCF 0x85 0xCC 0x88 0xCC 0x81
2805              *
2806              * This means that in case-insensitive matching (or "loose
2807              * matching", as Unicode calls it), an EXACTF of length six (the
2808              * UTF-8 encoded byte length of the above casefolded versions) can
2809              * match a target string of length two (the byte length of UTF-8
2810              * encoded U+0390 or U+03B0).  This would rather mess up the
2811              * minimum length computation.  (there are other code points that
2812              * also fold to these two sequences, but the delta is smaller)
2813              *
2814              * If these sequences are found, the minimum length is decreased by
2815              * four (six minus two).
2816              *
2817              * Similarly, 'ss' may match the single char and byte LATIN SMALL
2818              * LETTER SHARP S.  We decrease the min length by 1 for each
2819              * occurrence of 'ss' found */
2820
2821 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2822 #           define U390_first_byte 0xb4
2823             const U8 U390_tail[] = "\x68\xaf\x49\xaf\x42";
2824 #           define U3B0_first_byte 0xb5
2825             const U8 U3B0_tail[] = "\x46\xaf\x49\xaf\x42";
2826 #else
2827 #           define U390_first_byte 0xce
2828             const U8 U390_tail[] = "\xb9\xcc\x88\xcc\x81";
2829 #           define U3B0_first_byte 0xcf
2830             const U8 U3B0_tail[] = "\x85\xcc\x88\xcc\x81";
2831 #endif
2832             const U8 len = sizeof(U390_tail); /* (-1 for NUL; +1 for 1st byte;
2833                                                  yields a net of 0 */
2834             /* Examine the string for one of the problematic sequences */
2835             for (s = s0;
2836                  s < s_end - 1; /* Can stop 1 before the end, as minimum length
2837                                  * sequence we are looking for is 2 */
2838                  s += UTF8SKIP(s))
2839             {
2840
2841                 /* Look for the first byte in each problematic sequence */
2842                 switch (*s) {
2843                     /* We don't have to worry about other things that fold to
2844                      * 's' (such as the long s, U+017F), as all above-latin1
2845                      * code points have been pre-folded */
2846                     case 's':
2847                     case 'S':
2848
2849                         /* Current character is an 's' or 'S'.  If next one is
2850                          * as well, we have the dreaded sequence */
2851                         if (((*(s+1) & S_or_s_mask) == s_masked)
2852                             /* These two node types don't have special handling
2853                              * for 'ss' */
2854                             && OP(scan) != EXACTFL && OP(scan) != EXACTFA)
2855                         {
2856                             *min_subtract += 1;
2857                             OP(scan) = EXACTFU_SS;
2858                             s++;    /* No need to look at this character again */
2859                         }
2860                         break;
2861
2862                     case U390_first_byte:
2863                         if (s_end - s >= len
2864
2865                             /* The 1's are because are skipping comparing the
2866                              * first byte */
2867                             && memEQ(s + 1, U390_tail, len - 1))
2868                         {
2869                             goto greek_sequence;
2870                         }
2871                         break;
2872
2873                     case U3B0_first_byte:
2874                         if (! (s_end - s >= len
2875                                && memEQ(s + 1, U3B0_tail, len - 1)))
2876                         {
2877                             break;
2878                         }
2879                       greek_sequence:
2880                         *min_subtract += 4;
2881
2882                         /* This can't currently be handled by trie's, so change
2883                          * the node type to indicate this.  If EXACTFA and
2884                          * EXACTFL were ever to be handled by trie's, this
2885                          * would have to be changed.  If this node has already
2886                          * been changed to EXACTFU_SS in this loop, leave it as
2887                          * is.  (I (khw) think it doesn't matter in regexec.c
2888                          * for UTF patterns, but no need to change it */
2889                         if (OP(scan) == EXACTFU) {
2890                             OP(scan) = EXACTFU_TRICKYFOLD;
2891                         }
2892                         s += 6; /* We already know what this sequence is.  Skip
2893                                    the rest of it */
2894                         break;
2895                 }
2896             }
2897         }
2898         else if (OP(scan) != EXACTFL && OP(scan) != EXACTFA) {
2899
2900             /* Here, the pattern is not UTF-8.  We need to look only for the
2901              * 'ss' sequence, and in the EXACTF case, the sharp s, which can be
2902              * in the final position.  Otherwise we can stop looking 1 byte
2903              * earlier because have to find both the first and second 's' */
2904             const U8* upper = (OP(scan) == EXACTF) ? s_end : s_end -1;
2905
2906             for (s = s0; s < upper; s++) {
2907                 switch (*s) {
2908                     case 'S':
2909                     case 's':
2910                         if (s_end - s > 1
2911                             && ((*(s+1) & S_or_s_mask) == s_masked))
2912                         {
2913                             *min_subtract += 1;
2914
2915                             /* EXACTF nodes need to know that the minimum
2916                              * length changed so that a sharp s in the string
2917                              * can match this ss in the pattern, but they
2918                              * remain EXACTF nodes, as they are not trie'able,
2919                              * so don't have to invent a new node type to
2920                              * exclude them from the trie code */
2921                             if (OP(scan) != EXACTF) {
2922                                 OP(scan) = EXACTFU_SS;
2923                             }
2924                             s++;
2925                         }
2926                         break;
2927                     case LATIN_SMALL_LETTER_SHARP_S:
2928                         if (OP(scan) == EXACTF) {
2929                             *has_exactf_sharp_s = TRUE;
2930                         }
2931                         break;
2932                 }
2933             }
2934         }
2935     }
2936
2937 #ifdef DEBUGGING
2938     /* Allow dumping but overwriting the collection of skipped
2939      * ops and/or strings with fake optimized ops */
2940     n = scan + NODE_SZ_STR(scan);
2941     while (n <= stop) {
2942         OP(n) = OPTIMIZED;
2943         FLAGS(n) = 0;
2944         NEXT_OFF(n) = 0;
2945         n++;
2946     }
2947 #endif
2948     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2949     return stopnow;
2950 }
2951
2952 /* REx optimizer.  Converts nodes into quicker variants "in place".
2953    Finds fixed substrings.  */
2954
2955 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2956    to the position after last scanned or to NULL. */
2957
2958 #define INIT_AND_WITHP \
2959     assert(!and_withp); \
2960     Newx(and_withp,1,struct regnode_charclass_class); \
2961     SAVEFREEPV(and_withp)
2962
2963 /* this is a chain of data about sub patterns we are processing that
2964    need to be handled separately/specially in study_chunk. Its so
2965    we can simulate recursion without losing state.  */
2966 struct scan_frame;
2967 typedef struct scan_frame {
2968     regnode *last;  /* last node to process in this frame */
2969     regnode *next;  /* next node to process when last is reached */
2970     struct scan_frame *prev; /*previous frame*/
2971     I32 stop; /* what stopparen do we use */
2972 } scan_frame;
2973
2974
2975 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2976
2977 #define CASE_SYNST_FNC(nAmE)                                       \
2978 case nAmE:                                                         \
2979     if (flags & SCF_DO_STCLASS_AND) {                              \
2980             for (value = 0; value < 256; value++)                  \
2981                 if (!is_ ## nAmE ## _cp(value))                       \
2982                     ANYOF_BITMAP_CLEAR(data->start_class, value);  \
2983     }                                                              \
2984     else {                                                         \
2985             for (value = 0; value < 256; value++)                  \
2986                 if (is_ ## nAmE ## _cp(value))                        \
2987                     ANYOF_BITMAP_SET(data->start_class, value);    \
2988     }                                                              \
2989     break;                                                         \
2990 case N ## nAmE:                                                    \
2991     if (flags & SCF_DO_STCLASS_AND) {                              \
2992             for (value = 0; value < 256; value++)                   \
2993                 if (is_ ## nAmE ## _cp(value))                         \
2994                     ANYOF_BITMAP_CLEAR(data->start_class, value);   \
2995     }                                                               \
2996     else {                                                          \
2997             for (value = 0; value < 256; value++)                   \
2998                 if (!is_ ## nAmE ## _cp(value))                        \
2999                     ANYOF_BITMAP_SET(data->start_class, value);     \
3000     }                                                               \
3001     break
3002
3003
3004
3005 STATIC I32
3006 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
3007                         I32 *minlenp, I32 *deltap,
3008                         regnode *last,
3009                         scan_data_t *data,
3010                         I32 stopparen,
3011                         U8* recursed,
3012                         struct regnode_charclass_class *and_withp,
3013                         U32 flags, U32 depth)
3014                         /* scanp: Start here (read-write). */
3015                         /* deltap: Write maxlen-minlen here. */
3016                         /* last: Stop before this one. */
3017                         /* data: string data about the pattern */
3018                         /* stopparen: treat close N as END */
3019                         /* recursed: which subroutines have we recursed into */
3020                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
3021 {
3022     dVAR;
3023     I32 min = 0, pars = 0, code;
3024     regnode *scan = *scanp, *next;
3025     I32 delta = 0;
3026     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
3027     int is_inf_internal = 0;            /* The studied chunk is infinite */
3028     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
3029     scan_data_t data_fake;
3030     SV *re_trie_maxbuff = NULL;
3031     regnode *first_non_open = scan;
3032     I32 stopmin = I32_MAX;
3033     scan_frame *frame = NULL;
3034     GET_RE_DEBUG_FLAGS_DECL;
3035
3036     PERL_ARGS_ASSERT_STUDY_CHUNK;
3037
3038 #ifdef DEBUGGING
3039     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
3040 #endif
3041
3042     if ( depth == 0 ) {
3043         while (first_non_open && OP(first_non_open) == OPEN)
3044             first_non_open=regnext(first_non_open);
3045     }
3046
3047
3048   fake_study_recurse:
3049     while ( scan && OP(scan) != END && scan < last ){
3050         UV min_subtract = 0;    /* How much to subtract from the minimum node
3051                                    length to get a real minimum (because the
3052                                    folded version may be shorter) */
3053         bool has_exactf_sharp_s = FALSE;
3054         /* Peephole optimizer: */
3055         DEBUG_STUDYDATA("Peep:", data,depth);
3056         DEBUG_PEEP("Peep",scan,depth);
3057
3058         /* Its not clear to khw or hv why this is done here, and not in the
3059          * clauses that deal with EXACT nodes.  khw's guess is that it's
3060          * because of a previous design */
3061         JOIN_EXACT(scan,&min_subtract, &has_exactf_sharp_s, 0);
3062
3063         /* Follow the next-chain of the current node and optimize
3064            away all the NOTHINGs from it.  */
3065         if (OP(scan) != CURLYX) {
3066             const int max = (reg_off_by_arg[OP(scan)]
3067                        ? I32_MAX
3068                        /* I32 may be smaller than U16 on CRAYs! */
3069                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
3070             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
3071             int noff;
3072             regnode *n = scan;
3073
3074             /* Skip NOTHING and LONGJMP. */
3075             while ((n = regnext(n))
3076                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
3077                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
3078                    && off + noff < max)
3079                 off += noff;
3080             if (reg_off_by_arg[OP(scan)])
3081                 ARG(scan) = off;
3082             else
3083                 NEXT_OFF(scan) = off;
3084         }
3085
3086
3087
3088         /* The principal pseudo-switch.  Cannot be a switch, since we
3089            look into several different things.  */
3090         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
3091                    || OP(scan) == IFTHEN) {
3092             next = regnext(scan);
3093             code = OP(scan);
3094             /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
3095
3096             if (OP(next) == code || code == IFTHEN) {
3097                 /* NOTE - There is similar code to this block below for handling
3098                    TRIE nodes on a re-study.  If you change stuff here check there
3099                    too. */
3100                 I32 max1 = 0, min1 = I32_MAX, num = 0;
3101                 struct regnode_charclass_class accum;
3102                 regnode * const startbranch=scan;
3103
3104                 if (flags & SCF_DO_SUBSTR)
3105                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
3106                 if (flags & SCF_DO_STCLASS)
3107                     cl_init_zero(pRExC_state, &accum);
3108
3109                 while (OP(scan) == code) {
3110                     I32 deltanext, minnext, f = 0, fake;
3111                     struct regnode_charclass_class this_class;
3112
3113                     num++;
3114                     data_fake.flags = 0;
3115                     if (data) {
3116                         data_fake.whilem_c = data->whilem_c;
3117                         data_fake.last_closep = data->last_closep;
3118                     }
3119                     else
3120                         data_fake.last_closep = &fake;
3121
3122                     data_fake.pos_delta = delta;
3123                     next = regnext(scan);
3124                     scan = NEXTOPER(scan);
3125                     if (code != BRANCH)
3126                         scan = NEXTOPER(scan);
3127                     if (flags & SCF_DO_STCLASS) {
3128                         cl_init(pRExC_state, &this_class);
3129                         data_fake.start_class = &this_class;
3130                         f = SCF_DO_STCLASS_AND;
3131                     }
3132                     if (flags & SCF_WHILEM_VISITED_POS)
3133                         f |= SCF_WHILEM_VISITED_POS;
3134
3135                     /* we suppose the run is continuous, last=next...*/
3136                     minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3137                                           next, &data_fake,
3138                                           stopparen, recursed, NULL, f,depth+1);
3139                     if (min1 > minnext)
3140                         min1 = minnext;
3141                     if (max1 < minnext + deltanext)
3142                         max1 = minnext + deltanext;
3143                     if (deltanext == I32_MAX)
3144                         is_inf = is_inf_internal = 1;
3145                     scan = next;
3146                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3147                         pars++;
3148                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
3149                         if ( stopmin > minnext) 
3150                             stopmin = min + min1;
3151                         flags &= ~SCF_DO_SUBSTR;
3152                         if (data)
3153                             data->flags |= SCF_SEEN_ACCEPT;
3154                     }
3155                     if (data) {
3156                         if (data_fake.flags & SF_HAS_EVAL)
3157                             data->flags |= SF_HAS_EVAL;
3158                         data->whilem_c = data_fake.whilem_c;
3159                     }
3160                     if (flags & SCF_DO_STCLASS)
3161                         cl_or(pRExC_state, &accum, &this_class);
3162                 }
3163                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
3164                     min1 = 0;
3165                 if (flags & SCF_DO_SUBSTR) {
3166                     data->pos_min += min1;
3167                     data->pos_delta += max1 - min1;
3168                     if (max1 != min1 || is_inf)
3169                         data->longest = &(data->longest_float);
3170                 }
3171                 min += min1;
3172                 delta += max1 - min1;
3173                 if (flags & SCF_DO_STCLASS_OR) {
3174                     cl_or(pRExC_state, data->start_class, &accum);
3175                     if (min1) {
3176                         cl_and(data->start_class, and_withp);
3177                         flags &= ~SCF_DO_STCLASS;
3178                     }
3179                 }
3180                 else if (flags & SCF_DO_STCLASS_AND) {
3181                     if (min1) {
3182                         cl_and(data->start_class, &accum);
3183                         flags &= ~SCF_DO_STCLASS;
3184                     }
3185                     else {
3186                         /* Switch to OR mode: cache the old value of
3187                          * data->start_class */
3188                         INIT_AND_WITHP;
3189                         StructCopy(data->start_class, and_withp,
3190                                    struct regnode_charclass_class);
3191                         flags &= ~SCF_DO_STCLASS_AND;
3192                         StructCopy(&accum, data->start_class,
3193                                    struct regnode_charclass_class);
3194                         flags |= SCF_DO_STCLASS_OR;
3195                         data->start_class->flags |= ANYOF_EOS;
3196                     }
3197                 }
3198
3199                 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
3200                 /* demq.
3201
3202                    Assuming this was/is a branch we are dealing with: 'scan' now
3203                    points at the item that follows the branch sequence, whatever
3204                    it is. We now start at the beginning of the sequence and look
3205                    for subsequences of
3206
3207                    BRANCH->EXACT=>x1
3208                    BRANCH->EXACT=>x2
3209                    tail
3210
3211                    which would be constructed from a pattern like /A|LIST|OF|WORDS/
3212
3213                    If we can find such a subsequence we need to turn the first
3214                    element into a trie and then add the subsequent branch exact
3215                    strings to the trie.
3216
3217                    We have two cases
3218
3219                      1. patterns where the whole set of branches can be converted. 
3220
3221                      2. patterns where only a subset can be converted.
3222
3223                    In case 1 we can replace the whole set with a single regop
3224                    for the trie. In case 2 we need to keep the start and end
3225                    branches so
3226
3227                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
3228                      becomes BRANCH TRIE; BRANCH X;
3229
3230                   There is an additional case, that being where there is a 
3231                   common prefix, which gets split out into an EXACT like node
3232                   preceding the TRIE node.
3233
3234                   If x(1..n)==tail then we can do a simple trie, if not we make
3235                   a "jump" trie, such that when we match the appropriate word
3236                   we "jump" to the appropriate tail node. Essentially we turn
3237                   a nested if into a case structure of sorts.
3238
3239                 */
3240
3241                     int made=0;
3242                     if (!re_trie_maxbuff) {
3243                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
3244                         if (!SvIOK(re_trie_maxbuff))
3245                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
3246                     }
3247                     if ( SvIV(re_trie_maxbuff)>=0  ) {
3248                         regnode *cur;
3249                         regnode *first = (regnode *)NULL;
3250                         regnode *last = (regnode *)NULL;
3251                         regnode *tail = scan;
3252                         U8 trietype = 0;
3253                         U32 count=0;
3254
3255 #ifdef DEBUGGING
3256                         SV * const mysv = sv_newmortal();       /* for dumping */
3257 #endif
3258                         /* var tail is used because there may be a TAIL
3259                            regop in the way. Ie, the exacts will point to the
3260                            thing following the TAIL, but the last branch will
3261                            point at the TAIL. So we advance tail. If we
3262                            have nested (?:) we may have to move through several
3263                            tails.
3264                          */
3265
3266                         while ( OP( tail ) == TAIL ) {
3267                             /* this is the TAIL generated by (?:) */
3268                             tail = regnext( tail );
3269                         }
3270
3271                         
3272                         DEBUG_TRIE_COMPILE_r({
3273                             regprop(RExC_rx, mysv, tail );
3274                             PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
3275                                 (int)depth * 2 + 2, "", 
3276                                 "Looking for TRIE'able sequences. Tail node is: ", 
3277                                 SvPV_nolen_const( mysv )
3278                             );
3279                         });
3280                         
3281                         /*
3282
3283                             Step through the branches
3284                                 cur represents each branch,
3285                                 noper is the first thing to be matched as part of that branch
3286                                 noper_next is the regnext() of that node.
3287
3288                             We normally handle a case like this /FOO[xyz]|BAR[pqr]/
3289                             via a "jump trie" but we also support building with NOJUMPTRIE,
3290                             which restricts the trie logic to structures like /FOO|BAR/.
3291
3292                             If noper is a trieable nodetype then the branch is a possible optimization
3293                             target. If we are building under NOJUMPTRIE then we require that noper_next
3294                             is the same as scan (our current position in the regex program).
3295
3296                             Once we have two or more consecutive such branches we can create a
3297                             trie of the EXACT's contents and stitch it in place into the program.
3298
3299                             If the sequence represents all of the branches in the alternation we
3300                             replace the entire thing with a single TRIE node.
3301
3302                             Otherwise when it is a subsequence we need to stitch it in place and
3303                             replace only the relevant branches. This means the first branch has
3304                             to remain as it is used by the alternation logic, and its next pointer,
3305                             and needs to be repointed at the item on the branch chain following
3306                             the last branch we have optimized away.
3307
3308                             This could be either a BRANCH, in which case the subsequence is internal,
3309                             or it could be the item following the branch sequence in which case the
3310                             subsequence is at the end (which does not necessarily mean the first node
3311                             is the start of the alternation).
3312
3313                             TRIE_TYPE(X) is a define which maps the optype to a trietype.
3314
3315                                 optype          |  trietype
3316                                 ----------------+-----------
3317                                 NOTHING         | NOTHING
3318                                 EXACT           | EXACT
3319                                 EXACTFU         | EXACTFU
3320                                 EXACTFU_SS      | EXACTFU
3321                                 EXACTFU_TRICKYFOLD | EXACTFU
3322                                 EXACTFA         | 0
3323
3324
3325                         */
3326 #define TRIE_TYPE(X) ( ( NOTHING == (X) ) ? NOTHING :   \
3327                        ( EXACT == (X) )   ? EXACT :        \
3328                        ( EXACTFU == (X) || EXACTFU_SS == (X) || EXACTFU_TRICKYFOLD == (X) ) ? EXACTFU :        \
3329                        0 )
3330
3331                         /* dont use tail as the end marker for this traverse */
3332                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
3333                             regnode * const noper = NEXTOPER( cur );
3334                             U8 noper_type = OP( noper );
3335                             U8 noper_trietype = TRIE_TYPE( noper_type );
3336 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
3337                             regnode * const noper_next = regnext( noper );
3338                             U8 noper_next_type = (noper_next && noper_next != tail) ? OP(noper_next) : 0;
3339                             U8 noper_next_trietype = (noper_next && noper_next != tail) ? TRIE_TYPE( noper_next_type ) :0;
3340 #endif
3341
3342                             DEBUG_TRIE_COMPILE_r({
3343                                 regprop(RExC_rx, mysv, cur);
3344                                 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
3345                                    (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
3346
3347                                 regprop(RExC_rx, mysv, noper);
3348                                 PerlIO_printf( Perl_debug_log, " -> %s",
3349                                     SvPV_nolen_const(mysv));
3350
3351                                 if ( noper_next ) {
3352                                   regprop(RExC_rx, mysv, noper_next );
3353                                   PerlIO_printf( Perl_debug_log,"\t=> %s\t",
3354                                     SvPV_nolen_const(mysv));
3355                                 }
3356                                 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d,tt==%s,nt==%s,nnt==%s)\n",
3357                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur),
3358                                    PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] 
3359                                 );
3360                             });
3361
3362                             /* Is noper a trieable nodetype that can be merged with the
3363                              * current trie (if there is one)? */
3364                             if ( noper_trietype
3365                                   &&
3366                                   (
3367                                         ( noper_trietype == NOTHING)
3368                                         || ( trietype == NOTHING )
3369                                         || ( trietype == noper_trietype )
3370                                   )
3371 #ifdef NOJUMPTRIE
3372                                   && noper_next == tail
3373 #endif
3374                                   && count < U16_MAX)
3375                             {
3376                                 /* Handle mergable triable node
3377                                  * Either we are the first node in a new trieable sequence,
3378                                  * in which case we do some bookkeeping, otherwise we update
3379                                  * the end pointer. */
3380                                 if ( !first ) {
3381                                     first = cur;
3382                                     trietype = noper_trietype;
3383                                     if ( noper_trietype == NOTHING ) {
3384 #if !defined(DEBUGGING) && !defined(NOJUMPTRIE)
3385                                         regnode * const noper_next = regnext( noper );
3386                                         U8 noper_next_type = (noper_next && noper_next!=tail) ? OP(noper_next) : 0;
3387                                         U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0;
3388 #endif
3389
3390                                         if ( noper_next_trietype )
3391                                             trietype = noper_next_trietype;
3392                                     }
3393                                 } else {
3394                                     if ( trietype == NOTHING )
3395                                         trietype = noper_trietype;
3396                                     last = cur;
3397                                 }
3398                                 if (first)
3399                                     count++;
3400                             } /* end handle mergable triable node */
3401                             else {
3402                                 /* handle unmergable node -
3403                                  * noper may either be a triable node which can not be tried
3404                                  * together with the current trie, or a non triable node */
3405                                 if ( last ) {
3406                                     /* If last is set and trietype is not NOTHING then we have found
3407                                      * at least two triable branch sequences in a row of a similar
3408                                      * trietype so we can turn them into a trie. If/when we
3409                                      * allow NOTHING to start a trie sequence this condition will be
3410                                      * required, and it isn't expensive so we leave it in for now. */
3411                                     if ( trietype != NOTHING )
3412                                         make_trie( pRExC_state,
3413                                                 startbranch, first, cur, tail, count,
3414                                                 trietype, depth+1 );
3415                                     last = NULL; /* note: we clear/update first, trietype etc below, so we dont do it here */
3416                                 }
3417                                 if ( noper_trietype
3418 #ifdef NOJUMPTRIE
3419                                      && noper_next == tail
3420 #endif
3421                                 ){
3422                                     /* noper is triable, so we can start a new trie sequence */
3423                                     count = 1;
3424                                     first = cur;
3425                                     trietype = noper_trietype;
3426                                 } else if (first) {
3427                                     /* if we already saw a first but the current node is not triable then we have
3428                                      * to reset the first information. */
3429                                     count = 0;
3430                                     first = NULL;
3431                                     trietype = 0;
3432                                 }
3433                             } /* end handle unmergable node */
3434                         } /* loop over branches */
3435                         DEBUG_TRIE_COMPILE_r({
3436                             regprop(RExC_rx, mysv, cur);
3437                             PerlIO_printf( Perl_debug_log,
3438                               "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
3439                               "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
3440
3441                         });
3442                         if ( last ) {
3443                             if ( trietype != NOTHING ) {
3444                                 /* the last branch of the sequence was part of a trie,
3445                                  * so we have to construct it here outside of the loop
3446                                  */
3447                                 made= make_trie( pRExC_state, startbranch, first, scan, tail, count, trietype, depth+1 );
3448 #ifdef TRIE_STUDY_OPT
3449                                 if ( ((made == MADE_EXACT_TRIE &&
3450                                      startbranch == first)
3451                                      || ( first_non_open == first )) &&
3452                                      depth==0 ) {
3453                                     flags |= SCF_TRIE_RESTUDY;
3454                                     if ( startbranch == first
3455                                          && scan == tail )
3456                                     {
3457                                         RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
3458                                     }
3459                                 }
3460 #endif
3461                             } else {
3462                                 /* at this point we know whatever we have is a NOTHING sequence/branch
3463                                  * AND if 'startbranch' is 'first' then we can turn the whole thing into a NOTHING
3464                                  */
3465                                 if ( startbranch == first ) {
3466                                     regnode *opt;
3467                                     /* the entire thing is a NOTHING sequence, something like this:
3468                                      * (?:|) So we can turn it into a plain NOTHING op. */
3469                                     DEBUG_TRIE_COMPILE_r({
3470                                         regprop(RExC_rx, mysv, cur);
3471                                         PerlIO_printf( Perl_debug_log,
3472                                           "%*s- %s (%d) <NOTHING BRANCH SEQUENCE>\n", (int)depth * 2 + 2,
3473                                           "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
3474
3475                                     });
3476                                     OP(startbranch)= NOTHING;
3477                                     NEXT_OFF(startbranch)= tail - startbranch;
3478                                     for ( opt= startbranch + 1; opt < tail ; opt++ )
3479                                         OP(opt)= OPTIMIZED;
3480                                 }
3481                             }
3482                         } /* end if ( last) */
3483                     } /* TRIE_MAXBUF is non zero */
3484                     
3485                 } /* do trie */
3486                 
3487             }
3488             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
3489                 scan = NEXTOPER(NEXTOPER(scan));
3490             } else                      /* single branch is optimized. */
3491                 scan = NEXTOPER(scan);
3492             continue;
3493         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
3494             scan_frame *newframe = NULL;
3495             I32 paren;
3496             regnode *start;
3497             regnode *end;
3498
3499             if (OP(scan) != SUSPEND) {
3500             /* set the pointer */
3501                 if (OP(scan) == GOSUB) {
3502                     paren = ARG(scan);
3503                     RExC_recurse[ARG2L(scan)] = scan;
3504                     start = RExC_open_parens[paren-1];
3505                     end   = RExC_close_parens[paren-1];
3506                 } else {
3507                     paren = 0;
3508                     start = RExC_rxi->program + 1;
3509                     end   = RExC_opend;
3510                 }
3511                 if (!recursed) {
3512                     Newxz(recursed, (((RExC_npar)>>3) +1), U8);
3513                     SAVEFREEPV(recursed);
3514                 }
3515                 if (!PAREN_TEST(recursed,paren+1)) {
3516                     PAREN_SET(recursed,paren+1);
3517                     Newx(newframe,1,scan_frame);
3518                 } else {
3519                     if (flags & SCF_DO_SUBSTR) {
3520                         SCAN_COMMIT(pRExC_state,data,minlenp);
3521                         data->longest = &(data->longest_float);
3522                     }
3523                     is_inf = is_inf_internal = 1;
3524                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3525                         cl_anything(pRExC_state, data->start_class);
3526                     flags &= ~SCF_DO_STCLASS;
3527                 }
3528             } else {
3529                 Newx(newframe,1,scan_frame);
3530                 paren = stopparen;
3531                 start = scan+2;
3532                 end = regnext(scan);
3533             }
3534             if (newframe) {
3535                 assert(start);
3536                 assert(end);
3537                 SAVEFREEPV(newframe);
3538                 newframe->next = regnext(scan);
3539                 newframe->last = last;
3540                 newframe->stop = stopparen;
3541                 newframe->prev = frame;
3542
3543                 frame = newframe;
3544                 scan =  start;
3545                 stopparen = paren;
3546                 last = end;
3547
3548                 continue;
3549             }
3550         }
3551         else if (OP(scan) == EXACT) {
3552             I32 l = STR_LEN(scan);
3553             UV uc;
3554             if (UTF) {
3555                 const U8 * const s = (U8*)STRING(scan);
3556                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
3557                 l = utf8_length(s, s + l);
3558             } else {
3559                 uc = *((U8*)STRING(scan));
3560             }
3561             min += l;
3562             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3563                 /* The code below prefers earlier match for fixed
3564                    offset, later match for variable offset.  */
3565                 if (data->last_end == -1) { /* Update the start info. */
3566                     data->last_start_min = data->pos_min;
3567                     data->last_start_max = is_inf
3568                         ? I32_MAX : data->pos_min + data->pos_delta;
3569                 }
3570                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3571                 if (UTF)
3572                     SvUTF8_on(data->last_found);
3573                 {
3574                     SV * const sv = data->last_found;
3575                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3576                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
3577                     if (mg && mg->mg_len >= 0)
3578                         mg->mg_len += utf8_length((U8*)STRING(scan),
3579                                                   (U8*)STRING(scan)+STR_LEN(scan));
3580                 }
3581                 data->last_end = data->pos_min + l;
3582                 data->pos_min += l; /* As in the first entry. */
3583                 data->flags &= ~SF_BEFORE_EOL;
3584             }
3585             if (flags & SCF_DO_STCLASS_AND) {
3586                 /* Check whether it is compatible with what we know already! */
3587                 int compat = 1;
3588
3589
3590                 /* If compatible, we or it in below.  It is compatible if is
3591                  * in the bitmp and either 1) its bit or its fold is set, or 2)
3592                  * it's for a locale.  Even if there isn't unicode semantics
3593                  * here, at runtime there may be because of matching against a
3594                  * utf8 string, so accept a possible false positive for
3595                  * latin1-range folds */
3596                 if (uc >= 0x100 ||
3597                     (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3598                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
3599                     && (!(data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD)
3600                         || !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3601                     )
3602                 {
3603                     compat = 0;
3604                 }
3605                 ANYOF_CLASS_ZERO(data->start_class);
3606                 ANYOF_BITMAP_ZERO(data->start_class);
3607                 if (compat)
3608                     ANYOF_BITMAP_SET(data->start_class, uc);
3609                 else if (uc >= 0x100) {
3610                     int i;
3611
3612                     /* Some Unicode code points fold to the Latin1 range; as
3613                      * XXX temporary code, instead of figuring out if this is
3614                      * one, just assume it is and set all the start class bits
3615                      * that could be some such above 255 code point's fold
3616                      * which will generate fals positives.  As the code
3617                      * elsewhere that does compute the fold settles down, it
3618                      * can be extracted out and re-used here */
3619                     for (i = 0; i < 256; i++){
3620                         if (HAS_NONLATIN1_FOLD_CLOSURE(i)) {
3621                             ANYOF_BITMAP_SET(data->start_class, i);
3622                         }
3623                     }
3624                 }
3625                 data->start_class->flags &= ~ANYOF_EOS;
3626                 if (uc < 0x100)
3627                   data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3628             }
3629             else if (flags & SCF_DO_STCLASS_OR) {
3630                 /* false positive possible if the class is case-folded */
3631                 if (uc < 0x100)
3632                     ANYOF_BITMAP_SET(data->start_class, uc);
3633                 else
3634                     data->start_class->flags |= ANYOF_UNICODE_ALL;
3635                 data->start_class->flags &= ~ANYOF_EOS;
3636                 cl_and(data->start_class, and_withp);
3637             }
3638             flags &= ~SCF_DO_STCLASS;
3639         }
3640         else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3641             I32 l = STR_LEN(scan);
3642             UV uc = *((U8*)STRING(scan));
3643
3644             /* Search for fixed substrings supports EXACT only. */
3645             if (flags & SCF_DO_SUBSTR) {
3646                 assert(data);
3647                 SCAN_COMMIT(pRExC_state, data, minlenp);
3648             }
3649             if (UTF) {
3650                 const U8 * const s = (U8 *)STRING(scan);
3651                 uc = utf8_to_uvchr_buf(s, s + l, NULL);
3652                 l = utf8_length(s, s + l);
3653             }
3654             else if (has_exactf_sharp_s) {
3655                 RExC_seen |= REG_SEEN_EXACTF_SHARP_S;
3656             }
3657             min += l - min_subtract;
3658             if (min < 0) {
3659                 min = 0;
3660             }
3661             delta += min_subtract;
3662             if (flags & SCF_DO_SUBSTR) {
3663                 data->pos_min += l - min_subtract;
3664                 if (data->pos_min < 0) {
3665                     data->pos_min = 0;
3666                 }
3667                 data->pos_delta += min_subtract;
3668                 if (min_subtract) {
3669                     data->longest = &(data->longest_float);
3670                 }
3671             }
3672             if (flags & SCF_DO_STCLASS_AND) {
3673                 /* Check whether it is compatible with what we know already! */
3674                 int compat = 1;
3675                 if (uc >= 0x100 ||
3676                  (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3677                   && !ANYOF_BITMAP_TEST(data->start_class, uc)
3678                   && !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3679                 {
3680                     compat = 0;
3681                 }
3682                 ANYOF_CLASS_ZERO(data->start_class);
3683                 ANYOF_BITMAP_ZERO(data->start_class);
3684                 if (compat) {
3685                     ANYOF_BITMAP_SET(data->start_class, uc);
3686                     data->start_class->flags &= ~ANYOF_EOS;
3687                     data->start_class->flags |= ANYOF_LOC_NONBITMAP_FOLD;
3688                     if (OP(scan) == EXACTFL) {
3689                         /* XXX This set is probably no longer necessary, and
3690                          * probably wrong as LOCALE now is on in the initial
3691                          * state */
3692                         data->start_class->flags |= ANYOF_LOCALE;
3693                     }
3694                     else {
3695
3696                         /* Also set the other member of the fold pair.  In case
3697                          * that unicode semantics is called for at runtime, use
3698                          * the full latin1 fold.  (Can't do this for locale,
3699                          * because not known until runtime) */
3700                         ANYOF_BITMAP_SET(data->start_class, PL_fold_latin1[uc]);
3701
3702                         /* All other (EXACTFL handled above) folds except under
3703                          * /iaa that include s, S, and sharp_s also may include
3704                          * the others */
3705                         if (OP(scan) != EXACTFA) {
3706                             if (uc == 's' || uc == 'S') {
3707                                 ANYOF_BITMAP_SET(data->start_class,
3708                                                  LATIN_SMALL_LETTER_SHARP_S);
3709                             }
3710                             else if (uc == LATIN_SMALL_LETTER_SHARP_S) {
3711                                 ANYOF_BITMAP_SET(data->start_class, 's');
3712                                 ANYOF_BITMAP_SET(data->start_class, 'S');
3713                             }
3714                         }
3715                     }
3716                 }
3717                 else if (uc >= 0x100) {
3718                     int i;
3719                     for (i = 0; i < 256; i++){
3720                         if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)) {
3721                             ANYOF_BITMAP_SET(data->start_class, i);
3722                         }
3723                     }
3724                 }
3725             }
3726             else if (flags & SCF_DO_STCLASS_OR) {
3727                 if (data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD) {
3728                     /* false positive possible if the class is case-folded.
3729                        Assume that the locale settings are the same... */
3730                     if (uc < 0x100) {
3731                         ANYOF_BITMAP_SET(data->start_class, uc);
3732                         if (OP(scan) != EXACTFL) {
3733
3734                             /* And set the other member of the fold pair, but
3735                              * can't do that in locale because not known until
3736                              * run-time */
3737                             ANYOF_BITMAP_SET(data->start_class,
3738                                              PL_fold_latin1[uc]);
3739
3740                             /* All folds except under /iaa that include s, S,
3741                              * and sharp_s also may include the others */
3742                             if (OP(scan) != EXACTFA) {
3743                                 if (uc == 's' || uc == 'S') {
3744                                     ANYOF_BITMAP_SET(data->start_class,
3745                                                    LATIN_SMALL_LETTER_SHARP_S);
3746                                 }
3747                                 else if (uc == LATIN_SMALL_LETTER_SHARP_S) {
3748                                     ANYOF_BITMAP_SET(data->start_class, 's');
3749                                     ANYOF_BITMAP_SET(data->start_class, 'S');
3750                                 }
3751                             }
3752                         }
3753                     }
3754                     data->start_class->flags &= ~ANYOF_EOS;
3755                 }
3756                 cl_and(data->start_class, and_withp);
3757             }
3758             flags &= ~SCF_DO_STCLASS;
3759         }
3760         else if (REGNODE_VARIES(OP(scan))) {
3761             I32 mincount, maxcount, minnext, deltanext, fl = 0;
3762             I32 f = flags, pos_before = 0;
3763             regnode * const oscan = scan;
3764             struct regnode_charclass_class this_class;
3765             struct regnode_charclass_class *oclass = NULL;
3766             I32 next_is_eval = 0;
3767
3768             switch (PL_regkind[OP(scan)]) {
3769             case WHILEM:                /* End of (?:...)* . */
3770                 scan = NEXTOPER(scan);
3771                 goto finish;
3772             case PLUS:
3773                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3774                     next = NEXTOPER(scan);
3775                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3776                         mincount = 1;
3777                         maxcount = REG_INFTY;
3778                         next = regnext(scan);
3779                         scan = NEXTOPER(scan);
3780                         goto do_curly;
3781                     }
3782                 }
3783                 if (flags & SCF_DO_SUBSTR)
3784                     data->pos_min++;
3785                 min++;
3786                 /* Fall through. */
3787             case STAR:
3788                 if (flags & SCF_DO_STCLASS) {
3789                     mincount = 0;
3790                     maxcount = REG_INFTY;
3791                     next = regnext(scan);
3792                     scan = NEXTOPER(scan);
3793                     goto do_curly;
3794                 }
3795                 is_inf = is_inf_internal = 1;
3796                 scan = regnext(scan);
3797                 if (flags & SCF_DO_SUBSTR) {
3798                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
3799                     data->longest = &(data->longest_float);
3800                 }
3801                 goto optimize_curly_tail;
3802             case CURLY:
3803                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3804                     && (scan->flags == stopparen))
3805                 {
3806                     mincount = 1;
3807                     maxcount = 1;
3808                 } else {
3809                     mincount = ARG1(scan);
3810                     maxcount = ARG2(scan);
3811                 }
3812                 next = regnext(scan);
3813                 if (OP(scan) == CURLYX) {
3814                     I32 lp = (data ? *(data->last_closep) : 0);
3815                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3816                 }
3817                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3818                 next_is_eval = (OP(scan) == EVAL);
3819               do_curly:
3820                 if (flags & SCF_DO_SUBSTR) {
3821                     if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3822                     pos_before = data->pos_min;
3823                 }
3824                 if (data) {
3825                     fl = data->flags;
3826                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3827                     if (is_inf)
3828                         data->flags |= SF_IS_INF;
3829                 }
3830                 if (flags & SCF_DO_STCLASS) {
3831                     cl_init(pRExC_state, &this_class);
3832                     oclass = data->start_class;
3833                     data->start_class = &this_class;
3834                     f |= SCF_DO_STCLASS_AND;
3835                     f &= ~SCF_DO_STCLASS_OR;
3836                 }
3837                 /* Exclude from super-linear cache processing any {n,m}
3838                    regops for which the combination of input pos and regex
3839                    pos is not enough information to determine if a match
3840                    will be possible.
3841
3842                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
3843                    regex pos at the \s*, the prospects for a match depend not
3844                    only on the input position but also on how many (bar\s*)
3845                    repeats into the {4,8} we are. */
3846                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
3847                     f &= ~SCF_WHILEM_VISITED_POS;
3848
3849                 /* This will finish on WHILEM, setting scan, or on NULL: */
3850                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, 
3851                                       last, data, stopparen, recursed, NULL,
3852                                       (mincount == 0
3853                                         ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3854
3855                 if (flags & SCF_DO_STCLASS)
3856                     data->start_class = oclass;
3857                 if (mincount == 0 || minnext == 0) {
3858                     if (flags & SCF_DO_STCLASS_OR) {
3859                         cl_or(pRExC_state, data->start_class, &this_class);
3860                     }
3861                     else if (flags & SCF_DO_STCLASS_AND) {
3862                         /* Switch to OR mode: cache the old value of
3863                          * data->start_class */
3864                         INIT_AND_WITHP;
3865                         StructCopy(data->start_class, and_withp,
3866                                    struct regnode_charclass_class);
3867                         flags &= ~SCF_DO_STCLASS_AND;
3868                         StructCopy(&this_class, data->start_class,
3869                                    struct regnode_charclass_class);
3870                         flags |= SCF_DO_STCLASS_OR;
3871                         data->start_class->flags |= ANYOF_EOS;
3872                     }
3873                 } else {                /* Non-zero len */
3874                     if (flags & SCF_DO_STCLASS_OR) {
3875                         cl_or(pRExC_state, data->start_class, &this_class);
3876                         cl_and(data->start_class, and_withp);
3877                     }
3878                     else if (flags & SCF_DO_STCLASS_AND)
3879                         cl_and(data->start_class, &this_class);
3880                     flags &= ~SCF_DO_STCLASS;
3881                 }
3882                 if (!scan)              /* It was not CURLYX, but CURLY. */
3883                     scan = next;
3884                 if ( /* ? quantifier ok, except for (?{ ... }) */
3885                     (next_is_eval || !(mincount == 0 && maxcount == 1))
3886                     && (minnext == 0) && (deltanext == 0)
3887                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3888                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
3889                 {
3890                     ckWARNreg(RExC_parse,
3891                               "Quantifier unexpected on zero-length expression");
3892                 }
3893
3894                 min += minnext * mincount;
3895                 is_inf_internal |= ((maxcount == REG_INFTY
3896                                      && (minnext + deltanext) > 0)
3897                                     || deltanext == I32_MAX);
3898                 is_inf |= is_inf_internal;
3899                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3900
3901                 /* Try powerful optimization CURLYX => CURLYN. */
3902                 if (  OP(oscan) == CURLYX && data
3903                       && data->flags & SF_IN_PAR
3904                       && !(data->flags & SF_HAS_EVAL)
3905                       && !deltanext && minnext == 1 ) {
3906                     /* Try to optimize to CURLYN.  */
3907                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3908                     regnode * const nxt1 = nxt;
3909 #ifdef DEBUGGING
3910                     regnode *nxt2;
3911 #endif
3912
3913                     /* Skip open. */
3914                     nxt = regnext(nxt);
3915                     if (!REGNODE_SIMPLE(OP(nxt))
3916                         && !(PL_regkind[OP(nxt)] == EXACT
3917                              && STR_LEN(nxt) == 1))
3918                         goto nogo;
3919 #ifdef DEBUGGING
3920                     nxt2 = nxt;
3921 #endif
3922                     nxt = regnext(nxt);
3923                     if (OP(nxt) != CLOSE)
3924                         goto nogo;
3925                     if (RExC_open_parens) {
3926                         RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3927                         RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3928                     }
3929                     /* Now we know that nxt2 is the only contents: */
3930                     oscan->flags = (U8)ARG(nxt);
3931                     OP(oscan) = CURLYN;
3932                     OP(nxt1) = NOTHING; /* was OPEN. */
3933
3934 #ifdef DEBUGGING
3935                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3936                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
3937                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
3938                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
3939                     OP(nxt + 1) = OPTIMIZED; /* was count. */
3940                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
3941 #endif
3942                 }
3943               nogo:
3944
3945                 /* Try optimization CURLYX => CURLYM. */
3946                 if (  OP(oscan) == CURLYX && data
3947                       && !(data->flags & SF_HAS_PAR)
3948                       && !(data->flags & SF_HAS_EVAL)
3949                       && !deltanext     /* atom is fixed width */
3950                       && minnext != 0   /* CURLYM can't handle zero width */
3951                 ) {
3952                     /* XXXX How to optimize if data == 0? */
3953                     /* Optimize to a simpler form.  */
3954                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3955                     regnode *nxt2;
3956
3957                     OP(oscan) = CURLYM;
3958                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3959                             && (OP(nxt2) != WHILEM))
3960                         nxt = nxt2;
3961                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
3962                     /* Need to optimize away parenths. */
3963                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
3964                         /* Set the parenth number.  */
3965                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3966
3967                         oscan->flags = (U8)ARG(nxt);
3968                         if (RExC_open_parens) {
3969                             RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3970                             RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3971                         }
3972                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
3973                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
3974
3975 #ifdef DEBUGGING
3976                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3977                         OP(nxt + 1) = OPTIMIZED; /* was count. */
3978                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
3979                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
3980 #endif
3981 #if 0
3982                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
3983                             regnode *nnxt = regnext(nxt1);
3984                             if (nnxt == nxt) {
3985                                 if (reg_off_by_arg[OP(nxt1)])
3986                                     ARG_SET(nxt1, nxt2 - nxt1);
3987                                 else if (nxt2 - nxt1 < U16_MAX)
3988                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
3989                                 else
3990                                     OP(nxt) = NOTHING;  /* Cannot beautify */
3991                             }
3992                             nxt1 = nnxt;
3993                         }
3994 #endif
3995                         /* Optimize again: */
3996                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3997                                     NULL, stopparen, recursed, NULL, 0,depth+1);
3998                     }
3999                     else
4000                         oscan->flags = 0;
4001                 }
4002                 else if ((OP(oscan) == CURLYX)
4003                          && (flags & SCF_WHILEM_VISITED_POS)
4004                          /* See the comment on a similar expression above.
4005                             However, this time it's not a subexpression
4006                             we care about, but the expression itself. */
4007                          && (maxcount == REG_INFTY)
4008                          && data && ++data->whilem_c < 16) {
4009                     /* This stays as CURLYX, we can put the count/of pair. */
4010                     /* Find WHILEM (as in regexec.c) */
4011                     regnode *nxt = oscan + NEXT_OFF(oscan);
4012
4013                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
4014                         nxt += ARG(nxt);
4015                     PREVOPER(nxt)->flags = (U8)(data->whilem_c
4016                         | (RExC_whilem_seen << 4)); /* On WHILEM */
4017                 }
4018                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
4019                     pars++;
4020                 if (flags & SCF_DO_SUBSTR) {
4021                     SV *last_str = NULL;
4022                     int counted = mincount != 0;
4023
4024                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
4025 #if defined(SPARC64_GCC_WORKAROUND)
4026                         I32 b = 0;
4027                         STRLEN l = 0;
4028                         const char *s = NULL;
4029                         I32 old = 0;
4030
4031                         if (pos_before >= data->last_start_min)
4032                             b = pos_before;
4033                         else
4034                             b = data->last_start_min;
4035
4036                         l = 0;
4037                         s = SvPV_const(data->last_found, l);
4038                         old = b - data->last_start_min;
4039
4040 #else
4041                         I32 b = pos_before >= data->last_start_min
4042                             ? pos_before : data->last_start_min;
4043                         STRLEN l;
4044                         const char * const s = SvPV_const(data->last_found, l);
4045                         I32 old = b - data->last_start_min;
4046 #endif
4047
4048                         if (UTF)
4049                             old = utf8_hop((U8*)s, old) - (U8*)s;
4050                         l -= old;
4051                         /* Get the added string: */
4052                         last_str = newSVpvn_utf8(s  + old, l, UTF);
4053                         if (deltanext == 0 && pos_before == b) {
4054                             /* What was added is a constant string */
4055                             if (mincount > 1) {
4056                                 SvGROW(last_str, (mincount * l) + 1);
4057                                 repeatcpy(SvPVX(last_str) + l,
4058                                           SvPVX_const(last_str), l, mincount - 1);
4059                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
4060                                 /* Add additional parts. */
4061                                 SvCUR_set(data->last_found,
4062                                           SvCUR(data->last_found) - l);
4063                                 sv_catsv(data->last_found, last_str);
4064                                 {
4065                                     SV * sv = data->last_found;
4066                                     MAGIC *mg =
4067                                         SvUTF8(sv) && SvMAGICAL(sv) ?
4068                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
4069                                     if (mg && mg->mg_len >= 0)
4070                                         mg->mg_len += CHR_SVLEN(last_str) - l;
4071                                 }
4072                                 data->last_end += l * (mincount - 1);
4073                             }
4074                         } else {
4075                             /* start offset must point into the last copy */
4076                             data->last_start_min += minnext * (mincount - 1);
4077                             data->last_start_max += is_inf ? I32_MAX
4078                                 : (maxcount - 1) * (minnext + data->pos_delta);
4079                         }
4080                     }
4081                     /* It is counted once already... */
4082                     data->pos_min += minnext * (mincount - counted);
4083                     data->pos_delta += - counted * deltanext +
4084                         (minnext + deltanext) * maxcount - minnext * mincount;
4085                     if (mincount != maxcount) {
4086                          /* Cannot extend fixed substrings found inside
4087                             the group.  */
4088                         SCAN_COMMIT(pRExC_state,data,minlenp);
4089                         if (mincount && last_str) {
4090                             SV * const sv = data->last_found;
4091                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
4092                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
4093
4094                             if (mg)
4095                                 mg->mg_len = -1;
4096                             sv_setsv(sv, last_str);
4097                             data->last_end = data->pos_min;
4098                             data->last_start_min =
4099                                 data->pos_min - CHR_SVLEN(last_str);
4100                             data->last_start_max = is_inf
4101                                 ? I32_MAX
4102                                 : data->pos_min + data->pos_delta
4103                                 - CHR_SVLEN(last_str);
4104                         }
4105                         data->longest = &(data->longest_float);
4106                     }
4107                     SvREFCNT_dec(last_str);
4108                 }
4109                 if (data && (fl & SF_HAS_EVAL))
4110                     data->flags |= SF_HAS_EVAL;
4111               optimize_curly_tail:
4112                 if (OP(oscan) != CURLYX) {
4113                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
4114                            && NEXT_OFF(next))
4115                         NEXT_OFF(oscan) += NEXT_OFF(next);
4116                 }
4117                 continue;
4118             default:                    /* REF, ANYOFV, and CLUMP only? */
4119                 if (flags & SCF_DO_SUBSTR) {
4120                     SCAN_COMMIT(pRExC_state,data,minlenp);      /* Cannot expect anything... */
4121                     data->longest = &(data->longest_float);
4122                 }
4123                 is_inf = is_inf_internal = 1;
4124                 if (flags & SCF_DO_STCLASS_OR)
4125                     cl_anything(pRExC_state, data->start_class);
4126                 flags &= ~SCF_DO_STCLASS;
4127                 break;
4128             }
4129         }
4130         else if (OP(scan) == LNBREAK) {
4131             if (flags & SCF_DO_STCLASS) {
4132                 int value = 0;
4133                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
4134                 if (flags & SCF_DO_STCLASS_AND) {
4135                     for (value = 0; value < 256; value++)
4136                         if (!is_VERTWS_cp(value))
4137                             ANYOF_BITMAP_CLEAR(data->start_class, value);
4138                 }
4139                 else {
4140                     for (value = 0; value < 256; value++)
4141                         if (is_VERTWS_cp(value))
4142                             ANYOF_BITMAP_SET(data->start_class, value);
4143                 }
4144                 if (flags & SCF_DO_STCLASS_OR)
4145                     cl_and(data->start_class, and_withp);
4146                 flags &= ~SCF_DO_STCLASS;
4147             }
4148             min += 1;
4149             delta += 1;
4150             if (flags & SCF_DO_SUBSTR) {
4151                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4152                 data->pos_min += 1;
4153                 data->pos_delta += 1;
4154                 data->longest = &(data->longest_float);
4155             }
4156         }
4157         else if (REGNODE_SIMPLE(OP(scan))) {
4158             int value = 0;
4159
4160             if (flags & SCF_DO_SUBSTR) {
4161                 SCAN_COMMIT(pRExC_state,data,minlenp);
4162                 data->pos_min++;
4163             }
4164             min++;
4165             if (flags & SCF_DO_STCLASS) {
4166                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
4167
4168                 /* Some of the logic below assumes that switching
4169                    locale on will only add false positives. */
4170                 switch (PL_regkind[OP(scan)]) {
4171                 case SANY:
4172                 default:
4173                   do_default:
4174                     /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
4175                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4176                         cl_anything(pRExC_state, data->start_class);
4177                     break;
4178                 case REG_ANY:
4179                     if (OP(scan) == SANY)
4180                         goto do_default;
4181                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
4182                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
4183                                  || ANYOF_CLASS_TEST_ANY_SET(data->start_class));
4184                         cl_anything(pRExC_state, data->start_class);
4185                     }
4186                     if (flags & SCF_DO_STCLASS_AND || !value)
4187                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
4188                     break;
4189                 case ANYOF:
4190                     if (flags & SCF_DO_STCLASS_AND)
4191                         cl_and(data->start_class,
4192                                (struct regnode_charclass_class*)scan);
4193                     else
4194                         cl_or(pRExC_state, data->start_class,
4195                               (struct regnode_charclass_class*)scan);
4196                     break;
4197                 case ALNUM:
4198                     if (flags & SCF_DO_STCLASS_AND) {
4199                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4200                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
4201                             if (OP(scan) == ALNUMU) {
4202                                 for (value = 0; value < 256; value++) {
4203                                     if (!isWORDCHAR_L1(value)) {
4204                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4205                                     }
4206                                 }
4207                             } else {
4208                                 for (value = 0; value < 256; value++) {
4209                                     if (!isALNUM(value)) {
4210                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4211                                     }
4212                                 }
4213                             }
4214                         }
4215                     }
4216                     else {
4217                         if (data->start_class->flags & ANYOF_LOCALE)
4218                             ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
4219
4220                         /* Even if under locale, set the bits for non-locale
4221                          * in case it isn't a true locale-node.  This will
4222                          * create false positives if it truly is locale */
4223                         if (OP(scan) == ALNUMU) {
4224                             for (value = 0; value < 256; value++) {
4225                                 if (isWORDCHAR_L1(value)) {
4226                                     ANYOF_BITMAP_SET(data->start_class, value);
4227                                 }
4228                             }
4229                         } else {
4230                             for (value = 0; value < 256; value++) {
4231                                 if (isALNUM(value)) {
4232                                     ANYOF_BITMAP_SET(data->start_class, value);
4233                                 }
4234                             }
4235                         }
4236                     }
4237                     break;
4238                 case NALNUM:
4239                     if (flags & SCF_DO_STCLASS_AND) {
4240                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4241                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
4242                             if (OP(scan) == NALNUMU) {
4243                                 for (value = 0; value < 256; value++) {
4244                                     if (isWORDCHAR_L1(value)) {
4245                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4246                                     }
4247                                 }
4248                             } else {
4249                                 for (value = 0; value < 256; value++) {
4250                                     if (isALNUM(value)) {
4251                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4252                                     }
4253                                 }
4254                             }
4255                         }
4256                     }
4257                     else {
4258                         if (data->start_class->flags & ANYOF_LOCALE)
4259                             ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
4260
4261                         /* Even if under locale, set the bits for non-locale in
4262                          * case it isn't a true locale-node.  This will create
4263                          * false positives if it truly is locale */
4264                         if (OP(scan) == NALNUMU) {
4265                             for (value = 0; value < 256; value++) {
4266                                 if (! isWORDCHAR_L1(value)) {
4267                                     ANYOF_BITMAP_SET(data->start_class, value);
4268                                 }
4269                             }
4270                         } else {
4271                             for (value = 0; value < 256; value++) {
4272                                 if (! isALNUM(value)) {
4273                                     ANYOF_BITMAP_SET(data->start_class, value);
4274                                 }
4275                             }
4276                         }
4277                     }
4278                     break;
4279                 case SPACE:
4280                     if (flags & SCF_DO_STCLASS_AND) {
4281                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4282                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
4283                             if (OP(scan) == SPACEU) {
4284                                 for (value = 0; value < 256; value++) {
4285                                     if (!isSPACE_L1(value)) {
4286                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4287                                     }
4288                                 }
4289                             } else {
4290                                 for (value = 0; value < 256; value++) {
4291                                     if (!isSPACE(value)) {
4292                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4293                                     }
4294                                 }
4295                             }
4296                         }
4297                     }
4298                     else {
4299                         if (data->start_class->flags & ANYOF_LOCALE) {
4300                             ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
4301                         }
4302                         if (OP(scan) == SPACEU) {
4303                             for (value = 0; value < 256; value++) {
4304                                 if (isSPACE_L1(value)) {
4305                                     ANYOF_BITMAP_SET(data->start_class, value);
4306                                 }
4307                             }
4308                         } else {
4309                             for (value = 0; value < 256; value++) {
4310                                 if (isSPACE(value)) {
4311                                     ANYOF_BITMAP_SET(data->start_class, value);
4312                                 }
4313                             }
4314                         }
4315                     }
4316                     break;
4317                 case NSPACE:
4318                     if (flags & SCF_DO_STCLASS_AND) {
4319                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4320                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
4321                             if (OP(scan) == NSPACEU) {
4322                                 for (value = 0; value < 256; value++) {
4323                                     if (isSPACE_L1(value)) {
4324                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4325                                     }
4326                                 }
4327                             } else {
4328                                 for (value = 0; value < 256; value++) {
4329                                     if (isSPACE(value)) {
4330                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4331                                     }
4332                                 }
4333                             }
4334                         }
4335                     }
4336                     else {
4337                         if (data->start_class->flags & ANYOF_LOCALE)
4338                             ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
4339                         if (OP(scan) == NSPACEU) {
4340                             for (value = 0; value < 256; value++) {
4341                                 if (!isSPACE_L1(value)) {
4342                                     ANYOF_BITMAP_SET(data->start_class, value);
4343                                 }
4344                             }
4345                         }
4346                         else {
4347                             for (value = 0; value < 256; value++) {
4348                                 if (!isSPACE(value)) {
4349                                     ANYOF_BITMAP_SET(data->start_class, value);
4350                                 }
4351                             }
4352                         }
4353                     }
4354                     break;
4355                 case DIGIT:
4356                     if (flags & SCF_DO_STCLASS_AND) {
4357                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4358                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
4359                             for (value = 0; value < 256; value++)
4360                                 if (!isDIGIT(value))
4361                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
4362                         }
4363                     }
4364                     else {
4365                         if (data->start_class->flags & ANYOF_LOCALE)
4366                             ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
4367                         for (value = 0; value < 256; value++)
4368                             if (isDIGIT(value))
4369                                 ANYOF_BITMAP_SET(data->start_class, value);
4370                     }
4371                     break;
4372                 case NDIGIT:
4373                     if (flags & SCF_DO_STCLASS_AND) {
4374                         if (!(data->start_class->flags & ANYOF_LOCALE))
4375                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
4376                         for (value = 0; value < 256; value++)
4377                             if (isDIGIT(value))
4378                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
4379                     }
4380                     else {
4381                         if (data->start_class->flags & ANYOF_LOCALE)
4382                             ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
4383                         for (value = 0; value < 256; value++)
4384                             if (!isDIGIT(value))
4385                                 ANYOF_BITMAP_SET(data->start_class, value);
4386                     }
4387                     break;
4388                 CASE_SYNST_FNC(VERTWS);
4389                 CASE_SYNST_FNC(HORIZWS);
4390
4391                 }
4392                 if (flags & SCF_DO_STCLASS_OR)
4393                     cl_and(data->start_class, and_withp);
4394                 flags &= ~SCF_DO_STCLASS;
4395             }
4396         }
4397         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
4398             data->flags |= (OP(scan) == MEOL
4399                             ? SF_BEFORE_MEOL
4400                             : SF_BEFORE_SEOL);
4401         }
4402         else if (  PL_regkind[OP(scan)] == BRANCHJ
4403                  /* Lookbehind, or need to calculate parens/evals/stclass: */
4404                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
4405                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
4406             if ( OP(scan) == UNLESSM &&
4407                  scan->flags == 0 &&
4408                  OP(NEXTOPER(NEXTOPER(scan))) == NOTHING &&
4409                  OP(regnext(NEXTOPER(NEXTOPER(scan)))) == SUCCEED
4410             ) {
4411                 regnode *opt;
4412                 regnode *upto= regnext(scan);
4413                 DEBUG_PARSE_r({
4414                     SV * const mysv_val=sv_newmortal();
4415                     DEBUG_STUDYDATA("OPFAIL",data,depth);
4416
4417                     /*DEBUG_PARSE_MSG("opfail");*/
4418                     regprop(RExC_rx, mysv_val, upto);
4419                     PerlIO_printf(Perl_debug_log, "~ replace with OPFAIL pointed at %s (%"IVdf") offset %"IVdf"\n",
4420                                   SvPV_nolen_const(mysv_val),
4421                                   (IV)REG_NODE_NUM(upto),
4422                                   (IV)(upto - scan)
4423                     );
4424                 });
4425                 OP(scan) = OPFAIL;
4426                 NEXT_OFF(scan) = upto - scan;
4427                 for (opt= scan + 1; opt < upto ; opt++)
4428                     OP(opt) = OPTIMIZED;
4429                 scan= upto;
4430                 continue;
4431             }
4432             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY 
4433                 || OP(scan) == UNLESSM )
4434             {
4435                 /* Negative Lookahead/lookbehind
4436                    In this case we can't do fixed string optimisation.
4437                 */
4438
4439                 I32 deltanext, minnext, fake = 0;
4440                 regnode *nscan;
4441                 struct regnode_charclass_class intrnl;
4442                 int f = 0;
4443
4444                 data_fake.flags = 0;
4445                 if (data) {
4446                     data_fake.whilem_c = data->whilem_c;
4447                     data_fake.last_closep = data->last_closep;
4448                 }
4449                 else
4450                     data_fake.last_closep = &fake;
4451                 data_fake.pos_delta = delta;
4452                 if ( flags & SCF_DO_STCLASS && !scan->flags
4453                      && OP(scan) == IFMATCH ) { /* Lookahead */
4454                     cl_init(pRExC_state, &intrnl);
4455                     data_fake.start_class = &intrnl;
4456                     f |= SCF_DO_STCLASS_AND;
4457                 }
4458                 if (flags & SCF_WHILEM_VISITED_POS)
4459                     f |= SCF_WHILEM_VISITED_POS;
4460                 next = regnext(scan);
4461                 nscan = NEXTOPER(NEXTOPER(scan));
4462                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, 
4463                     last, &data_fake, stopparen, recursed, NULL, f, depth+1);
4464                 if (scan->flags) {
4465                     if (deltanext) {
4466                         FAIL("Variable length lookbehind not implemented");
4467                     }
4468                     else if (minnext > (I32)U8_MAX) {
4469                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
4470                     }
4471                     scan->flags = (U8)minnext;
4472                 }
4473                 if (data) {
4474                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4475                         pars++;
4476                     if (data_fake.flags & SF_HAS_EVAL)
4477                         data->flags |= SF_HAS_EVAL;
4478                     data->whilem_c = data_fake.whilem_c;
4479                 }
4480                 if (f & SCF_DO_STCLASS_AND) {
4481                     if (flags & SCF_DO_STCLASS_OR) {
4482                         /* OR before, AND after: ideally we would recurse with
4483                          * data_fake to get the AND applied by study of the
4484                          * remainder of the pattern, and then derecurse;
4485                          * *** HACK *** for now just treat as "no information".
4486                          * See [perl #56690].
4487                          */
4488                         cl_init(pRExC_state, data->start_class);
4489                     }  else {
4490                         /* AND before and after: combine and continue */
4491                         const int was = (data->start_class->flags & ANYOF_EOS);
4492
4493                         cl_and(data->start_class, &intrnl);
4494                         if (was)
4495                             data->start_class->flags |= ANYOF_EOS;
4496                     }
4497                 }
4498             }
4499 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
4500             else {
4501                 /* Positive Lookahead/lookbehind
4502                    In this case we can do fixed string optimisation,
4503                    but we must be careful about it. Note in the case of
4504                    lookbehind the positions will be offset by the minimum
4505                    length of the pattern, something we won't know about
4506                    until after the recurse.
4507                 */
4508                 I32 deltanext, fake = 0;
4509                 regnode *nscan;
4510                 struct regnode_charclass_class intrnl;
4511                 int f = 0;
4512                 /* We use SAVEFREEPV so that when the full compile 
4513                     is finished perl will clean up the allocated 
4514                     minlens when it's all done. This way we don't
4515                     have to worry about freeing them when we know
4516                     they wont be used, which would be a pain.
4517                  */
4518                 I32 *minnextp;
4519                 Newx( minnextp, 1, I32 );
4520                 SAVEFREEPV(minnextp);
4521
4522                 if (data) {
4523                     StructCopy(data, &data_fake, scan_data_t);
4524                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
4525                         f |= SCF_DO_SUBSTR;
4526                         if (scan->flags) 
4527                             SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
4528                         data_fake.last_found=newSVsv(data->last_found);
4529                     }
4530                 }
4531                 else
4532                     data_fake.last_closep = &fake;
4533                 data_fake.flags = 0;
4534                 data_fake.pos_delta = delta;
4535                 if (is_inf)
4536                     data_fake.flags |= SF_IS_INF;
4537                 if ( flags & SCF_DO_STCLASS && !scan->flags
4538                      && OP(scan) == IFMATCH ) { /* Lookahead */
4539                     cl_init(pRExC_state, &intrnl);
4540                     data_fake.start_class = &intrnl;
4541                     f |= SCF_DO_STCLASS_AND;
4542                 }
4543                 if (flags & SCF_WHILEM_VISITED_POS)
4544                     f |= SCF_WHILEM_VISITED_POS;
4545                 next = regnext(scan);
4546                 nscan = NEXTOPER(NEXTOPER(scan));
4547
4548                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, 
4549                     last, &data_fake, stopparen, recursed, NULL, f,depth+1);
4550                 if (scan->flags) {
4551                     if (deltanext) {
4552                         FAIL("Variable length lookbehind not implemented");
4553                     }
4554                     else if (*minnextp > (I32)U8_MAX) {
4555                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
4556                     }
4557                     scan->flags = (U8)*minnextp;
4558                 }
4559
4560                 *minnextp += min;
4561
4562                 if (f & SCF_DO_STCLASS_AND) {
4563                     const int was = (data->start_class->flags & ANYOF_EOS);
4564
4565                     cl_and(data->start_class, &intrnl);
4566                     if (was)
4567                         data->start_class->flags |= ANYOF_EOS;
4568                 }
4569                 if (data) {
4570                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4571                         pars++;
4572                     if (data_fake.flags & SF_HAS_EVAL)
4573                         data->flags |= SF_HAS_EVAL;
4574                     data->whilem_c = data_fake.whilem_c;
4575                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
4576                         if (RExC_rx->minlen<*minnextp)
4577                             RExC_rx->minlen=*minnextp;
4578                         SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
4579                         SvREFCNT_dec(data_fake.last_found);
4580                         
4581                         if ( data_fake.minlen_fixed != minlenp ) 
4582                         {
4583                             data->offset_fixed= data_fake.offset_fixed;
4584                             data->minlen_fixed= data_fake.minlen_fixed;
4585                             data->lookbehind_fixed+= scan->flags;
4586                         }
4587                         if ( data_fake.minlen_float != minlenp )
4588                         {
4589                             data->minlen_float= data_fake.minlen_float;
4590                             data->offset_float_min=data_fake.offset_float_min;
4591                             data->offset_float_max=data_fake.offset_float_max;
4592                             data->lookbehind_float+= scan->flags;
4593                         }
4594                     }
4595                 }
4596             }
4597 #endif
4598         }
4599         else if (OP(scan) == OPEN) {
4600             if (stopparen != (I32)ARG(scan))
4601                 pars++;
4602         }
4603         else if (OP(scan) == CLOSE) {
4604             if (stopparen == (I32)ARG(scan)) {
4605                 break;
4606             }
4607             if ((I32)ARG(scan) == is_par) {
4608                 next = regnext(scan);
4609
4610                 if ( next && (OP(next) != WHILEM) && next < last)
4611                     is_par = 0;         /* Disable optimization */
4612             }
4613             if (data)
4614                 *(data->last_closep) = ARG(scan);
4615         }
4616         else if (OP(scan) == EVAL) {
4617                 if (data)
4618                     data->flags |= SF_HAS_EVAL;
4619         }
4620         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
4621             if (flags & SCF_DO_SUBSTR) {
4622                 SCAN_COMMIT(pRExC_state,data,minlenp);
4623                 flags &= ~SCF_DO_SUBSTR;
4624             }
4625             if (data && OP(scan)==ACCEPT) {
4626                 data->flags |= SCF_SEEN_ACCEPT;
4627                 if (stopmin > min)
4628                     stopmin = min;
4629             }
4630         }
4631         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
4632         {
4633                 if (flags & SCF_DO_SUBSTR) {
4634                     SCAN_COMMIT(pRExC_state,data,minlenp);
4635                     data->longest = &(data->longest_float);
4636                 }
4637                 is_inf = is_inf_internal = 1;
4638                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4639                     cl_anything(pRExC_state, data->start_class);
4640                 flags &= ~SCF_DO_STCLASS;
4641         }
4642         else if (OP(scan) == GPOS) {
4643             if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
4644                 !(delta || is_inf || (data && data->pos_delta))) 
4645             {
4646                 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
4647                     RExC_rx->extflags |= RXf_ANCH_GPOS;
4648                 if (RExC_rx->gofs < (U32)min)
4649                     RExC_rx->gofs = min;
4650             } else {
4651                 RExC_rx->extflags |= RXf_GPOS_FLOAT;
4652                 RExC_rx->gofs = 0;
4653             }       
4654         }
4655 #ifdef TRIE_STUDY_OPT
4656 #ifdef FULL_TRIE_STUDY
4657         else if (PL_regkind[OP(scan)] == TRIE) {
4658             /* NOTE - There is similar code to this block above for handling
4659                BRANCH nodes on the initial study.  If you change stuff here
4660                check there too. */
4661             regnode *trie_node= scan;
4662             regnode *tail= regnext(scan);
4663             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4664             I32 max1 = 0, min1 = I32_MAX;
4665             struct regnode_charclass_class accum;
4666
4667             if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
4668                 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
4669             if (flags & SCF_DO_STCLASS)
4670                 cl_init_zero(pRExC_state, &accum);
4671                 
4672             if (!trie->jump) {
4673                 min1= trie->minlen;
4674                 max1= trie->maxlen;
4675             } else {
4676                 const regnode *nextbranch= NULL;
4677                 U32 word;
4678                 
4679                 for ( word=1 ; word <= trie->wordcount ; word++) 
4680                 {
4681                     I32 deltanext=0, minnext=0, f = 0, fake;
4682                     struct regnode_charclass_class this_class;
4683                     
4684                     data_fake.flags = 0;
4685                     if (data) {
4686                         data_fake.whilem_c = data->whilem_c;
4687                         data_fake.last_closep = data->last_closep;
4688                     }
4689                     else
4690                         data_fake.last_closep = &fake;
4691                     data_fake.pos_delta = delta;
4692                     if (flags & SCF_DO_STCLASS) {
4693                         cl_init(pRExC_state, &this_class);
4694                         data_fake.start_class = &this_class;
4695                         f = SCF_DO_STCLASS_AND;
4696                     }
4697                     if (flags & SCF_WHILEM_VISITED_POS)
4698                         f |= SCF_WHILEM_VISITED_POS;
4699     
4700                     if (trie->jump[word]) {
4701                         if (!nextbranch)
4702                             nextbranch = trie_node + trie->jump[0];
4703                         scan= trie_node + trie->jump[word];
4704                         /* We go from the jump point to the branch that follows
4705                            it. Note this means we need the vestigal unused branches
4706                            even though they arent otherwise used.
4707                          */
4708                         minnext = study_chunk(pRExC_state, &scan, minlenp, 
4709                             &deltanext, (regnode *)nextbranch, &data_fake, 
4710                             stopparen, recursed, NULL, f,depth+1);
4711                     }
4712                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
4713                         nextbranch= regnext((regnode*)nextbranch);
4714                     
4715                     if (min1 > (I32)(minnext + trie->minlen))
4716                         min1 = minnext + trie->minlen;
4717                     if (max1 < (I32)(minnext + deltanext + trie->maxlen))
4718                         max1 = minnext + deltanext + trie->maxlen;
4719                     if (deltanext == I32_MAX)
4720                         is_inf = is_inf_internal = 1;
4721                     
4722                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4723                         pars++;
4724                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4725                         if ( stopmin > min + min1) 
4726                             stopmin = min + min1;
4727                         flags &= ~SCF_DO_SUBSTR;
4728                         if (data)
4729                             data->flags |= SCF_SEEN_ACCEPT;
4730                     }
4731                     if (data) {
4732                         if (data_fake.flags & SF_HAS_EVAL)
4733                             data->flags |= SF_HAS_EVAL;
4734                         data->whilem_c = data_fake.whilem_c;
4735                     }
4736                     if (flags & SCF_DO_STCLASS)
4737                         cl_or(pRExC_state, &accum, &this_class);
4738                 }
4739             }
4740             if (flags & SCF_DO_SUBSTR) {
4741                 data->pos_min += min1;
4742                 data->pos_delta += max1 - min1;
4743                 if (max1 != min1 || is_inf)
4744                     data->longest = &(data->longest_float);
4745             }
4746             min += min1;
4747             delta += max1 - min1;
4748             if (flags & SCF_DO_STCLASS_OR) {
4749                 cl_or(pRExC_state, data->start_class, &accum);
4750                 if (min1) {
4751                     cl_and(data->start_class, and_withp);
4752                     flags &= ~SCF_DO_STCLASS;
4753                 }
4754             }
4755             else if (flags & SCF_DO_STCLASS_AND) {
4756                 if (min1) {
4757                     cl_and(data->start_class, &accum);
4758                     flags &= ~SCF_DO_STCLASS;
4759                 }
4760                 else {
4761                     /* Switch to OR mode: cache the old value of
4762                      * data->start_class */
4763                     INIT_AND_WITHP;
4764                     StructCopy(data->start_class, and_withp,
4765                                struct regnode_charclass_class);
4766                     flags &= ~SCF_DO_STCLASS_AND;
4767                     StructCopy(&accum, data->start_class,
4768                                struct regnode_charclass_class);
4769                     flags |= SCF_DO_STCLASS_OR;
4770                     data->start_class->flags |= ANYOF_EOS;
4771                 }
4772             }
4773             scan= tail;
4774             continue;
4775         }
4776 #else
4777         else if (PL_regkind[OP(scan)] == TRIE) {
4778             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4779             U8*bang=NULL;
4780             
4781             min += trie->minlen;
4782             delta += (trie->maxlen - trie->minlen);
4783             flags &= ~SCF_DO_STCLASS; /* xxx */
4784             if (flags & SCF_DO_SUBSTR) {
4785                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4786                 data->pos_min += trie->minlen;
4787                 data->pos_delta += (trie->maxlen - trie->minlen);
4788                 if (trie->maxlen != trie->minlen)
4789                     data->longest = &(data->longest_float);
4790             }
4791             if (trie->jump) /* no more substrings -- for now /grr*/
4792                 flags &= ~SCF_DO_SUBSTR; 
4793         }
4794 #endif /* old or new */
4795 #endif /* TRIE_STUDY_OPT */
4796
4797         /* Else: zero-length, ignore. */
4798         scan = regnext(scan);
4799     }
4800     if (frame) {
4801         last = frame->last;
4802         scan = frame->next;
4803         stopparen = frame->stop;
4804         frame = frame->prev;
4805         goto fake_study_recurse;
4806     }
4807
4808   finish:
4809     assert(!frame);
4810     DEBUG_STUDYDATA("pre-fin:",data,depth);
4811
4812     *scanp = scan;
4813     *deltap = is_inf_internal ? I32_MAX : delta;
4814     if (flags & SCF_DO_SUBSTR && is_inf)
4815         data->pos_delta = I32_MAX - data->pos_min;
4816     if (is_par > (I32)U8_MAX)
4817         is_par = 0;
4818     if (is_par && pars==1 && data) {
4819         data->flags |= SF_IN_PAR;
4820         data->flags &= ~SF_HAS_PAR;
4821     }
4822     else if (pars && data) {
4823         data->flags |= SF_HAS_PAR;
4824         data->flags &= ~SF_IN_PAR;
4825     }
4826     if (flags & SCF_DO_STCLASS_OR)
4827         cl_and(data->start_class, and_withp);
4828     if (flags & SCF_TRIE_RESTUDY)
4829         data->flags |=  SCF_TRIE_RESTUDY;
4830     
4831     DEBUG_STUDYDATA("post-fin:",data,depth);
4832     
4833     return min < stopmin ? min : stopmin;
4834 }
4835
4836 STATIC U32
4837 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
4838 {
4839     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
4840
4841     PERL_ARGS_ASSERT_ADD_DATA;
4842
4843     Renewc(RExC_rxi->data,
4844            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
4845            char, struct reg_data);
4846     if(count)
4847         Renew(RExC_rxi->data->what, count + n, U8);
4848     else
4849         Newx(RExC_rxi->data->what, n, U8);
4850     RExC_rxi->data->count = count + n;
4851     Copy(s, RExC_rxi->data->what + count, n, U8);
4852     return count;
4853 }
4854
4855 /*XXX: todo make this not included in a non debugging perl */
4856 #ifndef PERL_IN_XSUB_RE
4857 void
4858 Perl_reginitcolors(pTHX)
4859 {
4860     dVAR;
4861     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
4862     if (s) {
4863         char *t = savepv(s);
4864         int i = 0;
4865         PL_colors[0] = t;
4866         while (++i < 6) {
4867             t = strchr(t, '\t');
4868             if (t) {
4869                 *t = '\0';
4870                 PL_colors[i] = ++t;
4871             }
4872             else
4873                 PL_colors[i] = t = (char *)"";
4874         }
4875     } else {
4876         int i = 0;
4877         while (i < 6)
4878             PL_colors[i++] = (char *)"";
4879     }
4880     PL_colorset = 1;
4881 }
4882 #endif
4883
4884
4885 #ifdef TRIE_STUDY_OPT
4886 #define CHECK_RESTUDY_GOTO                                  \
4887         if (                                                \
4888               (data.flags & SCF_TRIE_RESTUDY)               \
4889               && ! restudied++                              \
4890         )     goto reStudy
4891 #else
4892 #define CHECK_RESTUDY_GOTO
4893 #endif        
4894
4895 /*
4896  * pregcomp - compile a regular expression into internal code
4897  *
4898  * Decides which engine's compiler to call based on the hint currently in
4899  * scope
4900  */
4901
4902 #ifndef PERL_IN_XSUB_RE 
4903
4904 /* return the currently in-scope regex engine (or the default if none)  */
4905
4906 regexp_engine const *
4907 Perl_current_re_engine(pTHX)
4908 {
4909     dVAR;
4910
4911     if (IN_PERL_COMPILETIME) {
4912         HV * const table = GvHV(PL_hintgv);
4913         SV **ptr;
4914
4915         if (!table)
4916             return &PL_core_reg_engine;
4917         ptr = hv_fetchs(table, "regcomp", FALSE);
4918         if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr)))
4919             return &PL_core_reg_engine;
4920         return INT2PTR(regexp_engine*,SvIV(*ptr));
4921     }
4922     else {
4923         SV *ptr;
4924         if (!PL_curcop->cop_hints_hash)
4925             return &PL_core_reg_engine;
4926         ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0);
4927         if ( !(ptr && SvIOK(ptr) && SvIV(ptr)))
4928             return &PL_core_reg_engine;
4929         return INT2PTR(regexp_engine*,SvIV(ptr));
4930     }
4931 }
4932
4933
4934 REGEXP *
4935 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
4936 {
4937     dVAR;
4938     regexp_engine const *eng = current_re_engine();
4939     GET_RE_DEBUG_FLAGS_DECL;
4940
4941     PERL_ARGS_ASSERT_PREGCOMP;
4942
4943     /* Dispatch a request to compile a regexp to correct regexp engine. */
4944     DEBUG_COMPILE_r({
4945         PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4946                         PTR2UV(eng));
4947     });
4948     return CALLREGCOMP_ENG(eng, pattern, flags);
4949 }
4950 #endif
4951
4952 /* public(ish) wrapper for Perl_re_op_compile that only takes an SV
4953  * pattern rather than a list of OPs */
4954
4955 REGEXP *
4956 Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags)
4957 {
4958     SV *pat = pattern; /* defeat constness! */
4959     PERL_ARGS_ASSERT_RE_COMPILE;
4960     return Perl_re_op_compile(aTHX_ &pat, 1, NULL, current_re_engine(),
4961                                 NULL, NULL, rx_flags, 0);
4962 }
4963
4964 /* see if there are any run-time code blocks in the pattern.
4965  * False positives are allowed */
4966
4967 static bool
4968 S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state, OP *expr,
4969                     U32 pm_flags, char *pat, STRLEN plen)
4970 {
4971     int n = 0;
4972     STRLEN s;
4973
4974     /* avoid infinitely recursing when we recompile the pattern parcelled up
4975      * as qr'...'. A single constant qr// string can't have have any
4976      * run-time component in it, and thus, no runtime code. (A non-qr
4977      * string, however, can, e.g. $x =~ '(?{})') */
4978     if  ((pm_flags & PMf_IS_QR) && expr && expr->op_type == OP_CONST)
4979         return 0;
4980
4981     for (s = 0; s < plen; s++) {
4982         if (n < pRExC_state->num_code_blocks
4983             && s == pRExC_state->code_blocks[n].start)
4984         {
4985             s = pRExC_state->code_blocks[n].end;
4986             n++;
4987             continue;
4988         }
4989         /* TODO ideally should handle [..], (#..), /#.../x to reduce false
4990          * positives here */
4991         if (pat[s] == '(' && pat[s+1] == '?' &&
4992             (pat[s+2] == '{' || (pat[s+2] == '?' && pat[s+3] == '{'))
4993         )
4994             return 1;
4995     }
4996     return 0;
4997 }
4998
4999 /* Handle run-time code blocks. We will already have compiled any direct
5000  * or indirect literal code blocks. Now, take the pattern 'pat' and make a
5001  * copy of it, but with any literal code blocks blanked out and
5002  * appropriate chars escaped; then feed it into
5003  *
5004  *    eval "qr'modified_pattern'"
5005  *
5006  * For example,
5007  *
5008  *       a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno
5009  *
5010  * becomes
5011  *
5012  *    qr'a\\bc                       def\'ghi\\\\jkl(?{"this is runtime"})mno'
5013  *
5014  * After eval_sv()-ing that, grab any new code blocks from the returned qr
5015  * and merge them with any code blocks of the original regexp.
5016  *
5017  * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge;
5018  * instead, just save the qr and return FALSE; this tells our caller that
5019  * the original pattern needs upgrading to utf8.
5020  */
5021
5022 bool
5023 S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state,
5024     char *pat, STRLEN plen)
5025 {
5026     SV *qr;
5027
5028     GET_RE_DEBUG_FLAGS_DECL;
5029
5030     if (pRExC_state->runtime_code_qr) {
5031         /* this is the second time we've been called; this should
5032          * only happen if the main pattern got upgraded to utf8
5033          * during compilation; re-use the qr we compiled first time
5034          * round (which should be utf8 too)
5035          */
5036         qr = pRExC_state->runtime_code_qr;
5037         pRExC_state->runtime_code_qr = NULL;
5038         assert(RExC_utf8 && SvUTF8(qr));
5039     }
5040     else {
5041         int n = 0;
5042         STRLEN s;
5043         char *p, *newpat;
5044         int newlen = plen + 6; /* allow for "qr''x\0" extra chars */
5045         SV *sv, *qr_ref;
5046         dSP;
5047
5048         /* determine how many extra chars we need for ' and \ escaping */
5049         for (s = 0; s < plen; s++) {
5050             if (pat[s] == '\'' || pat[s] == '\\')
5051                 newlen++;
5052         }
5053
5054         Newx(newpat, newlen, char);
5055         p = newpat;
5056         *p++ = 'q'; *p++ = 'r'; *p++ = '\'';
5057
5058         for (s = 0; s < plen; s++) {
5059             if (n < pRExC_state->num_code_blocks
5060                 && s == pRExC_state->code_blocks[n].start)
5061             {
5062                 /* blank out literal code block */
5063                 assert(pat[s] == '(');
5064                 while (s <= pRExC_state->code_blocks[n].end) {
5065                     *p++ = ' ';
5066                     s++;
5067                 }
5068                 s--;
5069                 n++;
5070                 continue;
5071             }
5072             if (pat[s] == '\'' || pat[s] == '\\')
5073                 *p++ = '\\';
5074             *p++ = pat[s];
5075         }
5076         *p++ = '\'';
5077         if (pRExC_state->pm_flags & RXf_PMf_EXTENDED)
5078             *p++ = 'x';
5079         *p++ = '\0';
5080         DEBUG_COMPILE_r({
5081             PerlIO_printf(Perl_debug_log,
5082                 "%sre-parsing pattern for runtime code:%s %s\n",
5083                 PL_colors[4],PL_colors[5],newpat);
5084         });
5085
5086         sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0);
5087         Safefree(newpat);
5088
5089         ENTER;
5090         SAVETMPS;
5091         save_re_context();
5092         PUSHSTACKi(PERLSI_REQUIRE);
5093         /* this causes the toker to collapse \\ into \ when parsing
5094          * qr''; normally only q'' does this. It also alters hints
5095          * handling */
5096         PL_reg_state.re_reparsing = TRUE;
5097         eval_sv(sv, G_SCALAR);
5098         SvREFCNT_dec(sv);
5099         SPAGAIN;
5100         qr_ref = POPs;
5101         PUTBACK;
5102         if (SvTRUE(ERRSV))
5103             Perl_croak(aTHX_ "%s", SvPVx_nolen_const(ERRSV));
5104         assert(SvROK(qr_ref));
5105         qr = SvRV(qr_ref);
5106         assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp);
5107         /* the leaving below frees the tmp qr_ref.
5108          * Give qr a life of its own */
5109         SvREFCNT_inc(qr);
5110         POPSTACK;
5111         FREETMPS;
5112         LEAVE;
5113
5114     }
5115
5116     if (!RExC_utf8 && SvUTF8(qr)) {
5117         /* first time through; the pattern got upgraded; save the
5118          * qr for the next time through */
5119         assert(!pRExC_state->runtime_code_qr);
5120         pRExC_state->runtime_code_qr = qr;
5121         return 0;
5122     }
5123
5124
5125     /* extract any code blocks within the returned qr//  */
5126
5127
5128     /* merge the main (r1) and run-time (r2) code blocks into one */
5129     {
5130         RXi_GET_DECL(((struct regexp*)SvANY(qr)), r2);
5131         struct reg_code_block *new_block, *dst;
5132         RExC_state_t * const r1 = pRExC_state; /* convenient alias */
5133         int i1 = 0, i2 = 0;
5134
5135         if (!r2->num_code_blocks) /* we guessed wrong */
5136             return 1;
5137
5138         Newx(new_block,
5139             r1->num_code_blocks + r2->num_code_blocks,
5140             struct reg_code_block);
5141         dst = new_block;
5142
5143         while (    i1 < r1->num_code_blocks
5144                 || i2 < r2->num_code_blocks)
5145         {
5146             struct reg_code_block *src;
5147             bool is_qr = 0;
5148
5149             if (i1 == r1->num_code_blocks) {
5150                 src = &r2->code_blocks[i2++];
5151                 is_qr = 1;
5152             }
5153             else if (i2 == r2->num_code_blocks)
5154                 src = &r1->code_blocks[i1++];
5155             else if (  r1->code_blocks[i1].start
5156                      < r2->code_blocks[i2].start)
5157             {
5158                 src = &r1->code_blocks[i1++];
5159                 assert(src->end < r2->code_blocks[i2].start);
5160             }
5161             else {
5162                 assert(  r1->code_blocks[i1].start
5163                        > r2->code_blocks[i2].start);
5164                 src = &r2->code_blocks[i2++];
5165                 is_qr = 1;
5166                 assert(src->end < r1->code_blocks[i1].start);
5167             }
5168
5169             assert(pat[src->start] == '(');
5170             assert(pat[src->end]   == ')');
5171             dst->start      = src->start;
5172             dst->end        = src->end;
5173             dst->block      = src->block;
5174             dst->src_regex  = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr)
5175                                     : src->src_regex;
5176             dst++;
5177         }
5178         r1->num_code_blocks += r2->num_code_blocks;
5179         Safefree(r1->code_blocks);
5180         r1->code_blocks = new_block;
5181     }
5182
5183     SvREFCNT_dec(qr);
5184     return 1;
5185 }
5186
5187
5188 /*
5189  * Perl_re_op_compile - the perl internal RE engine's function to compile a
5190  * regular expression into internal code.
5191  * The pattern may be passed either as:
5192  *    a list of SVs (patternp plus pat_count)
5193  *    a list of OPs (expr)
5194  * If both are passed, the SV list is used, but the OP list indicates
5195  * which SVs are actually pre-compiled code blocks
5196  *
5197  * The SVs in the list have magic and qr overloading applied to them (and
5198  * the list may be modified in-place with replacement SVs in the latter
5199  * case).
5200  *
5201  * If the pattern hasn't changed from old_re, then old_re will be
5202  * returned.
5203  *
5204  * eng is the current engine. If that engine has an op_comp method, then
5205  * handle directly (i.e. we assume that op_comp was us); otherwise, just
5206  * do the initial concatenation of arguments and pass on to the external
5207  * engine.
5208  *
5209  * If is_bare_re is not null, set it to a boolean indicating whether the
5210  * arg list reduced (after overloading) to a single bare regex which has
5211  * been returned (i.e. /$qr/).
5212  *
5213  * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details.
5214  *
5215  * pm_flags contains the PMf_* flags, typically based on those from the
5216  * pm_flags field of the related PMOP. Currently we're only interested in
5217  * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL.
5218  *
5219  * We can't allocate space until we know how big the compiled form will be,
5220  * but we can't compile it (and thus know how big it is) until we've got a
5221  * place to put the code.  So we cheat:  we compile it twice, once with code
5222  * generation turned off and size counting turned on, and once "for real".
5223  * This also means that we don't allocate space until we are sure that the
5224  * thing really will compile successfully, and we never have to move the
5225  * code and thus invalidate pointers into it.  (Note that it has to be in
5226  * one piece because free() must be able to free it all.) [NB: not true in perl]
5227  *
5228  * Beware that the optimization-preparation code in here knows about some
5229  * of the structure of the compiled regexp.  [I'll say.]
5230  */
5231
5232 REGEXP *
5233 Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
5234                     OP *expr, const regexp_engine* eng, REGEXP *VOL old_re,
5235                      bool *is_bare_re, U32 orig_rx_flags, U32 pm_flags)
5236 {
5237     dVAR;
5238     REGEXP *rx;
5239     struct regexp *r;
5240     register regexp_internal *ri;
5241     STRLEN plen;
5242     char  * VOL exp;
5243     char* xend;
5244     regnode *scan;
5245     I32 flags;
5246     I32 minlen = 0;
5247     U32 rx_flags;
5248     SV * VOL pat;
5249
5250     /* these are all flags - maybe they should be turned
5251      * into a single int with different bit masks */
5252     I32 sawlookahead = 0;
5253     I32 sawplus = 0;
5254     I32 sawopen = 0;
5255     bool used_setjump = FALSE;
5256     regex_charset initial_charset = get_regex_charset(orig_rx_flags);
5257     bool code_is_utf8 = 0;
5258     bool VOL recompile = 0;
5259     bool runtime_code = 0;
5260     U8 jump_ret = 0;
5261     dJMPENV;
5262     scan_data_t data;
5263     RExC_state_t RExC_state;
5264     RExC_state_t * const pRExC_state = &RExC_state;
5265 #ifdef TRIE_STUDY_OPT    
5266     int restudied;
5267     RExC_state_t copyRExC_state;
5268 #endif    
5269     GET_RE_DEBUG_FLAGS_DECL;
5270
5271     PERL_ARGS_ASSERT_RE_OP_COMPILE;
5272
5273     DEBUG_r(if (!PL_colorset) reginitcolors());
5274
5275 #ifndef PERL_IN_XSUB_RE
5276     /* Initialize these here instead of as-needed, as is quick and avoids
5277      * having to test them each time otherwise */
5278     if (! PL_AboveLatin1) {
5279         PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist);
5280         PL_ASCII = _new_invlist_C_array(ASCII_invlist);
5281         PL_Latin1 = _new_invlist_C_array(Latin1_invlist);
5282
5283         PL_L1PosixAlnum = _new_invlist_C_array(L1PosixAlnum_invlist);
5284         PL_PosixAlnum = _new_invlist_C_array(PosixAlnum_invlist);
5285
5286         PL_L1PosixAlpha = _new_invlist_C_array(L1PosixAlpha_invlist);
5287         PL_PosixAlpha = _new_invlist_C_array(PosixAlpha_invlist);
5288
5289         PL_PosixBlank = _new_invlist_C_array(PosixBlank_invlist);
5290         PL_XPosixBlank = _new_invlist_C_array(XPosixBlank_invlist);
5291
5292         PL_L1Cased = _new_invlist_C_array(L1Cased_invlist);
5293
5294         PL_PosixCntrl = _new_invlist_C_array(PosixCntrl_invlist);
5295         PL_XPosixCntrl = _new_invlist_C_array(XPosixCntrl_invlist);
5296
5297         PL_PosixDigit = _new_invlist_C_array(PosixDigit_invlist);
5298
5299         PL_L1PosixGraph = _new_invlist_C_array(L1PosixGraph_invlist);
5300         PL_PosixGraph = _new_invlist_C_array(PosixGraph_invlist);
5301
5302         PL_L1PosixAlnum = _new_invlist_C_array(L1PosixAlnum_invlist);
5303         PL_PosixAlnum = _new_invlist_C_array(PosixAlnum_invlist);
5304
5305         PL_L1PosixLower = _new_invlist_C_array(L1PosixLower_invlist);
5306         PL_PosixLower = _new_invlist_C_array(PosixLower_invlist);
5307
5308         PL_L1PosixPrint = _new_invlist_C_array(L1PosixPrint_invlist);
5309         PL_PosixPrint = _new_invlist_C_array(PosixPrint_invlist);
5310
5311         PL_L1PosixPunct = _new_invlist_C_array(L1PosixPunct_invlist);
5312         PL_PosixPunct = _new_invlist_C_array(PosixPunct_invlist);
5313
5314         PL_PerlSpace = _new_invlist_C_array(PerlSpace_invlist);
5315         PL_XPerlSpace = _new_invlist_C_array(XPerlSpace_invlist);
5316
5317         PL_PosixSpace = _new_invlist_C_array(PosixSpace_invlist);
5318         PL_XPosixSpace = _new_invlist_C_array(XPosixSpace_invlist);
5319
5320         PL_L1PosixUpper = _new_invlist_C_array(L1PosixUpper_invlist);
5321         PL_PosixUpper = _new_invlist_C_array(PosixUpper_invlist);
5322
5323         PL_VertSpace = _new_invlist_C_array(VertSpace_invlist);
5324
5325         PL_PosixWord = _new_invlist_C_array(PosixWord_invlist);
5326         PL_L1PosixWord = _new_invlist_C_array(L1PosixWord_invlist);
5327
5328         PL_PosixXDigit = _new_invlist_C_array(PosixXDigit_invlist);
5329         PL_XPosixXDigit = _new_invlist_C_array(XPosixXDigit_invlist);
5330     }
5331 #endif
5332
5333     pRExC_state->code_blocks = NULL;
5334     pRExC_state->num_code_blocks = 0;
5335
5336     if (is_bare_re)
5337         *is_bare_re = FALSE;
5338
5339     if (expr && (expr->op_type == OP_LIST ||
5340                 (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) {
5341
5342         /* is the source UTF8, and how many code blocks are there? */
5343         OP *o;
5344         int ncode = 0;
5345
5346         for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
5347             if (o->op_type == OP_CONST && SvUTF8(cSVOPo_sv))
5348                 code_is_utf8 = 1;
5349             else if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL))
5350                 /* count of DO blocks */
5351                 ncode++;
5352         }
5353         if (ncode) {
5354             pRExC_state->num_code_blocks = ncode;
5355             Newx(pRExC_state->code_blocks, ncode, struct reg_code_block);
5356         }
5357     }
5358
5359     if (pat_count) {
5360         /* handle a list of SVs */
5361
5362         SV **svp;
5363
5364         /* apply magic and RE overloading to each arg */
5365         for (svp = patternp; svp < patternp + pat_count; svp++) {
5366             SV *rx = *svp;
5367             SvGETMAGIC(rx);
5368             if (SvROK(rx) && SvAMAGIC(rx)) {
5369                 SV *sv = AMG_CALLunary(rx, regexp_amg);
5370                 if (sv) {
5371                     if (SvROK(sv))
5372                         sv = SvRV(sv);
5373                     if (SvTYPE(sv) != SVt_REGEXP)
5374                         Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP");
5375                     *svp = sv;
5376                 }
5377             }
5378         }
5379
5380         if (pat_count > 1) {
5381             /* concat multiple args and find any code block indexes */
5382
5383             OP *o = NULL;
5384             int n = 0;
5385             bool utf8 = 0;
5386
5387             if (pRExC_state->num_code_blocks) {
5388                 o = cLISTOPx(expr)->op_first;
5389                 assert(o->op_type == OP_PUSHMARK);
5390                 o = o->op_sibling;
5391             }
5392
5393             pat = newSVpvn("", 0);
5394             SAVEFREESV(pat);
5395
5396             /* determine if the pattern is going to be utf8 (needed
5397              * in advance to align code block indices correctly).
5398              * XXX This could fail to be detected for an arg with
5399              * overloading but not concat overloading; but the main effect
5400              * in this obscure case is to need a 'use re eval' for a
5401              * literal code block */
5402             for (svp = patternp; svp < patternp + pat_count; svp++) {
5403                 if (SvUTF8(*svp))
5404                     utf8 = 1;
5405             }
5406             if (utf8)
5407                 SvUTF8_on(pat);
5408
5409             for (svp = patternp; svp < patternp + pat_count; svp++) {
5410                 SV *sv, *msv = *svp;
5411                 SV *rx;
5412                 bool code = 0;
5413                 if (o) {
5414                     if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5415                         assert(n < pRExC_state->num_code_blocks);
5416                         pRExC_state->code_blocks[n].start = SvCUR(pat);
5417                         pRExC_state->code_blocks[n].block = o;
5418                         pRExC_state->code_blocks[n].src_regex = NULL;
5419                         n++;
5420                         code = 1;
5421                         o = o->op_sibling; /* skip CONST */
5422                         assert(o);
5423                     }
5424                     o = o->op_sibling;;
5425                 }
5426
5427                 /* extract any code blocks within any embedded qr//'s */
5428                 rx = msv;
5429                 if (SvROK(rx))
5430                     rx = SvRV(rx);
5431                 if (SvTYPE(rx) == SVt_REGEXP
5432                     && RX_ENGINE((REGEXP*)rx)->op_comp)
5433                 {
5434
5435                     RXi_GET_DECL(((struct regexp*)SvANY(rx)), ri);
5436                     if (ri->num_code_blocks) {
5437                         int i;
5438                         /* the presence of an embedded qr// with code means
5439                          * we should always recompile: the text of the
5440                          * qr// may not have changed, but it may be a
5441                          * different closure than last time */
5442                         recompile = 1;
5443                         Renew(pRExC_state->code_blocks,
5444                             pRExC_state->num_code_blocks + ri->num_code_blocks,
5445                             struct reg_code_block);
5446                         pRExC_state->num_code_blocks += ri->num_code_blocks;
5447                         for (i=0; i < ri->num_code_blocks; i++) {
5448                             struct reg_code_block *src, *dst;
5449                             STRLEN offset =  SvCUR(pat)
5450                                 + ((struct regexp *)SvANY(rx))->pre_prefix;
5451                             assert(n < pRExC_state->num_code_blocks);
5452                             src = &ri->code_blocks[i];
5453                             dst = &pRExC_state->code_blocks[n];
5454                             dst->start      = src->start + offset;
5455                             dst->end        = src->end   + offset;
5456                             dst->block      = src->block;
5457                             dst->src_regex  = (REGEXP*) SvREFCNT_inc( (SV*)
5458                                                     src->src_regex
5459                                                         ? src->src_regex
5460                                                         : (REGEXP*)rx);
5461                             n++;
5462                         }
5463                     }
5464                 }
5465
5466                 if ((SvAMAGIC(pat) || SvAMAGIC(msv)) &&
5467                         (sv = amagic_call(pat, msv, concat_amg, AMGf_assign)))
5468                 {
5469                     sv_setsv(pat, sv);
5470                     /* overloading involved: all bets are off over literal
5471                      * code. Pretend we haven't seen it */
5472                     pRExC_state->num_code_blocks -= n;
5473                     n = 0;
5474
5475                 }
5476                 else {
5477                     if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP)
5478                         msv = SvRV(msv);
5479                     sv_catsv_nomg(pat, msv);
5480                     if (code)
5481                         pRExC_state->code_blocks[n-1].end = SvCUR(pat)-1;
5482                 }
5483             }
5484             SvSETMAGIC(pat);
5485         }
5486         else
5487             pat = *patternp;
5488
5489         /* handle bare regex: foo =~ $re */
5490         {
5491             SV *re = pat;
5492             if (SvROK(re))
5493                 re = SvRV(re);
5494             if (SvTYPE(re) == SVt_REGEXP) {
5495                 if (is_bare_re)
5496                     *is_bare_re = TRUE;
5497                 SvREFCNT_inc(re);
5498                 Safefree(pRExC_state->code_blocks);
5499                 return (REGEXP*)re;
5500             }
5501         }
5502     }
5503     else {
5504         /* not a list of SVs, so must be a list of OPs */
5505         assert(expr);
5506         if (expr->op_type == OP_LIST) {
5507             int i = -1;
5508             bool is_code = 0;
5509             OP *o;
5510
5511             pat = newSVpvn("", 0);
5512             SAVEFREESV(pat);
5513             if (code_is_utf8)
5514                 SvUTF8_on(pat);
5515
5516             /* given a list of CONSTs and DO blocks in expr, append all
5517              * the CONSTs to pat, and record the start and end of each
5518              * code block in code_blocks[] (each DO{} op is followed by an
5519              * OP_CONST containing the corresponding literal '(?{...})
5520              * text)
5521              */
5522             for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
5523                 if (o->op_type == OP_CONST) {
5524                     sv_catsv(pat, cSVOPo_sv);
5525                     if (is_code) {
5526                         pRExC_state->code_blocks[i].end = SvCUR(pat)-1;
5527                         is_code = 0;
5528                     }
5529                 }
5530                 else if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
5531                     assert(i+1 < pRExC_state->num_code_blocks);
5532                     pRExC_state->code_blocks[++i].start = SvCUR(pat);
5533                     pRExC_state->code_blocks[i].block = o;
5534                     pRExC_state->code_blocks[i].src_regex = NULL;
5535                     is_code = 1;
5536                 }
5537             }
5538         }
5539         else {
5540             assert(expr->op_type == OP_CONST);
5541             pat = cSVOPx_sv(expr);
5542         }
5543     }
5544
5545     exp = SvPV_nomg(pat, plen);
5546
5547     if (!eng->op_comp) {
5548         if ((SvUTF8(pat) && IN_BYTES)
5549                 || SvGMAGICAL(pat) || SvAMAGIC(pat))
5550         {
5551             /* make a temporary copy; either to convert to bytes,
5552              * or to avoid repeating get-magic / overloaded stringify */
5553             pat = newSVpvn_flags(exp, plen, SVs_TEMP |
5554                                         (IN_BYTES ? 0 : SvUTF8(pat)));
5555         }
5556         Safefree(pRExC_state->code_blocks);
5557         return CALLREGCOMP_ENG(eng, pat, orig_rx_flags);
5558     }
5559
5560     /* ignore the utf8ness if the pattern is 0 length */
5561     RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat);
5562     RExC_uni_semantics = 0;
5563     RExC_contains_locale = 0;
5564     pRExC_state->runtime_code_qr = NULL;
5565
5566     /****************** LONG JUMP TARGET HERE***********************/
5567     /* Longjmp back to here if have to switch in midstream to utf8 */
5568     if (! RExC_orig_utf8) {
5569         JMPENV_PUSH(jump_ret);
5570         used_setjump = TRUE;
5571     }
5572
5573     if (jump_ret == 0) {    /* First time through */
5574         xend = exp + plen;
5575
5576         DEBUG_COMPILE_r({
5577             SV *dsv= sv_newmortal();
5578             RE_PV_QUOTED_DECL(s, RExC_utf8,
5579                 dsv, exp, plen, 60);
5580             PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
5581                            PL_colors[4],PL_colors[5],s);
5582         });
5583     }
5584     else {  /* longjumped back */
5585         U8 *src, *dst;
5586         int n=0;
5587         STRLEN s = 0, d = 0;
5588         bool do_end = 0;
5589
5590         /* If the cause for the longjmp was other than changing to utf8, pop
5591          * our own setjmp, and longjmp to the correct handler */
5592         if (jump_ret != UTF8_LONGJMP) {
5593             JMPENV_POP;
5594             JMPENV_JUMP(jump_ret);
5595         }
5596
5597         GET_RE_DEBUG_FLAGS;
5598
5599         /* It's possible to write a regexp in ascii that represents Unicode
5600         codepoints outside of the byte range, such as via \x{100}. If we
5601         detect such a sequence we have to convert the entire pattern to utf8
5602         and then recompile, as our sizing calculation will have been based
5603         on 1 byte == 1 character, but we will need to use utf8 to encode
5604         at least some part of the pattern, and therefore must convert the whole
5605         thing.
5606         -- dmq */
5607         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
5608             "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
5609
5610         /* upgrade pattern to UTF8, and if there are code blocks,
5611          * recalculate the indices.
5612          * This is essentially an unrolled Perl_bytes_to_utf8() */
5613
5614         src = (U8*)SvPV_nomg(pat, plen);
5615         Newx(dst, plen * 2 + 1, U8);
5616
5617         while (s < plen) {
5618             const UV uv = NATIVE_TO_ASCII(src[s]);
5619             if (UNI_IS_INVARIANT(uv))
5620                 dst[d]   = (U8)UTF_TO_NATIVE(uv);
5621             else {
5622                 dst[d++] = (U8)UTF8_EIGHT_BIT_HI(uv);
5623                 dst[d]   = (U8)UTF8_EIGHT_BIT_LO(uv);
5624             }
5625             if (n < pRExC_state->num_code_blocks) {
5626                 if (!do_end && pRExC_state->code_blocks[n].start == s) {
5627                     pRExC_state->code_blocks[n].start = d;
5628                     assert(dst[d] == '(');
5629                     do_end = 1;
5630                 }
5631                 else if (do_end && pRExC_state->code_blocks[n].end == s) {
5632                     pRExC_state->code_blocks[n].end = d;
5633                     assert(dst[d] == ')');
5634                     do_end = 0;
5635                     n++;
5636                 }
5637             }
5638             s++;
5639             d++;
5640         }
5641         dst[d] = '\0';
5642         plen = d;
5643         exp = (char*) dst;
5644         xend = exp + plen;
5645         SAVEFREEPV(exp);
5646         RExC_orig_utf8 = RExC_utf8 = 1;
5647     }
5648
5649     /* return old regex if pattern hasn't changed */
5650
5651     if (   old_re
5652         && !recompile
5653         && !!RX_UTF8(old_re) == !!RExC_utf8
5654         && RX_PRECOMP(old_re)
5655         && RX_PRELEN(old_re) == plen
5656         && memEQ(RX_PRECOMP(old_re), exp, plen))
5657     {
5658         /* with runtime code, always recompile */
5659         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, expr, pm_flags,
5660                                             exp, plen);
5661         if (!runtime_code) {
5662             ReREFCNT_inc(old_re);
5663             if (used_setjump) {
5664                 JMPENV_POP;
5665             }
5666             Safefree(pRExC_state->code_blocks);
5667             return old_re;
5668         }
5669     }
5670     else if ((pm_flags & PMf_USE_RE_EVAL)
5671                 /* this second condition covers the non-regex literal case,
5672                  * i.e.  $foo =~ '(?{})'. */
5673                 || ( !PL_reg_state.re_reparsing && IN_PERL_COMPILETIME
5674                     && (PL_hints & HINT_RE_EVAL))
5675     )
5676         runtime_code = S_has_runtime_code(aTHX_ pRExC_state, expr, pm_flags,
5677                             exp, plen);
5678
5679 #ifdef TRIE_STUDY_OPT
5680     restudied = 0;
5681 #endif
5682
5683     rx_flags = orig_rx_flags;
5684
5685     if (initial_charset == REGEX_LOCALE_CHARSET) {
5686         RExC_contains_locale = 1;
5687     }
5688     else if (RExC_utf8 && initial_charset == REGEX_DEPENDS_CHARSET) {
5689
5690         /* Set to use unicode semantics if the pattern is in utf8 and has the
5691          * 'depends' charset specified, as it means unicode when utf8  */
5692         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
5693     }
5694
5695     RExC_precomp = exp;
5696     RExC_flags = rx_flags;
5697     RExC_pm_flags = pm_flags;
5698
5699     if (runtime_code) {
5700         if (PL_tainting && PL_tainted)
5701             Perl_croak(aTHX_ "Eval-group in insecure regular expression");
5702
5703         if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) {
5704             /* whoops, we have a non-utf8 pattern, whilst run-time code
5705              * got compiled as utf8. Try again with a utf8 pattern */
5706              JMPENV_JUMP(UTF8_LONGJMP);
5707         }
5708     }
5709     assert(!pRExC_state->runtime_code_qr);
5710
5711     RExC_sawback = 0;
5712
5713     RExC_seen = 0;
5714     RExC_in_lookbehind = 0;
5715     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
5716     RExC_extralen = 0;
5717     RExC_override_recoding = 0;
5718
5719     /* First pass: determine size, legality. */
5720     RExC_parse = exp;
5721     RExC_start = exp;
5722     RExC_end = xend;
5723     RExC_naughty = 0;
5724     RExC_npar = 1;
5725     RExC_nestroot = 0;
5726     RExC_size = 0L;
5727     RExC_emit = &PL_regdummy;
5728     RExC_whilem_seen = 0;
5729     RExC_open_parens = NULL;
5730     RExC_close_parens = NULL;
5731     RExC_opend = NULL;
5732     RExC_paren_names = NULL;
5733 #ifdef DEBUGGING
5734     RExC_paren_name_list = NULL;
5735 #endif
5736     RExC_recurse = NULL;
5737     RExC_recurse_count = 0;
5738     pRExC_state->code_index = 0;
5739
5740 #if 0 /* REGC() is (currently) a NOP at the first pass.
5741        * Clever compilers notice this and complain. --jhi */
5742     REGC((U8)REG_MAGIC, (char*)RExC_emit);
5743 #endif
5744     DEBUG_PARSE_r(
5745         PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n");
5746         RExC_lastnum=0;
5747         RExC_lastparse=NULL;
5748     );
5749     if (reg(pRExC_state, 0, &flags,1) == NULL) {
5750         RExC_precomp = NULL;
5751         Safefree(pRExC_state->code_blocks);
5752         return(NULL);
5753     }
5754
5755     /* Here, finished first pass.  Get rid of any added setjmp */
5756     if (used_setjump) {
5757         JMPENV_POP;
5758     }
5759
5760     DEBUG_PARSE_r({
5761         PerlIO_printf(Perl_debug_log, 
5762             "Required size %"IVdf" nodes\n"
5763             "Starting second pass (creation)\n", 
5764             (IV)RExC_size);
5765         RExC_lastnum=0; 
5766         RExC_lastparse=NULL; 
5767     });
5768
5769     /* The first pass could have found things that force Unicode semantics */
5770     if ((RExC_utf8 || RExC_uni_semantics)
5771          && get_regex_charset(rx_flags) == REGEX_DEPENDS_CHARSET)
5772     {
5773         set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET);
5774     }
5775
5776     /* Small enough for pointer-storage convention?
5777        If extralen==0, this means that we will not need long jumps. */
5778     if (RExC_size >= 0x10000L && RExC_extralen)
5779         RExC_size += RExC_extralen;
5780     else
5781         RExC_extralen = 0;
5782     if (RExC_whilem_seen > 15)
5783         RExC_whilem_seen = 15;
5784
5785     /* Allocate space and zero-initialize. Note, the two step process 
5786        of zeroing when in debug mode, thus anything assigned has to 
5787        happen after that */
5788     rx = (REGEXP*) newSV_type(SVt_REGEXP);
5789     r = (struct regexp*)SvANY(rx);
5790     Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
5791          char, regexp_internal);
5792     if ( r == NULL || ri == NULL )
5793         FAIL("Regexp out of space");
5794 #ifdef DEBUGGING
5795     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
5796     Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
5797 #else 
5798     /* bulk initialize base fields with 0. */
5799     Zero(ri, sizeof(regexp_internal), char);        
5800 #endif
5801
5802     /* non-zero initialization begins here */
5803     RXi_SET( r, ri );
5804     r->engine= eng;
5805     r->extflags = rx_flags;
5806     if (pm_flags & PMf_IS_QR) {
5807         ri->code_blocks = pRExC_state->code_blocks;
5808         ri->num_code_blocks = pRExC_state->num_code_blocks;
5809     }
5810     else
5811         SAVEFREEPV(pRExC_state->code_blocks);
5812
5813     {
5814         bool has_p     = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
5815         bool has_charset = (get_regex_charset(r->extflags) != REGEX_DEPENDS_CHARSET);
5816
5817         /* The caret is output if there are any defaults: if not all the STD
5818          * flags are set, or if no character set specifier is needed */
5819         bool has_default =
5820                     (((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
5821                     || ! has_charset);
5822         bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
5823         U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD)
5824                             >> RXf_PMf_STD_PMMOD_SHIFT);
5825         const char *fptr = STD_PAT_MODS;        /*"msix"*/
5826         char *p;
5827         /* Allocate for the worst case, which is all the std flags are turned
5828          * on.  If more precision is desired, we could do a population count of
5829          * the flags set.  This could be done with a small lookup table, or by
5830          * shifting, masking and adding, or even, when available, assembly
5831          * language for a machine-language population count.
5832          * We never output a minus, as all those are defaults, so are
5833          * covered by the caret */
5834         const STRLEN wraplen = plen + has_p + has_runon
5835             + has_default       /* If needs a caret */
5836
5837                 /* If needs a character set specifier */
5838             + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
5839             + (sizeof(STD_PAT_MODS) - 1)
5840             + (sizeof("(?:)") - 1);
5841
5842         p = sv_grow(MUTABLE_SV(rx), wraplen + 1); /* +1 for the ending NUL */
5843         SvPOK_on(rx);
5844         if (RExC_utf8)
5845             SvFLAGS(rx) |= SVf_UTF8;
5846         *p++='('; *p++='?';
5847
5848         /* If a default, cover it using the caret */
5849         if (has_default) {
5850             *p++= DEFAULT_PAT_MOD;
5851         }
5852         if (has_charset) {
5853             STRLEN len;
5854             const char* const name = get_regex_charset_name(r->extflags, &len);
5855             Copy(name, p, len, char);
5856             p += len;
5857         }
5858         if (has_p)
5859             *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
5860         {
5861             char ch;
5862             while((ch = *fptr++)) {
5863                 if(reganch & 1)
5864                     *p++ = ch;
5865                 reganch >>= 1;
5866             }
5867         }
5868
5869         *p++ = ':';
5870         Copy(RExC_precomp, p, plen, char);
5871         assert ((RX_WRAPPED(rx) - p) < 16);
5872         r->pre_prefix = p - RX_WRAPPED(rx);
5873         p += plen;
5874         if (has_runon)
5875             *p++ = '\n';
5876         *p++ = ')';
5877         *p = 0;
5878         SvCUR_set(rx, p - SvPVX_const(rx));
5879     }
5880
5881     r->intflags = 0;
5882     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
5883     
5884     if (RExC_seen & REG_SEEN_RECURSE) {
5885         Newxz(RExC_open_parens, RExC_npar,regnode *);
5886         SAVEFREEPV(RExC_open_parens);
5887         Newxz(RExC_close_parens,RExC_npar,regnode *);
5888         SAVEFREEPV(RExC_close_parens);
5889     }
5890
5891     /* Useful during FAIL. */
5892 #ifdef RE_TRACK_PATTERN_OFFSETS
5893     Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
5894     DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
5895                           "%s %"UVuf" bytes for offset annotations.\n",
5896                           ri->u.offsets ? "Got" : "Couldn't get",
5897                           (UV)((2*RExC_size+1) * sizeof(U32))));
5898 #endif
5899     SetProgLen(ri,RExC_size);
5900     RExC_rx_sv = rx;
5901     RExC_rx = r;
5902     RExC_rxi = ri;
5903
5904     /* Second pass: emit code. */
5905     RExC_flags = rx_flags;      /* don't let top level (?i) bleed */
5906     RExC_pm_flags = pm_flags;
5907     RExC_parse = exp;
5908     RExC_end = xend;
5909     RExC_naughty = 0;
5910     RExC_npar = 1;
5911     RExC_emit_start = ri->program;
5912     RExC_emit = ri->program;
5913     RExC_emit_bound = ri->program + RExC_size + 1;
5914     pRExC_state->code_index = 0;
5915
5916     REGC((U8)REG_MAGIC, (char*) RExC_emit++);
5917     if (reg(pRExC_state, 0, &flags,1) == NULL) {
5918         ReREFCNT_dec(rx);   
5919         return(NULL);
5920     }
5921     /* XXXX To minimize changes to RE engine we always allocate
5922        3-units-long substrs field. */
5923     Newx(r->substrs, 1, struct reg_substr_data);
5924     if (RExC_recurse_count) {
5925         Newxz(RExC_recurse,RExC_recurse_count,regnode *);
5926         SAVEFREEPV(RExC_recurse);
5927     }
5928
5929 reStudy:
5930     r->minlen = minlen = sawlookahead = sawplus = sawopen = 0;
5931     Zero(r->substrs, 1, struct reg_substr_data);
5932
5933 #ifdef TRIE_STUDY_OPT
5934     if (!restudied) {
5935         StructCopy(&zero_scan_data, &data, scan_data_t);
5936         copyRExC_state = RExC_state;
5937     } else {
5938         U32 seen=RExC_seen;
5939         DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
5940         
5941         RExC_state = copyRExC_state;
5942         if (seen & REG_TOP_LEVEL_BRANCHES) 
5943             RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5944         else
5945             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
5946         if (data.last_found) {
5947             SvREFCNT_dec(data.longest_fixed);
5948             SvREFCNT_dec(data.longest_float);
5949             SvREFCNT_dec(data.last_found);
5950         }
5951         StructCopy(&zero_scan_data, &data, scan_data_t);
5952     }
5953 #else
5954     StructCopy(&zero_scan_data, &data, scan_data_t);
5955 #endif    
5956
5957     /* Dig out information for optimizations. */
5958     r->extflags = RExC_flags; /* was pm_op */
5959     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
5960  
5961     if (UTF)
5962         SvUTF8_on(rx);  /* Unicode in it? */
5963     ri->regstclass = NULL;
5964     if (RExC_naughty >= 10)     /* Probably an expensive pattern. */
5965         r->intflags |= PREGf_NAUGHTY;
5966     scan = ri->program + 1;             /* First BRANCH. */
5967
5968     /* testing for BRANCH here tells us whether there is "must appear"
5969        data in the pattern. If there is then we can use it for optimisations */
5970     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /*  Only one top-level choice. */
5971         I32 fake;
5972         STRLEN longest_float_length, longest_fixed_length;
5973         struct regnode_charclass_class ch_class; /* pointed to by data */
5974         int stclass_flag;
5975         I32 last_close = 0; /* pointed to by data */
5976         regnode *first= scan;
5977         regnode *first_next= regnext(first);
5978         /*
5979          * Skip introductions and multiplicators >= 1
5980          * so that we can extract the 'meat' of the pattern that must 
5981          * match in the large if() sequence following.
5982          * NOTE that EXACT is NOT covered here, as it is normally
5983          * picked up by the optimiser separately. 
5984          *
5985          * This is unfortunate as the optimiser isnt handling lookahead
5986          * properly currently.
5987          *
5988          */
5989         while ((OP(first) == OPEN && (sawopen = 1)) ||
5990                /* An OR of *one* alternative - should not happen now. */
5991             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
5992             /* for now we can't handle lookbehind IFMATCH*/
5993             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
5994             (OP(first) == PLUS) ||
5995             (OP(first) == MINMOD) ||
5996                /* An {n,m} with n>0 */
5997             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
5998             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
5999         {
6000                 /* 
6001                  * the only op that could be a regnode is PLUS, all the rest
6002                  * will be regnode_1 or regnode_2.
6003                  *
6004                  */
6005                 if (OP(first) == PLUS)
6006                     sawplus = 1;
6007                 else
6008                     first += regarglen[OP(first)];
6009
6010                 first = NEXTOPER(first);
6011                 first_next= regnext(first);
6012         }
6013
6014         /* Starting-point info. */
6015       again:
6016         DEBUG_PEEP("first:",first,0);
6017         /* Ignore EXACT as we deal with it later. */
6018         if (PL_regkind[OP(first)] == EXACT) {
6019             if (OP(first) == EXACT)
6020                 NOOP;   /* Empty, get anchored substr later. */
6021             else
6022                 ri->regstclass = first;
6023         }
6024 #ifdef TRIE_STCLASS
6025         else if (PL_regkind[OP(first)] == TRIE &&
6026                 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0) 
6027         {
6028             regnode *trie_op;
6029             /* this can happen only on restudy */
6030             if ( OP(first) == TRIE ) {
6031                 struct regnode_1 *trieop = (struct regnode_1 *)
6032                     PerlMemShared_calloc(1, sizeof(struct regnode_1));
6033                 StructCopy(first,trieop,struct regnode_1);
6034                 trie_op=(regnode *)trieop;
6035             } else {
6036                 struct regnode_charclass *trieop = (struct regnode_charclass *)
6037                     PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
6038                 StructCopy(first,trieop,struct regnode_charclass);
6039                 trie_op=(regnode *)trieop;
6040             }
6041             OP(trie_op)+=2;
6042             make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
6043             ri->regstclass = trie_op;
6044         }
6045 #endif
6046         else if (REGNODE_SIMPLE(OP(first)))
6047             ri->regstclass = first;
6048         else if (PL_regkind[OP(first)] == BOUND ||
6049                  PL_regkind[OP(first)] == NBOUND)
6050             ri->regstclass = first;
6051         else if (PL_regkind[OP(first)] == BOL) {
6052             r->extflags |= (OP(first) == MBOL
6053                            ? RXf_ANCH_MBOL
6054                            : (OP(first) == SBOL
6055                               ? RXf_ANCH_SBOL
6056                               : RXf_ANCH_BOL));
6057             first = NEXTOPER(first);
6058             goto again;
6059         }
6060         else if (OP(first) == GPOS) {
6061             r->extflags |= RXf_ANCH_GPOS;
6062             first = NEXTOPER(first);
6063             goto again;
6064         }
6065         else if ((!sawopen || !RExC_sawback) &&
6066             (OP(first) == STAR &&
6067             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
6068             !(r->extflags & RXf_ANCH) && !pRExC_state->num_code_blocks)
6069         {
6070             /* turn .* into ^.* with an implied $*=1 */
6071             const int type =
6072                 (OP(NEXTOPER(first)) == REG_ANY)
6073                     ? RXf_ANCH_MBOL
6074                     : RXf_ANCH_SBOL;
6075             r->extflags |= type;
6076             r->intflags |= PREGf_IMPLICIT;
6077             first = NEXTOPER(first);
6078             goto again;
6079         }
6080         if (sawplus && !sawlookahead && (!sawopen || !RExC_sawback)
6081             && !pRExC_state->num_code_blocks) /* May examine pos and $& */
6082             /* x+ must match at the 1st pos of run of x's */
6083             r->intflags |= PREGf_SKIP;
6084
6085         /* Scan is after the zeroth branch, first is atomic matcher. */
6086 #ifdef TRIE_STUDY_OPT
6087         DEBUG_PARSE_r(
6088             if (!restudied)
6089                 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
6090                               (IV)(first - scan + 1))
6091         );
6092 #else
6093         DEBUG_PARSE_r(
6094             PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
6095                 (IV)(first - scan + 1))
6096         );
6097 #endif
6098
6099
6100         /*
6101         * If there's something expensive in the r.e., find the
6102         * longest literal string that must appear and make it the
6103         * regmust.  Resolve ties in favor of later strings, since
6104         * the regstart check works with the beginning of the r.e.
6105         * and avoiding duplication strengthens checking.  Not a
6106         * strong reason, but sufficient in the absence of others.
6107         * [Now we resolve ties in favor of the earlier string if
6108         * it happens that c_offset_min has been invalidated, since the
6109         * earlier string may buy us something the later one won't.]
6110         */
6111
6112         data.longest_fixed = newSVpvs("");
6113         data.longest_float = newSVpvs("");
6114         data.last_found = newSVpvs("");
6115         data.longest = &(data.longest_fixed);
6116         first = scan;
6117         if (!ri->regstclass) {
6118             cl_init(pRExC_state, &ch_class);
6119             data.start_class = &ch_class;
6120             stclass_flag = SCF_DO_STCLASS_AND;
6121         } else                          /* XXXX Check for BOUND? */
6122             stclass_flag = 0;
6123         data.last_closep = &last_close;
6124         
6125         minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
6126             &data, -1, NULL, NULL,
6127             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
6128
6129
6130         CHECK_RESTUDY_GOTO;
6131
6132
6133         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
6134              && data.last_start_min == 0 && data.last_end > 0
6135              && !RExC_seen_zerolen
6136              && !(RExC_seen & REG_SEEN_VERBARG)
6137              && (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
6138             r->extflags |= RXf_CHECK_ALL;
6139         scan_commit(pRExC_state, &data,&minlen,0);
6140         SvREFCNT_dec(data.last_found);
6141
6142         /* Note that code very similar to this but for anchored string 
6143            follows immediately below, changes may need to be made to both. 
6144            Be careful. 
6145          */
6146         longest_float_length = CHR_SVLEN(data.longest_float);
6147         if (longest_float_length
6148             || (data.flags & SF_FL_BEFORE_EOL
6149                 && (!(data.flags & SF_FL_BEFORE_MEOL)
6150                     || (RExC_flags & RXf_PMf_MULTILINE)))) 
6151         {
6152             I32 t,ml;
6153
6154             /* See comments for join_exact for why REG_SEEN_EXACTF_SHARP_S */
6155             if ((RExC_seen & REG_SEEN_EXACTF_SHARP_S)
6156                 || (SvCUR(data.longest_fixed)  /* ok to leave SvCUR */
6157                     && data.offset_fixed == data.offset_float_min
6158                     && SvCUR(data.longest_fixed) == SvCUR(data.longest_float)))
6159                     goto remove_float;          /* As in (a)+. */
6160
6161             /* copy the information about the longest float from the reg_scan_data
6162                over to the program. */
6163             if (SvUTF8(data.longest_float)) {
6164                 r->float_utf8 = data.longest_float;
6165                 r->float_substr = NULL;
6166             } else {
6167                 r->float_substr = data.longest_float;
6168                 r->float_utf8 = NULL;
6169             }
6170             /* float_end_shift is how many chars that must be matched that 
6171                follow this item. We calculate it ahead of time as once the
6172                lookbehind offset is added in we lose the ability to correctly
6173                calculate it.*/
6174             ml = data.minlen_float ? *(data.minlen_float) 
6175                                    : (I32)longest_float_length;
6176             r->float_end_shift = ml - data.offset_float_min
6177                 - longest_float_length + (SvTAIL(data.longest_float) != 0)
6178                 + data.lookbehind_float;
6179             r->float_min_offset = data.offset_float_min - data.lookbehind_float;
6180             r->float_max_offset = data.offset_float_max;
6181             if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
6182                 r->float_max_offset -= data.lookbehind_float;
6183             
6184             t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
6185                        && (!(data.flags & SF_FL_BEFORE_MEOL)
6186                            || (RExC_flags & RXf_PMf_MULTILINE)));
6187             fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
6188         }
6189         else {
6190           remove_float:
6191             r->float_substr = r->float_utf8 = NULL;
6192             SvREFCNT_dec(data.longest_float);
6193             longest_float_length = 0;
6194         }
6195
6196         /* Note that code very similar to this but for floating string 
6197            is immediately above, changes may need to be made to both. 
6198            Be careful. 
6199          */
6200         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
6201
6202         /* See comments for join_exact for why REG_SEEN_EXACTF_SHARP_S */
6203         if (! (RExC_seen & REG_SEEN_EXACTF_SHARP_S)
6204             && (longest_fixed_length
6205                 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
6206                     && (!(data.flags & SF_FIX_BEFORE_MEOL)
6207                         || (RExC_flags & RXf_PMf_MULTILINE)))) )
6208         {
6209             I32 t,ml;
6210
6211             /* copy the information about the longest fixed 
6212                from the reg_scan_data over to the program. */
6213             if (SvUTF8(data.longest_fixed)) {
6214                 r->anchored_utf8 = data.longest_fixed;
6215                 r->anchored_substr = NULL;
6216             } else {
6217                 r->anchored_substr = data.longest_fixed;
6218                 r->anchored_utf8 = NULL;
6219             }
6220             /* fixed_end_shift is how many chars that must be matched that 
6221                follow this item. We calculate it ahead of time as once the
6222                lookbehind offset is added in we lose the ability to correctly
6223                calculate it.*/
6224             ml = data.minlen_fixed ? *(data.minlen_fixed) 
6225                                    : (I32)longest_fixed_length;
6226             r->anchored_end_shift = ml - data.offset_fixed
6227                 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
6228                 + data.lookbehind_fixed;
6229             r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
6230
6231             t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
6232                  && (!(data.flags & SF_FIX_BEFORE_MEOL)
6233                      || (RExC_flags & RXf_PMf_MULTILINE)));
6234             fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
6235         }
6236         else {
6237             r->anchored_substr = r->anchored_utf8 = NULL;
6238             SvREFCNT_dec(data.longest_fixed);
6239             longest_fixed_length = 0;
6240         }
6241         if (ri->regstclass
6242             && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
6243             ri->regstclass = NULL;
6244
6245         if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
6246             && stclass_flag
6247             && !(data.start_class->flags & ANYOF_EOS)
6248             && !cl_is_anything(data.start_class))
6249         {
6250             const U32 n = add_data(pRExC_state, 1, "f");
6251             data.start_class->flags |= ANYOF_IS_SYNTHETIC;
6252
6253             Newx(RExC_rxi->data->data[n], 1,
6254                 struct regnode_charclass_class);
6255             StructCopy(data.start_class,
6256                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
6257                        struct regnode_charclass_class);
6258             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
6259             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
6260             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
6261                       regprop(r, sv, (regnode*)data.start_class);
6262                       PerlIO_printf(Perl_debug_log,
6263                                     "synthetic stclass \"%s\".\n",
6264                                     SvPVX_const(sv));});
6265         }
6266
6267         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
6268         if (longest_fixed_length > longest_float_length) {
6269             r->check_end_shift = r->anchored_end_shift;
6270             r->check_substr = r->anchored_substr;
6271             r->check_utf8 = r->anchored_utf8;
6272             r->check_offset_min = r->check_offset_max = r->anchored_offset;
6273             if (r->extflags & RXf_ANCH_SINGLE)
6274                 r->extflags |= RXf_NOSCAN;
6275         }
6276         else {
6277             r->check_end_shift = r->float_end_shift;
6278             r->check_substr = r->float_substr;
6279             r->check_utf8 = r->float_utf8;
6280             r->check_offset_min = r->float_min_offset;
6281             r->check_offset_max = r->float_max_offset;
6282         }
6283         /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
6284            This should be changed ASAP!  */
6285         if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
6286             r->extflags |= RXf_USE_INTUIT;
6287             if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
6288                 r->extflags |= RXf_INTUIT_TAIL;
6289         }
6290         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
6291         if ( (STRLEN)minlen < longest_float_length )
6292             minlen= longest_float_length;
6293         if ( (STRLEN)minlen < longest_fixed_length )
6294             minlen= longest_fixed_length;     
6295         */
6296     }
6297     else {
6298         /* Several toplevels. Best we can is to set minlen. */
6299         I32 fake;
6300         struct regnode_charclass_class ch_class;
6301         I32 last_close = 0;
6302
6303         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
6304
6305         scan = ri->program + 1;
6306         cl_init(pRExC_state, &ch_class);
6307         data.start_class = &ch_class;
6308         data.last_closep = &last_close;
6309
6310         
6311         minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
6312             &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
6313         
6314         CHECK_RESTUDY_GOTO;
6315
6316         r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
6317                 = r->float_substr = r->float_utf8 = NULL;
6318
6319         if (!(data.start_class->flags & ANYOF_EOS)
6320             && !cl_is_anything(data.start_class))
6321         {
6322             const U32 n = add_data(pRExC_state, 1, "f");
6323             data.start_class->flags |= ANYOF_IS_SYNTHETIC;
6324
6325             Newx(RExC_rxi->data->data[n], 1,
6326                 struct regnode_charclass_class);
6327             StructCopy(data.start_class,
6328                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
6329                        struct regnode_charclass_class);
6330             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
6331             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
6332             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
6333                       regprop(r, sv, (regnode*)data.start_class);
6334                       PerlIO_printf(Perl_debug_log,
6335                                     "synthetic stclass \"%s\".\n",
6336                                     SvPVX_const(sv));});
6337         }
6338     }
6339
6340     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
6341        the "real" pattern. */
6342     DEBUG_OPTIMISE_r({
6343         PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
6344                       (IV)minlen, (IV)r->minlen);
6345     });
6346     r->minlenret = minlen;
6347     if (r->minlen < minlen) 
6348         r->minlen = minlen;
6349     
6350     if (RExC_seen & REG_SEEN_GPOS)
6351         r->extflags |= RXf_GPOS_SEEN;
6352     if (RExC_seen & REG_SEEN_LOOKBEHIND)
6353         r->extflags |= RXf_LOOKBEHIND_SEEN;
6354     if (pRExC_state->num_code_blocks)
6355         r->extflags |= RXf_EVAL_SEEN;
6356     if (RExC_seen & REG_SEEN_CANY)
6357         r->extflags |= RXf_CANY_SEEN;
6358     if (RExC_seen & REG_SEEN_VERBARG)
6359         r->intflags |= PREGf_VERBARG_SEEN;
6360     if (RExC_seen & REG_SEEN_CUTGROUP)
6361         r->intflags |= PREGf_CUTGROUP_SEEN;
6362     if (pm_flags & PMf_USE_RE_EVAL)
6363         r->intflags |= PREGf_USE_RE_EVAL;
6364     if (RExC_paren_names)
6365         RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
6366     else
6367         RXp_PAREN_NAMES(r) = NULL;
6368
6369 #ifdef STUPID_PATTERN_CHECKS            
6370     if (RX_PRELEN(rx) == 0)
6371         r->extflags |= RXf_NULL;
6372     if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
6373         /* XXX: this should happen BEFORE we compile */
6374         r->extflags |= (RXf_SKIPWHITE|RXf_WHITE); 
6375     else if (RX_PRELEN(rx) == 3 && memEQ("\\s+", RX_PRECOMP(rx), 3))
6376         r->extflags |= RXf_WHITE;
6377     else if (RX_PRELEN(rx) == 1 && RXp_PRECOMP(rx)[0] == '^')
6378         r->extflags |= RXf_START_ONLY;
6379 #else
6380     if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
6381             /* XXX: this should happen BEFORE we compile */
6382             r->extflags |= (RXf_SKIPWHITE|RXf_WHITE); 
6383     else {
6384         regnode *first = ri->program + 1;
6385         U8 fop = OP(first);
6386
6387         if (PL_regkind[fop] == NOTHING && OP(NEXTOPER(first)) == END)
6388             r->extflags |= RXf_NULL;
6389         else if (PL_regkind[fop] == BOL && OP(NEXTOPER(first)) == END)
6390             r->extflags |= RXf_START_ONLY;
6391         else if (fop == PLUS && OP(NEXTOPER(first)) == SPACE
6392                              && OP(regnext(first)) == END)
6393             r->extflags |= RXf_WHITE;    
6394     }
6395 #endif
6396 #ifdef DEBUGGING
6397     if (RExC_paren_names) {
6398         ri->name_list_idx = add_data( pRExC_state, 1, "a" );
6399         ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
6400     } else
6401 #endif
6402         ri->name_list_idx = 0;
6403
6404     if (RExC_recurse_count) {
6405         for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
6406             const regnode *scan = RExC_recurse[RExC_recurse_count-1];
6407             ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
6408         }
6409     }
6410     Newxz(r->offs, RExC_npar, regexp_paren_pair);
6411     /* assume we don't need to swap parens around before we match */
6412
6413     DEBUG_DUMP_r({
6414         PerlIO_printf(Perl_debug_log,"Final program:\n");
6415         regdump(r);
6416     });
6417 #ifdef RE_TRACK_PATTERN_OFFSETS
6418     DEBUG_OFFSETS_r(if (ri->u.offsets) {
6419         const U32 len = ri->u.offsets[0];
6420         U32 i;
6421         GET_RE_DEBUG_FLAGS_DECL;
6422         PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
6423         for (i = 1; i <= len; i++) {
6424             if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
6425                 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
6426                 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
6427             }
6428         PerlIO_printf(Perl_debug_log, "\n");
6429     });
6430 #endif
6431     return rx;
6432 }
6433
6434
6435 SV*
6436 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
6437                     const U32 flags)
6438 {
6439     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
6440
6441     PERL_UNUSED_ARG(value);
6442
6443     if (flags & RXapif_FETCH) {
6444         return reg_named_buff_fetch(rx, key, flags);
6445     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
6446         Perl_croak_no_modify(aTHX);
6447         return NULL;
6448     } else if (flags & RXapif_EXISTS) {
6449         return reg_named_buff_exists(rx, key, flags)
6450             ? &PL_sv_yes
6451             : &PL_sv_no;
6452     } else if (flags & RXapif_REGNAMES) {
6453         return reg_named_buff_all(rx, flags);
6454     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
6455         return reg_named_buff_scalar(rx, flags);
6456     } else {
6457         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
6458         return NULL;
6459     }
6460 }
6461
6462 SV*
6463 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
6464                          const U32 flags)
6465 {
6466     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
6467     PERL_UNUSED_ARG(lastkey);
6468
6469     if (flags & RXapif_FIRSTKEY)
6470         return reg_named_buff_firstkey(rx, flags);
6471     else if (flags & RXapif_NEXTKEY)
6472         return reg_named_buff_nextkey(rx, flags);
6473     else {
6474         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags);
6475         return NULL;
6476     }
6477 }
6478
6479 SV*
6480 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
6481                           const U32 flags)
6482 {
6483     AV *retarray = NULL;
6484     SV *ret;
6485     struct regexp *const rx = (struct regexp *)SvANY(r);
6486
6487     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
6488
6489     if (flags & RXapif_ALL)
6490         retarray=newAV();
6491
6492     if (rx && RXp_PAREN_NAMES(rx)) {
6493         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
6494         if (he_str) {
6495             IV i;
6496             SV* sv_dat=HeVAL(he_str);
6497             I32 *nums=(I32*)SvPVX(sv_dat);
6498             for ( i=0; i<SvIVX(sv_dat); i++ ) {
6499                 if ((I32)(rx->nparens) >= nums[i]
6500                     && rx->offs[nums[i]].start != -1
6501                     && rx->offs[nums[i]].end != -1)
6502                 {
6503                     ret = newSVpvs("");
6504                     CALLREG_NUMBUF_FETCH(r,nums[i],ret);
6505                     if (!retarray)
6506                         return ret;
6507                 } else {
6508                     if (retarray)
6509                         ret = newSVsv(&PL_sv_undef);
6510                 }
6511                 if (retarray)
6512                     av_push(retarray, ret);
6513             }
6514             if (retarray)
6515                 return newRV_noinc(MUTABLE_SV(retarray));
6516         }
6517     }
6518     return NULL;
6519 }
6520
6521 bool
6522 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
6523                            const U32 flags)
6524 {
6525     struct regexp *const rx = (struct regexp *)SvANY(r);
6526
6527     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
6528
6529     if (rx && RXp_PAREN_NAMES(rx)) {
6530         if (flags & RXapif_ALL) {
6531             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
6532         } else {
6533             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
6534             if (sv) {
6535                 SvREFCNT_dec(sv);
6536                 return TRUE;
6537             } else {
6538                 return FALSE;
6539             }
6540         }
6541     } else {
6542         return FALSE;
6543     }
6544 }
6545
6546 SV*
6547 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
6548 {
6549     struct regexp *const rx = (struct regexp *)SvANY(r);
6550
6551     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
6552
6553     if ( rx && RXp_PAREN_NAMES(rx) ) {
6554         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
6555
6556         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
6557     } else {
6558         return FALSE;
6559     }
6560 }
6561
6562 SV*
6563 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
6564 {
6565     struct regexp *const rx = (struct regexp *)SvANY(r);
6566     GET_RE_DEBUG_FLAGS_DECL;
6567
6568     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
6569
6570     if (rx && RXp_PAREN_NAMES(rx)) {
6571         HV *hv = RXp_PAREN_NAMES(rx);
6572         HE *temphe;
6573         while ( (temphe = hv_iternext_flags(hv,0)) ) {
6574             IV i;
6575             IV parno = 0;
6576             SV* sv_dat = HeVAL(temphe);
6577             I32 *nums = (I32*)SvPVX(sv_dat);
6578             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
6579                 if ((I32)(rx->lastparen) >= nums[i] &&
6580                     rx->offs[nums[i]].start != -1 &&
6581                     rx->offs[nums[i]].end != -1)
6582                 {
6583                     parno = nums[i];
6584                     break;
6585                 }
6586             }
6587             if (parno || flags & RXapif_ALL) {
6588                 return newSVhek(HeKEY_hek(temphe));
6589             }
6590         }
6591     }
6592     return NULL;
6593 }
6594
6595 SV*
6596 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
6597 {
6598     SV *ret;
6599     AV *av;
6600     I32 length;
6601     struct regexp *const rx = (struct regexp *)SvANY(r);
6602
6603     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
6604
6605     if (rx && RXp_PAREN_NAMES(rx)) {
6606         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
6607             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
6608         } else if (flags & RXapif_ONE) {
6609             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
6610             av = MUTABLE_AV(SvRV(ret));
6611             length = av_len(av);
6612             SvREFCNT_dec(ret);
6613             return newSViv(length + 1);
6614         } else {
6615             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags);
6616             return NULL;
6617         }
6618     }
6619     return &PL_sv_undef;
6620 }
6621
6622 SV*
6623 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
6624 {
6625     struct regexp *const rx = (struct regexp *)SvANY(r);
6626     AV *av = newAV();
6627
6628     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
6629
6630     if (rx && RXp_PAREN_NAMES(rx)) {
6631         HV *hv= RXp_PAREN_NAMES(rx);
6632         HE *temphe;
6633         (void)hv_iterinit(hv);
6634         while ( (temphe = hv_iternext_flags(hv,0)) ) {
6635             IV i;
6636             IV parno = 0;
6637             SV* sv_dat = HeVAL(temphe);
6638             I32 *nums = (I32*)SvPVX(sv_dat);
6639             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
6640                 if ((I32)(rx->lastparen) >= nums[i] &&
6641                     rx->offs[nums[i]].start != -1 &&
6642                     rx->offs[nums[i]].end != -1)
6643                 {
6644                     parno = nums[i];
6645                     break;
6646                 }
6647             }
6648             if (parno || flags & RXapif_ALL) {
6649                 av_push(av, newSVhek(HeKEY_hek(temphe)));
6650             }
6651         }
6652     }
6653
6654     return newRV_noinc(MUTABLE_SV(av));
6655 }
6656
6657 void
6658 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
6659                              SV * const sv)
6660 {
6661     struct regexp *const rx = (struct regexp *)SvANY(r);
6662     char *s = NULL;
6663     I32 i = 0;
6664     I32 s1, t1;
6665
6666     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
6667         
6668     if (!rx->subbeg) {
6669         sv_setsv(sv,&PL_sv_undef);
6670         return;
6671     } 
6672     else               
6673     if (paren == RX_BUFF_IDX_PREMATCH && rx->offs[0].start != -1) {
6674         /* $` */
6675         i = rx->offs[0].start;
6676         s = rx->subbeg;
6677     }
6678     else 
6679     if (paren == RX_BUFF_IDX_POSTMATCH && rx->offs[0].end != -1) {
6680         /* $' */
6681         s = rx->subbeg + rx->offs[0].end;
6682         i = rx->sublen - rx->offs[0].end;
6683     } 
6684     else
6685     if ( 0 <= paren && paren <= (I32)rx->nparens &&
6686         (s1 = rx->offs[paren].start) != -1 &&
6687         (t1 = rx->offs[paren].end) != -1)
6688     {
6689         /* $& $1 ... */
6690         i = t1 - s1;
6691         s = rx->subbeg + s1;
6692     } else {
6693         sv_setsv(sv,&PL_sv_undef);
6694         return;
6695     }          
6696     assert(rx->sublen >= (s - rx->subbeg) + i );
6697     if (i >= 0) {
6698         const int oldtainted = PL_tainted;
6699         TAINT_NOT;
6700         sv_setpvn(sv, s, i);
6701         PL_tainted = oldtainted;
6702         if ( (rx->extflags & RXf_CANY_SEEN)
6703             ? (RXp_MATCH_UTF8(rx)
6704                         && (!i || is_utf8_string((U8*)s, i)))
6705             : (RXp_MATCH_UTF8(rx)) )
6706         {
6707             SvUTF8_on(sv);
6708         }
6709         else
6710             SvUTF8_off(sv);
6711         if (PL_tainting) {
6712             if (RXp_MATCH_TAINTED(rx)) {
6713                 if (SvTYPE(sv) >= SVt_PVMG) {
6714                     MAGIC* const mg = SvMAGIC(sv);
6715                     MAGIC* mgt;
6716                     PL_tainted = 1;
6717                     SvMAGIC_set(sv, mg->mg_moremagic);
6718                     SvTAINT(sv);
6719                     if ((mgt = SvMAGIC(sv))) {
6720                         mg->mg_moremagic = mgt;
6721                         SvMAGIC_set(sv, mg);
6722                     }
6723                 } else {
6724                     PL_tainted = 1;
6725                     SvTAINT(sv);
6726                 }
6727             } else 
6728                 SvTAINTED_off(sv);
6729         }
6730     } else {
6731         sv_setsv(sv,&PL_sv_undef);
6732         return;
6733     }
6734 }
6735
6736 void
6737 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
6738                                                          SV const * const value)
6739 {
6740     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
6741
6742     PERL_UNUSED_ARG(rx);
6743     PERL_UNUSED_ARG(paren);
6744     PERL_UNUSED_ARG(value);
6745
6746     if (!PL_localizing)
6747         Perl_croak_no_modify(aTHX);
6748 }
6749
6750 I32
6751 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
6752                               const I32 paren)
6753 {
6754     struct regexp *const rx = (struct regexp *)SvANY(r);
6755     I32 i;
6756     I32 s1, t1;
6757
6758     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
6759
6760     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
6761         switch (paren) {
6762       /* $` / ${^PREMATCH} */
6763       case RX_BUFF_IDX_PREMATCH:
6764         if (rx->offs[0].start != -1) {
6765                         i = rx->offs[0].start;
6766                         if (i > 0) {
6767                                 s1 = 0;
6768                                 t1 = i;
6769                                 goto getlen;
6770                         }
6771             }
6772         return 0;
6773       /* $' / ${^POSTMATCH} */
6774       case RX_BUFF_IDX_POSTMATCH:
6775             if (rx->offs[0].end != -1) {
6776                         i = rx->sublen - rx->offs[0].end;
6777                         if (i > 0) {
6778                                 s1 = rx->offs[0].end;
6779                                 t1 = rx->sublen;
6780                                 goto getlen;
6781                         }
6782             }
6783         return 0;
6784       /* $& / ${^MATCH}, $1, $2, ... */
6785       default:
6786             if (paren <= (I32)rx->nparens &&
6787             (s1 = rx->offs[paren].start) != -1 &&
6788             (t1 = rx->offs[paren].end) != -1)
6789             {
6790             i = t1 - s1;
6791             goto getlen;
6792         } else {
6793             if (ckWARN(WARN_UNINITIALIZED))
6794                 report_uninit((const SV *)sv);
6795             return 0;
6796         }
6797     }
6798   getlen:
6799     if (i > 0 && RXp_MATCH_UTF8(rx)) {
6800         const char * const s = rx->subbeg + s1;
6801         const U8 *ep;
6802         STRLEN el;
6803
6804         i = t1 - s1;
6805         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
6806                         i = el;
6807     }
6808     return i;
6809 }
6810
6811 SV*
6812 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
6813 {
6814     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
6815         PERL_UNUSED_ARG(rx);
6816         if (0)
6817             return NULL;
6818         else
6819             return newSVpvs("Regexp");
6820 }
6821
6822 /* Scans the name of a named buffer from the pattern.
6823  * If flags is REG_RSN_RETURN_NULL returns null.
6824  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
6825  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
6826  * to the parsed name as looked up in the RExC_paren_names hash.
6827  * If there is an error throws a vFAIL().. type exception.
6828  */
6829
6830 #define REG_RSN_RETURN_NULL    0
6831 #define REG_RSN_RETURN_NAME    1
6832 #define REG_RSN_RETURN_DATA    2
6833
6834 STATIC SV*
6835 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
6836 {
6837     char *name_start = RExC_parse;
6838
6839     PERL_ARGS_ASSERT_REG_SCAN_NAME;
6840
6841     if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
6842          /* skip IDFIRST by using do...while */
6843         if (UTF)
6844             do {
6845                 RExC_parse += UTF8SKIP(RExC_parse);
6846             } while (isALNUM_utf8((U8*)RExC_parse));
6847         else
6848             do {
6849                 RExC_parse++;
6850             } while (isALNUM(*RExC_parse));
6851     }
6852
6853     if ( flags ) {
6854         SV* sv_name
6855             = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
6856                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
6857         if ( flags == REG_RSN_RETURN_NAME)
6858             return sv_name;
6859         else if (flags==REG_RSN_RETURN_DATA) {
6860             HE *he_str = NULL;
6861             SV *sv_dat = NULL;
6862             if ( ! sv_name )      /* should not happen*/
6863                 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
6864             if (RExC_paren_names)
6865                 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
6866             if ( he_str )
6867                 sv_dat = HeVAL(he_str);
6868             if ( ! sv_dat )
6869                 vFAIL("Reference to nonexistent named group");
6870             return sv_dat;
6871         }
6872         else {
6873             Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
6874                        (unsigned long) flags);
6875         }
6876         /* NOT REACHED */
6877     }
6878     return NULL;
6879 }
6880
6881 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
6882     int rem=(int)(RExC_end - RExC_parse);                       \
6883     int cut;                                                    \
6884     int num;                                                    \
6885     int iscut=0;                                                \
6886     if (rem>10) {                                               \
6887         rem=10;                                                 \
6888         iscut=1;                                                \
6889     }                                                           \
6890     cut=10-rem;                                                 \
6891     if (RExC_lastparse!=RExC_parse)                             \
6892         PerlIO_printf(Perl_debug_log," >%.*s%-*s",              \
6893             rem, RExC_parse,                                    \
6894             cut + 4,                                            \
6895             iscut ? "..." : "<"                                 \
6896         );                                                      \
6897     else                                                        \
6898         PerlIO_printf(Perl_debug_log,"%16s","");                \
6899                                                                 \
6900     if (SIZE_ONLY)                                              \
6901        num = RExC_size + 1;                                     \
6902     else                                                        \
6903        num=REG_NODE_NUM(RExC_emit);                             \
6904     if (RExC_lastnum!=num)                                      \
6905        PerlIO_printf(Perl_debug_log,"|%4d",num);                \
6906     else                                                        \
6907        PerlIO_printf(Perl_debug_log,"|%4s","");                 \
6908     PerlIO_printf(Perl_debug_log,"|%*s%-4s",                    \
6909         (int)((depth*2)), "",                                   \
6910         (funcname)                                              \
6911     );                                                          \
6912     RExC_lastnum=num;                                           \
6913     RExC_lastparse=RExC_parse;                                  \
6914 })
6915
6916
6917
6918 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
6919     DEBUG_PARSE_MSG((funcname));                            \
6920     PerlIO_printf(Perl_debug_log,"%4s","\n");               \
6921 })
6922 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({           \
6923     DEBUG_PARSE_MSG((funcname));                            \
6924     PerlIO_printf(Perl_debug_log,fmt "\n",args);               \
6925 })
6926
6927 /* This section of code defines the inversion list object and its methods.  The
6928  * interfaces are highly subject to change, so as much as possible is static to
6929  * this file.  An inversion list is here implemented as a malloc'd C UV array
6930  * with some added info that is placed as UVs at the beginning in a header
6931  * portion.  An inversion list for Unicode is an array of code points, sorted
6932  * by ordinal number.  The zeroth element is the first code point in the list.
6933  * The 1th element is the first element beyond that not in the list.  In other
6934  * words, the first range is
6935  *  invlist[0]..(invlist[1]-1)
6936  * The other ranges follow.  Thus every element whose index is divisible by two
6937  * marks the beginning of a range that is in the list, and every element not
6938  * divisible by two marks the beginning of a range not in the list.  A single
6939  * element inversion list that contains the single code point N generally
6940  * consists of two elements
6941  *  invlist[0] == N
6942  *  invlist[1] == N+1
6943  * (The exception is when N is the highest representable value on the
6944  * machine, in which case the list containing just it would be a single
6945  * element, itself.  By extension, if the last range in the list extends to
6946  * infinity, then the first element of that range will be in the inversion list
6947  * at a position that is divisible by two, and is the final element in the
6948  * list.)
6949  * Taking the complement (inverting) an inversion list is quite simple, if the
6950  * first element is 0, remove it; otherwise add a 0 element at the beginning.
6951  * This implementation reserves an element at the beginning of each inversion list
6952  * to contain 0 when the list contains 0, and contains 1 otherwise.  The actual
6953  * beginning of the list is either that element if 0, or the next one if 1.
6954  *
6955  * More about inversion lists can be found in "Unicode Demystified"
6956  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
6957  * More will be coming when functionality is added later.
6958  *
6959  * The inversion list data structure is currently implemented as an SV pointing
6960  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
6961  * array of UV whose memory management is automatically handled by the existing
6962  * facilities for SV's.
6963  *
6964  * Some of the methods should always be private to the implementation, and some
6965  * should eventually be made public */
6966
6967 #define INVLIST_LEN_OFFSET 0    /* Number of elements in the inversion list */
6968 #define INVLIST_ITER_OFFSET 1   /* Current iteration position */
6969
6970 /* This is a combination of a version and data structure type, so that one
6971  * being passed in can be validated to be an inversion list of the correct
6972  * vintage.  When the structure of the header is changed, a new random number
6973  * in the range 2**31-1 should be generated and the new() method changed to
6974  * insert that at this location.  Then, if an auxiliary program doesn't change
6975  * correspondingly, it will be discovered immediately */
6976 #define INVLIST_VERSION_ID_OFFSET 2
6977 #define INVLIST_VERSION_ID 1064334010
6978
6979 /* For safety, when adding new elements, remember to #undef them at the end of
6980  * the inversion list code section */
6981
6982 #define INVLIST_ZERO_OFFSET 3   /* 0 or 1; must be last element in header */
6983 /* The UV at position ZERO contains either 0 or 1.  If 0, the inversion list
6984  * contains the code point U+00000, and begins here.  If 1, the inversion list
6985  * doesn't contain U+0000, and it begins at the next UV in the array.
6986  * Inverting an inversion list consists of adding or removing the 0 at the
6987  * beginning of it.  By reserving a space for that 0, inversion can be made
6988  * very fast */
6989
6990 #define HEADER_LENGTH (INVLIST_ZERO_OFFSET + 1)
6991
6992 /* Internally things are UVs */
6993 #define TO_INTERNAL_SIZE(x) ((x + HEADER_LENGTH) * sizeof(UV))
6994 #define FROM_INTERNAL_SIZE(x) ((x / sizeof(UV)) - HEADER_LENGTH)
6995
6996 #define INVLIST_INITIAL_LEN 10
6997
6998 PERL_STATIC_INLINE UV*
6999 S__invlist_array_init(pTHX_ SV* const invlist, const bool will_have_0)
7000 {
7001     /* Returns a pointer to the first element in the inversion list's array.
7002      * This is called upon initialization of an inversion list.  Where the
7003      * array begins depends on whether the list has the code point U+0000
7004      * in it or not.  The other parameter tells it whether the code that
7005      * follows this call is about to put a 0 in the inversion list or not.
7006      * The first element is either the element with 0, if 0, or the next one,
7007      * if 1 */
7008
7009     UV* zero = get_invlist_zero_addr(invlist);
7010
7011     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
7012
7013     /* Must be empty */
7014     assert(! *get_invlist_len_addr(invlist));
7015
7016     /* 1^1 = 0; 1^0 = 1 */
7017     *zero = 1 ^ will_have_0;
7018     return zero + *zero;
7019 }
7020
7021 PERL_STATIC_INLINE UV*
7022 S_invlist_array(pTHX_ SV* const invlist)
7023 {
7024     /* Returns the pointer to the inversion list's array.  Every time the
7025      * length changes, this needs to be called in case malloc or realloc moved
7026      * it */
7027
7028     PERL_ARGS_ASSERT_INVLIST_ARRAY;
7029
7030     /* Must not be empty.  If these fail, you probably didn't check for <len>
7031      * being non-zero before trying to get the array */
7032     assert(*get_invlist_len_addr(invlist));
7033     assert(*get_invlist_zero_addr(invlist) == 0
7034            || *get_invlist_zero_addr(invlist) == 1);
7035
7036     /* The array begins either at the element reserved for zero if the
7037      * list contains 0 (that element will be set to 0), or otherwise the next
7038      * element (in which case the reserved element will be set to 1). */
7039     return (UV *) (get_invlist_zero_addr(invlist)
7040                    + *get_invlist_zero_addr(invlist));
7041 }
7042
7043 PERL_STATIC_INLINE UV*
7044 S_get_invlist_len_addr(pTHX_ SV* invlist)
7045 {
7046     /* Return the address of the UV that contains the current number
7047      * of used elements in the inversion list */
7048
7049     PERL_ARGS_ASSERT_GET_INVLIST_LEN_ADDR;
7050
7051     return (UV *) (SvPVX(invlist) + (INVLIST_LEN_OFFSET * sizeof (UV)));
7052 }
7053
7054 PERL_STATIC_INLINE UV
7055 S_invlist_len(pTHX_ SV* const invlist)
7056 {
7057     /* Returns the current number of elements stored in the inversion list's
7058      * array */
7059
7060     PERL_ARGS_ASSERT_INVLIST_LEN;
7061
7062     return *get_invlist_len_addr(invlist);
7063 }
7064
7065 PERL_STATIC_INLINE void
7066 S_invlist_set_len(pTHX_ SV* const invlist, const UV len)
7067 {
7068     /* Sets the current number of elements stored in the inversion list */
7069
7070     PERL_ARGS_ASSERT_INVLIST_SET_LEN;
7071
7072     *get_invlist_len_addr(invlist) = len;
7073
7074     assert(len <= SvLEN(invlist));
7075
7076     SvCUR_set(invlist, TO_INTERNAL_SIZE(len));
7077     /* If the list contains U+0000, that element is part of the header,
7078      * and should not be counted as part of the array.  It will contain
7079      * 0 in that case, and 1 otherwise.  So we could flop 0=>1, 1=>0 and
7080      * subtract:
7081      *  SvCUR_set(invlist,
7082      *            TO_INTERNAL_SIZE(len
7083      *                             - (*get_invlist_zero_addr(inv_list) ^ 1)));
7084      * But, this is only valid if len is not 0.  The consequences of not doing
7085      * this is that the memory allocation code may think that 1 more UV is
7086      * being used than actually is, and so might do an unnecessary grow.  That
7087      * seems worth not bothering to make this the precise amount.
7088      *
7089      * Note that when inverting, SvCUR shouldn't change */
7090 }
7091
7092 PERL_STATIC_INLINE UV
7093 S_invlist_max(pTHX_ SV* const invlist)
7094 {
7095     /* Returns the maximum number of elements storable in the inversion list's
7096      * array, without having to realloc() */
7097
7098     PERL_ARGS_ASSERT_INVLIST_MAX;
7099
7100     return FROM_INTERNAL_SIZE(SvLEN(invlist));
7101 }
7102
7103 PERL_STATIC_INLINE UV*
7104 S_get_invlist_zero_addr(pTHX_ SV* invlist)
7105 {
7106     /* Return the address of the UV that is reserved to hold 0 if the inversion
7107      * list contains 0.  This has to be the last element of the heading, as the
7108      * list proper starts with either it if 0, or the next element if not.
7109      * (But we force it to contain either 0 or 1) */
7110
7111     PERL_ARGS_ASSERT_GET_INVLIST_ZERO_ADDR;
7112
7113     return (UV *) (SvPVX(invlist) + (INVLIST_ZERO_OFFSET * sizeof (UV)));
7114 }
7115
7116 #ifndef PERL_IN_XSUB_RE
7117 SV*
7118 Perl__new_invlist(pTHX_ IV initial_size)
7119 {
7120
7121     /* Return a pointer to a newly constructed inversion list, with enough
7122      * space to store 'initial_size' elements.  If that number is negative, a
7123      * system default is used instead */
7124
7125     SV* new_list;
7126
7127     if (initial_size < 0) {
7128         initial_size = INVLIST_INITIAL_LEN;
7129     }
7130
7131     /* Allocate the initial space */
7132     new_list = newSV(TO_INTERNAL_SIZE(initial_size));
7133     invlist_set_len(new_list, 0);
7134
7135     /* Force iterinit() to be used to get iteration to work */
7136     *get_invlist_iter_addr(new_list) = UV_MAX;
7137
7138     /* This should force a segfault if a method doesn't initialize this
7139      * properly */
7140     *get_invlist_zero_addr(new_list) = UV_MAX;
7141
7142     *get_invlist_version_id_addr(new_list) = INVLIST_VERSION_ID;
7143 #if HEADER_LENGTH != 4
7144 #   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
7145 #endif
7146
7147     return new_list;
7148 }
7149 #endif
7150
7151 STATIC SV*
7152 S__new_invlist_C_array(pTHX_ UV* list)
7153 {
7154     /* Return a pointer to a newly constructed inversion list, initialized to
7155      * point to <list>, which has to be in the exact correct inversion list
7156      * form, including internal fields.  Thus this is a dangerous routine that
7157      * should not be used in the wrong hands */
7158
7159     SV* invlist = newSV_type(SVt_PV);
7160
7161     PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY;
7162
7163     SvPV_set(invlist, (char *) list);
7164     SvLEN_set(invlist, 0);  /* Means we own the contents, and the system
7165                                shouldn't touch it */
7166     SvCUR_set(invlist, TO_INTERNAL_SIZE(invlist_len(invlist)));
7167
7168     if (*get_invlist_version_id_addr(invlist) != INVLIST_VERSION_ID) {
7169         Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list");
7170     }
7171
7172     return invlist;
7173 }
7174
7175 STATIC void
7176 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
7177 {
7178     /* Grow the maximum size of an inversion list */
7179
7180     PERL_ARGS_ASSERT_INVLIST_EXTEND;
7181
7182     SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max));
7183 }
7184
7185 PERL_STATIC_INLINE void
7186 S_invlist_trim(pTHX_ SV* const invlist)
7187 {
7188     PERL_ARGS_ASSERT_INVLIST_TRIM;
7189
7190     /* Change the length of the inversion list to how many entries it currently
7191      * has */
7192
7193     SvPV_shrink_to_cur((SV *) invlist);
7194 }
7195
7196 /* An element is in an inversion list iff its index is even numbered: 0, 2, 4,
7197  * etc */
7198 #define ELEMENT_RANGE_MATCHES_INVLIST(i) (! ((i) & 1))
7199 #define PREV_RANGE_MATCHES_INVLIST(i) (! ELEMENT_RANGE_MATCHES_INVLIST(i))
7200
7201 #define _invlist_union_complement_2nd(a, b, output) _invlist_union_maybe_complement_2nd(a, b, TRUE, output)
7202
7203 STATIC void
7204 S__append_range_to_invlist(pTHX_ SV* const invlist, const UV start, const UV end)
7205 {
7206    /* Subject to change or removal.  Append the range from 'start' to 'end' at
7207     * the end of the inversion list.  The range must be above any existing
7208     * ones. */
7209
7210     UV* array;
7211     UV max = invlist_max(invlist);
7212     UV len = invlist_len(invlist);
7213
7214     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
7215
7216     if (len == 0) { /* Empty lists must be initialized */
7217         array = _invlist_array_init(invlist, start == 0);
7218     }
7219     else {
7220         /* Here, the existing list is non-empty. The current max entry in the
7221          * list is generally the first value not in the set, except when the
7222          * set extends to the end of permissible values, in which case it is
7223          * the first entry in that final set, and so this call is an attempt to
7224          * append out-of-order */
7225
7226         UV final_element = len - 1;
7227         array = invlist_array(invlist);
7228         if (array[final_element] > start
7229             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
7230         {
7231             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",
7232                        array[final_element], start,
7233                        ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
7234         }
7235
7236         /* Here, it is a legal append.  If the new range begins with the first
7237          * value not in the set, it is extending the set, so the new first
7238          * value not in the set is one greater than the newly extended range.
7239          * */
7240         if (array[final_element] == start) {
7241             if (end != UV_MAX) {
7242                 array[final_element] = end + 1;
7243             }
7244             else {
7245                 /* But if the end is the maximum representable on the machine,
7246                  * just let the range that this would extend to have no end */
7247                 invlist_set_len(invlist, len - 1);
7248             }
7249             return;
7250         }
7251     }
7252
7253     /* Here the new range doesn't extend any existing set.  Add it */
7254
7255     len += 2;   /* Includes an element each for the start and end of range */
7256
7257     /* If overflows the existing space, extend, which may cause the array to be
7258      * moved */
7259     if (max < len) {
7260         invlist_extend(invlist, len);
7261         invlist_set_len(invlist, len);  /* Have to set len here to avoid assert
7262                                            failure in invlist_array() */
7263         array = invlist_array(invlist);
7264     }
7265     else {
7266         invlist_set_len(invlist, len);
7267     }
7268
7269     /* The next item on the list starts the range, the one after that is
7270      * one past the new range.  */
7271     array[len - 2] = start;
7272     if (end != UV_MAX) {
7273         array[len - 1] = end + 1;
7274     }
7275     else {
7276         /* But if the end is the maximum representable on the machine, just let
7277          * the range have no end */
7278         invlist_set_len(invlist, len - 1);
7279     }
7280 }
7281
7282 #ifndef PERL_IN_XSUB_RE
7283
7284 STATIC IV
7285 S_invlist_search(pTHX_ SV* const invlist, const UV cp)
7286 {
7287     /* Searches the inversion list for the entry that contains the input code
7288      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
7289      * return value is the index into the list's array of the range that
7290      * contains <cp> */
7291
7292     IV low = 0;
7293     IV high = invlist_len(invlist);
7294     const UV * const array = invlist_array(invlist);
7295
7296     PERL_ARGS_ASSERT_INVLIST_SEARCH;
7297
7298     /* If list is empty or the code point is before the first element, return
7299      * failure. */
7300     if (high == 0 || cp < array[0]) {
7301         return -1;
7302     }
7303
7304     /* Binary search.  What we are looking for is <i> such that
7305      *  array[i] <= cp < array[i+1]
7306      * The loop below converges on the i+1. */
7307     while (low < high) {
7308         IV mid = (low + high) / 2;
7309         if (array[mid] <= cp) {
7310             low = mid + 1;
7311
7312             /* We could do this extra test to exit the loop early.
7313             if (cp < array[low]) {
7314                 return mid;
7315             }
7316             */
7317         }
7318         else { /* cp < array[mid] */
7319             high = mid;
7320         }
7321     }
7322
7323     return high - 1;
7324 }
7325
7326 void
7327 Perl__invlist_populate_swatch(pTHX_ SV* const invlist, const UV start, const UV end, U8* swatch)
7328 {
7329     /* populates a swatch of a swash the same way swatch_get() does in utf8.c,
7330      * but is used when the swash has an inversion list.  This makes this much
7331      * faster, as it uses a binary search instead of a linear one.  This is
7332      * intimately tied to that function, and perhaps should be in utf8.c,
7333      * except it is intimately tied to inversion lists as well.  It assumes
7334      * that <swatch> is all 0's on input */
7335
7336     UV current = start;
7337     const IV len = invlist_len(invlist);
7338     IV i;
7339     const UV * array;
7340
7341     PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
7342
7343     if (len == 0) { /* Empty inversion list */
7344         return;
7345     }
7346
7347     array = invlist_array(invlist);
7348
7349     /* Find which element it is */
7350     i = invlist_search(invlist, start);
7351
7352     /* We populate from <start> to <end> */
7353     while (current < end) {
7354         UV upper;
7355
7356         /* The inversion list gives the results for every possible code point
7357          * after the first one in the list.  Only those ranges whose index is
7358          * even are ones that the inversion list matches.  For the odd ones,
7359          * and if the initial code point is not in the list, we have to skip
7360          * forward to the next element */
7361         if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
7362             i++;
7363             if (i >= len) { /* Finished if beyond the end of the array */
7364                 return;
7365             }
7366             current = array[i];
7367             if (current >= end) {   /* Finished if beyond the end of what we
7368                                        are populating */
7369                 return;
7370             }
7371         }
7372         assert(current >= start);
7373
7374         /* The current range ends one below the next one, except don't go past
7375          * <end> */
7376         i++;
7377         upper = (i < len && array[i] < end) ? array[i] : end;
7378
7379         /* Here we are in a range that matches.  Populate a bit in the 3-bit U8
7380          * for each code point in it */
7381         for (; current < upper; current++) {
7382             const STRLEN offset = (STRLEN)(current - start);
7383             swatch[offset >> 3] |= 1 << (offset & 7);
7384         }
7385
7386         /* Quit if at the end of the list */
7387         if (i >= len) {
7388
7389             /* But first, have to deal with the highest possible code point on
7390              * the platform.  The previous code assumes that <end> is one
7391              * beyond where we want to populate, but that is impossible at the
7392              * platform's infinity, so have to handle it specially */
7393             if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
7394             {
7395                 const STRLEN offset = (STRLEN)(end - start);
7396                 swatch[offset >> 3] |= 1 << (offset & 7);
7397             }
7398             return;
7399         }
7400
7401         /* Advance to the next range, which will be for code points not in the
7402          * inversion list */
7403         current = array[i];
7404     }
7405
7406     return;
7407 }
7408
7409
7410 void
7411 Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, bool complement_b, SV** output)
7412 {
7413     /* Take the union of two inversion lists and point <output> to it.  *output
7414      * should be defined upon input, and if it points to one of the two lists,
7415      * the reference count to that list will be decremented.  The first list,
7416      * <a>, may be NULL, in which case a copy of the second list is returned.
7417      * If <complement_b> is TRUE, the union is taken of the complement
7418      * (inversion) of <b> instead of b itself.
7419      *
7420      * The basis for this comes from "Unicode Demystified" Chapter 13 by
7421      * Richard Gillam, published by Addison-Wesley, and explained at some
7422      * length there.  The preface says to incorporate its examples into your
7423      * code at your own risk.
7424      *
7425      * The algorithm is like a merge sort.
7426      *
7427      * XXX A potential performance improvement is to keep track as we go along
7428      * if only one of the inputs contributes to the result, meaning the other
7429      * is a subset of that one.  In that case, we can skip the final copy and
7430      * return the larger of the input lists, but then outside code might need
7431      * to keep track of whether to free the input list or not */
7432
7433     UV* array_a;    /* a's array */
7434     UV* array_b;
7435     UV len_a;       /* length of a's array */
7436     UV len_b;
7437
7438     SV* u;                      /* the resulting union */
7439     UV* array_u;
7440     UV len_u;
7441
7442     UV i_a = 0;             /* current index into a's array */
7443     UV i_b = 0;
7444     UV i_u = 0;
7445
7446     /* running count, as explained in the algorithm source book; items are
7447      * stopped accumulating and are output when the count changes to/from 0.
7448      * The count is incremented when we start a range that's in the set, and
7449      * decremented when we start a range that's not in the set.  So its range
7450      * is 0 to 2.  Only when the count is zero is something not in the set.
7451      */
7452     UV count = 0;
7453
7454     PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND;
7455     assert(a != b);
7456
7457     /* If either one is empty, the union is the other one */
7458     if (a == NULL || ((len_a = invlist_len(a)) == 0)) {
7459         if (*output == a) {
7460             if (a != NULL) {
7461                 SvREFCNT_dec(a);
7462             }
7463         }
7464         if (*output != b) {
7465             *output = invlist_clone(b);
7466             if (complement_b) {
7467                 _invlist_invert(*output);
7468             }
7469         } /* else *output already = b; */
7470         return;
7471     }
7472     else if ((len_b = invlist_len(b)) == 0) {
7473         if (*output == b) {
7474             SvREFCNT_dec(b);
7475         }
7476
7477         /* The complement of an empty list is a list that has everything in it,
7478          * so the union with <a> includes everything too */
7479         if (complement_b) {
7480             if (a == *output) {
7481                 SvREFCNT_dec(a);
7482             }
7483             *output = _new_invlist(1);
7484             _append_range_to_invlist(*output, 0, UV_MAX);
7485         }
7486         else if (*output != a) {
7487             *output = invlist_clone(a);
7488         }
7489         /* else *output already = a; */
7490         return;
7491     }
7492
7493     /* Here both lists exist and are non-empty */
7494     array_a = invlist_array(a);
7495     array_b = invlist_array(b);
7496
7497     /* If are to take the union of 'a' with the complement of b, set it
7498      * up so are looking at b's complement. */
7499     if (complement_b) {
7500
7501         /* To complement, we invert: if the first element is 0, remove it.  To
7502          * do this, we just pretend the array starts one later, and clear the
7503          * flag as we don't have to do anything else later */
7504         if (array_b[0] == 0) {
7505             array_b++;
7506             len_b--;
7507             complement_b = FALSE;
7508         }
7509         else {
7510
7511             /* But if the first element is not zero, we unshift a 0 before the
7512              * array.  The data structure reserves a space for that 0 (which
7513              * should be a '1' right now), so physical shifting is unneeded,
7514              * but temporarily change that element to 0.  Before exiting the
7515              * routine, we must restore the element to '1' */
7516             array_b--;
7517             len_b++;
7518             array_b[0] = 0;
7519         }
7520     }
7521
7522     /* Size the union for the worst case: that the sets are completely
7523      * disjoint */
7524     u = _new_invlist(len_a + len_b);
7525
7526     /* Will contain U+0000 if either component does */
7527     array_u = _invlist_array_init(u, (len_a > 0 && array_a[0] == 0)
7528                                       || (len_b > 0 && array_b[0] == 0));
7529
7530     /* Go through each list item by item, stopping when exhausted one of
7531      * them */
7532     while (i_a < len_a && i_b < len_b) {
7533         UV cp;      /* The element to potentially add to the union's array */
7534         bool cp_in_set;   /* is it in the the input list's set or not */
7535
7536         /* We need to take one or the other of the two inputs for the union.
7537          * Since we are merging two sorted lists, we take the smaller of the
7538          * next items.  In case of a tie, we take the one that is in its set
7539          * first.  If we took one not in the set first, it would decrement the
7540          * count, possibly to 0 which would cause it to be output as ending the
7541          * range, and the next time through we would take the same number, and
7542          * output it again as beginning the next range.  By doing it the
7543          * opposite way, there is no possibility that the count will be
7544          * momentarily decremented to 0, and thus the two adjoining ranges will
7545          * be seamlessly merged.  (In a tie and both are in the set or both not
7546          * in the set, it doesn't matter which we take first.) */
7547         if (array_a[i_a] < array_b[i_b]
7548             || (array_a[i_a] == array_b[i_b]
7549                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
7550         {
7551             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
7552             cp= array_a[i_a++];
7553         }
7554         else {
7555             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
7556             cp= array_b[i_b++];
7557         }
7558
7559         /* Here, have chosen which of the two inputs to look at.  Only output
7560          * if the running count changes to/from 0, which marks the
7561          * beginning/end of a range in that's in the set */
7562         if (cp_in_set) {
7563             if (count == 0) {
7564                 array_u[i_u++] = cp;
7565             }
7566             count++;
7567         }
7568         else {
7569             count--;
7570             if (count == 0) {
7571                 array_u[i_u++] = cp;
7572             }
7573         }
7574     }
7575
7576     /* Here, we are finished going through at least one of the lists, which
7577      * means there is something remaining in at most one.  We check if the list
7578      * that hasn't been exhausted is positioned such that we are in the middle
7579      * of a range in its set or not.  (i_a and i_b point to the element beyond
7580      * the one we care about.) If in the set, we decrement 'count'; if 0, there
7581      * is potentially more to output.
7582      * There are four cases:
7583      *  1) Both weren't in their sets, count is 0, and remains 0.  What's left
7584      *     in the union is entirely from the non-exhausted set.
7585      *  2) Both were in their sets, count is 2.  Nothing further should
7586      *     be output, as everything that remains will be in the exhausted
7587      *     list's set, hence in the union; decrementing to 1 but not 0 insures
7588      *     that
7589      *  3) the exhausted was in its set, non-exhausted isn't, count is 1.
7590      *     Nothing further should be output because the union includes
7591      *     everything from the exhausted set.  Not decrementing ensures that.
7592      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1;
7593      *     decrementing to 0 insures that we look at the remainder of the
7594      *     non-exhausted set */
7595     if ((i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
7596         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
7597     {
7598         count--;
7599     }
7600
7601     /* The final length is what we've output so far, plus what else is about to
7602      * be output.  (If 'count' is non-zero, then the input list we exhausted
7603      * has everything remaining up to the machine's limit in its set, and hence
7604      * in the union, so there will be no further output. */
7605     len_u = i_u;
7606     if (count == 0) {
7607         /* At most one of the subexpressions will be non-zero */
7608         len_u += (len_a - i_a) + (len_b - i_b);
7609     }
7610
7611     /* Set result to final length, which can change the pointer to array_u, so
7612      * re-find it */
7613     if (len_u != invlist_len(u)) {
7614         invlist_set_len(u, len_u);
7615         invlist_trim(u);
7616         array_u = invlist_array(u);
7617     }
7618
7619     /* When 'count' is 0, the list that was exhausted (if one was shorter than
7620      * the other) ended with everything above it not in its set.  That means
7621      * that the remaining part of the union is precisely the same as the
7622      * non-exhausted list, so can just copy it unchanged.  (If both list were
7623      * exhausted at the same time, then the operations below will be both 0.)
7624      */
7625     if (count == 0) {
7626         IV copy_count; /* At most one will have a non-zero copy count */
7627         if ((copy_count = len_a - i_a) > 0) {
7628             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
7629         }
7630         else if ((copy_count = len_b - i_b) > 0) {
7631             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
7632         }
7633     }
7634
7635     /*  We may be removing a reference to one of the inputs */
7636     if (a == *output || b == *output) {
7637         SvREFCNT_dec(*output);
7638     }
7639
7640     /* If we've changed b, restore it */
7641     if (complement_b) {
7642         array_b[0] = 1;
7643     }
7644
7645     *output = u;
7646     return;
7647 }
7648
7649 void
7650 Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, bool complement_b, SV** i)
7651 {
7652     /* Take the intersection of two inversion lists and point <i> to it.  *i
7653      * should be defined upon input, and if it points to one of the two lists,
7654      * the reference count to that list will be decremented.
7655      * If <complement_b> is TRUE, the result will be the intersection of <a>
7656      * and the complement (or inversion) of <b> instead of <b> directly.
7657      *
7658      * The basis for this comes from "Unicode Demystified" Chapter 13 by
7659      * Richard Gillam, published by Addison-Wesley, and explained at some
7660      * length there.  The preface says to incorporate its examples into your
7661      * code at your own risk.  In fact, it had bugs
7662      *
7663      * The algorithm is like a merge sort, and is essentially the same as the
7664      * union above
7665      */
7666
7667     UV* array_a;                /* a's array */
7668     UV* array_b;
7669     UV len_a;   /* length of a's array */
7670     UV len_b;
7671
7672     SV* r;                   /* the resulting intersection */
7673     UV* array_r;
7674     UV len_r;
7675
7676     UV i_a = 0;             /* current index into a's array */
7677     UV i_b = 0;
7678     UV i_r = 0;
7679
7680     /* running count, as explained in the algorithm source book; items are
7681      * stopped accumulating and are output when the count changes to/from 2.
7682      * The count is incremented when we start a range that's in the set, and
7683      * decremented when we start a range that's not in the set.  So its range
7684      * is 0 to 2.  Only when the count is 2 is something in the intersection.
7685      */
7686     UV count = 0;
7687
7688     PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND;
7689     assert(a != b);
7690
7691     /* Special case if either one is empty */
7692     len_a = invlist_len(a);
7693     if ((len_a == 0) || ((len_b = invlist_len(b)) == 0)) {
7694
7695         if (len_a != 0 && complement_b) {
7696
7697             /* Here, 'a' is not empty, therefore from the above 'if', 'b' must
7698              * be empty.  Here, also we are using 'b's complement, which hence
7699              * must be every possible code point.  Thus the intersection is
7700              * simply 'a'. */
7701             if (*i != a) {
7702                 *i = invlist_clone(a);
7703
7704                 if (*i == b) {
7705                     SvREFCNT_dec(b);
7706                 }
7707             }
7708             /* else *i is already 'a' */
7709             return;
7710         }
7711
7712         /* Here, 'a' or 'b' is empty and not using the complement of 'b'.  The
7713          * intersection must be empty */
7714         if (*i == a) {
7715             SvREFCNT_dec(a);
7716         }
7717         else if (*i == b) {
7718             SvREFCNT_dec(b);
7719         }
7720         *i = _new_invlist(0);
7721         return;
7722     }
7723
7724     /* Here both lists exist and are non-empty */
7725     array_a = invlist_array(a);
7726     array_b = invlist_array(b);
7727
7728     /* If are to take the intersection of 'a' with the complement of b, set it
7729      * up so are looking at b's complement. */
7730     if (complement_b) {
7731
7732         /* To complement, we invert: if the first element is 0, remove it.  To
7733          * do this, we just pretend the array starts one later, and clear the
7734          * flag as we don't have to do anything else later */
7735         if (array_b[0] == 0) {
7736             array_b++;
7737             len_b--;
7738             complement_b = FALSE;
7739         }
7740         else {
7741
7742             /* But if the first element is not zero, we unshift a 0 before the
7743              * array.  The data structure reserves a space for that 0 (which
7744              * should be a '1' right now), so physical shifting is unneeded,
7745              * but temporarily change that element to 0.  Before exiting the
7746              * routine, we must restore the element to '1' */
7747             array_b--;
7748             len_b++;
7749             array_b[0] = 0;
7750         }
7751     }
7752
7753     /* Size the intersection for the worst case: that the intersection ends up
7754      * fragmenting everything to be completely disjoint */
7755     r= _new_invlist(len_a + len_b);
7756
7757     /* Will contain U+0000 iff both components do */
7758     array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
7759                                      && len_b > 0 && array_b[0] == 0);
7760
7761     /* Go through each list item by item, stopping when exhausted one of
7762      * them */
7763     while (i_a < len_a && i_b < len_b) {
7764         UV cp;      /* The element to potentially add to the intersection's
7765                        array */
7766         bool cp_in_set; /* Is it in the input list's set or not */
7767
7768         /* We need to take one or the other of the two inputs for the
7769          * intersection.  Since we are merging two sorted lists, we take the
7770          * smaller of the next items.  In case of a tie, we take the one that
7771          * is not in its set first (a difference from the union algorithm).  If
7772          * we took one in the set first, it would increment the count, possibly
7773          * to 2 which would cause it to be output as starting a range in the
7774          * intersection, and the next time through we would take that same
7775          * number, and output it again as ending the set.  By doing it the
7776          * opposite of this, there is no possibility that the count will be
7777          * momentarily incremented to 2.  (In a tie and both are in the set or
7778          * both not in the set, it doesn't matter which we take first.) */
7779         if (array_a[i_a] < array_b[i_b]
7780             || (array_a[i_a] == array_b[i_b]
7781                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
7782         {
7783             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
7784             cp= array_a[i_a++];
7785         }
7786         else {
7787             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
7788             cp= array_b[i_b++];
7789         }
7790
7791         /* Here, have chosen which of the two inputs to look at.  Only output
7792          * if the running count changes to/from 2, which marks the
7793          * beginning/end of a range that's in the intersection */
7794         if (cp_in_set) {
7795             count++;
7796             if (count == 2) {
7797                 array_r[i_r++] = cp;
7798             }
7799         }
7800         else {
7801             if (count == 2) {
7802                 array_r[i_r++] = cp;
7803             }
7804             count--;
7805         }
7806     }
7807
7808     /* Here, we are finished going through at least one of the lists, which
7809      * means there is something remaining in at most one.  We check if the list
7810      * that has been exhausted is positioned such that we are in the middle
7811      * of a range in its set or not.  (i_a and i_b point to elements 1 beyond
7812      * the ones we care about.)  There are four cases:
7813      *  1) Both weren't in their sets, count is 0, and remains 0.  There's
7814      *     nothing left in the intersection.
7815      *  2) Both were in their sets, count is 2 and perhaps is incremented to
7816      *     above 2.  What should be output is exactly that which is in the
7817      *     non-exhausted set, as everything it has is also in the intersection
7818      *     set, and everything it doesn't have can't be in the intersection
7819      *  3) The exhausted was in its set, non-exhausted isn't, count is 1, and
7820      *     gets incremented to 2.  Like the previous case, the intersection is
7821      *     everything that remains in the non-exhausted set.
7822      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1, and
7823      *     remains 1.  And the intersection has nothing more. */
7824     if ((i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
7825         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
7826     {
7827         count++;
7828     }
7829
7830     /* The final length is what we've output so far plus what else is in the
7831      * intersection.  At most one of the subexpressions below will be non-zero */
7832     len_r = i_r;
7833     if (count >= 2) {
7834         len_r += (len_a - i_a) + (len_b - i_b);
7835     }
7836
7837     /* Set result to final length, which can change the pointer to array_r, so
7838      * re-find it */
7839     if (len_r != invlist_len(r)) {
7840         invlist_set_len(r, len_r);
7841         invlist_trim(r);
7842         array_r = invlist_array(r);
7843     }
7844
7845     /* Finish outputting any remaining */
7846     if (count >= 2) { /* At most one will have a non-zero copy count */
7847         IV copy_count;
7848         if ((copy_count = len_a - i_a) > 0) {
7849             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
7850         }
7851         else if ((copy_count = len_b - i_b) > 0) {
7852             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
7853         }
7854     }
7855
7856     /*  We may be removing a reference to one of the inputs */
7857     if (a == *i || b == *i) {
7858         SvREFCNT_dec(*i);
7859     }
7860
7861     /* If we've changed b, restore it */
7862     if (complement_b) {
7863         array_b[0] = 1;
7864     }
7865
7866     *i = r;
7867     return;
7868 }
7869
7870 SV*
7871 Perl__add_range_to_invlist(pTHX_ SV* invlist, const UV start, const UV end)
7872 {
7873     /* Add the range from 'start' to 'end' inclusive to the inversion list's
7874      * set.  A pointer to the inversion list is returned.  This may actually be
7875      * a new list, in which case the passed in one has been destroyed.  The
7876      * passed in inversion list can be NULL, in which case a new one is created
7877      * with just the one range in it */
7878
7879     SV* range_invlist;
7880     UV len;
7881
7882     if (invlist == NULL) {
7883         invlist = _new_invlist(2);
7884         len = 0;
7885     }
7886     else {
7887         len = invlist_len(invlist);
7888     }
7889
7890     /* If comes after the final entry, can just append it to the end */
7891     if (len == 0
7892         || start >= invlist_array(invlist)
7893                                     [invlist_len(invlist) - 1])
7894     {
7895         _append_range_to_invlist(invlist, start, end);
7896         return invlist;
7897     }
7898
7899     /* Here, can't just append things, create and return a new inversion list
7900      * which is the union of this range and the existing inversion list */
7901     range_invlist = _new_invlist(2);
7902     _append_range_to_invlist(range_invlist, start, end);
7903
7904     _invlist_union(invlist, range_invlist, &invlist);
7905
7906     /* The temporary can be freed */
7907     SvREFCNT_dec(range_invlist);
7908
7909     return invlist;
7910 }
7911
7912 #endif
7913
7914 PERL_STATIC_INLINE SV*
7915 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
7916     return _add_range_to_invlist(invlist, cp, cp);
7917 }
7918
7919 #ifndef PERL_IN_XSUB_RE
7920 void
7921 Perl__invlist_invert(pTHX_ SV* const invlist)
7922 {
7923     /* Complement the input inversion list.  This adds a 0 if the list didn't
7924      * have a zero; removes it otherwise.  As described above, the data
7925      * structure is set up so that this is very efficient */
7926
7927     UV* len_pos = get_invlist_len_addr(invlist);
7928
7929     PERL_ARGS_ASSERT__INVLIST_INVERT;
7930
7931     /* The inverse of matching nothing is matching everything */
7932     if (*len_pos == 0) {
7933         _append_range_to_invlist(invlist, 0, UV_MAX);
7934         return;
7935     }
7936
7937     /* The exclusive or complents 0 to 1; and 1 to 0.  If the result is 1, the
7938      * zero element was a 0, so it is being removed, so the length decrements
7939      * by 1; and vice-versa.  SvCUR is unaffected */
7940     if (*get_invlist_zero_addr(invlist) ^= 1) {
7941         (*len_pos)--;
7942     }
7943     else {
7944         (*len_pos)++;
7945     }
7946 }
7947
7948 void
7949 Perl__invlist_invert_prop(pTHX_ SV* const invlist)
7950 {
7951     /* Complement the input inversion list (which must be a Unicode property,
7952      * all of which don't match above the Unicode maximum code point.)  And
7953      * Perl has chosen to not have the inversion match above that either.  This
7954      * adds a 0x110000 if the list didn't end with it, and removes it if it did
7955      */
7956
7957     UV len;
7958     UV* array;
7959
7960     PERL_ARGS_ASSERT__INVLIST_INVERT_PROP;
7961
7962     _invlist_invert(invlist);
7963
7964     len = invlist_len(invlist);
7965
7966     if (len != 0) { /* If empty do nothing */
7967         array = invlist_array(invlist);
7968         if (array[len - 1] != PERL_UNICODE_MAX + 1) {
7969             /* Add 0x110000.  First, grow if necessary */
7970             len++;
7971             if (invlist_max(invlist) < len) {
7972                 invlist_extend(invlist, len);
7973                 array = invlist_array(invlist);
7974             }
7975             invlist_set_len(invlist, len);
7976             array[len - 1] = PERL_UNICODE_MAX + 1;
7977         }
7978         else {  /* Remove the 0x110000 */
7979             invlist_set_len(invlist, len - 1);
7980         }
7981     }
7982
7983     return;
7984 }
7985 #endif
7986
7987 PERL_STATIC_INLINE SV*
7988 S_invlist_clone(pTHX_ SV* const invlist)
7989 {
7990
7991     /* Return a new inversion list that is a copy of the input one, which is
7992      * unchanged */
7993
7994     /* Need to allocate extra space to accommodate Perl's addition of a
7995      * trailing NUL to SvPV's, since it thinks they are always strings */
7996     SV* new_invlist = _new_invlist(invlist_len(invlist) + 1);
7997     STRLEN length = SvCUR(invlist);
7998
7999     PERL_ARGS_ASSERT_INVLIST_CLONE;
8000
8001     SvCUR_set(new_invlist, length); /* This isn't done automatically */
8002     Copy(SvPVX(invlist), SvPVX(new_invlist), length, char);
8003
8004     return new_invlist;
8005 }
8006
8007 PERL_STATIC_INLINE UV*
8008 S_get_invlist_iter_addr(pTHX_ SV* invlist)
8009 {
8010     /* Return the address of the UV that contains the current iteration
8011      * position */
8012
8013     PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
8014
8015     return (UV *) (SvPVX(invlist) + (INVLIST_ITER_OFFSET * sizeof (UV)));
8016 }
8017
8018 PERL_STATIC_INLINE UV*
8019 S_get_invlist_version_id_addr(pTHX_ SV* invlist)
8020 {
8021     /* Return the address of the UV that contains the version id. */
8022
8023     PERL_ARGS_ASSERT_GET_INVLIST_VERSION_ID_ADDR;
8024
8025     return (UV *) (SvPVX(invlist) + (INVLIST_VERSION_ID_OFFSET * sizeof (UV)));
8026 }
8027
8028 PERL_STATIC_INLINE void
8029 S_invlist_iterinit(pTHX_ SV* invlist)   /* Initialize iterator for invlist */
8030 {
8031     PERL_ARGS_ASSERT_INVLIST_ITERINIT;
8032
8033     *get_invlist_iter_addr(invlist) = 0;
8034 }
8035
8036 STATIC bool
8037 S_invlist_iternext(pTHX_ SV* invlist, UV* start, UV* end)
8038 {
8039     /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
8040      * This call sets in <*start> and <*end>, the next range in <invlist>.
8041      * Returns <TRUE> if successful and the next call will return the next
8042      * range; <FALSE> if was already at the end of the list.  If the latter,
8043      * <*start> and <*end> are unchanged, and the next call to this function
8044      * will start over at the beginning of the list */
8045
8046     UV* pos = get_invlist_iter_addr(invlist);
8047     UV len = invlist_len(invlist);
8048     UV *array;
8049
8050     PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
8051
8052     if (*pos >= len) {
8053         *pos = UV_MAX;  /* Force iternit() to be required next time */
8054         return FALSE;
8055     }
8056
8057     array = invlist_array(invlist);
8058
8059     *start = array[(*pos)++];
8060
8061     if (*pos >= len) {
8062         *end = UV_MAX;
8063     }
8064     else {
8065         *end = array[(*pos)++] - 1;
8066     }
8067
8068     return TRUE;
8069 }
8070
8071 #ifndef PERL_IN_XSUB_RE
8072 SV *
8073 Perl__invlist_contents(pTHX_ SV* const invlist)
8074 {
8075     /* Get the contents of an inversion list into a string SV so that they can
8076      * be printed out.  It uses the format traditionally done for debug tracing
8077      */
8078
8079     UV start, end;
8080     SV* output = newSVpvs("\n");
8081
8082     PERL_ARGS_ASSERT__INVLIST_CONTENTS;
8083
8084     invlist_iterinit(invlist);
8085     while (invlist_iternext(invlist, &start, &end)) {
8086         if (end == UV_MAX) {
8087             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\tINFINITY\n", start);
8088         }
8089         else if (end != start) {
8090             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\t%04"UVXf"\n",
8091                     start,       end);
8092         }
8093         else {
8094             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\n", start);
8095         }
8096     }
8097
8098     return output;
8099 }
8100 #endif
8101
8102 #if 0
8103 void
8104 S_invlist_dump(pTHX_ SV* const invlist, const char * const header)
8105 {
8106     /* Dumps out the ranges in an inversion list.  The string 'header'
8107      * if present is output on a line before the first range */
8108
8109     UV start, end;
8110
8111     if (header && strlen(header)) {
8112         PerlIO_printf(Perl_debug_log, "%s\n", header);
8113     }
8114     invlist_iterinit(invlist);
8115     while (invlist_iternext(invlist, &start, &end)) {
8116         if (end == UV_MAX) {
8117             PerlIO_printf(Perl_debug_log, "0x%04"UVXf" .. INFINITY\n", start);
8118         }
8119         else {
8120             PerlIO_printf(Perl_debug_log, "0x%04"UVXf" .. 0x%04"UVXf"\n", start, end);
8121         }
8122     }
8123 }
8124 #endif
8125
8126 #undef HEADER_LENGTH
8127 #undef INVLIST_INITIAL_LENGTH
8128 #undef TO_INTERNAL_SIZE
8129 #undef FROM_INTERNAL_SIZE
8130 #undef INVLIST_LEN_OFFSET
8131 #undef INVLIST_ZERO_OFFSET
8132 #undef INVLIST_ITER_OFFSET
8133 #undef INVLIST_VERSION_ID
8134
8135 /* End of inversion list object */
8136
8137 /*
8138  - reg - regular expression, i.e. main body or parenthesized thing
8139  *
8140  * Caller must absorb opening parenthesis.
8141  *
8142  * Combining parenthesis handling with the base level of regular expression
8143  * is a trifle forced, but the need to tie the tails of the branches to what
8144  * follows makes it hard to avoid.
8145  */
8146 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
8147 #ifdef DEBUGGING
8148 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
8149 #else
8150 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
8151 #endif
8152
8153 STATIC regnode *
8154 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
8155     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
8156 {
8157     dVAR;
8158     register regnode *ret;              /* Will be the head of the group. */
8159     register regnode *br;
8160     register regnode *lastbr;
8161     register regnode *ender = NULL;
8162     register I32 parno = 0;
8163     I32 flags;
8164     U32 oregflags = RExC_flags;
8165     bool have_branch = 0;
8166     bool is_open = 0;
8167     I32 freeze_paren = 0;
8168     I32 after_freeze = 0;
8169
8170     /* for (?g), (?gc), and (?o) warnings; warning
8171        about (?c) will warn about (?g) -- japhy    */
8172
8173 #define WASTED_O  0x01
8174 #define WASTED_G  0x02
8175 #define WASTED_C  0x04
8176 #define WASTED_GC (0x02|0x04)
8177     I32 wastedflags = 0x00;
8178
8179     char * parse_start = RExC_parse; /* MJD */
8180     char * const oregcomp_parse = RExC_parse;
8181
8182     GET_RE_DEBUG_FLAGS_DECL;
8183
8184     PERL_ARGS_ASSERT_REG;
8185     DEBUG_PARSE("reg ");
8186
8187     *flagp = 0;                         /* Tentatively. */
8188
8189
8190     /* Make an OPEN node, if parenthesized. */
8191     if (paren) {
8192         if ( *RExC_parse == '*') { /* (*VERB:ARG) */
8193             char *start_verb = RExC_parse;
8194             STRLEN verb_len = 0;
8195             char *start_arg = NULL;
8196             unsigned char op = 0;
8197             int argok = 1;
8198             int internal_argval = 0; /* internal_argval is only useful if !argok */
8199             while ( *RExC_parse && *RExC_parse != ')' ) {
8200                 if ( *RExC_parse == ':' ) {
8201                     start_arg = RExC_parse + 1;
8202                     break;
8203                 }
8204                 RExC_parse++;
8205             }
8206             ++start_verb;
8207             verb_len = RExC_parse - start_verb;
8208             if ( start_arg ) {
8209                 RExC_parse++;
8210                 while ( *RExC_parse && *RExC_parse != ')' ) 
8211                     RExC_parse++;
8212                 if ( *RExC_parse != ')' ) 
8213                     vFAIL("Unterminated verb pattern argument");
8214                 if ( RExC_parse == start_arg )
8215                     start_arg = NULL;
8216             } else {
8217                 if ( *RExC_parse != ')' )
8218                     vFAIL("Unterminated verb pattern");
8219             }
8220             
8221             switch ( *start_verb ) {
8222             case 'A':  /* (*ACCEPT) */
8223                 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
8224                     op = ACCEPT;
8225                     internal_argval = RExC_nestroot;
8226                 }
8227                 break;
8228             case 'C':  /* (*COMMIT) */
8229                 if ( memEQs(start_verb,verb_len,"COMMIT") )
8230                     op = COMMIT;
8231                 break;
8232             case 'F':  /* (*FAIL) */
8233                 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
8234                     op = OPFAIL;
8235                     argok = 0;
8236                 }
8237                 break;
8238             case ':':  /* (*:NAME) */
8239             case 'M':  /* (*MARK:NAME) */
8240                 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
8241                     op = MARKPOINT;
8242                     argok = -1;
8243                 }
8244                 break;
8245             case 'P':  /* (*PRUNE) */
8246                 if ( memEQs(start_verb,verb_len,"PRUNE") )
8247                     op = PRUNE;
8248                 break;
8249             case 'S':   /* (*SKIP) */  
8250                 if ( memEQs(start_verb,verb_len,"SKIP") ) 
8251                     op = SKIP;
8252                 break;
8253             case 'T':  /* (*THEN) */
8254                 /* [19:06] <TimToady> :: is then */
8255                 if ( memEQs(start_verb,verb_len,"THEN") ) {
8256                     op = CUTGROUP;
8257                     RExC_seen |= REG_SEEN_CUTGROUP;
8258                 }
8259                 break;
8260             }
8261             if ( ! op ) {
8262                 RExC_parse++;
8263                 vFAIL3("Unknown verb pattern '%.*s'",
8264                     verb_len, start_verb);
8265             }
8266             if ( argok ) {
8267                 if ( start_arg && internal_argval ) {
8268                     vFAIL3("Verb pattern '%.*s' may not have an argument",
8269                         verb_len, start_verb); 
8270                 } else if ( argok < 0 && !start_arg ) {
8271                     vFAIL3("Verb pattern '%.*s' has a mandatory argument",
8272                         verb_len, start_verb);    
8273                 } else {
8274                     ret = reganode(pRExC_state, op, internal_argval);
8275                     if ( ! internal_argval && ! SIZE_ONLY ) {
8276                         if (start_arg) {
8277                             SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
8278                             ARG(ret) = add_data( pRExC_state, 1, "S" );
8279                             RExC_rxi->data->data[ARG(ret)]=(void*)sv;
8280                             ret->flags = 0;
8281                         } else {
8282                             ret->flags = 1; 
8283                         }
8284                     }               
8285                 }
8286                 if (!internal_argval)
8287                     RExC_seen |= REG_SEEN_VERBARG;
8288             } else if ( start_arg ) {
8289                 vFAIL3("Verb pattern '%.*s' may not have an argument",
8290                         verb_len, start_verb);    
8291             } else {
8292                 ret = reg_node(pRExC_state, op);
8293             }
8294             nextchar(pRExC_state);
8295             return ret;
8296         } else 
8297         if (*RExC_parse == '?') { /* (?...) */
8298             bool is_logical = 0;
8299             const char * const seqstart = RExC_parse;
8300             bool has_use_defaults = FALSE;
8301
8302             RExC_parse++;
8303             paren = *RExC_parse++;
8304             ret = NULL;                 /* For look-ahead/behind. */
8305             switch (paren) {
8306
8307             case 'P':   /* (?P...) variants for those used to PCRE/Python */
8308                 paren = *RExC_parse++;
8309                 if ( paren == '<')         /* (?P<...>) named capture */
8310                     goto named_capture;
8311                 else if (paren == '>') {   /* (?P>name) named recursion */
8312                     goto named_recursion;
8313                 }
8314                 else if (paren == '=') {   /* (?P=...)  named backref */
8315                     /* this pretty much dupes the code for \k<NAME> in regatom(), if
8316                        you change this make sure you change that */
8317                     char* name_start = RExC_parse;
8318                     U32 num = 0;
8319                     SV *sv_dat = reg_scan_name(pRExC_state,
8320                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8321                     if (RExC_parse == name_start || *RExC_parse != ')')
8322                         vFAIL2("Sequence %.3s... not terminated",parse_start);
8323
8324                     if (!SIZE_ONLY) {
8325                         num = add_data( pRExC_state, 1, "S" );
8326                         RExC_rxi->data->data[num]=(void*)sv_dat;
8327                         SvREFCNT_inc_simple_void(sv_dat);
8328                     }
8329                     RExC_sawback = 1;
8330                     ret = reganode(pRExC_state,
8331                                    ((! FOLD)
8332                                      ? NREF
8333                                      : (MORE_ASCII_RESTRICTED)
8334                                        ? NREFFA
8335                                        : (AT_LEAST_UNI_SEMANTICS)
8336                                          ? NREFFU
8337                                          : (LOC)
8338                                            ? NREFFL
8339                                            : NREFF),
8340                                     num);
8341                     *flagp |= HASWIDTH;
8342
8343                     Set_Node_Offset(ret, parse_start+1);
8344                     Set_Node_Cur_Length(ret); /* MJD */
8345
8346                     nextchar(pRExC_state);
8347                     return ret;
8348                 }
8349                 RExC_parse++;
8350                 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8351                 /*NOTREACHED*/
8352             case '<':           /* (?<...) */
8353                 if (*RExC_parse == '!')
8354                     paren = ',';
8355                 else if (*RExC_parse != '=') 
8356               named_capture:
8357                 {               /* (?<...>) */
8358                     char *name_start;
8359                     SV *svname;
8360                     paren= '>';
8361             case '\'':          /* (?'...') */
8362                     name_start= RExC_parse;
8363                     svname = reg_scan_name(pRExC_state,
8364                         SIZE_ONLY ?  /* reverse test from the others */
8365                         REG_RSN_RETURN_NAME : 
8366                         REG_RSN_RETURN_NULL);
8367                     if (RExC_parse == name_start) {
8368                         RExC_parse++;
8369                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8370                         /*NOTREACHED*/
8371                     }
8372                     if (*RExC_parse != paren)
8373                         vFAIL2("Sequence (?%c... not terminated",
8374                             paren=='>' ? '<' : paren);
8375                     if (SIZE_ONLY) {
8376                         HE *he_str;
8377                         SV *sv_dat = NULL;
8378                         if (!svname) /* shouldn't happen */
8379                             Perl_croak(aTHX_
8380                                 "panic: reg_scan_name returned NULL");
8381                         if (!RExC_paren_names) {
8382                             RExC_paren_names= newHV();
8383                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
8384 #ifdef DEBUGGING
8385                             RExC_paren_name_list= newAV();
8386                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
8387 #endif
8388                         }
8389                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
8390                         if ( he_str )
8391                             sv_dat = HeVAL(he_str);
8392                         if ( ! sv_dat ) {
8393                             /* croak baby croak */
8394                             Perl_croak(aTHX_
8395                                 "panic: paren_name hash element allocation failed");
8396                         } else if ( SvPOK(sv_dat) ) {
8397                             /* (?|...) can mean we have dupes so scan to check
8398                                its already been stored. Maybe a flag indicating
8399                                we are inside such a construct would be useful,
8400                                but the arrays are likely to be quite small, so
8401                                for now we punt -- dmq */
8402                             IV count = SvIV(sv_dat);
8403                             I32 *pv = (I32*)SvPVX(sv_dat);
8404                             IV i;
8405                             for ( i = 0 ; i < count ; i++ ) {
8406                                 if ( pv[i] == RExC_npar ) {
8407                                     count = 0;
8408                                     break;
8409                                 }
8410                             }
8411                             if ( count ) {
8412                                 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
8413                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
8414                                 pv[count] = RExC_npar;
8415                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
8416                             }
8417                         } else {
8418                             (void)SvUPGRADE(sv_dat,SVt_PVNV);
8419                             sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
8420                             SvIOK_on(sv_dat);
8421                             SvIV_set(sv_dat, 1);
8422                         }
8423 #ifdef DEBUGGING
8424                         /* Yes this does cause a memory leak in debugging Perls */
8425                         if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
8426                             SvREFCNT_dec(svname);
8427 #endif
8428
8429                         /*sv_dump(sv_dat);*/
8430                     }
8431                     nextchar(pRExC_state);
8432                     paren = 1;
8433                     goto capturing_parens;
8434                 }
8435                 RExC_seen |= REG_SEEN_LOOKBEHIND;
8436                 RExC_in_lookbehind++;
8437                 RExC_parse++;
8438             case '=':           /* (?=...) */
8439                 RExC_seen_zerolen++;
8440                 break;
8441             case '!':           /* (?!...) */
8442                 RExC_seen_zerolen++;
8443                 if (*RExC_parse == ')') {
8444                     ret=reg_node(pRExC_state, OPFAIL);
8445                     nextchar(pRExC_state);
8446                     return ret;
8447                 }
8448                 break;
8449             case '|':           /* (?|...) */
8450                 /* branch reset, behave like a (?:...) except that
8451                    buffers in alternations share the same numbers */
8452                 paren = ':'; 
8453                 after_freeze = freeze_paren = RExC_npar;
8454                 break;
8455             case ':':           /* (?:...) */
8456             case '>':           /* (?>...) */
8457                 break;
8458             case '$':           /* (?$...) */
8459             case '@':           /* (?@...) */
8460                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
8461                 break;
8462             case '#':           /* (?#...) */
8463                 while (*RExC_parse && *RExC_parse != ')')
8464                     RExC_parse++;
8465                 if (*RExC_parse != ')')
8466                     FAIL("Sequence (?#... not terminated");
8467                 nextchar(pRExC_state);
8468                 *flagp = TRYAGAIN;
8469                 return NULL;
8470             case '0' :           /* (?0) */
8471             case 'R' :           /* (?R) */
8472                 if (*RExC_parse != ')')
8473                     FAIL("Sequence (?R) not terminated");
8474                 ret = reg_node(pRExC_state, GOSTART);
8475                 *flagp |= POSTPONED;
8476                 nextchar(pRExC_state);
8477                 return ret;
8478                 /*notreached*/
8479             { /* named and numeric backreferences */
8480                 I32 num;
8481             case '&':            /* (?&NAME) */
8482                 parse_start = RExC_parse - 1;
8483               named_recursion:
8484                 {
8485                     SV *sv_dat = reg_scan_name(pRExC_state,
8486                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8487                      num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
8488                 }
8489                 goto gen_recurse_regop;
8490                 /* NOT REACHED */
8491             case '+':
8492                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
8493                     RExC_parse++;
8494                     vFAIL("Illegal pattern");
8495                 }
8496                 goto parse_recursion;
8497                 /* NOT REACHED*/
8498             case '-': /* (?-1) */
8499                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
8500                     RExC_parse--; /* rewind to let it be handled later */
8501                     goto parse_flags;
8502                 } 
8503                 /*FALLTHROUGH */
8504             case '1': case '2': case '3': case '4': /* (?1) */
8505             case '5': case '6': case '7': case '8': case '9':
8506                 RExC_parse--;
8507               parse_recursion:
8508                 num = atoi(RExC_parse);
8509                 parse_start = RExC_parse - 1; /* MJD */
8510                 if (*RExC_parse == '-')
8511                     RExC_parse++;
8512                 while (isDIGIT(*RExC_parse))
8513                         RExC_parse++;
8514                 if (*RExC_parse!=')') 
8515                     vFAIL("Expecting close bracket");
8516
8517               gen_recurse_regop:
8518                 if ( paren == '-' ) {
8519                     /*
8520                     Diagram of capture buffer numbering.
8521                     Top line is the normal capture buffer numbers
8522                     Bottom line is the negative indexing as from
8523                     the X (the (?-2))
8524
8525                     +   1 2    3 4 5 X          6 7
8526                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
8527                     -   5 4    3 2 1 X          x x
8528
8529                     */
8530                     num = RExC_npar + num;
8531                     if (num < 1)  {
8532                         RExC_parse++;
8533                         vFAIL("Reference to nonexistent group");
8534                     }
8535                 } else if ( paren == '+' ) {
8536                     num = RExC_npar + num - 1;
8537                 }
8538
8539                 ret = reganode(pRExC_state, GOSUB, num);
8540                 if (!SIZE_ONLY) {
8541                     if (num > (I32)RExC_rx->nparens) {
8542                         RExC_parse++;
8543                         vFAIL("Reference to nonexistent group");
8544                     }
8545                     ARG2L_SET( ret, RExC_recurse_count++);
8546                     RExC_emit++;
8547                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
8548                         "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
8549                 } else {
8550                     RExC_size++;
8551                 }
8552                 RExC_seen |= REG_SEEN_RECURSE;
8553                 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
8554                 Set_Node_Offset(ret, parse_start); /* MJD */
8555
8556                 *flagp |= POSTPONED;
8557                 nextchar(pRExC_state);
8558                 return ret;
8559             } /* named and numeric backreferences */
8560             /* NOT REACHED */
8561
8562             case '?':           /* (??...) */
8563                 is_logical = 1;
8564                 if (*RExC_parse != '{') {
8565                     RExC_parse++;
8566                     vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8567                     /*NOTREACHED*/
8568                 }
8569                 *flagp |= POSTPONED;
8570                 paren = *RExC_parse++;
8571                 /* FALL THROUGH */
8572             case '{':           /* (?{...}) */
8573             {
8574                 U32 n = 0;
8575                 struct reg_code_block *cb;
8576
8577                 RExC_seen_zerolen++;
8578
8579                 if (   !pRExC_state->num_code_blocks
8580                     || pRExC_state->code_index >= pRExC_state->num_code_blocks
8581                     || pRExC_state->code_blocks[pRExC_state->code_index].start
8582                         != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0))
8583                             - RExC_start)
8584                 ) {
8585                     if (RExC_pm_flags & PMf_USE_RE_EVAL)
8586                         FAIL("panic: Sequence (?{...}): no code block found\n");
8587                     FAIL("Eval-group not allowed at runtime, use re 'eval'");
8588                 }
8589                 /* this is a pre-compiled code block (?{...}) */
8590                 cb = &pRExC_state->code_blocks[pRExC_state->code_index];
8591                 RExC_parse = RExC_start + cb->end;
8592                 if (!SIZE_ONLY) {
8593                     OP *o = cb->block;
8594                     if (cb->src_regex) {
8595                         n = add_data(pRExC_state, 2, "rl");
8596                         RExC_rxi->data->data[n] =
8597                             (void*)SvREFCNT_inc((SV*)cb->src_regex);
8598                         RExC_rxi->data->data[n+1] = (void*)o;
8599                     }
8600                     else {
8601                         n = add_data(pRExC_state, 1,
8602                                (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l");
8603                         RExC_rxi->data->data[n] = (void*)o;
8604                     }
8605                 }
8606                 pRExC_state->code_index++;
8607                 nextchar(pRExC_state);
8608
8609                 if (is_logical) {
8610                     regnode *eval;
8611                     ret = reg_node(pRExC_state, LOGICAL);
8612                     eval = reganode(pRExC_state, EVAL, n);
8613                     if (!SIZE_ONLY) {
8614                         ret->flags = 2;
8615                         /* for later propagation into (??{}) return value */
8616                         eval->flags = (U8) (RExC_flags & RXf_PMf_COMPILETIME);
8617                     }
8618                     REGTAIL(pRExC_state, ret, eval);
8619                     /* deal with the length of this later - MJD */
8620                     return ret;
8621                 }
8622                 ret = reganode(pRExC_state, EVAL, n);
8623                 Set_Node_Length(ret, RExC_parse - parse_start + 1);
8624                 Set_Node_Offset(ret, parse_start);
8625                 return ret;
8626             }
8627             case '(':           /* (?(?{...})...) and (?(?=...)...) */
8628             {
8629                 int is_define= 0;
8630                 if (RExC_parse[0] == '?') {        /* (?(?...)) */
8631                     if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
8632                         || RExC_parse[1] == '<'
8633                         || RExC_parse[1] == '{') { /* Lookahead or eval. */
8634                         I32 flag;
8635
8636                         ret = reg_node(pRExC_state, LOGICAL);
8637                         if (!SIZE_ONLY)
8638                             ret->flags = 1;
8639                         REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
8640                         goto insert_if;
8641                     }
8642                 }
8643                 else if ( RExC_parse[0] == '<'     /* (?(<NAME>)...) */
8644                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
8645                 {
8646                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
8647                     char *name_start= RExC_parse++;
8648                     U32 num = 0;
8649                     SV *sv_dat=reg_scan_name(pRExC_state,
8650                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8651                     if (RExC_parse == name_start || *RExC_parse != ch)
8652                         vFAIL2("Sequence (?(%c... not terminated",
8653                             (ch == '>' ? '<' : ch));
8654                     RExC_parse++;
8655                     if (!SIZE_ONLY) {
8656                         num = add_data( pRExC_state, 1, "S" );
8657                         RExC_rxi->data->data[num]=(void*)sv_dat;
8658                         SvREFCNT_inc_simple_void(sv_dat);
8659                     }
8660                     ret = reganode(pRExC_state,NGROUPP,num);
8661                     goto insert_if_check_paren;
8662                 }
8663                 else if (RExC_parse[0] == 'D' &&
8664                          RExC_parse[1] == 'E' &&
8665                          RExC_parse[2] == 'F' &&
8666                          RExC_parse[3] == 'I' &&
8667                          RExC_parse[4] == 'N' &&
8668                          RExC_parse[5] == 'E')
8669                 {
8670                     ret = reganode(pRExC_state,DEFINEP,0);
8671                     RExC_parse +=6 ;
8672                     is_define = 1;
8673                     goto insert_if_check_paren;
8674                 }
8675                 else if (RExC_parse[0] == 'R') {
8676                     RExC_parse++;
8677                     parno = 0;
8678                     if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
8679                         parno = atoi(RExC_parse++);
8680                         while (isDIGIT(*RExC_parse))
8681                             RExC_parse++;
8682                     } else if (RExC_parse[0] == '&') {
8683                         SV *sv_dat;
8684                         RExC_parse++;
8685                         sv_dat = reg_scan_name(pRExC_state,
8686                             SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
8687                         parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
8688                     }
8689                     ret = reganode(pRExC_state,INSUBP,parno); 
8690                     goto insert_if_check_paren;
8691                 }
8692                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
8693                     /* (?(1)...) */
8694                     char c;
8695                     parno = atoi(RExC_parse++);
8696
8697                     while (isDIGIT(*RExC_parse))
8698                         RExC_parse++;
8699                     ret = reganode(pRExC_state, GROUPP, parno);
8700
8701                  insert_if_check_paren:
8702                     if ((c = *nextchar(pRExC_state)) != ')')
8703                         vFAIL("Switch condition not recognized");
8704                   insert_if:
8705                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
8706                     br = regbranch(pRExC_state, &flags, 1,depth+1);
8707                     if (br == NULL)
8708                         br = reganode(pRExC_state, LONGJMP, 0);
8709                     else
8710                         REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
8711                     c = *nextchar(pRExC_state);
8712                     if (flags&HASWIDTH)
8713                         *flagp |= HASWIDTH;
8714                     if (c == '|') {
8715                         if (is_define) 
8716                             vFAIL("(?(DEFINE)....) does not allow branches");
8717                         lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
8718                         regbranch(pRExC_state, &flags, 1,depth+1);
8719                         REGTAIL(pRExC_state, ret, lastbr);
8720                         if (flags&HASWIDTH)
8721                             *flagp |= HASWIDTH;
8722                         c = *nextchar(pRExC_state);
8723                     }
8724                     else
8725                         lastbr = NULL;
8726                     if (c != ')')
8727                         vFAIL("Switch (?(condition)... contains too many branches");
8728                     ender = reg_node(pRExC_state, TAIL);
8729                     REGTAIL(pRExC_state, br, ender);
8730                     if (lastbr) {
8731                         REGTAIL(pRExC_state, lastbr, ender);
8732                         REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
8733                     }
8734                     else
8735                         REGTAIL(pRExC_state, ret, ender);
8736                     RExC_size++; /* XXX WHY do we need this?!!
8737                                     For large programs it seems to be required
8738                                     but I can't figure out why. -- dmq*/
8739                     return ret;
8740                 }
8741                 else {
8742                     vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
8743                 }
8744             }
8745             case 0:
8746                 RExC_parse--; /* for vFAIL to print correctly */
8747                 vFAIL("Sequence (? incomplete");
8748                 break;
8749             case DEFAULT_PAT_MOD:   /* Use default flags with the exceptions
8750                                        that follow */
8751                 has_use_defaults = TRUE;
8752                 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
8753                 set_regex_charset(&RExC_flags, (RExC_utf8 || RExC_uni_semantics)
8754                                                 ? REGEX_UNICODE_CHARSET
8755                                                 : REGEX_DEPENDS_CHARSET);
8756                 goto parse_flags;
8757             default:
8758                 --RExC_parse;
8759                 parse_flags:      /* (?i) */  
8760             {
8761                 U32 posflags = 0, negflags = 0;
8762                 U32 *flagsp = &posflags;
8763                 char has_charset_modifier = '\0';
8764                 regex_charset cs = get_regex_charset(RExC_flags);
8765                 if (cs == REGEX_DEPENDS_CHARSET
8766                     && (RExC_utf8 || RExC_uni_semantics))
8767                 {
8768                     cs = REGEX_UNICODE_CHARSET;
8769                 }
8770
8771                 while (*RExC_parse) {
8772                     /* && strchr("iogcmsx", *RExC_parse) */
8773                     /* (?g), (?gc) and (?o) are useless here
8774                        and must be globally applied -- japhy */
8775                     switch (*RExC_parse) {
8776                     CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
8777                     case LOCALE_PAT_MOD:
8778                         if (has_charset_modifier) {
8779                             goto excess_modifier;
8780                         }
8781                         else if (flagsp == &negflags) {
8782                             goto neg_modifier;
8783                         }
8784                         cs = REGEX_LOCALE_CHARSET;
8785                         has_charset_modifier = LOCALE_PAT_MOD;
8786                         RExC_contains_locale = 1;
8787                         break;
8788                     case UNICODE_PAT_MOD:
8789                         if (has_charset_modifier) {
8790                             goto excess_modifier;
8791                         }
8792                         else if (flagsp == &negflags) {
8793                             goto neg_modifier;
8794                         }
8795                         cs = REGEX_UNICODE_CHARSET;
8796                         has_charset_modifier = UNICODE_PAT_MOD;
8797                         break;
8798                     case ASCII_RESTRICT_PAT_MOD:
8799                         if (flagsp == &negflags) {
8800                             goto neg_modifier;
8801                         }
8802                         if (has_charset_modifier) {
8803                             if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
8804                                 goto excess_modifier;
8805                             }
8806                             /* Doubled modifier implies more restricted */
8807                             cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
8808                         }
8809                         else {
8810                             cs = REGEX_ASCII_RESTRICTED_CHARSET;
8811                         }
8812                         has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
8813                         break;
8814                     case DEPENDS_PAT_MOD:
8815                         if (has_use_defaults) {
8816                             goto fail_modifiers;
8817                         }
8818                         else if (flagsp == &negflags) {
8819                             goto neg_modifier;
8820                         }
8821                         else if (has_charset_modifier) {
8822                             goto excess_modifier;
8823                         }
8824
8825                         /* The dual charset means unicode semantics if the
8826                          * pattern (or target, not known until runtime) are
8827                          * utf8, or something in the pattern indicates unicode
8828                          * semantics */
8829                         cs = (RExC_utf8 || RExC_uni_semantics)
8830                              ? REGEX_UNICODE_CHARSET
8831                              : REGEX_DEPENDS_CHARSET;
8832                         has_charset_modifier = DEPENDS_PAT_MOD;
8833                         break;
8834                     excess_modifier:
8835                         RExC_parse++;
8836                         if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
8837                             vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
8838                         }
8839                         else if (has_charset_modifier == *(RExC_parse - 1)) {
8840                             vFAIL2("Regexp modifier \"%c\" may not appear twice", *(RExC_parse - 1));
8841                         }
8842                         else {
8843                             vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
8844                         }
8845                         /*NOTREACHED*/
8846                     neg_modifier:
8847                         RExC_parse++;
8848                         vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"", *(RExC_parse - 1));
8849                         /*NOTREACHED*/
8850                     case ONCE_PAT_MOD: /* 'o' */
8851                     case GLOBAL_PAT_MOD: /* 'g' */
8852                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
8853                             const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
8854                             if (! (wastedflags & wflagbit) ) {
8855                                 wastedflags |= wflagbit;
8856                                 vWARN5(
8857                                     RExC_parse + 1,
8858                                     "Useless (%s%c) - %suse /%c modifier",
8859                                     flagsp == &negflags ? "?-" : "?",
8860                                     *RExC_parse,
8861                                     flagsp == &negflags ? "don't " : "",
8862                                     *RExC_parse
8863                                 );
8864                             }
8865                         }
8866                         break;
8867                         
8868                     case CONTINUE_PAT_MOD: /* 'c' */
8869                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
8870                             if (! (wastedflags & WASTED_C) ) {
8871                                 wastedflags |= WASTED_GC;
8872                                 vWARN3(
8873                                     RExC_parse + 1,
8874                                     "Useless (%sc) - %suse /gc modifier",
8875                                     flagsp == &negflags ? "?-" : "?",
8876                                     flagsp == &negflags ? "don't " : ""
8877                                 );
8878                             }
8879                         }
8880                         break;
8881                     case KEEPCOPY_PAT_MOD: /* 'p' */
8882                         if (flagsp == &negflags) {
8883                             if (SIZE_ONLY)
8884                                 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
8885                         } else {
8886                             *flagsp |= RXf_PMf_KEEPCOPY;
8887                         }
8888                         break;
8889                     case '-':
8890                         /* A flag is a default iff it is following a minus, so
8891                          * if there is a minus, it means will be trying to
8892                          * re-specify a default which is an error */
8893                         if (has_use_defaults || flagsp == &negflags) {
8894             fail_modifiers:
8895                             RExC_parse++;
8896                             vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8897                             /*NOTREACHED*/
8898                         }
8899                         flagsp = &negflags;
8900                         wastedflags = 0;  /* reset so (?g-c) warns twice */
8901                         break;
8902                     case ':':
8903                         paren = ':';
8904                         /*FALLTHROUGH*/
8905                     case ')':
8906                         RExC_flags |= posflags;
8907                         RExC_flags &= ~negflags;
8908                         set_regex_charset(&RExC_flags, cs);
8909                         if (paren != ':') {
8910                             oregflags |= posflags;
8911                             oregflags &= ~negflags;
8912                             set_regex_charset(&oregflags, cs);
8913                         }
8914                         nextchar(pRExC_state);
8915                         if (paren != ':') {
8916                             *flagp = TRYAGAIN;
8917                             return NULL;
8918                         } else {
8919                             ret = NULL;
8920                             goto parse_rest;
8921                         }
8922                         /*NOTREACHED*/
8923                     default:
8924                         RExC_parse++;
8925                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8926                         /*NOTREACHED*/
8927                     }                           
8928                     ++RExC_parse;
8929                 }
8930             }} /* one for the default block, one for the switch */
8931         }
8932         else {                  /* (...) */
8933           capturing_parens:
8934             parno = RExC_npar;
8935             RExC_npar++;
8936             
8937             ret = reganode(pRExC_state, OPEN, parno);
8938             if (!SIZE_ONLY ){
8939                 if (!RExC_nestroot) 
8940                     RExC_nestroot = parno;
8941                 if (RExC_seen & REG_SEEN_RECURSE
8942                     && !RExC_open_parens[parno-1])
8943                 {
8944                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
8945                         "Setting open paren #%"IVdf" to %d\n", 
8946                         (IV)parno, REG_NODE_NUM(ret)));
8947                     RExC_open_parens[parno-1]= ret;
8948                 }
8949             }
8950             Set_Node_Length(ret, 1); /* MJD */
8951             Set_Node_Offset(ret, RExC_parse); /* MJD */
8952             is_open = 1;
8953         }
8954     }
8955     else                        /* ! paren */
8956         ret = NULL;
8957    
8958    parse_rest:
8959     /* Pick up the branches, linking them together. */
8960     parse_start = RExC_parse;   /* MJD */
8961     br = regbranch(pRExC_state, &flags, 1,depth+1);
8962
8963     /*     branch_len = (paren != 0); */
8964
8965     if (br == NULL)
8966         return(NULL);
8967     if (*RExC_parse == '|') {
8968         if (!SIZE_ONLY && RExC_extralen) {
8969             reginsert(pRExC_state, BRANCHJ, br, depth+1);
8970         }
8971         else {                  /* MJD */
8972             reginsert(pRExC_state, BRANCH, br, depth+1);
8973             Set_Node_Length(br, paren != 0);
8974             Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
8975         }
8976         have_branch = 1;
8977         if (SIZE_ONLY)
8978             RExC_extralen += 1;         /* For BRANCHJ-BRANCH. */
8979     }
8980     else if (paren == ':') {
8981         *flagp |= flags&SIMPLE;
8982     }
8983     if (is_open) {                              /* Starts with OPEN. */
8984         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
8985     }
8986     else if (paren != '?')              /* Not Conditional */
8987         ret = br;
8988     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
8989     lastbr = br;
8990     while (*RExC_parse == '|') {
8991         if (!SIZE_ONLY && RExC_extralen) {
8992             ender = reganode(pRExC_state, LONGJMP,0);
8993             REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
8994         }
8995         if (SIZE_ONLY)
8996             RExC_extralen += 2;         /* Account for LONGJMP. */
8997         nextchar(pRExC_state);
8998         if (freeze_paren) {
8999             if (RExC_npar > after_freeze)
9000                 after_freeze = RExC_npar;
9001             RExC_npar = freeze_paren;       
9002         }
9003         br = regbranch(pRExC_state, &flags, 0, depth+1);
9004
9005         if (br == NULL)
9006             return(NULL);
9007         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
9008         lastbr = br;
9009         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
9010     }
9011
9012     if (have_branch || paren != ':') {
9013         /* Make a closing node, and hook it on the end. */
9014         switch (paren) {
9015         case ':':
9016             ender = reg_node(pRExC_state, TAIL);
9017             break;
9018         case 1:
9019             ender = reganode(pRExC_state, CLOSE, parno);
9020             if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
9021                 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
9022                         "Setting close paren #%"IVdf" to %d\n", 
9023                         (IV)parno, REG_NODE_NUM(ender)));
9024                 RExC_close_parens[parno-1]= ender;
9025                 if (RExC_nestroot == parno) 
9026                     RExC_nestroot = 0;
9027             }       
9028             Set_Node_Offset(ender,RExC_parse+1); /* MJD */
9029             Set_Node_Length(ender,1); /* MJD */
9030             break;
9031         case '<':
9032         case ',':
9033         case '=':
9034         case '!':
9035             *flagp &= ~HASWIDTH;
9036             /* FALL THROUGH */
9037         case '>':
9038             ender = reg_node(pRExC_state, SUCCEED);
9039             break;
9040         case 0:
9041             ender = reg_node(pRExC_state, END);
9042             if (!SIZE_ONLY) {
9043                 assert(!RExC_opend); /* there can only be one! */
9044                 RExC_opend = ender;
9045             }
9046             break;
9047         }
9048         DEBUG_PARSE_r(if (!SIZE_ONLY) {
9049             SV * const mysv_val1=sv_newmortal();
9050             SV * const mysv_val2=sv_newmortal();
9051             DEBUG_PARSE_MSG("lsbr");
9052             regprop(RExC_rx, mysv_val1, lastbr);
9053             regprop(RExC_rx, mysv_val2, ender);
9054             PerlIO_printf(Perl_debug_log, "~ tying lastbr %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
9055                           SvPV_nolen_const(mysv_val1),
9056                           (IV)REG_NODE_NUM(lastbr),
9057                           SvPV_nolen_const(mysv_val2),
9058                           (IV)REG_NODE_NUM(ender),
9059                           (IV)(ender - lastbr)
9060             );
9061         });
9062         REGTAIL(pRExC_state, lastbr, ender);
9063
9064         if (have_branch && !SIZE_ONLY) {
9065             char is_nothing= 1;
9066             if (depth==1)
9067                 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
9068
9069             /* Hook the tails of the branches to the closing node. */
9070             for (br = ret; br; br = regnext(br)) {
9071                 const U8 op = PL_regkind[OP(br)];
9072                 if (op == BRANCH) {
9073                     REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
9074                     if (OP(NEXTOPER(br)) != NOTHING || regnext(NEXTOPER(br)) != ender)
9075                         is_nothing= 0;
9076                 }
9077                 else if (op == BRANCHJ) {
9078                     REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
9079                     /* for now we always disable this optimisation * /
9080                     if (OP(NEXTOPER(NEXTOPER(br))) != NOTHING || regnext(NEXTOPER(NEXTOPER(br))) != ender)
9081                     */
9082                         is_nothing= 0;
9083                 }
9084             }
9085             if (is_nothing) {
9086                 br= PL_regkind[OP(ret)] != BRANCH ? regnext(ret) : ret;
9087                 DEBUG_PARSE_r(if (!SIZE_ONLY) {
9088                     SV * const mysv_val1=sv_newmortal();
9089                     SV * const mysv_val2=sv_newmortal();
9090                     DEBUG_PARSE_MSG("NADA");
9091                     regprop(RExC_rx, mysv_val1, ret);
9092                     regprop(RExC_rx, mysv_val2, ender);
9093                     PerlIO_printf(Perl_debug_log, "~ converting ret %s (%"IVdf") to ender %s (%"IVdf") offset %"IVdf"\n",
9094                                   SvPV_nolen_const(mysv_val1),
9095                                   (IV)REG_NODE_NUM(ret),
9096                                   SvPV_nolen_const(mysv_val2),
9097                                   (IV)REG_NODE_NUM(ender),
9098                                   (IV)(ender - ret)
9099                     );
9100                 });
9101                 OP(br)= NOTHING;
9102                 if (OP(ender) == TAIL) {
9103                     NEXT_OFF(br)= 0;
9104                     RExC_emit= br + 1;
9105                 } else {
9106                     regnode *opt;
9107                     for ( opt= br + 1; opt < ender ; opt++ )
9108                         OP(opt)= OPTIMIZED;
9109                     NEXT_OFF(br)= ender - br;
9110                 }
9111             }
9112         }
9113     }
9114
9115     {
9116         const char *p;
9117         static const char parens[] = "=!<,>";
9118
9119         if (paren && (p = strchr(parens, paren))) {
9120             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
9121             int flag = (p - parens) > 1;
9122
9123             if (paren == '>')
9124                 node = SUSPEND, flag = 0;
9125             reginsert(pRExC_state, node,ret, depth+1);
9126             Set_Node_Cur_Length(ret);
9127             Set_Node_Offset(ret, parse_start + 1);
9128             ret->flags = flag;
9129             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
9130         }
9131     }
9132
9133     /* Check for proper termination. */
9134     if (paren) {
9135         RExC_flags = oregflags;
9136         if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
9137             RExC_parse = oregcomp_parse;
9138             vFAIL("Unmatched (");
9139         }
9140     }
9141     else if (!paren && RExC_parse < RExC_end) {
9142         if (*RExC_parse == ')') {
9143             RExC_parse++;
9144             vFAIL("Unmatched )");
9145         }
9146         else
9147             FAIL("Junk on end of regexp");      /* "Can't happen". */
9148         /* NOTREACHED */
9149     }
9150
9151     if (RExC_in_lookbehind) {
9152         RExC_in_lookbehind--;
9153     }
9154     if (after_freeze > RExC_npar)
9155         RExC_npar = after_freeze;
9156     return(ret);
9157 }
9158
9159 /*
9160  - regbranch - one alternative of an | operator
9161  *
9162  * Implements the concatenation operator.
9163  */
9164 STATIC regnode *
9165 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
9166 {
9167     dVAR;
9168     register regnode *ret;
9169     register regnode *chain = NULL;
9170     register regnode *latest;
9171     I32 flags = 0, c = 0;
9172     GET_RE_DEBUG_FLAGS_DECL;
9173
9174     PERL_ARGS_ASSERT_REGBRANCH;
9175
9176     DEBUG_PARSE("brnc");
9177
9178     if (first)
9179         ret = NULL;
9180     else {
9181         if (!SIZE_ONLY && RExC_extralen)
9182             ret = reganode(pRExC_state, BRANCHJ,0);
9183         else {
9184             ret = reg_node(pRExC_state, BRANCH);
9185             Set_Node_Length(ret, 1);
9186         }
9187     }
9188
9189     if (!first && SIZE_ONLY)
9190         RExC_extralen += 1;                     /* BRANCHJ */
9191
9192     *flagp = WORST;                     /* Tentatively. */
9193
9194     RExC_parse--;
9195     nextchar(pRExC_state);
9196     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
9197         flags &= ~TRYAGAIN;
9198         latest = regpiece(pRExC_state, &flags,depth+1);
9199         if (latest == NULL) {
9200             if (flags & TRYAGAIN)
9201                 continue;
9202             return(NULL);
9203         }
9204         else if (ret == NULL)
9205             ret = latest;
9206         *flagp |= flags&(HASWIDTH|POSTPONED);
9207         if (chain == NULL)      /* First piece. */
9208             *flagp |= flags&SPSTART;
9209         else {
9210             RExC_naughty++;
9211             REGTAIL(pRExC_state, chain, latest);
9212         }
9213         chain = latest;
9214         c++;
9215     }
9216     if (chain == NULL) {        /* Loop ran zero times. */
9217         chain = reg_node(pRExC_state, NOTHING);
9218         if (ret == NULL)
9219             ret = chain;
9220     }
9221     if (c == 1) {
9222         *flagp |= flags&SIMPLE;
9223     }
9224
9225     return ret;
9226 }
9227
9228 /*
9229  - regpiece - something followed by possible [*+?]
9230  *
9231  * Note that the branching code sequences used for ? and the general cases
9232  * of * and + are somewhat optimized:  they use the same NOTHING node as
9233  * both the endmarker for their branch list and the body of the last branch.
9234  * It might seem that this node could be dispensed with entirely, but the
9235  * endmarker role is not redundant.
9236  */
9237 STATIC regnode *
9238 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
9239 {
9240     dVAR;
9241     register regnode *ret;
9242     register char op;
9243     register char *next;
9244     I32 flags;
9245     const char * const origparse = RExC_parse;
9246     I32 min;
9247     I32 max = REG_INFTY;
9248 #ifdef RE_TRACK_PATTERN_OFFSETS
9249     char *parse_start;
9250 #endif
9251     const char *maxpos = NULL;
9252     GET_RE_DEBUG_FLAGS_DECL;
9253
9254     PERL_ARGS_ASSERT_REGPIECE;
9255
9256     DEBUG_PARSE("piec");
9257
9258     ret = regatom(pRExC_state, &flags,depth+1);
9259     if (ret == NULL) {
9260         if (flags & TRYAGAIN)
9261             *flagp |= TRYAGAIN;
9262         return(NULL);
9263     }
9264
9265     op = *RExC_parse;
9266
9267     if (op == '{' && regcurly(RExC_parse)) {
9268         maxpos = NULL;
9269 #ifdef RE_TRACK_PATTERN_OFFSETS
9270         parse_start = RExC_parse; /* MJD */
9271 #endif
9272         next = RExC_parse + 1;
9273         while (isDIGIT(*next) || *next == ',') {
9274             if (*next == ',') {
9275                 if (maxpos)
9276                     break;
9277                 else
9278                     maxpos = next;
9279             }
9280             next++;
9281         }
9282         if (*next == '}') {             /* got one */
9283             if (!maxpos)
9284                 maxpos = next;
9285             RExC_parse++;
9286             min = atoi(RExC_parse);
9287             if (*maxpos == ',')
9288                 maxpos++;
9289             else
9290                 maxpos = RExC_parse;
9291             max = atoi(maxpos);
9292             if (!max && *maxpos != '0')
9293                 max = REG_INFTY;                /* meaning "infinity" */
9294             else if (max >= REG_INFTY)
9295                 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
9296             RExC_parse = next;
9297             nextchar(pRExC_state);
9298
9299         do_curly:
9300             if ((flags&SIMPLE)) {
9301                 RExC_naughty += 2 + RExC_naughty / 2;
9302                 reginsert(pRExC_state, CURLY, ret, depth+1);
9303                 Set_Node_Offset(ret, parse_start+1); /* MJD */
9304                 Set_Node_Cur_Length(ret);
9305             }
9306             else {
9307                 regnode * const w = reg_node(pRExC_state, WHILEM);
9308
9309                 w->flags = 0;
9310                 REGTAIL(pRExC_state, ret, w);
9311                 if (!SIZE_ONLY && RExC_extralen) {
9312                     reginsert(pRExC_state, LONGJMP,ret, depth+1);
9313                     reginsert(pRExC_state, NOTHING,ret, depth+1);
9314                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
9315                 }
9316                 reginsert(pRExC_state, CURLYX,ret, depth+1);
9317                                 /* MJD hk */
9318                 Set_Node_Offset(ret, parse_start+1);
9319                 Set_Node_Length(ret,
9320                                 op == '{' ? (RExC_parse - parse_start) : 1);
9321
9322                 if (!SIZE_ONLY && RExC_extralen)
9323                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
9324                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
9325                 if (SIZE_ONLY)
9326                     RExC_whilem_seen++, RExC_extralen += 3;
9327                 RExC_naughty += 4 + RExC_naughty;       /* compound interest */
9328             }
9329             ret->flags = 0;
9330
9331             if (min > 0)
9332                 *flagp = WORST;
9333             if (max > 0)
9334                 *flagp |= HASWIDTH;
9335             if (max < min)
9336                 vFAIL("Can't do {n,m} with n > m");
9337             if (!SIZE_ONLY) {
9338                 ARG1_SET(ret, (U16)min);
9339                 ARG2_SET(ret, (U16)max);
9340             }
9341
9342             goto nest_check;
9343         }
9344     }
9345
9346     if (!ISMULT1(op)) {
9347         *flagp = flags;
9348         return(ret);
9349     }
9350
9351 #if 0                           /* Now runtime fix should be reliable. */
9352
9353     /* if this is reinstated, don't forget to put this back into perldiag:
9354
9355             =item Regexp *+ operand could be empty at {#} in regex m/%s/
9356
9357            (F) The part of the regexp subject to either the * or + quantifier
9358            could match an empty string. The {#} shows in the regular
9359            expression about where the problem was discovered.
9360
9361     */
9362
9363     if (!(flags&HASWIDTH) && op != '?')
9364       vFAIL("Regexp *+ operand could be empty");
9365 #endif
9366
9367 #ifdef RE_TRACK_PATTERN_OFFSETS
9368     parse_start = RExC_parse;
9369 #endif
9370     nextchar(pRExC_state);
9371
9372     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
9373
9374     if (op == '*' && (flags&SIMPLE)) {
9375         reginsert(pRExC_state, STAR, ret, depth+1);
9376         ret->flags = 0;
9377         RExC_naughty += 4;
9378     }
9379     else if (op == '*') {
9380         min = 0;
9381         goto do_curly;
9382     }
9383     else if (op == '+' && (flags&SIMPLE)) {
9384         reginsert(pRExC_state, PLUS, ret, depth+1);
9385         ret->flags = 0;
9386         RExC_naughty += 3;
9387     }
9388     else if (op == '+') {
9389         min = 1;
9390         goto do_curly;
9391     }
9392     else if (op == '?') {
9393         min = 0; max = 1;
9394         goto do_curly;
9395     }
9396   nest_check:
9397     if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
9398         ckWARN3reg(RExC_parse,
9399                    "%.*s matches null string many times",
9400                    (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
9401                    origparse);
9402     }
9403
9404     if (RExC_parse < RExC_end && *RExC_parse == '?') {
9405         nextchar(pRExC_state);
9406         reginsert(pRExC_state, MINMOD, ret, depth+1);
9407         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
9408     }
9409 #ifndef REG_ALLOW_MINMOD_SUSPEND
9410     else
9411 #endif
9412     if (RExC_parse < RExC_end && *RExC_parse == '+') {
9413         regnode *ender;
9414         nextchar(pRExC_state);
9415         ender = reg_node(pRExC_state, SUCCEED);
9416         REGTAIL(pRExC_state, ret, ender);
9417         reginsert(pRExC_state, SUSPEND, ret, depth+1);
9418         ret->flags = 0;
9419         ender = reg_node(pRExC_state, TAIL);
9420         REGTAIL(pRExC_state, ret, ender);
9421         /*ret= ender;*/
9422     }
9423
9424     if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
9425         RExC_parse++;
9426         vFAIL("Nested quantifiers");
9427     }
9428
9429     return(ret);
9430 }
9431
9432
9433 /* reg_namedseq(pRExC_state,UVp, UV depth)
9434    
9435    This is expected to be called by a parser routine that has 
9436    recognized '\N' and needs to handle the rest. RExC_parse is
9437    expected to point at the first char following the N at the time
9438    of the call.
9439
9440    The \N may be inside (indicated by valuep not being NULL) or outside a
9441    character class.
9442
9443    \N may begin either a named sequence, or if outside a character class, mean
9444    to match a non-newline.  For non single-quoted regexes, the tokenizer has
9445    attempted to decide which, and in the case of a named sequence converted it
9446    into one of the forms: \N{} (if the sequence is null), or \N{U+c1.c2...},
9447    where c1... are the characters in the sequence.  For single-quoted regexes,
9448    the tokenizer passes the \N sequence through unchanged; this code will not
9449    attempt to determine this nor expand those.  The net effect is that if the
9450    beginning of the passed-in pattern isn't '{U+' or there is no '}', it
9451    signals that this \N occurrence means to match a non-newline.
9452    
9453    Only the \N{U+...} form should occur in a character class, for the same
9454    reason that '.' inside a character class means to just match a period: it
9455    just doesn't make sense.
9456    
9457    If valuep is non-null then it is assumed that we are parsing inside 
9458    of a charclass definition and the first codepoint in the resolved
9459    string is returned via *valuep and the routine will return NULL. 
9460    In this mode if a multichar string is returned from the charnames 
9461    handler, a warning will be issued, and only the first char in the 
9462    sequence will be examined. If the string returned is zero length
9463    then the value of *valuep is undefined and NON-NULL will 
9464    be returned to indicate failure. (This will NOT be a valid pointer 
9465    to a regnode.)
9466    
9467    If valuep is null then it is assumed that we are parsing normal text and a
9468    new EXACT node is inserted into the program containing the resolved string,
9469    and a pointer to the new node is returned.  But if the string is zero length
9470    a NOTHING node is emitted instead.
9471
9472    On success RExC_parse is set to the char following the endbrace.
9473    Parsing failures will generate a fatal error via vFAIL(...)
9474  */
9475 STATIC regnode *
9476 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep, I32 *flagp, U32 depth)
9477 {
9478     char * endbrace;    /* '}' following the name */
9479     regnode *ret = NULL;
9480     char* p;
9481
9482     GET_RE_DEBUG_FLAGS_DECL;
9483  
9484     PERL_ARGS_ASSERT_REG_NAMEDSEQ;
9485
9486     GET_RE_DEBUG_FLAGS;
9487
9488     /* The [^\n] meaning of \N ignores spaces and comments under the /x
9489      * modifier.  The other meaning does not */
9490     p = (RExC_flags & RXf_PMf_EXTENDED)
9491         ? regwhite( pRExC_state, RExC_parse )
9492         : RExC_parse;
9493    
9494     /* Disambiguate between \N meaning a named character versus \N meaning
9495      * [^\n].  The former is assumed when it can't be the latter. */
9496     if (*p != '{' || regcurly(p)) {
9497         RExC_parse = p;
9498         if (valuep) {
9499             /* no bare \N in a charclass */
9500             vFAIL("\\N in a character class must be a named character: \\N{...}");
9501         }
9502         nextchar(pRExC_state);
9503         ret = reg_node(pRExC_state, REG_ANY);
9504         *flagp |= HASWIDTH|SIMPLE;
9505         RExC_naughty++;
9506         RExC_parse--;
9507         Set_Node_Length(ret, 1); /* MJD */
9508         return ret;
9509     }
9510
9511     /* Here, we have decided it should be a named sequence */
9512
9513     /* The test above made sure that the next real character is a '{', but
9514      * under the /x modifier, it could be separated by space (or a comment and
9515      * \n) and this is not allowed (for consistency with \x{...} and the
9516      * tokenizer handling of \N{NAME}). */
9517     if (*RExC_parse != '{') {
9518         vFAIL("Missing braces on \\N{}");
9519     }
9520
9521     RExC_parse++;       /* Skip past the '{' */
9522
9523     if (! (endbrace = strchr(RExC_parse, '}')) /* no trailing brace */
9524         || ! (endbrace == RExC_parse            /* nothing between the {} */
9525               || (endbrace - RExC_parse >= 2    /* U+ (bad hex is checked below */
9526                   && strnEQ(RExC_parse, "U+", 2)))) /* for a better error msg) */
9527     {
9528         if (endbrace) RExC_parse = endbrace;    /* position msg's '<--HERE' */
9529         vFAIL("\\N{NAME} must be resolved by the lexer");
9530     }
9531
9532     if (endbrace == RExC_parse) {   /* empty: \N{} */
9533         if (! valuep) {
9534             RExC_parse = endbrace + 1;  
9535             return reg_node(pRExC_state,NOTHING);
9536         }
9537
9538         if (SIZE_ONLY) {
9539             ckWARNreg(RExC_parse,
9540                     "Ignoring zero length \\N{} in character class"
9541             );
9542             RExC_parse = endbrace + 1;  
9543         }
9544         *valuep = 0;
9545         return (regnode *) &RExC_parse; /* Invalid regnode pointer */
9546     }
9547
9548     REQUIRE_UTF8;       /* named sequences imply Unicode semantics */
9549     RExC_parse += 2;    /* Skip past the 'U+' */
9550
9551     if (valuep) {   /* In a bracketed char class */
9552         /* We only pay attention to the first char of 
9553         multichar strings being returned. I kinda wonder
9554         if this makes sense as it does change the behaviour
9555         from earlier versions, OTOH that behaviour was broken
9556         as well. XXX Solution is to recharacterize as
9557         [rest-of-class]|multi1|multi2... */
9558
9559         STRLEN length_of_hex;
9560         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
9561             | PERL_SCAN_DISALLOW_PREFIX
9562             | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
9563     
9564         char * endchar = RExC_parse + strcspn(RExC_parse, ".}");
9565         if (endchar < endbrace) {
9566             ckWARNreg(endchar, "Using just the first character returned by \\N{} in character class");
9567         }
9568
9569         length_of_hex = (STRLEN)(endchar - RExC_parse);
9570         *valuep = grok_hex(RExC_parse, &length_of_hex, &flags, NULL);
9571
9572         /* The tokenizer should have guaranteed validity, but it's possible to
9573          * bypass it by using single quoting, so check */
9574         if (length_of_hex == 0
9575             || length_of_hex != (STRLEN)(endchar - RExC_parse) )
9576         {
9577             RExC_parse += length_of_hex;        /* Includes all the valid */
9578             RExC_parse += (RExC_orig_utf8)      /* point to after 1st invalid */
9579                             ? UTF8SKIP(RExC_parse)
9580                             : 1;
9581             /* Guard against malformed utf8 */
9582             if (RExC_parse >= endchar) RExC_parse = endchar;
9583             vFAIL("Invalid hexadecimal number in \\N{U+...}");
9584         }    
9585
9586         RExC_parse = endbrace + 1;
9587         if (endchar == endbrace) return NULL;
9588
9589         ret = (regnode *) &RExC_parse;  /* Invalid regnode pointer */
9590     }
9591     else {      /* Not a char class */
9592
9593         /* What is done here is to convert this to a sub-pattern of the form
9594          * (?:\x{char1}\x{char2}...)
9595          * and then call reg recursively.  That way, it retains its atomicness,
9596          * while not having to worry about special handling that some code
9597          * points may have.  toke.c has converted the original Unicode values
9598          * to native, so that we can just pass on the hex values unchanged.  We
9599          * do have to set a flag to keep recoding from happening in the
9600          * recursion */
9601
9602         SV * substitute_parse = newSVpvn_flags("?:", 2, SVf_UTF8|SVs_TEMP);
9603         STRLEN len;
9604         char *endchar;      /* Points to '.' or '}' ending cur char in the input
9605                                stream */
9606         char *orig_end = RExC_end;
9607
9608         while (RExC_parse < endbrace) {
9609
9610             /* Code points are separated by dots.  If none, there is only one
9611              * code point, and is terminated by the brace */
9612             endchar = RExC_parse + strcspn(RExC_parse, ".}");
9613
9614             /* Convert to notation the rest of the code understands */
9615             sv_catpv(substitute_parse, "\\x{");
9616             sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse);
9617             sv_catpv(substitute_parse, "}");
9618
9619             /* Point to the beginning of the next character in the sequence. */
9620             RExC_parse = endchar + 1;
9621         }
9622         sv_catpv(substitute_parse, ")");
9623
9624         RExC_parse = SvPV(substitute_parse, len);
9625
9626         /* Don't allow empty number */
9627         if (len < 8) {
9628             vFAIL("Invalid hexadecimal number in \\N{U+...}");
9629         }
9630         RExC_end = RExC_parse + len;
9631
9632         /* The values are Unicode, and therefore not subject to recoding */
9633         RExC_override_recoding = 1;
9634
9635         ret = reg(pRExC_state, 1, flagp, depth+1);
9636
9637         RExC_parse = endbrace;
9638         RExC_end = orig_end;
9639         RExC_override_recoding = 0;
9640
9641         nextchar(pRExC_state);
9642     }
9643
9644     return ret;
9645 }
9646
9647
9648 /*
9649  * reg_recode
9650  *
9651  * It returns the code point in utf8 for the value in *encp.
9652  *    value: a code value in the source encoding
9653  *    encp:  a pointer to an Encode object
9654  *
9655  * If the result from Encode is not a single character,
9656  * it returns U+FFFD (Replacement character) and sets *encp to NULL.
9657  */
9658 STATIC UV
9659 S_reg_recode(pTHX_ const char value, SV **encp)
9660 {
9661     STRLEN numlen = 1;
9662     SV * const sv = newSVpvn_flags(&value, numlen, SVs_TEMP);
9663     const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
9664     const STRLEN newlen = SvCUR(sv);
9665     UV uv = UNICODE_REPLACEMENT;
9666
9667     PERL_ARGS_ASSERT_REG_RECODE;
9668
9669     if (newlen)
9670         uv = SvUTF8(sv)
9671              ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
9672              : *(U8*)s;
9673
9674     if (!newlen || numlen != newlen) {
9675         uv = UNICODE_REPLACEMENT;
9676         *encp = NULL;
9677     }
9678     return uv;
9679 }
9680
9681
9682 /*
9683  - regatom - the lowest level
9684
9685    Try to identify anything special at the start of the pattern. If there
9686    is, then handle it as required. This may involve generating a single regop,
9687    such as for an assertion; or it may involve recursing, such as to
9688    handle a () structure.
9689
9690    If the string doesn't start with something special then we gobble up
9691    as much literal text as we can.
9692
9693    Once we have been able to handle whatever type of thing started the
9694    sequence, we return.
9695
9696    Note: we have to be careful with escapes, as they can be both literal
9697    and special, and in the case of \10 and friends can either, depending
9698    on context. Specifically there are two separate switches for handling
9699    escape sequences, with the one for handling literal escapes requiring
9700    a dummy entry for all of the special escapes that are actually handled
9701    by the other.
9702 */
9703
9704 STATIC regnode *
9705 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
9706 {
9707     dVAR;
9708     register regnode *ret = NULL;
9709     I32 flags;
9710     char *parse_start = RExC_parse;
9711     U8 op;
9712     GET_RE_DEBUG_FLAGS_DECL;
9713     DEBUG_PARSE("atom");
9714     *flagp = WORST;             /* Tentatively. */
9715
9716     PERL_ARGS_ASSERT_REGATOM;
9717
9718 tryagain:
9719     switch ((U8)*RExC_parse) {
9720     case '^':
9721         RExC_seen_zerolen++;
9722         nextchar(pRExC_state);
9723         if (RExC_flags & RXf_PMf_MULTILINE)
9724             ret = reg_node(pRExC_state, MBOL);
9725         else if (RExC_flags & RXf_PMf_SINGLELINE)
9726             ret = reg_node(pRExC_state, SBOL);
9727         else
9728             ret = reg_node(pRExC_state, BOL);
9729         Set_Node_Length(ret, 1); /* MJD */
9730         break;
9731     case '$':
9732         nextchar(pRExC_state);
9733         if (*RExC_parse)
9734             RExC_seen_zerolen++;
9735         if (RExC_flags & RXf_PMf_MULTILINE)
9736             ret = reg_node(pRExC_state, MEOL);
9737         else if (RExC_flags & RXf_PMf_SINGLELINE)
9738             ret = reg_node(pRExC_state, SEOL);
9739         else
9740             ret = reg_node(pRExC_state, EOL);
9741         Set_Node_Length(ret, 1); /* MJD */
9742         break;
9743     case '.':
9744         nextchar(pRExC_state);
9745         if (RExC_flags & RXf_PMf_SINGLELINE)
9746             ret = reg_node(pRExC_state, SANY);
9747         else
9748             ret = reg_node(pRExC_state, REG_ANY);
9749         *flagp |= HASWIDTH|SIMPLE;
9750         RExC_naughty++;
9751         Set_Node_Length(ret, 1); /* MJD */
9752         break;
9753     case '[':
9754     {
9755         char * const oregcomp_parse = ++RExC_parse;
9756         ret = regclass(pRExC_state,depth+1);
9757         if (*RExC_parse != ']') {
9758             RExC_parse = oregcomp_parse;
9759             vFAIL("Unmatched [");
9760         }
9761         nextchar(pRExC_state);
9762         *flagp |= HASWIDTH|SIMPLE;
9763         Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
9764         break;
9765     }
9766     case '(':
9767         nextchar(pRExC_state);
9768         ret = reg(pRExC_state, 1, &flags,depth+1);
9769         if (ret == NULL) {
9770                 if (flags & TRYAGAIN) {
9771                     if (RExC_parse == RExC_end) {
9772                          /* Make parent create an empty node if needed. */
9773                         *flagp |= TRYAGAIN;
9774                         return(NULL);
9775                     }
9776                     goto tryagain;
9777                 }
9778                 return(NULL);
9779         }
9780         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
9781         break;
9782     case '|':
9783     case ')':
9784         if (flags & TRYAGAIN) {
9785             *flagp |= TRYAGAIN;
9786             return NULL;
9787         }
9788         vFAIL("Internal urp");
9789                                 /* Supposed to be caught earlier. */
9790         break;
9791     case '?':
9792     case '+':
9793     case '*':
9794         RExC_parse++;
9795         vFAIL("Quantifier follows nothing");
9796         break;
9797     case '\\':
9798         /* Special Escapes
9799
9800            This switch handles escape sequences that resolve to some kind
9801            of special regop and not to literal text. Escape sequnces that
9802            resolve to literal text are handled below in the switch marked
9803            "Literal Escapes".
9804
9805            Every entry in this switch *must* have a corresponding entry
9806            in the literal escape switch. However, the opposite is not
9807            required, as the default for this switch is to jump to the
9808            literal text handling code.
9809         */
9810         switch ((U8)*++RExC_parse) {
9811         /* Special Escapes */
9812         case 'A':
9813             RExC_seen_zerolen++;
9814             ret = reg_node(pRExC_state, SBOL);
9815             *flagp |= SIMPLE;
9816             goto finish_meta_pat;
9817         case 'G':
9818             ret = reg_node(pRExC_state, GPOS);
9819             RExC_seen |= REG_SEEN_GPOS;
9820             *flagp |= SIMPLE;
9821             goto finish_meta_pat;
9822         case 'K':
9823             RExC_seen_zerolen++;
9824             ret = reg_node(pRExC_state, KEEPS);
9825             *flagp |= SIMPLE;
9826             /* XXX:dmq : disabling in-place substitution seems to
9827              * be necessary here to avoid cases of memory corruption, as
9828              * with: C<$_="x" x 80; s/x\K/y/> -- rgs
9829              */
9830             RExC_seen |= REG_SEEN_LOOKBEHIND;
9831             goto finish_meta_pat;
9832         case 'Z':
9833             ret = reg_node(pRExC_state, SEOL);
9834             *flagp |= SIMPLE;
9835             RExC_seen_zerolen++;                /* Do not optimize RE away */
9836             goto finish_meta_pat;
9837         case 'z':
9838             ret = reg_node(pRExC_state, EOS);
9839             *flagp |= SIMPLE;
9840             RExC_seen_zerolen++;                /* Do not optimize RE away */
9841             goto finish_meta_pat;
9842         case 'C':
9843             ret = reg_node(pRExC_state, CANY);
9844             RExC_seen |= REG_SEEN_CANY;
9845             *flagp |= HASWIDTH|SIMPLE;
9846             goto finish_meta_pat;
9847         case 'X':
9848             ret = reg_node(pRExC_state, CLUMP);
9849             *flagp |= HASWIDTH;
9850             goto finish_meta_pat;
9851         case 'w':
9852             switch (get_regex_charset(RExC_flags)) {
9853                 case REGEX_LOCALE_CHARSET:
9854                     op = ALNUML;
9855                     break;
9856                 case REGEX_UNICODE_CHARSET:
9857                     op = ALNUMU;
9858                     break;
9859                 case REGEX_ASCII_RESTRICTED_CHARSET:
9860                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9861                     op = ALNUMA;
9862                     break;
9863                 case REGEX_DEPENDS_CHARSET:
9864                     op = ALNUM;
9865                     break;
9866                 default:
9867                     goto bad_charset;
9868             }
9869             ret = reg_node(pRExC_state, op);
9870             *flagp |= HASWIDTH|SIMPLE;
9871             goto finish_meta_pat;
9872         case 'W':
9873             switch (get_regex_charset(RExC_flags)) {
9874                 case REGEX_LOCALE_CHARSET:
9875                     op = NALNUML;
9876                     break;
9877                 case REGEX_UNICODE_CHARSET:
9878                     op = NALNUMU;
9879                     break;
9880                 case REGEX_ASCII_RESTRICTED_CHARSET:
9881                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9882                     op = NALNUMA;
9883                     break;
9884                 case REGEX_DEPENDS_CHARSET:
9885                     op = NALNUM;
9886                     break;
9887                 default:
9888                     goto bad_charset;
9889             }
9890             ret = reg_node(pRExC_state, op);
9891             *flagp |= HASWIDTH|SIMPLE;
9892             goto finish_meta_pat;
9893         case 'b':
9894             RExC_seen_zerolen++;
9895             RExC_seen |= REG_SEEN_LOOKBEHIND;
9896             switch (get_regex_charset(RExC_flags)) {
9897                 case REGEX_LOCALE_CHARSET:
9898                     op = BOUNDL;
9899                     break;
9900                 case REGEX_UNICODE_CHARSET:
9901                     op = BOUNDU;
9902                     break;
9903                 case REGEX_ASCII_RESTRICTED_CHARSET:
9904                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9905                     op = BOUNDA;
9906                     break;
9907                 case REGEX_DEPENDS_CHARSET:
9908                     op = BOUND;
9909                     break;
9910                 default:
9911                     goto bad_charset;
9912             }
9913             ret = reg_node(pRExC_state, op);
9914             FLAGS(ret) = get_regex_charset(RExC_flags);
9915             *flagp |= SIMPLE;
9916             goto finish_meta_pat;
9917         case 'B':
9918             RExC_seen_zerolen++;
9919             RExC_seen |= REG_SEEN_LOOKBEHIND;
9920             switch (get_regex_charset(RExC_flags)) {
9921                 case REGEX_LOCALE_CHARSET:
9922                     op = NBOUNDL;
9923                     break;
9924                 case REGEX_UNICODE_CHARSET:
9925                     op = NBOUNDU;
9926                     break;
9927                 case REGEX_ASCII_RESTRICTED_CHARSET:
9928                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9929                     op = NBOUNDA;
9930                     break;
9931                 case REGEX_DEPENDS_CHARSET:
9932                     op = NBOUND;
9933                     break;
9934                 default:
9935                     goto bad_charset;
9936             }
9937             ret = reg_node(pRExC_state, op);
9938             FLAGS(ret) = get_regex_charset(RExC_flags);
9939             *flagp |= SIMPLE;
9940             goto finish_meta_pat;
9941         case 's':
9942             switch (get_regex_charset(RExC_flags)) {
9943                 case REGEX_LOCALE_CHARSET:
9944                     op = SPACEL;
9945                     break;
9946                 case REGEX_UNICODE_CHARSET:
9947                     op = SPACEU;
9948                     break;
9949                 case REGEX_ASCII_RESTRICTED_CHARSET:
9950                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9951                     op = SPACEA;
9952                     break;
9953                 case REGEX_DEPENDS_CHARSET:
9954                     op = SPACE;
9955                     break;
9956                 default:
9957                     goto bad_charset;
9958             }
9959             ret = reg_node(pRExC_state, op);
9960             *flagp |= HASWIDTH|SIMPLE;
9961             goto finish_meta_pat;
9962         case 'S':
9963             switch (get_regex_charset(RExC_flags)) {
9964                 case REGEX_LOCALE_CHARSET:
9965                     op = NSPACEL;
9966                     break;
9967                 case REGEX_UNICODE_CHARSET:
9968                     op = NSPACEU;
9969                     break;
9970                 case REGEX_ASCII_RESTRICTED_CHARSET:
9971                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9972                     op = NSPACEA;
9973                     break;
9974                 case REGEX_DEPENDS_CHARSET:
9975                     op = NSPACE;
9976                     break;
9977                 default:
9978                     goto bad_charset;
9979             }
9980             ret = reg_node(pRExC_state, op);
9981             *flagp |= HASWIDTH|SIMPLE;
9982             goto finish_meta_pat;
9983         case 'd':
9984             switch (get_regex_charset(RExC_flags)) {
9985                 case REGEX_LOCALE_CHARSET:
9986                     op = DIGITL;
9987                     break;
9988                 case REGEX_ASCII_RESTRICTED_CHARSET:
9989                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9990                     op = DIGITA;
9991                     break;
9992                 case REGEX_DEPENDS_CHARSET: /* No difference between these */
9993                 case REGEX_UNICODE_CHARSET:
9994                     op = DIGIT;
9995                     break;
9996                 default:
9997                     goto bad_charset;
9998             }
9999             ret = reg_node(pRExC_state, op);
10000             *flagp |= HASWIDTH|SIMPLE;
10001             goto finish_meta_pat;
10002         case 'D':
10003             switch (get_regex_charset(RExC_flags)) {
10004                 case REGEX_LOCALE_CHARSET:
10005                     op = NDIGITL;
10006                     break;
10007                 case REGEX_ASCII_RESTRICTED_CHARSET:
10008                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
10009                     op = NDIGITA;
10010                     break;
10011                 case REGEX_DEPENDS_CHARSET: /* No difference between these */
10012                 case REGEX_UNICODE_CHARSET:
10013                     op = NDIGIT;
10014                     break;
10015                 default:
10016                     goto bad_charset;
10017             }
10018             ret = reg_node(pRExC_state, op);
10019             *flagp |= HASWIDTH|SIMPLE;
10020             goto finish_meta_pat;
10021         case 'R':
10022             ret = reg_node(pRExC_state, LNBREAK);
10023             *flagp |= HASWIDTH|SIMPLE;
10024             goto finish_meta_pat;
10025         case 'h':
10026             ret = reg_node(pRExC_state, HORIZWS);
10027             *flagp |= HASWIDTH|SIMPLE;
10028             goto finish_meta_pat;
10029         case 'H':
10030             ret = reg_node(pRExC_state, NHORIZWS);
10031             *flagp |= HASWIDTH|SIMPLE;
10032             goto finish_meta_pat;
10033         case 'v':
10034             ret = reg_node(pRExC_state, VERTWS);
10035             *flagp |= HASWIDTH|SIMPLE;
10036             goto finish_meta_pat;
10037         case 'V':
10038             ret = reg_node(pRExC_state, NVERTWS);
10039             *flagp |= HASWIDTH|SIMPLE;
10040          finish_meta_pat:           
10041             nextchar(pRExC_state);
10042             Set_Node_Length(ret, 2); /* MJD */
10043             break;          
10044         case 'p':
10045         case 'P':
10046             {
10047                 char* const oldregxend = RExC_end;
10048 #ifdef DEBUGGING
10049                 char* parse_start = RExC_parse - 2;
10050 #endif
10051
10052                 if (RExC_parse[1] == '{') {
10053                   /* a lovely hack--pretend we saw [\pX] instead */
10054                     RExC_end = strchr(RExC_parse, '}');
10055                     if (!RExC_end) {
10056                         const U8 c = (U8)*RExC_parse;
10057                         RExC_parse += 2;
10058                         RExC_end = oldregxend;
10059                         vFAIL2("Missing right brace on \\%c{}", c);
10060                     }
10061                     RExC_end++;
10062                 }
10063                 else {
10064                     RExC_end = RExC_parse + 2;
10065                     if (RExC_end > oldregxend)
10066                         RExC_end = oldregxend;
10067                 }
10068                 RExC_parse--;
10069
10070                 ret = regclass(pRExC_state,depth+1);
10071
10072                 RExC_end = oldregxend;
10073                 RExC_parse--;
10074
10075                 Set_Node_Offset(ret, parse_start + 2);
10076                 Set_Node_Cur_Length(ret);
10077                 nextchar(pRExC_state);
10078                 *flagp |= HASWIDTH|SIMPLE;
10079             }
10080             break;
10081         case 'N': 
10082             /* Handle \N and \N{NAME} here and not below because it can be
10083             multicharacter. join_exact() will join them up later on. 
10084             Also this makes sure that things like /\N{BLAH}+/ and 
10085             \N{BLAH} being multi char Just Happen. dmq*/
10086             ++RExC_parse;
10087             ret= reg_namedseq(pRExC_state, NULL, flagp, depth);
10088             break;
10089         case 'k':    /* Handle \k<NAME> and \k'NAME' */
10090         parse_named_seq:
10091         {   
10092             char ch= RExC_parse[1];         
10093             if (ch != '<' && ch != '\'' && ch != '{') {
10094                 RExC_parse++;
10095                 vFAIL2("Sequence %.2s... not terminated",parse_start);
10096             } else {
10097                 /* this pretty much dupes the code for (?P=...) in reg(), if
10098                    you change this make sure you change that */
10099                 char* name_start = (RExC_parse += 2);
10100                 U32 num = 0;
10101                 SV *sv_dat = reg_scan_name(pRExC_state,
10102                     SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
10103                 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
10104                 if (RExC_parse == name_start || *RExC_parse != ch)
10105                     vFAIL2("Sequence %.3s... not terminated",parse_start);
10106
10107                 if (!SIZE_ONLY) {
10108                     num = add_data( pRExC_state, 1, "S" );
10109                     RExC_rxi->data->data[num]=(void*)sv_dat;
10110                     SvREFCNT_inc_simple_void(sv_dat);
10111                 }
10112
10113                 RExC_sawback = 1;
10114                 ret = reganode(pRExC_state,
10115                                ((! FOLD)
10116                                  ? NREF
10117                                  : (MORE_ASCII_RESTRICTED)
10118                                    ? NREFFA
10119                                    : (AT_LEAST_UNI_SEMANTICS)
10120                                      ? NREFFU
10121                                      : (LOC)
10122                                        ? NREFFL
10123                                        : NREFF),
10124                                 num);
10125                 *flagp |= HASWIDTH;
10126
10127                 /* override incorrect value set in reganode MJD */
10128                 Set_Node_Offset(ret, parse_start+1);
10129                 Set_Node_Cur_Length(ret); /* MJD */
10130                 nextchar(pRExC_state);
10131
10132             }
10133             break;
10134         }
10135         case 'g': 
10136         case '1': case '2': case '3': case '4':
10137         case '5': case '6': case '7': case '8': case '9':
10138             {
10139                 I32 num;
10140                 bool isg = *RExC_parse == 'g';
10141                 bool isrel = 0; 
10142                 bool hasbrace = 0;
10143                 if (isg) {
10144                     RExC_parse++;
10145                     if (*RExC_parse == '{') {
10146                         RExC_parse++;
10147                         hasbrace = 1;
10148                     }
10149                     if (*RExC_parse == '-') {
10150                         RExC_parse++;
10151                         isrel = 1;
10152                     }
10153                     if (hasbrace && !isDIGIT(*RExC_parse)) {
10154                         if (isrel) RExC_parse--;
10155                         RExC_parse -= 2;                            
10156                         goto parse_named_seq;
10157                 }   }
10158                 num = atoi(RExC_parse);
10159                 if (isg && num == 0)
10160                     vFAIL("Reference to invalid group 0");
10161                 if (isrel) {
10162                     num = RExC_npar - num;
10163                     if (num < 1)
10164                         vFAIL("Reference to nonexistent or unclosed group");
10165                 }
10166                 if (!isg && num > 9 && num >= RExC_npar)
10167                     goto defchar;
10168                 else {
10169                     char * const parse_start = RExC_parse - 1; /* MJD */
10170                     while (isDIGIT(*RExC_parse))
10171                         RExC_parse++;
10172                     if (parse_start == RExC_parse - 1) 
10173                         vFAIL("Unterminated \\g... pattern");
10174                     if (hasbrace) {
10175                         if (*RExC_parse != '}') 
10176                             vFAIL("Unterminated \\g{...} pattern");
10177                         RExC_parse++;
10178                     }    
10179                     if (!SIZE_ONLY) {
10180                         if (num > (I32)RExC_rx->nparens)
10181                             vFAIL("Reference to nonexistent group");
10182                     }
10183                     RExC_sawback = 1;
10184                     ret = reganode(pRExC_state,
10185                                    ((! FOLD)
10186                                      ? REF
10187                                      : (MORE_ASCII_RESTRICTED)
10188                                        ? REFFA
10189                                        : (AT_LEAST_UNI_SEMANTICS)
10190                                          ? REFFU
10191                                          : (LOC)
10192                                            ? REFFL
10193                                            : REFF),
10194                                     num);
10195                     *flagp |= HASWIDTH;
10196
10197                     /* override incorrect value set in reganode MJD */
10198                     Set_Node_Offset(ret, parse_start+1);
10199                     Set_Node_Cur_Length(ret); /* MJD */
10200                     RExC_parse--;
10201                     nextchar(pRExC_state);
10202                 }
10203             }
10204             break;
10205         case '\0':
10206             if (RExC_parse >= RExC_end)
10207                 FAIL("Trailing \\");
10208             /* FALL THROUGH */
10209         default:
10210             /* Do not generate "unrecognized" warnings here, we fall
10211                back into the quick-grab loop below */
10212             parse_start--;
10213             goto defchar;
10214         }
10215         break;
10216
10217     case '#':
10218         if (RExC_flags & RXf_PMf_EXTENDED) {
10219             if ( reg_skipcomment( pRExC_state ) )
10220                 goto tryagain;
10221         }
10222         /* FALL THROUGH */
10223
10224     default:
10225
10226             parse_start = RExC_parse - 1;
10227
10228             RExC_parse++;
10229
10230         defchar: {
10231             register STRLEN len;
10232             register UV ender;
10233             register char *p;
10234             char *s;
10235             STRLEN foldlen;
10236             U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
10237             U8 node_type;
10238
10239             /* Is this a LATIN LOWER CASE SHARP S in an EXACTFU node?  If so,
10240              * it is folded to 'ss' even if not utf8 */
10241             bool is_exactfu_sharp_s;
10242
10243             ender = 0;
10244             node_type = ((! FOLD) ? EXACT
10245                         : (LOC)
10246                           ? EXACTFL
10247                           : (MORE_ASCII_RESTRICTED)
10248                             ? EXACTFA
10249                             : (AT_LEAST_UNI_SEMANTICS)
10250                               ? EXACTFU
10251                               : EXACTF);
10252             ret = reg_node(pRExC_state, node_type);
10253             s = STRING(ret);
10254
10255             /* XXX The node can hold up to 255 bytes, yet this only goes to
10256              * 127.  I (khw) do not know why.  Keeping it somewhat less than
10257              * 255 allows us to not have to worry about overflow due to
10258              * converting to utf8 and fold expansion, but that value is
10259              * 255-UTF8_MAXBYTES_CASE.  join_exact() may join adjacent nodes
10260              * split up by this limit into a single one using the real max of
10261              * 255.  Even at 127, this breaks under rare circumstances.  If
10262              * folding, we do not want to split a node at a character that is a
10263              * non-final in a multi-char fold, as an input string could just
10264              * happen to want to match across the node boundary.  The join
10265              * would solve that problem if the join actually happens.  But a
10266              * series of more than two nodes in a row each of 127 would cause
10267              * the first join to succeed to get to 254, but then there wouldn't
10268              * be room for the next one, which could at be one of those split
10269              * multi-char folds.  I don't know of any fool-proof solution.  One
10270              * could back off to end with only a code point that isn't such a
10271              * non-final, but it is possible for there not to be any in the
10272              * entire node. */
10273             for (len = 0, p = RExC_parse - 1;
10274                  len < 127 && p < RExC_end;
10275                  len++)
10276             {
10277                 char * const oldp = p;
10278
10279                 if (RExC_flags & RXf_PMf_EXTENDED)
10280                     p = regwhite( pRExC_state, p );
10281                 switch ((U8)*p) {
10282                 case '^':
10283                 case '$':
10284                 case '.':
10285                 case '[':
10286                 case '(':
10287                 case ')':
10288                 case '|':
10289                     goto loopdone;
10290                 case '\\':
10291                     /* Literal Escapes Switch
10292
10293                        This switch is meant to handle escape sequences that
10294                        resolve to a literal character.
10295
10296                        Every escape sequence that represents something
10297                        else, like an assertion or a char class, is handled
10298                        in the switch marked 'Special Escapes' above in this
10299                        routine, but also has an entry here as anything that
10300                        isn't explicitly mentioned here will be treated as
10301                        an unescaped equivalent literal.
10302                     */
10303
10304                     switch ((U8)*++p) {
10305                     /* These are all the special escapes. */
10306                     case 'A':             /* Start assertion */
10307                     case 'b': case 'B':   /* Word-boundary assertion*/
10308                     case 'C':             /* Single char !DANGEROUS! */
10309                     case 'd': case 'D':   /* digit class */
10310                     case 'g': case 'G':   /* generic-backref, pos assertion */
10311                     case 'h': case 'H':   /* HORIZWS */
10312                     case 'k': case 'K':   /* named backref, keep marker */
10313                     case 'N':             /* named char sequence */
10314                     case 'p': case 'P':   /* Unicode property */
10315                               case 'R':   /* LNBREAK */
10316                     case 's': case 'S':   /* space class */
10317                     case 'v': case 'V':   /* VERTWS */
10318                     case 'w': case 'W':   /* word class */
10319                     case 'X':             /* eXtended Unicode "combining character sequence" */
10320                     case 'z': case 'Z':   /* End of line/string assertion */
10321                         --p;
10322                         goto loopdone;
10323
10324                     /* Anything after here is an escape that resolves to a
10325                        literal. (Except digits, which may or may not)
10326                      */
10327                     case 'n':
10328                         ender = '\n';
10329                         p++;
10330                         break;
10331                     case 'r':
10332                         ender = '\r';
10333                         p++;
10334                         break;
10335                     case 't':
10336                         ender = '\t';
10337                         p++;
10338                         break;
10339                     case 'f':
10340                         ender = '\f';
10341                         p++;
10342                         break;
10343                     case 'e':
10344                           ender = ASCII_TO_NATIVE('\033');
10345                         p++;
10346                         break;
10347                     case 'a':
10348                           ender = ASCII_TO_NATIVE('\007');
10349                         p++;
10350                         break;
10351                     case 'o':
10352                         {
10353                             STRLEN brace_len = len;
10354                             UV result;
10355                             const char* error_msg;
10356
10357                             bool valid = grok_bslash_o(p,
10358                                                        &result,
10359                                                        &brace_len,
10360                                                        &error_msg,
10361                                                        1);
10362                             p += brace_len;
10363                             if (! valid) {
10364                                 RExC_parse = p; /* going to die anyway; point
10365                                                    to exact spot of failure */
10366                                 vFAIL(error_msg);
10367                             }
10368                             else
10369                             {
10370                                 ender = result;
10371                             }
10372                             if (PL_encoding && ender < 0x100) {
10373                                 goto recode_encoding;
10374                             }
10375                             if (ender > 0xff) {
10376                                 REQUIRE_UTF8;
10377                             }
10378                             break;
10379                         }
10380                     case 'x':
10381                         if (*++p == '{') {
10382                             char* const e = strchr(p, '}');
10383
10384                             if (!e) {
10385                                 RExC_parse = p + 1;
10386                                 vFAIL("Missing right brace on \\x{}");
10387                             }
10388                             else {
10389                                 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
10390                                     | PERL_SCAN_DISALLOW_PREFIX;
10391                                 STRLEN numlen = e - p - 1;
10392                                 ender = grok_hex(p + 1, &numlen, &flags, NULL);
10393                                 if (ender > 0xff)
10394                                     REQUIRE_UTF8;
10395                                 p = e + 1;
10396                             }
10397                         }
10398                         else {
10399                             I32 flags = PERL_SCAN_DISALLOW_PREFIX;
10400                             STRLEN numlen = 2;
10401                             ender = grok_hex(p, &numlen, &flags, NULL);
10402                             p += numlen;
10403                         }
10404                         if (PL_encoding && ender < 0x100)
10405                             goto recode_encoding;
10406                         break;
10407                     case 'c':
10408                         p++;
10409                         ender = grok_bslash_c(*p++, UTF, SIZE_ONLY);
10410                         break;
10411                     case '0': case '1': case '2': case '3':case '4':
10412                     case '5': case '6': case '7': case '8':case '9':
10413                         if (*p == '0' ||
10414                             (isDIGIT(p[1]) && atoi(p) >= RExC_npar))
10415                         {
10416                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
10417                             STRLEN numlen = 3;
10418                             ender = grok_oct(p, &numlen, &flags, NULL);
10419                             if (ender > 0xff) {
10420                                 REQUIRE_UTF8;
10421                             }
10422                             p += numlen;
10423                         }
10424                         else {
10425                             --p;
10426                             goto loopdone;
10427                         }
10428                         if (PL_encoding && ender < 0x100)
10429                             goto recode_encoding;
10430                         break;
10431                     recode_encoding:
10432                         if (! RExC_override_recoding) {
10433                             SV* enc = PL_encoding;
10434                             ender = reg_recode((const char)(U8)ender, &enc);
10435                             if (!enc && SIZE_ONLY)
10436                                 ckWARNreg(p, "Invalid escape in the specified encoding");
10437                             REQUIRE_UTF8;
10438                         }
10439                         break;
10440                     case '\0':
10441                         if (p >= RExC_end)
10442                             FAIL("Trailing \\");
10443                         /* FALL THROUGH */
10444                     default:
10445                         if (!SIZE_ONLY&& isALPHA(*p)) {
10446                             ckWARN2reg(p + 1, "Unrecognized escape \\%.1s passed through", p);
10447                         }
10448                         goto normal_default;
10449                     }
10450                     break;
10451                 case '{':
10452                     /* Currently we don't warn when the lbrace is at the start
10453                      * of a construct.  This catches it in the middle of a
10454                      * literal string, or when its the first thing after
10455                      * something like "\b" */
10456                     if (! SIZE_ONLY
10457                         && (len || (p > RExC_start && isALPHA_A(*(p -1)))))
10458                     {
10459                         ckWARNregdep(p + 1, "Unescaped left brace in regex is deprecated, passed through");
10460                     }
10461                     /*FALLTHROUGH*/
10462                 default:
10463                   normal_default:
10464                     if (UTF8_IS_START(*p) && UTF) {
10465                         STRLEN numlen;
10466                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
10467                                                &numlen, UTF8_ALLOW_DEFAULT);
10468                         p += numlen;
10469                     }
10470                     else
10471                         ender = (U8) *p++;
10472                     break;
10473                 } /* End of switch on the literal */
10474
10475                 is_exactfu_sharp_s = (node_type == EXACTFU
10476                                       && ender == LATIN_SMALL_LETTER_SHARP_S);
10477                 if ( RExC_flags & RXf_PMf_EXTENDED)
10478                     p = regwhite( pRExC_state, p );
10479                 if ((UTF && FOLD) || is_exactfu_sharp_s) {
10480                     /* Prime the casefolded buffer.  Locale rules, which apply
10481                      * only to code points < 256, aren't known until execution,
10482                      * so for them, just output the original character using
10483                      * utf8.  If we start to fold non-UTF patterns, be sure to
10484                      * update join_exact() */
10485                     if (LOC && ender < 256) {
10486                         if (UNI_IS_INVARIANT(ender)) {
10487                             *tmpbuf = (U8) ender;
10488                             foldlen = 1;
10489                         } else {
10490                             *tmpbuf = UTF8_TWO_BYTE_HI(ender);
10491                             *(tmpbuf + 1) = UTF8_TWO_BYTE_LO(ender);
10492                             foldlen = 2;
10493                         }
10494                     }
10495                     else if (isASCII(ender)) {  /* Note: Here can't also be LOC
10496                                                  */
10497                         ender = toLOWER(ender);
10498                         *tmpbuf = (U8) ender;
10499                         foldlen = 1;
10500                     }
10501                     else if (! MORE_ASCII_RESTRICTED && ! LOC) {
10502
10503                         /* Locale and /aa require more selectivity about the
10504                          * fold, so are handled below.  Otherwise, here, just
10505                          * use the fold */
10506                         ender = toFOLD_uni(ender, tmpbuf, &foldlen);
10507                     }
10508                     else {
10509                         /* Under locale rules or /aa we are not to mix,
10510                          * respectively, ords < 256 or ASCII with non-.  So
10511                          * reject folds that mix them, using only the
10512                          * non-folded code point.  So do the fold to a
10513                          * temporary, and inspect each character in it. */
10514                         U8 trialbuf[UTF8_MAXBYTES_CASE+1];
10515                         U8* s = trialbuf;
10516                         UV tmpender = toFOLD_uni(ender, trialbuf, &foldlen);
10517                         U8* e = s + foldlen;
10518                         bool fold_ok = TRUE;
10519
10520                         while (s < e) {
10521                             if (isASCII(*s)
10522                                 || (LOC && (UTF8_IS_INVARIANT(*s)
10523                                            || UTF8_IS_DOWNGRADEABLE_START(*s))))
10524                             {
10525                                 fold_ok = FALSE;
10526                                 break;
10527                             }
10528                             s += UTF8SKIP(s);
10529                         }
10530                         if (fold_ok) {
10531                             Copy(trialbuf, tmpbuf, foldlen, U8);
10532                             ender = tmpender;
10533                         }
10534                         else {
10535                             uvuni_to_utf8(tmpbuf, ender);
10536                             foldlen = UNISKIP(ender);
10537                         }
10538                     }
10539                 }
10540                 if (p < RExC_end && ISMULT2(p)) { /* Back off on ?+*. */
10541                     if (len)
10542                         p = oldp;
10543                     else if (UTF || is_exactfu_sharp_s) {
10544                          if (FOLD) {
10545                               /* Emit all the Unicode characters. */
10546                               STRLEN numlen;
10547                               for (foldbuf = tmpbuf;
10548                                    foldlen;
10549                                    foldlen -= numlen) {
10550
10551                                    /* tmpbuf has been constructed by us, so we
10552                                     * know it is valid utf8 */
10553                                    ender = valid_utf8_to_uvchr(foldbuf, &numlen);
10554                                    if (numlen > 0) {
10555                                         const STRLEN unilen = reguni(pRExC_state, ender, s);
10556                                         s       += unilen;
10557                                         len     += unilen;
10558                                         /* In EBCDIC the numlen
10559                                          * and unilen can differ. */
10560                                         foldbuf += numlen;
10561                                         if (numlen >= foldlen)
10562                                              break;
10563                                    }
10564                                    else
10565                                         break; /* "Can't happen." */
10566                               }
10567                          }
10568                          else {
10569                               const STRLEN unilen = reguni(pRExC_state, ender, s);
10570                               if (unilen > 0) {
10571                                    s   += unilen;
10572                                    len += unilen;
10573                               }
10574                          }
10575                     }
10576                     else {
10577                         len++;
10578                         REGC((char)ender, s++);
10579                     }
10580                     break;
10581                 }
10582                 if (UTF || is_exactfu_sharp_s) {
10583                      if (FOLD) {
10584                           /* Emit all the Unicode characters. */
10585                           STRLEN numlen;
10586                           for (foldbuf = tmpbuf;
10587                                foldlen;
10588                                foldlen -= numlen) {
10589                                ender = valid_utf8_to_uvchr(foldbuf, &numlen);
10590                                if (numlen > 0) {
10591                                     const STRLEN unilen = reguni(pRExC_state, ender, s);
10592                                     len     += unilen;
10593                                     s       += unilen;
10594                                     /* In EBCDIC the numlen
10595                                      * and unilen can differ. */
10596                                     foldbuf += numlen;
10597                                     if (numlen >= foldlen)
10598                                          break;
10599                                }
10600                                else
10601                                     break;
10602                           }
10603                      }
10604                      else {
10605                           const STRLEN unilen = reguni(pRExC_state, ender, s);
10606                           if (unilen > 0) {
10607                                s   += unilen;
10608                                len += unilen;
10609                           }
10610                      }
10611                      len--;
10612                 }
10613                 else {
10614                     REGC((char)ender, s++);
10615                 }
10616             }
10617         loopdone:   /* Jumped to when encounters something that shouldn't be in
10618                        the node */
10619             RExC_parse = p - 1;
10620             Set_Node_Cur_Length(ret); /* MJD */
10621             nextchar(pRExC_state);
10622             {
10623                 /* len is STRLEN which is unsigned, need to copy to signed */
10624                 IV iv = len;
10625                 if (iv < 0)
10626                     vFAIL("Internal disaster");
10627             }
10628             if (len > 0)
10629                 *flagp |= HASWIDTH;
10630             if (len == 1 && UNI_IS_INVARIANT(ender))
10631                 *flagp |= SIMPLE;
10632
10633             if (SIZE_ONLY)
10634                 RExC_size += STR_SZ(len);
10635             else {
10636                 STR_LEN(ret) = len;
10637                 RExC_emit += STR_SZ(len);
10638             }
10639         }
10640         break;
10641     }
10642
10643     return(ret);
10644
10645 /* Jumped to when an unrecognized character set is encountered */
10646 bad_charset:
10647     Perl_croak(aTHX_ "panic: Unknown regex character set encoding: %u", get_regex_charset(RExC_flags));
10648     return(NULL);
10649 }
10650
10651 STATIC char *
10652 S_regwhite( RExC_state_t *pRExC_state, char *p )
10653 {
10654     const char *e = RExC_end;
10655
10656     PERL_ARGS_ASSERT_REGWHITE;
10657
10658     while (p < e) {
10659         if (isSPACE(*p))
10660             ++p;
10661         else if (*p == '#') {
10662             bool ended = 0;
10663             do {
10664                 if (*p++ == '\n') {
10665                     ended = 1;
10666                     break;
10667                 }
10668             } while (p < e);
10669             if (!ended)
10670                 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
10671         }
10672         else
10673             break;
10674     }
10675     return p;
10676 }
10677
10678 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
10679    Character classes ([:foo:]) can also be negated ([:^foo:]).
10680    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
10681    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
10682    but trigger failures because they are currently unimplemented. */
10683
10684 #define POSIXCC_DONE(c)   ((c) == ':')
10685 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
10686 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
10687
10688 STATIC I32
10689 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
10690 {
10691     dVAR;
10692     I32 namedclass = OOB_NAMEDCLASS;
10693
10694     PERL_ARGS_ASSERT_REGPPOSIXCC;
10695
10696     if (value == '[' && RExC_parse + 1 < RExC_end &&
10697         /* I smell either [: or [= or [. -- POSIX has been here, right? */
10698         POSIXCC(UCHARAT(RExC_parse))) {
10699         const char c = UCHARAT(RExC_parse);
10700         char* const s = RExC_parse++;
10701
10702         while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
10703             RExC_parse++;
10704         if (RExC_parse == RExC_end)
10705             /* Grandfather lone [:, [=, [. */
10706             RExC_parse = s;
10707         else {
10708             const char* const t = RExC_parse++; /* skip over the c */
10709             assert(*t == c);
10710
10711             if (UCHARAT(RExC_parse) == ']') {
10712                 const char *posixcc = s + 1;
10713                 RExC_parse++; /* skip over the ending ] */
10714
10715                 if (*s == ':') {
10716                     const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
10717                     const I32 skip = t - posixcc;
10718
10719                     /* Initially switch on the length of the name.  */
10720                     switch (skip) {
10721                     case 4:
10722                         if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
10723                             namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
10724                         break;
10725                     case 5:
10726                         /* Names all of length 5.  */
10727                         /* alnum alpha ascii blank cntrl digit graph lower
10728                            print punct space upper  */
10729                         /* Offset 4 gives the best switch position.  */
10730                         switch (posixcc[4]) {
10731                         case 'a':
10732                             if (memEQ(posixcc, "alph", 4)) /* alpha */
10733                                 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
10734                             break;
10735                         case 'e':
10736                             if (memEQ(posixcc, "spac", 4)) /* space */
10737                                 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
10738                             break;
10739                         case 'h':
10740                             if (memEQ(posixcc, "grap", 4)) /* graph */
10741                                 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
10742                             break;
10743                         case 'i':
10744                             if (memEQ(posixcc, "asci", 4)) /* ascii */
10745                                 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
10746                             break;
10747                         case 'k':
10748                             if (memEQ(posixcc, "blan", 4)) /* blank */
10749                                 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
10750                             break;
10751                         case 'l':
10752                             if (memEQ(posixcc, "cntr", 4)) /* cntrl */
10753                                 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
10754                             break;
10755                         case 'm':
10756                             if (memEQ(posixcc, "alnu", 4)) /* alnum */
10757                                 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
10758                             break;
10759                         case 'r':
10760                             if (memEQ(posixcc, "lowe", 4)) /* lower */
10761                                 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
10762                             else if (memEQ(posixcc, "uppe", 4)) /* upper */
10763                                 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
10764                             break;
10765                         case 't':
10766                             if (memEQ(posixcc, "digi", 4)) /* digit */
10767                                 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
10768                             else if (memEQ(posixcc, "prin", 4)) /* print */
10769                                 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
10770                             else if (memEQ(posixcc, "punc", 4)) /* punct */
10771                                 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
10772                             break;
10773                         }
10774                         break;
10775                     case 6:
10776                         if (memEQ(posixcc, "xdigit", 6))
10777                             namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
10778                         break;
10779                     }
10780
10781                     if (namedclass == OOB_NAMEDCLASS)
10782                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
10783                                       t - s - 1, s + 1);
10784                     assert (posixcc[skip] == ':');
10785                     assert (posixcc[skip+1] == ']');
10786                 } else if (!SIZE_ONLY) {
10787                     /* [[=foo=]] and [[.foo.]] are still future. */
10788
10789                     /* adjust RExC_parse so the warning shows after
10790                        the class closes */
10791                     while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
10792                         RExC_parse++;
10793                     Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
10794                 }
10795             } else {
10796                 /* Maternal grandfather:
10797                  * "[:" ending in ":" but not in ":]" */
10798                 RExC_parse = s;
10799             }
10800         }
10801     }
10802
10803     return namedclass;
10804 }
10805
10806 STATIC void
10807 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
10808 {
10809     dVAR;
10810
10811     PERL_ARGS_ASSERT_CHECKPOSIXCC;
10812
10813     if (POSIXCC(UCHARAT(RExC_parse))) {
10814         const char *s = RExC_parse;
10815         const char  c = *s++;
10816
10817         while (isALNUM(*s))
10818             s++;
10819         if (*s && c == *s && s[1] == ']') {
10820             ckWARN3reg(s+2,
10821                        "POSIX syntax [%c %c] belongs inside character classes",
10822                        c, c);
10823
10824             /* [[=foo=]] and [[.foo.]] are still future. */
10825             if (POSIXCC_NOTYET(c)) {
10826                 /* adjust RExC_parse so the error shows after
10827                    the class closes */
10828                 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
10829                     NOOP;
10830                 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
10831             }
10832         }
10833     }
10834 }
10835
10836 /* Generate the code to add a full posix character <class> to the bracketed
10837  * character class given by <node>.  (<node> is needed only under locale rules)
10838  * destlist     is the inversion list for non-locale rules that this class is
10839  *              to be added to
10840  * sourcelist   is the ASCII-range inversion list to add under /a rules
10841  * Xsourcelist  is the full Unicode range list to use otherwise. */
10842 #define DO_POSIX(node, class, destlist, sourcelist, Xsourcelist)           \
10843     if (LOC) {                                                             \
10844         SV* scratch_list = NULL;                                           \
10845                                                                            \
10846         /* Set this class in the node for runtime matching */              \
10847         ANYOF_CLASS_SET(node, class);                                      \
10848                                                                            \
10849         /* For above Latin1 code points, we use the full Unicode range */  \
10850         _invlist_intersection(PL_AboveLatin1,                              \
10851                               Xsourcelist,                                 \
10852                               &scratch_list);                              \
10853         /* And set the output to it, adding instead if there already is an \
10854          * output.  Checking if <destlist> is NULL first saves an extra    \
10855          * clone.  Its reference count will be decremented at the next     \
10856          * union, etc, or if this is the only instance, at the end of the  \
10857          * routine */                                                      \
10858         if (! destlist) {                                                  \
10859             destlist = scratch_list;                                       \
10860         }                                                                  \
10861         else {                                                             \
10862             _invlist_union(destlist, scratch_list, &destlist);             \
10863             SvREFCNT_dec(scratch_list);                                    \
10864         }                                                                  \
10865     }                                                                      \
10866     else {                                                                 \
10867         /* For non-locale, just add it to any existing list */             \
10868         _invlist_union(destlist,                                           \
10869                        (AT_LEAST_ASCII_RESTRICTED)                         \
10870                            ? sourcelist                                    \
10871                            : Xsourcelist,                                  \
10872                        &destlist);                                         \
10873     }
10874
10875 /* Like DO_POSIX, but matches the complement of <sourcelist> and <Xsourcelist>.
10876  */
10877 #define DO_N_POSIX(node, class, destlist, sourcelist, Xsourcelist)         \
10878     if (LOC) {                                                             \
10879         SV* scratch_list = NULL;                                           \
10880         ANYOF_CLASS_SET(node, class);                                      \
10881         _invlist_subtract(PL_AboveLatin1, Xsourcelist, &scratch_list);     \
10882         if (! destlist) {                                                  \
10883             destlist = scratch_list;                                       \
10884         }                                                                  \
10885         else {                                                             \
10886             _invlist_union(destlist, scratch_list, &destlist);             \
10887             SvREFCNT_dec(scratch_list);                                    \
10888         }                                                                  \
10889     }                                                                      \
10890     else {                                                                 \
10891         _invlist_union_complement_2nd(destlist,                            \
10892                                     (AT_LEAST_ASCII_RESTRICTED)            \
10893                                         ? sourcelist                       \
10894                                         : Xsourcelist,                     \
10895                                     &destlist);                            \
10896         /* Under /d, everything in the upper half of the Latin1 range      \
10897          * matches this complement */                                      \
10898         if (DEPENDS_SEMANTICS) {                                           \
10899             ANYOF_FLAGS(node) |= ANYOF_NON_UTF8_LATIN1_ALL;                \
10900         }                                                                  \
10901     }
10902
10903 /* Generate the code to add a posix character <class> to the bracketed
10904  * character class given by <node>.  (<node> is needed only under locale rules)
10905  * destlist       is the inversion list for non-locale rules that this class is
10906  *                to be added to
10907  * sourcelist     is the ASCII-range inversion list to add under /a rules
10908  * l1_sourcelist  is the Latin1 range list to use otherwise.
10909  * Xpropertyname  is the name to add to <run_time_list> of the property to
10910  *                specify the code points above Latin1 that will have to be
10911  *                determined at run-time
10912  * run_time_list  is a SV* that contains text names of properties that are to
10913  *                be computed at run time.  This concatenates <Xpropertyname>
10914  *                to it, apppropriately
10915  * This is essentially DO_POSIX, but we know only the Latin1 values at compile
10916  * time */
10917 #define DO_POSIX_LATIN1_ONLY_KNOWN(node, class, destlist, sourcelist,      \
10918                               l1_sourcelist, Xpropertyname, run_time_list) \
10919         /* First, resolve whether to use the ASCII-only list or the L1     \
10920          * list */                                                         \
10921         DO_POSIX_LATIN1_ONLY_KNOWN_L1_RESOLVED(node, class, destlist,      \
10922                 ((AT_LEAST_ASCII_RESTRICTED) ? sourcelist : l1_sourcelist),\
10923                 Xpropertyname, run_time_list)
10924
10925 #define DO_POSIX_LATIN1_ONLY_KNOWN_L1_RESOLVED(node, class, destlist, sourcelist, \
10926                 Xpropertyname, run_time_list)                              \
10927     /* If not /a matching, there are going to be code points we will have  \
10928      * to defer to runtime to look-up */                                   \
10929     if (! AT_LEAST_ASCII_RESTRICTED) {                                     \
10930         Perl_sv_catpvf(aTHX_ run_time_list, "+utf8::%s\n", Xpropertyname); \
10931     }                                                                      \
10932     if (LOC) {                                                             \
10933         ANYOF_CLASS_SET(node, class);                                      \
10934     }                                                                      \
10935     else {                                                                 \
10936         _invlist_union(destlist, sourcelist, &destlist);                   \
10937     }
10938
10939 /* Like DO_POSIX_LATIN1_ONLY_KNOWN, but for the complement.  A combination of
10940  * this and DO_N_POSIX */
10941 #define DO_N_POSIX_LATIN1_ONLY_KNOWN(node, class, destlist, sourcelist,    \
10942                               l1_sourcelist, Xpropertyname, run_time_list) \
10943     if (AT_LEAST_ASCII_RESTRICTED) {                                       \
10944         _invlist_union_complement_2nd(destlist, sourcelist, &destlist);    \
10945     }                                                                      \
10946     else {                                                                 \
10947         Perl_sv_catpvf(aTHX_ run_time_list, "!utf8::%s\n", Xpropertyname); \
10948         if (LOC) {                                                         \
10949             ANYOF_CLASS_SET(node, namedclass);                             \
10950         }                                                                  \
10951         else {                                                             \
10952             SV* scratch_list = NULL;                                       \
10953             _invlist_subtract(PL_Latin1, l1_sourcelist, &scratch_list);    \
10954             if (! destlist) {                                              \
10955                 destlist = scratch_list;                                   \
10956             }                                                              \
10957             else {                                                         \
10958                 _invlist_union(destlist, scratch_list, &destlist);         \
10959                 SvREFCNT_dec(scratch_list);                                \
10960             }                                                              \
10961             if (DEPENDS_SEMANTICS) {                                       \
10962                 ANYOF_FLAGS(node) |= ANYOF_NON_UTF8_LATIN1_ALL;            \
10963             }                                                              \
10964         }                                                                  \
10965     }
10966
10967 STATIC U8
10968 S_set_regclass_bit_fold(pTHX_ RExC_state_t *pRExC_state, regnode* node, const U8 value, SV** invlist_ptr, AV** alternate_ptr)
10969 {
10970
10971     /* Handle the setting of folds in the bitmap for non-locale ANYOF nodes.
10972      * Locale folding is done at run-time, so this function should not be
10973      * called for nodes that are for locales.
10974      *
10975      * This function sets the bit corresponding to the fold of the input
10976      * 'value', if not already set.  The fold of 'f' is 'F', and the fold of
10977      * 'F' is 'f'.
10978      *
10979      * It also knows about the characters that are in the bitmap that have
10980      * folds that are matchable only outside it, and sets the appropriate lists
10981      * and flags.
10982      *
10983      * It returns the number of bits that actually changed from 0 to 1 */
10984
10985     U8 stored = 0;
10986     U8 fold;
10987
10988     PERL_ARGS_ASSERT_SET_REGCLASS_BIT_FOLD;
10989
10990     fold = (AT_LEAST_UNI_SEMANTICS) ? PL_fold_latin1[value]
10991                                     : PL_fold[value];
10992
10993     /* It assumes the bit for 'value' has already been set */
10994     if (fold != value && ! ANYOF_BITMAP_TEST(node, fold)) {
10995         ANYOF_BITMAP_SET(node, fold);
10996         stored++;
10997     }
10998     if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(value) && (! isASCII(value) || ! MORE_ASCII_RESTRICTED)) {
10999         /* Certain Latin1 characters have matches outside the bitmap.  To get
11000          * here, 'value' is one of those characters.   None of these matches is
11001          * valid for ASCII characters under /aa, which have been excluded by
11002          * the 'if' above.  The matches fall into three categories:
11003          * 1) They are singly folded-to or -from an above 255 character, as
11004          *    LATIN SMALL LETTER Y WITH DIAERESIS and LATIN CAPITAL LETTER Y
11005          *    WITH DIAERESIS;
11006          * 2) They are part of a multi-char fold with another character in the
11007          *    bitmap, only LATIN SMALL LETTER SHARP S => "ss" fits that bill;
11008          * 3) They are part of a multi-char fold with a character not in the
11009          *    bitmap, such as various ligatures.
11010          * We aren't dealing fully with multi-char folds, except we do deal
11011          * with the pattern containing a character that has a multi-char fold
11012          * (not so much the inverse).
11013          * For types 1) and 3), the matches only happen when the target string
11014          * is utf8; that's not true for 2), and we set a flag for it.
11015          *
11016          * The code below adds to the passed in inversion list the single fold
11017          * closures for 'value'.  The values are hard-coded here so that an
11018          * innocent-looking character class, like /[ks]/i won't have to go out
11019          * to disk to find the possible matches.  XXX It would be better to
11020          * generate these via regen, in case a new version of the Unicode
11021          * standard adds new mappings, though that is not really likely. */
11022         switch (value) {
11023             case 'k':
11024             case 'K':
11025                 /* KELVIN SIGN */
11026                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr, 0x212A);
11027                 break;
11028             case 's':
11029             case 'S':
11030                 /* LATIN SMALL LETTER LONG S */
11031                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr, 0x017F);
11032                 break;
11033             case MICRO_SIGN:
11034                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
11035                                                  GREEK_SMALL_LETTER_MU);
11036                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
11037                                                  GREEK_CAPITAL_LETTER_MU);
11038                 break;
11039             case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
11040             case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
11041                 /* ANGSTROM SIGN */
11042                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr, 0x212B);
11043                 if (DEPENDS_SEMANTICS) {    /* See DEPENDS comment below */
11044                     *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
11045                                                      PL_fold_latin1[value]);
11046                 }
11047                 break;
11048             case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
11049                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
11050                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
11051                 break;
11052             case LATIN_SMALL_LETTER_SHARP_S:
11053                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
11054                                         LATIN_CAPITAL_LETTER_SHARP_S);
11055
11056                 /* Under /a, /d, and /u, this can match the two chars "ss" */
11057                 if (! MORE_ASCII_RESTRICTED) {
11058                     add_alternate(alternate_ptr, (U8 *) "ss", 2);
11059
11060                     /* And under /u or /a, it can match even if the target is
11061                      * not utf8 */
11062                     if (AT_LEAST_UNI_SEMANTICS) {
11063                         ANYOF_FLAGS(node) |= ANYOF_NONBITMAP_NON_UTF8;
11064                     }
11065                 }
11066                 break;
11067             case 'F': case 'f':
11068             case 'I': case 'i':
11069             case 'L': case 'l':
11070             case 'T': case 't':
11071             case 'A': case 'a':
11072             case 'H': case 'h':
11073             case 'J': case 'j':
11074             case 'N': case 'n':
11075             case 'W': case 'w':
11076             case 'Y': case 'y':
11077                 /* These all are targets of multi-character folds from code
11078                  * points that require UTF8 to express, so they can't match
11079                  * unless the target string is in UTF-8, so no action here is
11080                  * necessary, as regexec.c properly handles the general case
11081                  * for UTF-8 matching */
11082                 break;
11083             default:
11084                 /* Use deprecated warning to increase the chances of this
11085                  * being output */
11086                 ckWARN2regdep(RExC_parse, "Perl folding rules are not up-to-date for 0x%x; please use the perlbug utility to report;", value);
11087                 break;
11088         }
11089     }
11090     else if (DEPENDS_SEMANTICS
11091             && ! isASCII(value)
11092             && PL_fold_latin1[value] != value)
11093     {
11094            /* Under DEPENDS rules, non-ASCII Latin1 characters match their
11095             * folds only when the target string is in UTF-8.  We add the fold
11096             * here to the list of things to match outside the bitmap, which
11097             * won't be looked at unless it is UTF8 (or else if something else
11098             * says to look even if not utf8, but those things better not happen
11099             * under DEPENDS semantics. */
11100         *invlist_ptr = add_cp_to_invlist(*invlist_ptr, PL_fold_latin1[value]);
11101     }
11102
11103     return stored;
11104 }
11105
11106
11107 PERL_STATIC_INLINE U8
11108 S_set_regclass_bit(pTHX_ RExC_state_t *pRExC_state, regnode* node, const U8 value, SV** invlist_ptr, AV** alternate_ptr)
11109 {
11110     /* This inline function sets a bit in the bitmap if not already set, and if
11111      * appropriate, its fold, returning the number of bits that actually
11112      * changed from 0 to 1 */
11113
11114     U8 stored;
11115
11116     PERL_ARGS_ASSERT_SET_REGCLASS_BIT;
11117
11118     if (ANYOF_BITMAP_TEST(node, value)) {   /* Already set */
11119         return 0;
11120     }
11121
11122     ANYOF_BITMAP_SET(node, value);
11123     stored = 1;
11124
11125     if (FOLD && ! LOC) {        /* Locale folds aren't known until runtime */
11126         stored += set_regclass_bit_fold(pRExC_state, node, value, invlist_ptr, alternate_ptr);
11127     }
11128
11129     return stored;
11130 }
11131
11132 STATIC void
11133 S_add_alternate(pTHX_ AV** alternate_ptr, U8* string, STRLEN len)
11134 {
11135     /* Adds input 'string' with length 'len' to the ANYOF node's unicode
11136      * alternate list, pointed to by 'alternate_ptr'.  This is an array of
11137      * the multi-character folds of characters in the node */
11138     SV *sv;
11139
11140     PERL_ARGS_ASSERT_ADD_ALTERNATE;
11141
11142     if (! *alternate_ptr) {
11143         *alternate_ptr = newAV();
11144     }
11145     sv = newSVpvn_utf8((char*)string, len, TRUE);
11146     av_push(*alternate_ptr, sv);
11147     return;
11148 }
11149
11150 /*
11151    parse a class specification and produce either an ANYOF node that
11152    matches the pattern or perhaps will be optimized into an EXACTish node
11153    instead. The node contains a bit map for the first 256 characters, with the
11154    corresponding bit set if that character is in the list.  For characters
11155    above 255, a range list is used */
11156
11157 STATIC regnode *
11158 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
11159 {
11160     dVAR;
11161     register UV nextvalue;
11162     register IV prevvalue = OOB_UNICODE;
11163     register IV range = 0;
11164     UV value = 0; /* XXX:dmq: needs to be referenceable (unfortunately) */
11165     register regnode *ret;
11166     STRLEN numlen;
11167     IV namedclass;
11168     char *rangebegin = NULL;
11169     bool need_class = 0;
11170     bool allow_full_fold = TRUE;   /* Assume wants multi-char folding */
11171     SV *listsv = NULL;
11172     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
11173                                       than just initialized.  */
11174     SV* properties = NULL;    /* Code points that match \p{} \P{} */
11175     UV element_count = 0;   /* Number of distinct elements in the class.
11176                                Optimizations may be possible if this is tiny */
11177     UV n;
11178
11179     /* Unicode properties are stored in a swash; this holds the current one
11180      * being parsed.  If this swash is the only above-latin1 component of the
11181      * character class, an optimization is to pass it directly on to the
11182      * execution engine.  Otherwise, it is set to NULL to indicate that there
11183      * are other things in the class that have to be dealt with at execution
11184      * time */
11185     SV* swash = NULL;           /* Code points that match \p{} \P{} */
11186
11187     /* Set if a component of this character class is user-defined; just passed
11188      * on to the engine */
11189     UV has_user_defined_property = 0;
11190
11191     /* code points this node matches that can't be stored in the bitmap */
11192     SV* nonbitmap = NULL;
11193
11194     /* The items that are to match that aren't stored in the bitmap, but are a
11195      * result of things that are stored there.  This is the fold closure of
11196      * such a character, either because it has DEPENDS semantics and shouldn't
11197      * be matched unless the target string is utf8, or is a code point that is
11198      * too large for the bit map, as for example, the fold of the MICRO SIGN is
11199      * above 255.  This all is solely for performance reasons.  By having this
11200      * code know the outside-the-bitmap folds that the bitmapped characters are
11201      * involved with, we don't have to go out to disk to find the list of
11202      * matches, unless the character class includes code points that aren't
11203      * storable in the bit map.  That means that a character class with an 's'
11204      * in it, for example, doesn't need to go out to disk to find everything
11205      * that matches.  A 2nd list is used so that the 'nonbitmap' list is kept
11206      * empty unless there is something whose fold we don't know about, and will
11207      * have to go out to the disk to find. */
11208     SV* l1_fold_invlist = NULL;
11209
11210     /* List of multi-character folds that are matched by this node */
11211     AV* unicode_alternate  = NULL;
11212 #ifdef EBCDIC
11213     UV literal_endpoint = 0;
11214 #endif
11215     UV stored = 0;  /* how many chars stored in the bitmap */
11216
11217     regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
11218         case we need to change the emitted regop to an EXACT. */
11219     const char * orig_parse = RExC_parse;
11220     GET_RE_DEBUG_FLAGS_DECL;
11221
11222     PERL_ARGS_ASSERT_REGCLASS;
11223 #ifndef DEBUGGING
11224     PERL_UNUSED_ARG(depth);
11225 #endif
11226
11227     DEBUG_PARSE("clas");
11228
11229     /* Assume we are going to generate an ANYOF node. */
11230     ret = reganode(pRExC_state, ANYOF, 0);
11231
11232
11233     if (!SIZE_ONLY) {
11234         ANYOF_FLAGS(ret) = 0;
11235     }
11236
11237     if (UCHARAT(RExC_parse) == '^') {   /* Complement of range. */
11238         RExC_naughty++;
11239         RExC_parse++;
11240         if (!SIZE_ONLY)
11241             ANYOF_FLAGS(ret) |= ANYOF_INVERT;
11242
11243         /* We have decided to not allow multi-char folds in inverted character
11244          * classes, due to the confusion that can happen, especially with
11245          * classes that are designed for a non-Unicode world:  You have the
11246          * peculiar case that:
11247             "s s" =~ /^[^\xDF]+$/i => Y
11248             "ss"  =~ /^[^\xDF]+$/i => N
11249          *
11250          * See [perl #89750] */
11251         allow_full_fold = FALSE;
11252     }
11253
11254     if (SIZE_ONLY) {
11255         RExC_size += ANYOF_SKIP;
11256         listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
11257     }
11258     else {
11259         RExC_emit += ANYOF_SKIP;
11260         if (LOC) {
11261             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
11262         }
11263         ANYOF_BITMAP_ZERO(ret);
11264         listsv = newSVpvs("# comment\n");
11265         initial_listsv_len = SvCUR(listsv);
11266     }
11267
11268     nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
11269
11270     if (!SIZE_ONLY && POSIXCC(nextvalue))
11271         checkposixcc(pRExC_state);
11272
11273     /* allow 1st char to be ] (allowing it to be - is dealt with later) */
11274     if (UCHARAT(RExC_parse) == ']')
11275         goto charclassloop;
11276
11277 parseit:
11278     while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
11279
11280     charclassloop:
11281
11282         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
11283
11284         if (!range) {
11285             rangebegin = RExC_parse;
11286             element_count++;
11287         }
11288         if (UTF) {
11289             value = utf8n_to_uvchr((U8*)RExC_parse,
11290                                    RExC_end - RExC_parse,
11291                                    &numlen, UTF8_ALLOW_DEFAULT);
11292             RExC_parse += numlen;
11293         }
11294         else
11295             value = UCHARAT(RExC_parse++);
11296
11297         nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
11298         if (value == '[' && POSIXCC(nextvalue))
11299             namedclass = regpposixcc(pRExC_state, value);
11300         else if (value == '\\') {
11301             if (UTF) {
11302                 value = utf8n_to_uvchr((U8*)RExC_parse,
11303                                    RExC_end - RExC_parse,
11304                                    &numlen, UTF8_ALLOW_DEFAULT);
11305                 RExC_parse += numlen;
11306             }
11307             else
11308                 value = UCHARAT(RExC_parse++);
11309             /* Some compilers cannot handle switching on 64-bit integer
11310              * values, therefore value cannot be an UV.  Yes, this will
11311              * be a problem later if we want switch on Unicode.
11312              * A similar issue a little bit later when switching on
11313              * namedclass. --jhi */
11314             switch ((I32)value) {
11315             case 'w':   namedclass = ANYOF_ALNUM;       break;
11316             case 'W':   namedclass = ANYOF_NALNUM;      break;
11317             case 's':   namedclass = ANYOF_SPACE;       break;
11318             case 'S':   namedclass = ANYOF_NSPACE;      break;
11319             case 'd':   namedclass = ANYOF_DIGIT;       break;
11320             case 'D':   namedclass = ANYOF_NDIGIT;      break;
11321             case 'v':   namedclass = ANYOF_VERTWS;      break;
11322             case 'V':   namedclass = ANYOF_NVERTWS;     break;
11323             case 'h':   namedclass = ANYOF_HORIZWS;     break;
11324             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
11325             case 'N':  /* Handle \N{NAME} in class */
11326                 {
11327                     /* We only pay attention to the first char of 
11328                     multichar strings being returned. I kinda wonder
11329                     if this makes sense as it does change the behaviour
11330                     from earlier versions, OTOH that behaviour was broken
11331                     as well. */
11332                     UV v; /* value is register so we cant & it /grrr */
11333                     if (reg_namedseq(pRExC_state, &v, NULL, depth)) {
11334                         goto parseit;
11335                     }
11336                     value= v; 
11337                 }
11338                 break;
11339             case 'p':
11340             case 'P':
11341                 {
11342                 char *e;
11343                 if (RExC_parse >= RExC_end)
11344                     vFAIL2("Empty \\%c{}", (U8)value);
11345                 if (*RExC_parse == '{') {
11346                     const U8 c = (U8)value;
11347                     e = strchr(RExC_parse++, '}');
11348                     if (!e)
11349                         vFAIL2("Missing right brace on \\%c{}", c);
11350                     while (isSPACE(UCHARAT(RExC_parse)))
11351                         RExC_parse++;
11352                     if (e == RExC_parse)
11353                         vFAIL2("Empty \\%c{}", c);
11354                     n = e - RExC_parse;
11355                     while (isSPACE(UCHARAT(RExC_parse + n - 1)))
11356                         n--;
11357                 }
11358                 else {
11359                     e = RExC_parse;
11360                     n = 1;
11361                 }
11362                 if (!SIZE_ONLY) {
11363                     SV** invlistsvp;
11364                     SV* invlist;
11365                     char* name;
11366                     if (UCHARAT(RExC_parse) == '^') {
11367                          RExC_parse++;
11368                          n--;
11369                          value = value == 'p' ? 'P' : 'p'; /* toggle */
11370                          while (isSPACE(UCHARAT(RExC_parse))) {
11371                               RExC_parse++;
11372                               n--;
11373                          }
11374                     }
11375                     /* Try to get the definition of the property into
11376                      * <invlist>.  If /i is in effect, the effective property
11377                      * will have its name be <__NAME_i>.  The design is
11378                      * discussed in commit
11379                      * 2f833f5208e26b208886e51e09e2c072b5eabb46 */
11380                     Newx(name, n + sizeof("_i__\n"), char);
11381
11382                     sprintf(name, "%s%.*s%s\n",
11383                                     (FOLD) ? "__" : "",
11384                                     (int)n,
11385                                     RExC_parse,
11386                                     (FOLD) ? "_i" : ""
11387                     );
11388
11389                     /* Look up the property name, and get its swash and
11390                      * inversion list, if the property is found  */
11391                     if (swash) {
11392                         SvREFCNT_dec(swash);
11393                     }
11394                     swash = _core_swash_init("utf8", name, &PL_sv_undef,
11395                                              1, /* binary */
11396                                              0, /* not tr/// */
11397                                              TRUE, /* this routine will handle
11398                                                       undefined properties */
11399                                              NULL, FALSE /* No inversion list */
11400                                             );
11401                     if (   ! swash
11402                         || ! SvROK(swash)
11403                         || ! SvTYPE(SvRV(swash)) == SVt_PVHV
11404                         || ! (invlistsvp =
11405                                 hv_fetchs(MUTABLE_HV(SvRV(swash)),
11406                                 "INVLIST", FALSE))
11407                         || ! (invlist = *invlistsvp))
11408                     {
11409                         if (swash) {
11410                             SvREFCNT_dec(swash);
11411                             swash = NULL;
11412                         }
11413
11414                         /* Here didn't find it.  It could be a user-defined
11415                          * property that will be available at run-time.  Add it
11416                          * to the list to look up then */
11417                         Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%s\n",
11418                                         (value == 'p' ? '+' : '!'),
11419                                         name);
11420                         has_user_defined_property = 1;
11421
11422                         /* We don't know yet, so have to assume that the
11423                          * property could match something in the Latin1 range,
11424                          * hence something that isn't utf8 */
11425                         ANYOF_FLAGS(ret) |= ANYOF_NONBITMAP_NON_UTF8;
11426                     }
11427                     else {
11428
11429                         /* Here, did get the swash and its inversion list.  If
11430                          * the swash is from a user-defined property, then this
11431                          * whole character class should be regarded as such */
11432                         SV** user_defined_svp =
11433                                             hv_fetchs(MUTABLE_HV(SvRV(swash)),
11434                                                         "USER_DEFINED", FALSE);
11435                         if (user_defined_svp) {
11436                             has_user_defined_property
11437                                                     |= SvUV(*user_defined_svp);
11438                         }
11439
11440                         /* Invert if asking for the complement */
11441                         if (value == 'P') {
11442                             _invlist_union_complement_2nd(properties, invlist, &properties);
11443
11444                             /* The swash can't be used as-is, because we've
11445                              * inverted things; delay removing it to here after
11446                              * have copied its invlist above */
11447                             SvREFCNT_dec(swash);
11448                             swash = NULL;
11449                         }
11450                         else {
11451                             _invlist_union(properties, invlist, &properties);
11452                         }
11453                     }
11454                     Safefree(name);
11455                 }
11456                 RExC_parse = e + 1;
11457                 namedclass = ANYOF_MAX;  /* no official name, but it's named */
11458
11459                 /* \p means they want Unicode semantics */
11460                 RExC_uni_semantics = 1;
11461                 }
11462                 break;
11463             case 'n':   value = '\n';                   break;
11464             case 'r':   value = '\r';                   break;
11465             case 't':   value = '\t';                   break;
11466             case 'f':   value = '\f';                   break;
11467             case 'b':   value = '\b';                   break;
11468             case 'e':   value = ASCII_TO_NATIVE('\033');break;
11469             case 'a':   value = ASCII_TO_NATIVE('\007');break;
11470             case 'o':
11471                 RExC_parse--;   /* function expects to be pointed at the 'o' */
11472                 {
11473                     const char* error_msg;
11474                     bool valid = grok_bslash_o(RExC_parse,
11475                                                &value,
11476                                                &numlen,
11477                                                &error_msg,
11478                                                SIZE_ONLY);
11479                     RExC_parse += numlen;
11480                     if (! valid) {
11481                         vFAIL(error_msg);
11482                     }
11483                 }
11484                 if (PL_encoding && value < 0x100) {
11485                     goto recode_encoding;
11486                 }
11487                 break;
11488             case 'x':
11489                 if (*RExC_parse == '{') {
11490                     I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
11491                         | PERL_SCAN_DISALLOW_PREFIX;
11492                     char * const e = strchr(RExC_parse++, '}');
11493                     if (!e)
11494                         vFAIL("Missing right brace on \\x{}");
11495
11496                     numlen = e - RExC_parse;
11497                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
11498                     RExC_parse = e + 1;
11499                 }
11500                 else {
11501                     I32 flags = PERL_SCAN_DISALLOW_PREFIX;
11502                     numlen = 2;
11503                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
11504                     RExC_parse += numlen;
11505                 }
11506                 if (PL_encoding && value < 0x100)
11507                     goto recode_encoding;
11508                 break;
11509             case 'c':
11510                 value = grok_bslash_c(*RExC_parse++, UTF, SIZE_ONLY);
11511                 break;
11512             case '0': case '1': case '2': case '3': case '4':
11513             case '5': case '6': case '7':
11514                 {
11515                     /* Take 1-3 octal digits */
11516                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
11517                     numlen = 3;
11518                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
11519                     RExC_parse += numlen;
11520                     if (PL_encoding && value < 0x100)
11521                         goto recode_encoding;
11522                     break;
11523                 }
11524             recode_encoding:
11525                 if (! RExC_override_recoding) {
11526                     SV* enc = PL_encoding;
11527                     value = reg_recode((const char)(U8)value, &enc);
11528                     if (!enc && SIZE_ONLY)
11529                         ckWARNreg(RExC_parse,
11530                                   "Invalid escape in the specified encoding");
11531                     break;
11532                 }
11533             default:
11534                 /* Allow \_ to not give an error */
11535                 if (!SIZE_ONLY && isALNUM(value) && value != '_') {
11536                     ckWARN2reg(RExC_parse,
11537                                "Unrecognized escape \\%c in character class passed through",
11538                                (int)value);
11539                 }
11540                 break;
11541             }
11542         } /* end of \blah */
11543 #ifdef EBCDIC
11544         else
11545             literal_endpoint++;
11546 #endif
11547
11548         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
11549
11550             /* What matches in a locale is not known until runtime, so need to
11551              * (one time per class) allocate extra space to pass to regexec.
11552              * The space will contain a bit for each named class that is to be
11553              * matched against.  This isn't needed for \p{} and pseudo-classes,
11554              * as they are not affected by locale, and hence are dealt with
11555              * separately */
11556             if (LOC && namedclass < ANYOF_MAX && ! need_class) {
11557                 need_class = 1;
11558                 if (SIZE_ONLY) {
11559                     RExC_size += ANYOF_CLASS_SKIP - ANYOF_SKIP;
11560                 }
11561                 else {
11562                     RExC_emit += ANYOF_CLASS_SKIP - ANYOF_SKIP;
11563                     ANYOF_CLASS_ZERO(ret);
11564                 }
11565                 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
11566             }
11567
11568             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
11569              * literal, as is the character that began the false range, i.e.
11570              * the 'a' in the examples */
11571             if (range) {
11572                 if (!SIZE_ONLY) {
11573                     const int w =
11574                         RExC_parse >= rangebegin ?
11575                         RExC_parse - rangebegin : 0;
11576                     ckWARN4reg(RExC_parse,
11577                                "False [] range \"%*.*s\"",
11578                                w, w, rangebegin);
11579
11580                     stored +=
11581                          set_regclass_bit(pRExC_state, ret, '-', &l1_fold_invlist, &unicode_alternate);
11582                     if (prevvalue < 256) {
11583                         stored +=
11584                          set_regclass_bit(pRExC_state, ret, (U8) prevvalue, &l1_fold_invlist, &unicode_alternate);
11585                     }
11586                     else {
11587                         nonbitmap = add_cp_to_invlist(nonbitmap, prevvalue);
11588                     }
11589                 }
11590
11591                 range = 0; /* this was not a true range */
11592             }
11593
11594             if (!SIZE_ONLY) {
11595
11596                 /* Possible truncation here but in some 64-bit environments
11597                  * the compiler gets heartburn about switch on 64-bit values.
11598                  * A similar issue a little earlier when switching on value.
11599                  * --jhi */
11600                 switch ((I32)namedclass) {
11601
11602                 case ANYOF_ALNUMC: /* C's alnum, in contrast to \w */
11603                     DO_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11604                         PL_PosixAlnum, PL_L1PosixAlnum, "XPosixAlnum", listsv);
11605                     break;
11606                 case ANYOF_NALNUMC:
11607                     DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11608                         PL_PosixAlnum, PL_L1PosixAlnum, "XPosixAlnum", listsv);
11609                     break;
11610                 case ANYOF_ALPHA:
11611                     DO_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11612                         PL_PosixAlpha, PL_L1PosixAlpha, "XPosixAlpha", listsv);
11613                     break;
11614                 case ANYOF_NALPHA:
11615                     DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11616                         PL_PosixAlpha, PL_L1PosixAlpha, "XPosixAlpha", listsv);
11617                     break;
11618                 case ANYOF_ASCII:
11619                     if (LOC) {
11620                         ANYOF_CLASS_SET(ret, namedclass);
11621                     }
11622                     else {
11623                         _invlist_union(properties, PL_ASCII, &properties);
11624                     }
11625                     break;
11626                 case ANYOF_NASCII:
11627                     if (LOC) {
11628                         ANYOF_CLASS_SET(ret, namedclass);
11629                     }
11630                     else {
11631                         _invlist_union_complement_2nd(properties,
11632                                                     PL_ASCII, &properties);
11633                         if (DEPENDS_SEMANTICS) {
11634                             ANYOF_FLAGS(ret) |= ANYOF_NON_UTF8_LATIN1_ALL;
11635                         }
11636                     }
11637                     break;
11638                 case ANYOF_BLANK:
11639                     DO_POSIX(ret, namedclass, properties,
11640                                             PL_PosixBlank, PL_XPosixBlank);
11641                     break;
11642                 case ANYOF_NBLANK:
11643                     DO_N_POSIX(ret, namedclass, properties,
11644                                             PL_PosixBlank, PL_XPosixBlank);
11645                     break;
11646                 case ANYOF_CNTRL:
11647                     DO_POSIX(ret, namedclass, properties,
11648                                             PL_PosixCntrl, PL_XPosixCntrl);
11649                     break;
11650                 case ANYOF_NCNTRL:
11651                     DO_N_POSIX(ret, namedclass, properties,
11652                                             PL_PosixCntrl, PL_XPosixCntrl);
11653                     break;
11654                 case ANYOF_DIGIT:
11655                     /* There are no digits in the Latin1 range outside of
11656                      * ASCII, so call the macro that doesn't have to resolve
11657                      * them */
11658                     DO_POSIX_LATIN1_ONLY_KNOWN_L1_RESOLVED(ret, namedclass, properties,
11659                         PL_PosixDigit, "XPosixDigit", listsv);
11660                     break;
11661                 case ANYOF_NDIGIT:
11662                     DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11663                         PL_PosixDigit, PL_PosixDigit, "XPosixDigit", listsv);
11664                     break;
11665                 case ANYOF_GRAPH:
11666                     DO_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11667                         PL_PosixGraph, PL_L1PosixGraph, "XPosixGraph", listsv);
11668                     break;
11669                 case ANYOF_NGRAPH:
11670                     DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11671                         PL_PosixGraph, PL_L1PosixGraph, "XPosixGraph", listsv);
11672                     break;
11673                 case ANYOF_HORIZWS:
11674                     /* For these, we use the nonbitmap, as /d doesn't make a
11675                      * difference in what these match.  There would be problems
11676                      * if these characters had folds other than themselves, as
11677                      * nonbitmap is subject to folding.  It turns out that \h
11678                      * is just a synonym for XPosixBlank */
11679                     _invlist_union(nonbitmap, PL_XPosixBlank, &nonbitmap);
11680                     break;
11681                 case ANYOF_NHORIZWS:
11682                     _invlist_union_complement_2nd(nonbitmap,
11683                                                  PL_XPosixBlank, &nonbitmap);
11684                     break;
11685                 case ANYOF_LOWER:
11686                 case ANYOF_NLOWER:
11687                 {   /* These require special handling, as they differ under
11688                        folding, matching Cased there (which in the ASCII range
11689                        is the same as Alpha */
11690
11691                     SV* ascii_source;
11692                     SV* l1_source;
11693                     const char *Xname;
11694
11695                     if (FOLD && ! LOC) {
11696                         ascii_source = PL_PosixAlpha;
11697                         l1_source = PL_L1Cased;
11698                         Xname = "Cased";
11699                     }
11700                     else {
11701                         ascii_source = PL_PosixLower;
11702                         l1_source = PL_L1PosixLower;
11703                         Xname = "XPosixLower";
11704                     }
11705                     if (namedclass == ANYOF_LOWER) {
11706                         DO_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11707                                     ascii_source, l1_source, Xname, listsv);
11708                     }
11709                     else {
11710                         DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass,
11711                             properties, ascii_source, l1_source, Xname, listsv);
11712                     }
11713                     break;
11714                 }
11715                 case ANYOF_PRINT:
11716                     DO_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11717                         PL_PosixPrint, PL_L1PosixPrint, "XPosixPrint", listsv);
11718                     break;
11719                 case ANYOF_NPRINT:
11720                     DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11721                         PL_PosixPrint, PL_L1PosixPrint, "XPosixPrint", listsv);
11722                     break;
11723                 case ANYOF_PUNCT:
11724                     DO_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11725                         PL_PosixPunct, PL_L1PosixPunct, "XPosixPunct", listsv);
11726                     break;
11727                 case ANYOF_NPUNCT:
11728                     DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11729                         PL_PosixPunct, PL_L1PosixPunct, "XPosixPunct", listsv);
11730                     break;
11731                 case ANYOF_PSXSPC:
11732                     DO_POSIX(ret, namedclass, properties,
11733                                             PL_PosixSpace, PL_XPosixSpace);
11734                     break;
11735                 case ANYOF_NPSXSPC:
11736                     DO_N_POSIX(ret, namedclass, properties,
11737                                             PL_PosixSpace, PL_XPosixSpace);
11738                     break;
11739                 case ANYOF_SPACE:
11740                     DO_POSIX(ret, namedclass, properties,
11741                                             PL_PerlSpace, PL_XPerlSpace);
11742                     break;
11743                 case ANYOF_NSPACE:
11744                     DO_N_POSIX(ret, namedclass, properties,
11745                                             PL_PerlSpace, PL_XPerlSpace);
11746                     break;
11747                 case ANYOF_UPPER:   /* Same as LOWER, above */
11748                 case ANYOF_NUPPER:
11749                 {
11750                     SV* ascii_source;
11751                     SV* l1_source;
11752                     const char *Xname;
11753
11754                     if (FOLD && ! LOC) {
11755                         ascii_source = PL_PosixAlpha;
11756                         l1_source = PL_L1Cased;
11757                         Xname = "Cased";
11758                     }
11759                     else {
11760                         ascii_source = PL_PosixUpper;
11761                         l1_source = PL_L1PosixUpper;
11762                         Xname = "XPosixUpper";
11763                     }
11764                     if (namedclass == ANYOF_UPPER) {
11765                         DO_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11766                                     ascii_source, l1_source, Xname, listsv);
11767                     }
11768                     else {
11769                         DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass,
11770                         properties, ascii_source, l1_source, Xname, listsv);
11771                     }
11772                     break;
11773                 }
11774                 case ANYOF_ALNUM:   /* Really is 'Word' */
11775                     DO_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11776                             PL_PosixWord, PL_L1PosixWord, "XPosixWord", listsv);
11777                     break;
11778                 case ANYOF_NALNUM:
11779                     DO_N_POSIX_LATIN1_ONLY_KNOWN(ret, namedclass, properties,
11780                             PL_PosixWord, PL_L1PosixWord, "XPosixWord", listsv);
11781                     break;
11782                 case ANYOF_VERTWS:
11783                     /* For these, we use the nonbitmap, as /d doesn't make a
11784                      * difference in what these match.  There would be problems
11785                      * if these characters had folds other than themselves, as
11786                      * nonbitmap is subject to folding */
11787                     _invlist_union(nonbitmap, PL_VertSpace, &nonbitmap);
11788                     break;
11789                 case ANYOF_NVERTWS:
11790                     _invlist_union_complement_2nd(nonbitmap,
11791                                                     PL_VertSpace, &nonbitmap);
11792                     break;
11793                 case ANYOF_XDIGIT:
11794                     DO_POSIX(ret, namedclass, properties,
11795                                             PL_PosixXDigit, PL_XPosixXDigit);
11796                     break;
11797                 case ANYOF_NXDIGIT:
11798                     DO_N_POSIX(ret, namedclass, properties,
11799                                             PL_PosixXDigit, PL_XPosixXDigit);
11800                     break;
11801                 case ANYOF_MAX:
11802                     /* this is to handle \p and \P */
11803                     break;
11804                 default:
11805                     vFAIL("Invalid [::] class");
11806                     break;
11807                 }
11808
11809                 continue;
11810             }
11811         } /* end of namedclass \blah */
11812
11813         if (range) {
11814             if (prevvalue > (IV)value) /* b-a */ {
11815                 const int w = RExC_parse - rangebegin;
11816                 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
11817                 range = 0; /* not a valid range */
11818             }
11819         }
11820         else {
11821             prevvalue = value; /* save the beginning of the range */
11822             if (RExC_parse+1 < RExC_end
11823                 && *RExC_parse == '-'
11824                 && RExC_parse[1] != ']')
11825             {
11826                 RExC_parse++;
11827
11828                 /* a bad range like \w-, [:word:]- ? */
11829                 if (namedclass > OOB_NAMEDCLASS) {
11830                     if (ckWARN(WARN_REGEXP)) {
11831                         const int w =
11832                             RExC_parse >= rangebegin ?
11833                             RExC_parse - rangebegin : 0;
11834                         vWARN4(RExC_parse,
11835                                "False [] range \"%*.*s\"",
11836                                w, w, rangebegin);
11837                     }
11838                     if (!SIZE_ONLY)
11839                         stored +=
11840                             set_regclass_bit(pRExC_state, ret, '-', &l1_fold_invlist, &unicode_alternate);
11841                 } else
11842                     range = 1;  /* yeah, it's a range! */
11843                 continue;       /* but do it the next time */
11844             }
11845         }
11846
11847         /* non-Latin1 code point implies unicode semantics.  Must be set in
11848          * pass1 so is there for the whole of pass 2 */
11849         if (value > 255) {
11850             RExC_uni_semantics = 1;
11851         }
11852
11853         /* now is the next time */
11854         if (!SIZE_ONLY) {
11855             if (prevvalue < 256) {
11856                 const IV ceilvalue = value < 256 ? value : 255;
11857                 IV i;
11858 #ifdef EBCDIC
11859                 /* In EBCDIC [\x89-\x91] should include
11860                  * the \x8e but [i-j] should not. */
11861                 if (literal_endpoint == 2 &&
11862                     ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
11863                      (isUPPER(prevvalue) && isUPPER(ceilvalue))))
11864                 {
11865                     if (isLOWER(prevvalue)) {
11866                         for (i = prevvalue; i <= ceilvalue; i++)
11867                             if (isLOWER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
11868                                 stored +=
11869                                   set_regclass_bit(pRExC_state, ret, (U8) i, &l1_fold_invlist, &unicode_alternate);
11870                             }
11871                     } else {
11872                         for (i = prevvalue; i <= ceilvalue; i++)
11873                             if (isUPPER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
11874                                 stored +=
11875                                   set_regclass_bit(pRExC_state, ret, (U8) i, &l1_fold_invlist, &unicode_alternate);
11876                             }
11877                     }
11878                 }
11879                 else
11880 #endif
11881                       for (i = prevvalue; i <= ceilvalue; i++) {
11882                         stored += set_regclass_bit(pRExC_state, ret, (U8) i, &l1_fold_invlist, &unicode_alternate);
11883                       }
11884           }
11885           if (value > 255) {
11886             const UV prevnatvalue  = NATIVE_TO_UNI(prevvalue);
11887             const UV natvalue      = NATIVE_TO_UNI(value);
11888             nonbitmap = _add_range_to_invlist(nonbitmap, prevnatvalue, natvalue);
11889         }
11890 #ifdef EBCDIC
11891             literal_endpoint = 0;
11892 #endif
11893         }
11894
11895         range = 0; /* this range (if it was one) is done now */
11896     }
11897
11898
11899
11900     if (SIZE_ONLY)
11901         return ret;
11902     /****** !SIZE_ONLY AFTER HERE *********/
11903
11904     /* If folding and there are code points above 255, we calculate all
11905      * characters that could fold to or from the ones already on the list */
11906     if (FOLD && nonbitmap) {
11907         UV start, end;  /* End points of code point ranges */
11908
11909         SV* fold_intersection = NULL;
11910
11911         /* This is a list of all the characters that participate in folds
11912             * (except marks, etc in multi-char folds */
11913         if (! PL_utf8_foldable) {
11914             SV* swash = swash_init("utf8", "Cased", &PL_sv_undef, 1, 0);
11915             PL_utf8_foldable = _swash_to_invlist(swash);
11916             SvREFCNT_dec(swash);
11917         }
11918
11919         /* This is a hash that for a particular fold gives all characters
11920             * that are involved in it */
11921         if (! PL_utf8_foldclosures) {
11922
11923             /* If we were unable to find any folds, then we likely won't be
11924              * able to find the closures.  So just create an empty list.
11925              * Folding will effectively be restricted to the non-Unicode rules
11926              * hard-coded into Perl.  (This case happens legitimately during
11927              * compilation of Perl itself before the Unicode tables are
11928              * generated) */
11929             if (invlist_len(PL_utf8_foldable) == 0) {
11930                 PL_utf8_foldclosures = newHV();
11931             } else {
11932                 /* If the folds haven't been read in, call a fold function
11933                     * to force that */
11934                 if (! PL_utf8_tofold) {
11935                     U8 dummy[UTF8_MAXBYTES+1];
11936                     STRLEN dummy_len;
11937
11938                     /* This particular string is above \xff in both UTF-8 and
11939                      * UTFEBCDIC */
11940                     to_utf8_fold((U8*) "\xC8\x80", dummy, &dummy_len);
11941                     assert(PL_utf8_tofold); /* Verify that worked */
11942                 }
11943                 PL_utf8_foldclosures = _swash_inversion_hash(PL_utf8_tofold);
11944             }
11945         }
11946
11947         /* Only the characters in this class that participate in folds need be
11948          * checked.  Get the intersection of this class and all the possible
11949          * characters that are foldable.  This can quickly narrow down a large
11950          * class */
11951         _invlist_intersection(PL_utf8_foldable, nonbitmap, &fold_intersection);
11952
11953         /* Now look at the foldable characters in this class individually */
11954         invlist_iterinit(fold_intersection);
11955         while (invlist_iternext(fold_intersection, &start, &end)) {
11956             UV j;
11957
11958             /* Look at every character in the range */
11959             for (j = start; j <= end; j++) {
11960
11961                 /* Get its fold */
11962                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
11963                 STRLEN foldlen;
11964                 const UV f =
11965                     _to_uni_fold_flags(j, foldbuf, &foldlen,
11966                                        (allow_full_fold) ? FOLD_FLAGS_FULL : 0);
11967
11968                 if (foldlen > (STRLEN)UNISKIP(f)) {
11969
11970                     /* Any multicharacter foldings (disallowed in lookbehind
11971                      * patterns) require the following transform: [ABCDEF] ->
11972                      * (?:[ABCabcDEFd]|pq|rst) where E folds into "pq" and F
11973                      * folds into "rst", all other characters fold to single
11974                      * characters.  We save away these multicharacter foldings,
11975                      * to be later saved as part of the additional "s" data. */
11976                     if (! RExC_in_lookbehind) {
11977                         U8* loc = foldbuf;
11978                         U8* e = foldbuf + foldlen;
11979
11980                         /* If any of the folded characters of this are in the
11981                          * Latin1 range, tell the regex engine that this can
11982                          * match a non-utf8 target string.  The only multi-byte
11983                          * fold whose source is in the Latin1 range (U+00DF)
11984                          * applies only when the target string is utf8, or
11985                          * under unicode rules */
11986                         if (j > 255 || AT_LEAST_UNI_SEMANTICS) {
11987                             while (loc < e) {
11988
11989                                 /* Can't mix ascii with non- under /aa */
11990                                 if (MORE_ASCII_RESTRICTED
11991                                     && (isASCII(*loc) != isASCII(j)))
11992                                 {
11993                                     goto end_multi_fold;
11994                                 }
11995                                 if (UTF8_IS_INVARIANT(*loc)
11996                                     || UTF8_IS_DOWNGRADEABLE_START(*loc))
11997                                 {
11998                                     /* Can't mix above and below 256 under LOC
11999                                      */
12000                                     if (LOC) {
12001                                         goto end_multi_fold;
12002                                     }
12003                                     ANYOF_FLAGS(ret)
12004                                             |= ANYOF_NONBITMAP_NON_UTF8;
12005                                     break;
12006                                 }
12007                                 loc += UTF8SKIP(loc);
12008                             }
12009                         }
12010
12011                         add_alternate(&unicode_alternate, foldbuf, foldlen);
12012                     end_multi_fold: ;
12013                     }
12014
12015                     /* This is special-cased, as it is the only letter which
12016                      * has both a multi-fold and single-fold in Latin1.  All
12017                      * the other chars that have single and multi-folds are
12018                      * always in utf8, and the utf8 folding algorithm catches
12019                      * them */
12020                     if (! LOC && j == LATIN_CAPITAL_LETTER_SHARP_S) {
12021                         stored += set_regclass_bit(pRExC_state,
12022                                         ret,
12023                                         LATIN_SMALL_LETTER_SHARP_S,
12024                                         &l1_fold_invlist, &unicode_alternate);
12025                     }
12026                 }
12027                 else {
12028                     /* Single character fold.  Add everything in its fold
12029                      * closure to the list that this node should match */
12030                     SV** listp;
12031
12032                     /* The fold closures data structure is a hash with the keys
12033                      * being every character that is folded to, like 'k', and
12034                      * the values each an array of everything that folds to its
12035                      * key.  e.g. [ 'k', 'K', KELVIN_SIGN ] */
12036                     if ((listp = hv_fetch(PL_utf8_foldclosures,
12037                                     (char *) foldbuf, foldlen, FALSE)))
12038                     {
12039                         AV* list = (AV*) *listp;
12040                         IV k;
12041                         for (k = 0; k <= av_len(list); k++) {
12042                             SV** c_p = av_fetch(list, k, FALSE);
12043                             UV c;
12044                             if (c_p == NULL) {
12045                                 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
12046                             }
12047                             c = SvUV(*c_p);
12048
12049                             /* /aa doesn't allow folds between ASCII and non-;
12050                              * /l doesn't allow them between above and below
12051                              * 256 */
12052                             if ((MORE_ASCII_RESTRICTED
12053                                  && (isASCII(c) != isASCII(j)))
12054                                     || (LOC && ((c < 256) != (j < 256))))
12055                             {
12056                                 continue;
12057                             }
12058
12059                             if (c < 256 && AT_LEAST_UNI_SEMANTICS) {
12060                                 stored += set_regclass_bit(pRExC_state,
12061                                         ret,
12062                                         (U8) c,
12063                                         &l1_fold_invlist, &unicode_alternate);
12064                             }
12065                                 /* It may be that the code point is already in
12066                                  * this range or already in the bitmap, in
12067                                  * which case we need do nothing */
12068                             else if ((c < start || c > end)
12069                                         && (c > 255
12070                                             || ! ANYOF_BITMAP_TEST(ret, c)))
12071                             {
12072                                 nonbitmap = add_cp_to_invlist(nonbitmap, c);
12073                             }
12074                         }
12075                     }
12076                 }
12077             }
12078         }
12079         SvREFCNT_dec(fold_intersection);
12080     }
12081
12082     /* Combine the two lists into one. */
12083     if (l1_fold_invlist) {
12084         if (nonbitmap) {
12085             _invlist_union(nonbitmap, l1_fold_invlist, &nonbitmap);
12086             SvREFCNT_dec(l1_fold_invlist);
12087         }
12088         else {
12089             nonbitmap = l1_fold_invlist;
12090         }
12091     }
12092
12093     /* And combine the result (if any) with any inversion list from properties.
12094      * The lists are kept separate up to now because we don't want to fold the
12095      * properties */
12096     if (properties) {
12097         if (nonbitmap) {
12098             _invlist_union(nonbitmap, properties, &nonbitmap);
12099             SvREFCNT_dec(properties);
12100         }
12101         else {
12102             nonbitmap = properties;
12103         }
12104     }
12105
12106     /* Here, <nonbitmap> contains all the code points we can determine at
12107      * compile time that we haven't put into the bitmap.  Go through it, and
12108      * for things that belong in the bitmap, put them there, and delete from
12109      * <nonbitmap> */
12110     if (nonbitmap) {
12111
12112         /* Above-ASCII code points in /d have to stay in <nonbitmap>, as they
12113          * possibly only should match when the target string is UTF-8 */
12114         UV max_cp_to_set = (DEPENDS_SEMANTICS) ? 127 : 255;
12115
12116         /* This gets set if we actually need to modify things */
12117         bool change_invlist = FALSE;
12118
12119         UV start, end;
12120
12121         /* Start looking through <nonbitmap> */
12122         invlist_iterinit(nonbitmap);
12123         while (invlist_iternext(nonbitmap, &start, &end)) {
12124             UV high;
12125             int i;
12126
12127             /* Quit if are above what we should change */
12128             if (start > max_cp_to_set) {
12129                 break;
12130             }
12131
12132             change_invlist = TRUE;
12133
12134             /* Set all the bits in the range, up to the max that we are doing */
12135             high = (end < max_cp_to_set) ? end : max_cp_to_set;
12136             for (i = start; i <= (int) high; i++) {
12137                 if (! ANYOF_BITMAP_TEST(ret, i)) {
12138                     ANYOF_BITMAP_SET(ret, i);
12139                     stored++;
12140                     prevvalue = value;
12141                     value = i;
12142                 }
12143             }
12144         }
12145
12146         /* Done with loop; remove any code points that are in the bitmap from
12147          * <nonbitmap> */
12148         if (change_invlist) {
12149             _invlist_subtract(nonbitmap,
12150                               (DEPENDS_SEMANTICS)
12151                                 ? PL_ASCII
12152                                 : PL_Latin1,
12153                               &nonbitmap);
12154         }
12155
12156         /* If have completely emptied it, remove it completely */
12157         if (invlist_len(nonbitmap) == 0) {
12158             SvREFCNT_dec(nonbitmap);
12159             nonbitmap = NULL;
12160         }
12161     }
12162
12163     /* Here, we have calculated what code points should be in the character
12164      * class.  <nonbitmap> does not overlap the bitmap except possibly in the
12165      * case of DEPENDS rules.
12166      *
12167      * Now we can see about various optimizations.  Fold calculation (which we
12168      * did above) needs to take place before inversion.  Otherwise /[^k]/i
12169      * would invert to include K, which under /i would match k, which it
12170      * shouldn't. */
12171
12172     /* Optimize inverted simple patterns (e.g. [^a-z]).  Note that we haven't
12173      * set the FOLD flag yet, so this does optimize those.  It doesn't
12174      * optimize locale.  Doing so perhaps could be done as long as there is
12175      * nothing like \w in it; some thought also would have to be given to the
12176      * interaction with above 0x100 chars */
12177     if ((ANYOF_FLAGS(ret) & ANYOF_INVERT)
12178         && ! LOC
12179         && ! unicode_alternate
12180         /* In case of /d, there are some things that should match only when in
12181          * not in the bitmap, i.e., they require UTF8 to match.  These are
12182          * listed in nonbitmap, but if ANYOF_NONBITMAP_NON_UTF8 is set in this
12183          * case, they don't require UTF8, so can invert here */
12184         && (! nonbitmap
12185             || ! DEPENDS_SEMANTICS
12186             || (ANYOF_FLAGS(ret) & ANYOF_NONBITMAP_NON_UTF8))
12187         && SvCUR(listsv) == initial_listsv_len)
12188     {
12189         int i;
12190         if (! nonbitmap) {
12191             for (i = 0; i < 256; ++i) {
12192                 if (ANYOF_BITMAP_TEST(ret, i)) {
12193                     ANYOF_BITMAP_CLEAR(ret, i);
12194                 }
12195                 else {
12196                     ANYOF_BITMAP_SET(ret, i);
12197                     prevvalue = value;
12198                     value = i;
12199                 }
12200             }
12201             /* The inversion means that everything above 255 is matched */
12202             ANYOF_FLAGS(ret) |= ANYOF_UNICODE_ALL;
12203         }
12204         else {
12205             /* Here, also has things outside the bitmap that may overlap with
12206              * the bitmap.  We have to sync them up, so that they get inverted
12207              * in both places.  Earlier, we removed all overlaps except in the
12208              * case of /d rules, so no syncing is needed except for this case
12209              */
12210             SV *remove_list = NULL;
12211
12212             if (DEPENDS_SEMANTICS) {
12213                 UV start, end;
12214
12215                 /* Set the bits that correspond to the ones that aren't in the
12216                  * bitmap.  Otherwise, when we invert, we'll miss these.
12217                  * Earlier, we removed from the nonbitmap all code points
12218                  * < 128, so there is no extra work here */
12219                 invlist_iterinit(nonbitmap);
12220                 while (invlist_iternext(nonbitmap, &start, &end)) {
12221                     if (start > 255) {  /* The bit map goes to 255 */
12222                         break;
12223                     }
12224                     if (end > 255) {
12225                         end = 255;
12226                     }
12227                     for (i = start; i <= (int) end; ++i) {
12228                         ANYOF_BITMAP_SET(ret, i);
12229                         prevvalue = value;
12230                         value = i;
12231                     }
12232                 }
12233             }
12234
12235             /* Now invert both the bitmap and the nonbitmap.  Anything in the
12236              * bitmap has to also be removed from the non-bitmap, but again,
12237              * there should not be overlap unless is /d rules. */
12238             _invlist_invert(nonbitmap);
12239
12240             /* Any swash can't be used as-is, because we've inverted things */
12241             if (swash) {
12242                 SvREFCNT_dec(swash);
12243                 swash = NULL;
12244             }
12245
12246             for (i = 0; i < 256; ++i) {
12247                 if (ANYOF_BITMAP_TEST(ret, i)) {
12248                     ANYOF_BITMAP_CLEAR(ret, i);
12249                     if (DEPENDS_SEMANTICS) {
12250                         if (! remove_list) {
12251                             remove_list = _new_invlist(2);
12252                         }
12253                         remove_list = add_cp_to_invlist(remove_list, i);
12254                     }
12255                 }
12256                 else {
12257                     ANYOF_BITMAP_SET(ret, i);
12258                     prevvalue = value;
12259                     value = i;
12260                 }
12261             }
12262
12263             /* And do the removal */
12264             if (DEPENDS_SEMANTICS) {
12265                 if (remove_list) {
12266                     _invlist_subtract(nonbitmap, remove_list, &nonbitmap);
12267                     SvREFCNT_dec(remove_list);
12268                 }
12269             }
12270             else {
12271                 /* There is no overlap for non-/d, so just delete anything
12272                  * below 256 */
12273                 _invlist_intersection(nonbitmap, PL_AboveLatin1, &nonbitmap);
12274             }
12275         }
12276
12277         stored = 256 - stored;
12278
12279         /* Clear the invert flag since have just done it here */
12280         ANYOF_FLAGS(ret) &= ~ANYOF_INVERT;
12281     }
12282
12283     /* Folding in the bitmap is taken care of above, but not for locale (for
12284      * which we have to wait to see what folding is in effect at runtime), and
12285      * for some things not in the bitmap (only the upper latin folds in this
12286      * case, as all other single-char folding has been set above).  Set
12287      * run-time fold flag for these */
12288     if (FOLD && (LOC
12289                 || (DEPENDS_SEMANTICS
12290                     && nonbitmap
12291                     && ! (ANYOF_FLAGS(ret) & ANYOF_NONBITMAP_NON_UTF8))
12292                 || unicode_alternate))
12293     {
12294         ANYOF_FLAGS(ret) |= ANYOF_LOC_NONBITMAP_FOLD;
12295     }
12296
12297     /* A single character class can be "optimized" into an EXACTish node.
12298      * Note that since we don't currently count how many characters there are
12299      * outside the bitmap, we are XXX missing optimization possibilities for
12300      * them.  This optimization can't happen unless this is a truly single
12301      * character class, which means that it can't be an inversion into a
12302      * many-character class, and there must be no possibility of there being
12303      * things outside the bitmap.  'stored' (only) for locales doesn't include
12304      * \w, etc, so have to make a special test that they aren't present
12305      *
12306      * Similarly A 2-character class of the very special form like [bB] can be
12307      * optimized into an EXACTFish node, but only for non-locales, and for
12308      * characters which only have the two folds; so things like 'fF' and 'Ii'
12309      * wouldn't work because they are part of the fold of 'LATIN SMALL LIGATURE
12310      * FI'. */
12311     if (! nonbitmap
12312         && ! unicode_alternate
12313         && SvCUR(listsv) == initial_listsv_len
12314         && ! (ANYOF_FLAGS(ret) & (ANYOF_INVERT|ANYOF_UNICODE_ALL))
12315         && (((stored == 1 && ((! (ANYOF_FLAGS(ret) & ANYOF_LOCALE))
12316                               || (! ANYOF_CLASS_TEST_ANY_SET(ret)))))
12317             || (stored == 2 && ((! (ANYOF_FLAGS(ret) & ANYOF_LOCALE))
12318                                  && (! _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(value))
12319                                  /* If the latest code point has a fold whose
12320                                   * bit is set, it must be the only other one */
12321                                 && ((prevvalue = PL_fold_latin1[value]) != (IV)value)
12322                                  && ANYOF_BITMAP_TEST(ret, prevvalue)))))
12323     {
12324         /* Note that the information needed to decide to do this optimization
12325          * is not currently available until the 2nd pass, and that the actually
12326          * used EXACTish node takes less space than the calculated ANYOF node,
12327          * and hence the amount of space calculated in the first pass is larger
12328          * than actually used, so this optimization doesn't gain us any space.
12329          * But an EXACT node is faster than an ANYOF node, and can be combined
12330          * with any adjacent EXACT nodes later by the optimizer for further
12331          * gains.  The speed of executing an EXACTF is similar to an ANYOF
12332          * node, so the optimization advantage comes from the ability to join
12333          * it to adjacent EXACT nodes */
12334
12335         const char * cur_parse= RExC_parse;
12336         U8 op;
12337         RExC_emit = (regnode *)orig_emit;
12338         RExC_parse = (char *)orig_parse;
12339
12340         if (stored == 1) {
12341
12342             /* A locale node with one point can be folded; all the other cases
12343              * with folding will have two points, since we calculate them above
12344              */
12345             if (ANYOF_FLAGS(ret) & ANYOF_LOC_NONBITMAP_FOLD) {
12346                  op = EXACTFL;
12347             }
12348             else {
12349                 op = EXACT;
12350             }
12351         }
12352         else {   /* else 2 chars in the bit map: the folds of each other */
12353
12354             /* Use the folded value, which for the cases where we get here,
12355              * is just the lower case of the current one (which may resolve to
12356              * itself, or to the other one */
12357             value = toLOWER_LATIN1(value);
12358
12359             /* To join adjacent nodes, they must be the exact EXACTish type.
12360              * Try to use the most likely type, by using EXACTFA if possible,
12361              * then EXACTFU if the regex calls for it, or is required because
12362              * the character is non-ASCII.  (If <value> is ASCII, its fold is
12363              * also ASCII for the cases where we get here.) */
12364             if (MORE_ASCII_RESTRICTED && isASCII(value)) {
12365                 op = EXACTFA;
12366             }
12367             else if (AT_LEAST_UNI_SEMANTICS || !isASCII(value)) {
12368                 op = EXACTFU;
12369             }
12370             else {    /* Otherwise, more likely to be EXACTF type */
12371                 op = EXACTF;
12372             }
12373         }
12374
12375         ret = reg_node(pRExC_state, op);
12376         RExC_parse = (char *)cur_parse;
12377         if (UTF && ! NATIVE_IS_INVARIANT(value)) {
12378             *STRING(ret)= UTF8_EIGHT_BIT_HI((U8) value);
12379             *(STRING(ret) + 1)= UTF8_EIGHT_BIT_LO((U8) value);
12380             STR_LEN(ret)= 2;
12381             RExC_emit += STR_SZ(2);
12382         }
12383         else {
12384             *STRING(ret)= (char)value;
12385             STR_LEN(ret)= 1;
12386             RExC_emit += STR_SZ(1);
12387         }
12388         SvREFCNT_dec(listsv);
12389         return ret;
12390     }
12391
12392     /* If there is a swash and more than one element, we can't use the swash in
12393      * the optimization below. */
12394     if (swash && element_count > 1) {
12395         SvREFCNT_dec(swash);
12396         swash = NULL;
12397     }
12398     if (! nonbitmap
12399         && SvCUR(listsv) == initial_listsv_len
12400         && ! unicode_alternate)
12401     {
12402         ARG_SET(ret, ANYOF_NONBITMAP_EMPTY);
12403         SvREFCNT_dec(listsv);
12404         SvREFCNT_dec(unicode_alternate);
12405     }
12406     else {
12407         /* av[0] stores the character class description in its textual form:
12408          *       used later (regexec.c:Perl_regclass_swash()) to initialize the
12409          *       appropriate swash, and is also useful for dumping the regnode.
12410          * av[1] if NULL, is a placeholder to later contain the swash computed
12411          *       from av[0].  But if no further computation need be done, the
12412          *       swash is stored there now.
12413          * av[2] stores the multicharacter foldings, used later in
12414          *       regexec.c:S_reginclass().
12415          * av[3] stores the nonbitmap inversion list for use in addition or
12416          *       instead of av[0]; not used if av[1] isn't NULL
12417          * av[4] is set if any component of the class is from a user-defined
12418          *       property; not used if av[1] isn't NULL */
12419         AV * const av = newAV();
12420         SV *rv;
12421
12422         av_store(av, 0, (SvCUR(listsv) == initial_listsv_len)
12423                         ? &PL_sv_undef
12424                         : listsv);
12425         if (swash) {
12426             av_store(av, 1, swash);
12427             SvREFCNT_dec(nonbitmap);
12428         }
12429         else {
12430             av_store(av, 1, NULL);
12431             if (nonbitmap) {
12432                 av_store(av, 3, nonbitmap);
12433                 av_store(av, 4, newSVuv(has_user_defined_property));
12434             }
12435         }
12436
12437         /* Store any computed multi-char folds only if we are allowing
12438          * them */
12439         if (allow_full_fold) {
12440             av_store(av, 2, MUTABLE_SV(unicode_alternate));
12441             if (unicode_alternate) { /* This node is variable length */
12442                 OP(ret) = ANYOFV;
12443             }
12444         }
12445         else {
12446             av_store(av, 2, NULL);
12447         }
12448         rv = newRV_noinc(MUTABLE_SV(av));
12449         n = add_data(pRExC_state, 1, "s");
12450         RExC_rxi->data->data[n] = (void*)rv;
12451         ARG_SET(ret, n);
12452     }
12453     return ret;
12454 }
12455
12456
12457 /* reg_skipcomment()
12458
12459    Absorbs an /x style # comments from the input stream.
12460    Returns true if there is more text remaining in the stream.
12461    Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
12462    terminates the pattern without including a newline.
12463
12464    Note its the callers responsibility to ensure that we are
12465    actually in /x mode
12466
12467 */
12468
12469 STATIC bool
12470 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
12471 {
12472     bool ended = 0;
12473
12474     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
12475
12476     while (RExC_parse < RExC_end)
12477         if (*RExC_parse++ == '\n') {
12478             ended = 1;
12479             break;
12480         }
12481     if (!ended) {
12482         /* we ran off the end of the pattern without ending
12483            the comment, so we have to add an \n when wrapping */
12484         RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
12485         return 0;
12486     } else
12487         return 1;
12488 }
12489
12490 /* nextchar()
12491
12492    Advances the parse position, and optionally absorbs
12493    "whitespace" from the inputstream.
12494
12495    Without /x "whitespace" means (?#...) style comments only,
12496    with /x this means (?#...) and # comments and whitespace proper.
12497
12498    Returns the RExC_parse point from BEFORE the scan occurs.
12499
12500    This is the /x friendly way of saying RExC_parse++.
12501 */
12502
12503 STATIC char*
12504 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
12505 {
12506     char* const retval = RExC_parse++;
12507
12508     PERL_ARGS_ASSERT_NEXTCHAR;
12509
12510     for (;;) {
12511         if (RExC_end - RExC_parse >= 3
12512             && *RExC_parse == '('
12513             && RExC_parse[1] == '?'
12514             && RExC_parse[2] == '#')
12515         {
12516             while (*RExC_parse != ')') {
12517                 if (RExC_parse == RExC_end)
12518                     FAIL("Sequence (?#... not terminated");
12519                 RExC_parse++;
12520             }
12521             RExC_parse++;
12522             continue;
12523         }
12524         if (RExC_flags & RXf_PMf_EXTENDED) {
12525             if (isSPACE(*RExC_parse)) {
12526                 RExC_parse++;
12527                 continue;
12528             }
12529             else if (*RExC_parse == '#') {
12530                 if ( reg_skipcomment( pRExC_state ) )
12531                     continue;
12532             }
12533         }
12534         return retval;
12535     }
12536 }
12537
12538 /*
12539 - reg_node - emit a node
12540 */
12541 STATIC regnode *                        /* Location. */
12542 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
12543 {
12544     dVAR;
12545     register regnode *ptr;
12546     regnode * const ret = RExC_emit;
12547     GET_RE_DEBUG_FLAGS_DECL;
12548
12549     PERL_ARGS_ASSERT_REG_NODE;
12550
12551     if (SIZE_ONLY) {
12552         SIZE_ALIGN(RExC_size);
12553         RExC_size += 1;
12554         return(ret);
12555     }
12556     if (RExC_emit >= RExC_emit_bound)
12557         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
12558                    op, RExC_emit, RExC_emit_bound);
12559
12560     NODE_ALIGN_FILL(ret);
12561     ptr = ret;
12562     FILL_ADVANCE_NODE(ptr, op);
12563 #ifdef RE_TRACK_PATTERN_OFFSETS
12564     if (RExC_offsets) {         /* MJD */
12565         MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n", 
12566               "reg_node", __LINE__, 
12567               PL_reg_name[op],
12568               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] 
12569                 ? "Overwriting end of array!\n" : "OK",
12570               (UV)(RExC_emit - RExC_emit_start),
12571               (UV)(RExC_parse - RExC_start),
12572               (UV)RExC_offsets[0])); 
12573         Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
12574     }
12575 #endif
12576     RExC_emit = ptr;
12577     return(ret);
12578 }
12579
12580 /*
12581 - reganode - emit a node with an argument
12582 */
12583 STATIC regnode *                        /* Location. */
12584 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
12585 {
12586     dVAR;
12587     register regnode *ptr;
12588     regnode * const ret = RExC_emit;
12589     GET_RE_DEBUG_FLAGS_DECL;
12590
12591     PERL_ARGS_ASSERT_REGANODE;
12592
12593     if (SIZE_ONLY) {
12594         SIZE_ALIGN(RExC_size);
12595         RExC_size += 2;
12596         /* 
12597            We can't do this:
12598            
12599            assert(2==regarglen[op]+1); 
12600
12601            Anything larger than this has to allocate the extra amount.
12602            If we changed this to be:
12603            
12604            RExC_size += (1 + regarglen[op]);
12605            
12606            then it wouldn't matter. Its not clear what side effect
12607            might come from that so its not done so far.
12608            -- dmq
12609         */
12610         return(ret);
12611     }
12612     if (RExC_emit >= RExC_emit_bound)
12613         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
12614                    op, RExC_emit, RExC_emit_bound);
12615
12616     NODE_ALIGN_FILL(ret);
12617     ptr = ret;
12618     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
12619 #ifdef RE_TRACK_PATTERN_OFFSETS
12620     if (RExC_offsets) {         /* MJD */
12621         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
12622               "reganode",
12623               __LINE__,
12624               PL_reg_name[op],
12625               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ? 
12626               "Overwriting end of array!\n" : "OK",
12627               (UV)(RExC_emit - RExC_emit_start),
12628               (UV)(RExC_parse - RExC_start),
12629               (UV)RExC_offsets[0])); 
12630         Set_Cur_Node_Offset;
12631     }
12632 #endif            
12633     RExC_emit = ptr;
12634     return(ret);
12635 }
12636
12637 /*
12638 - reguni - emit (if appropriate) a Unicode character
12639 */
12640 STATIC STRLEN
12641 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
12642 {
12643     dVAR;
12644
12645     PERL_ARGS_ASSERT_REGUNI;
12646
12647     return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
12648 }
12649
12650 /*
12651 - reginsert - insert an operator in front of already-emitted operand
12652 *
12653 * Means relocating the operand.
12654 */
12655 STATIC void
12656 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
12657 {
12658     dVAR;
12659     register regnode *src;
12660     register regnode *dst;
12661     register regnode *place;
12662     const int offset = regarglen[(U8)op];
12663     const int size = NODE_STEP_REGNODE + offset;
12664     GET_RE_DEBUG_FLAGS_DECL;
12665
12666     PERL_ARGS_ASSERT_REGINSERT;
12667     PERL_UNUSED_ARG(depth);
12668 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
12669     DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
12670     if (SIZE_ONLY) {
12671         RExC_size += size;
12672         return;
12673     }
12674
12675     src = RExC_emit;
12676     RExC_emit += size;
12677     dst = RExC_emit;
12678     if (RExC_open_parens) {
12679         int paren;
12680         /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
12681         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
12682             if ( RExC_open_parens[paren] >= opnd ) {
12683                 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
12684                 RExC_open_parens[paren] += size;
12685             } else {
12686                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
12687             }
12688             if ( RExC_close_parens[paren] >= opnd ) {
12689                 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
12690                 RExC_close_parens[paren] += size;
12691             } else {
12692                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
12693             }
12694         }
12695     }
12696
12697     while (src > opnd) {
12698         StructCopy(--src, --dst, regnode);
12699 #ifdef RE_TRACK_PATTERN_OFFSETS
12700         if (RExC_offsets) {     /* MJD 20010112 */
12701             MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
12702                   "reg_insert",
12703                   __LINE__,
12704                   PL_reg_name[op],
12705                   (UV)(dst - RExC_emit_start) > RExC_offsets[0] 
12706                     ? "Overwriting end of array!\n" : "OK",
12707                   (UV)(src - RExC_emit_start),
12708                   (UV)(dst - RExC_emit_start),
12709                   (UV)RExC_offsets[0])); 
12710             Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
12711             Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
12712         }
12713 #endif
12714     }
12715     
12716
12717     place = opnd;               /* Op node, where operand used to be. */
12718 #ifdef RE_TRACK_PATTERN_OFFSETS
12719     if (RExC_offsets) {         /* MJD */
12720         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
12721               "reginsert",
12722               __LINE__,
12723               PL_reg_name[op],
12724               (UV)(place - RExC_emit_start) > RExC_offsets[0] 
12725               ? "Overwriting end of array!\n" : "OK",
12726               (UV)(place - RExC_emit_start),
12727               (UV)(RExC_parse - RExC_start),
12728               (UV)RExC_offsets[0]));
12729         Set_Node_Offset(place, RExC_parse);
12730         Set_Node_Length(place, 1);
12731     }
12732 #endif    
12733     src = NEXTOPER(place);
12734     FILL_ADVANCE_NODE(place, op);
12735     Zero(src, offset, regnode);
12736 }
12737
12738 /*
12739 - regtail - set the next-pointer at the end of a node chain of p to val.
12740 - SEE ALSO: regtail_study
12741 */
12742 /* TODO: All three parms should be const */
12743 STATIC void
12744 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
12745 {
12746     dVAR;
12747     register regnode *scan;
12748     GET_RE_DEBUG_FLAGS_DECL;
12749
12750     PERL_ARGS_ASSERT_REGTAIL;
12751 #ifndef DEBUGGING
12752     PERL_UNUSED_ARG(depth);
12753 #endif
12754
12755     if (SIZE_ONLY)
12756         return;
12757
12758     /* Find last node. */
12759     scan = p;
12760     for (;;) {
12761         regnode * const temp = regnext(scan);
12762         DEBUG_PARSE_r({
12763             SV * const mysv=sv_newmortal();
12764             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
12765             regprop(RExC_rx, mysv, scan);
12766             PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
12767                 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
12768                     (temp == NULL ? "->" : ""),
12769                     (temp == NULL ? PL_reg_name[OP(val)] : "")
12770             );
12771         });
12772         if (temp == NULL)
12773             break;
12774         scan = temp;
12775     }
12776
12777     if (reg_off_by_arg[OP(scan)]) {
12778         ARG_SET(scan, val - scan);
12779     }
12780     else {
12781         NEXT_OFF(scan) = val - scan;
12782     }
12783 }
12784
12785 #ifdef DEBUGGING
12786 /*
12787 - regtail_study - set the next-pointer at the end of a node chain of p to val.
12788 - Look for optimizable sequences at the same time.
12789 - currently only looks for EXACT chains.
12790
12791 This is experimental code. The idea is to use this routine to perform 
12792 in place optimizations on branches and groups as they are constructed,
12793 with the long term intention of removing optimization from study_chunk so
12794 that it is purely analytical.
12795
12796 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
12797 to control which is which.
12798
12799 */
12800 /* TODO: All four parms should be const */
12801
12802 STATIC U8
12803 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
12804 {
12805     dVAR;
12806     register regnode *scan;
12807     U8 exact = PSEUDO;
12808 #ifdef EXPERIMENTAL_INPLACESCAN
12809     I32 min = 0;
12810 #endif
12811     GET_RE_DEBUG_FLAGS_DECL;
12812
12813     PERL_ARGS_ASSERT_REGTAIL_STUDY;
12814
12815
12816     if (SIZE_ONLY)
12817         return exact;
12818
12819     /* Find last node. */
12820
12821     scan = p;
12822     for (;;) {
12823         regnode * const temp = regnext(scan);
12824 #ifdef EXPERIMENTAL_INPLACESCAN
12825         if (PL_regkind[OP(scan)] == EXACT) {
12826             bool has_exactf_sharp_s;    /* Unexamined in this routine */
12827             if (join_exact(pRExC_state,scan,&min, &has_exactf_sharp_s, 1,val,depth+1))
12828                 return EXACT;
12829         }
12830 #endif
12831         if ( exact ) {
12832             switch (OP(scan)) {
12833                 case EXACT:
12834                 case EXACTF:
12835                 case EXACTFA:
12836                 case EXACTFU:
12837                 case EXACTFU_SS:
12838                 case EXACTFU_TRICKYFOLD:
12839                 case EXACTFL:
12840                         if( exact == PSEUDO )
12841                             exact= OP(scan);
12842                         else if ( exact != OP(scan) )
12843                             exact= 0;
12844                 case NOTHING:
12845                     break;
12846                 default:
12847                     exact= 0;
12848             }
12849         }
12850         DEBUG_PARSE_r({
12851             SV * const mysv=sv_newmortal();
12852             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
12853             regprop(RExC_rx, mysv, scan);
12854             PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
12855                 SvPV_nolen_const(mysv),
12856                 REG_NODE_NUM(scan),
12857                 PL_reg_name[exact]);
12858         });
12859         if (temp == NULL)
12860             break;
12861         scan = temp;
12862     }
12863     DEBUG_PARSE_r({
12864         SV * const mysv_val=sv_newmortal();
12865         DEBUG_PARSE_MSG("");
12866         regprop(RExC_rx, mysv_val, val);
12867         PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
12868                       SvPV_nolen_const(mysv_val),
12869                       (IV)REG_NODE_NUM(val),
12870                       (IV)(val - scan)
12871         );
12872     });
12873     if (reg_off_by_arg[OP(scan)]) {
12874         ARG_SET(scan, val - scan);
12875     }
12876     else {
12877         NEXT_OFF(scan) = val - scan;
12878     }
12879
12880     return exact;
12881 }
12882 #endif
12883
12884 /*
12885  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
12886  */
12887 #ifdef DEBUGGING
12888 static void 
12889 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
12890 {
12891     int bit;
12892     int set=0;
12893     regex_charset cs;
12894
12895     for (bit=0; bit<32; bit++) {
12896         if (flags & (1<<bit)) {
12897             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
12898                 continue;
12899             }
12900             if (!set++ && lead) 
12901                 PerlIO_printf(Perl_debug_log, "%s",lead);
12902             PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
12903         }               
12904     }      
12905     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
12906             if (!set++ && lead) {
12907                 PerlIO_printf(Perl_debug_log, "%s",lead);
12908             }
12909             switch (cs) {
12910                 case REGEX_UNICODE_CHARSET:
12911                     PerlIO_printf(Perl_debug_log, "UNICODE");
12912                     break;
12913                 case REGEX_LOCALE_CHARSET:
12914                     PerlIO_printf(Perl_debug_log, "LOCALE");
12915                     break;
12916                 case REGEX_ASCII_RESTRICTED_CHARSET:
12917                     PerlIO_printf(Perl_debug_log, "ASCII-RESTRICTED");
12918                     break;
12919                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
12920                     PerlIO_printf(Perl_debug_log, "ASCII-MORE_RESTRICTED");
12921                     break;
12922                 default:
12923                     PerlIO_printf(Perl_debug_log, "UNKNOWN CHARACTER SET");
12924                     break;
12925             }
12926     }
12927     if (lead)  {
12928         if (set) 
12929             PerlIO_printf(Perl_debug_log, "\n");
12930         else 
12931             PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
12932     }            
12933 }   
12934 #endif
12935
12936 void
12937 Perl_regdump(pTHX_ const regexp *r)
12938 {
12939 #ifdef DEBUGGING
12940     dVAR;
12941     SV * const sv = sv_newmortal();
12942     SV *dsv= sv_newmortal();
12943     RXi_GET_DECL(r,ri);
12944     GET_RE_DEBUG_FLAGS_DECL;
12945
12946     PERL_ARGS_ASSERT_REGDUMP;
12947
12948     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
12949
12950     /* Header fields of interest. */
12951     if (r->anchored_substr) {
12952         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr), 
12953             RE_SV_DUMPLEN(r->anchored_substr), 30);
12954         PerlIO_printf(Perl_debug_log,
12955                       "anchored %s%s at %"IVdf" ",
12956                       s, RE_SV_TAIL(r->anchored_substr),
12957                       (IV)r->anchored_offset);
12958     } else if (r->anchored_utf8) {
12959         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8), 
12960             RE_SV_DUMPLEN(r->anchored_utf8), 30);
12961         PerlIO_printf(Perl_debug_log,
12962                       "anchored utf8 %s%s at %"IVdf" ",
12963                       s, RE_SV_TAIL(r->anchored_utf8),
12964                       (IV)r->anchored_offset);
12965     }                 
12966     if (r->float_substr) {
12967         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr), 
12968             RE_SV_DUMPLEN(r->float_substr), 30);
12969         PerlIO_printf(Perl_debug_log,
12970                       "floating %s%s at %"IVdf"..%"UVuf" ",
12971                       s, RE_SV_TAIL(r->float_substr),
12972                       (IV)r->float_min_offset, (UV)r->float_max_offset);
12973     } else if (r->float_utf8) {
12974         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8), 
12975             RE_SV_DUMPLEN(r->float_utf8), 30);
12976         PerlIO_printf(Perl_debug_log,
12977                       "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
12978                       s, RE_SV_TAIL(r->float_utf8),
12979                       (IV)r->float_min_offset, (UV)r->float_max_offset);
12980     }
12981     if (r->check_substr || r->check_utf8)
12982         PerlIO_printf(Perl_debug_log,
12983                       (const char *)
12984                       (r->check_substr == r->float_substr
12985                        && r->check_utf8 == r->float_utf8
12986                        ? "(checking floating" : "(checking anchored"));
12987     if (r->extflags & RXf_NOSCAN)
12988         PerlIO_printf(Perl_debug_log, " noscan");
12989     if (r->extflags & RXf_CHECK_ALL)
12990         PerlIO_printf(Perl_debug_log, " isall");
12991     if (r->check_substr || r->check_utf8)
12992         PerlIO_printf(Perl_debug_log, ") ");
12993
12994     if (ri->regstclass) {
12995         regprop(r, sv, ri->regstclass);
12996         PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
12997     }
12998     if (r->extflags & RXf_ANCH) {
12999         PerlIO_printf(Perl_debug_log, "anchored");
13000         if (r->extflags & RXf_ANCH_BOL)
13001             PerlIO_printf(Perl_debug_log, "(BOL)");
13002         if (r->extflags & RXf_ANCH_MBOL)
13003             PerlIO_printf(Perl_debug_log, "(MBOL)");
13004         if (r->extflags & RXf_ANCH_SBOL)
13005             PerlIO_printf(Perl_debug_log, "(SBOL)");
13006         if (r->extflags & RXf_ANCH_GPOS)
13007             PerlIO_printf(Perl_debug_log, "(GPOS)");
13008         PerlIO_putc(Perl_debug_log, ' ');
13009     }
13010     if (r->extflags & RXf_GPOS_SEEN)
13011         PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
13012     if (r->intflags & PREGf_SKIP)
13013         PerlIO_printf(Perl_debug_log, "plus ");
13014     if (r->intflags & PREGf_IMPLICIT)
13015         PerlIO_printf(Perl_debug_log, "implicit ");
13016     PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
13017     if (r->extflags & RXf_EVAL_SEEN)
13018         PerlIO_printf(Perl_debug_log, "with eval ");
13019     PerlIO_printf(Perl_debug_log, "\n");
13020     DEBUG_FLAGS_r(regdump_extflags("r->extflags: ",r->extflags));            
13021 #else
13022     PERL_ARGS_ASSERT_REGDUMP;
13023     PERL_UNUSED_CONTEXT;
13024     PERL_UNUSED_ARG(r);
13025 #endif  /* DEBUGGING */
13026 }
13027
13028 /*
13029 - regprop - printable representation of opcode
13030 */
13031 #define EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags) \
13032 STMT_START { \
13033         if (do_sep) {                           \
13034             Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]); \
13035             if (flags & ANYOF_INVERT)           \
13036                 /*make sure the invert info is in each */ \
13037                 sv_catpvs(sv, "^");             \
13038             do_sep = 0;                         \
13039         }                                       \
13040 } STMT_END
13041
13042 void
13043 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
13044 {
13045 #ifdef DEBUGGING
13046     dVAR;
13047     register int k;
13048     RXi_GET_DECL(prog,progi);
13049     GET_RE_DEBUG_FLAGS_DECL;
13050     
13051     PERL_ARGS_ASSERT_REGPROP;
13052
13053     sv_setpvs(sv, "");
13054
13055     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
13056         /* It would be nice to FAIL() here, but this may be called from
13057            regexec.c, and it would be hard to supply pRExC_state. */
13058         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
13059     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
13060
13061     k = PL_regkind[OP(o)];
13062
13063     if (k == EXACT) {
13064         sv_catpvs(sv, " ");
13065         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT) 
13066          * is a crude hack but it may be the best for now since 
13067          * we have no flag "this EXACTish node was UTF-8" 
13068          * --jhi */
13069         pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
13070                   PERL_PV_ESCAPE_UNI_DETECT |
13071                   PERL_PV_ESCAPE_NONASCII   |
13072                   PERL_PV_PRETTY_ELLIPSES   |
13073                   PERL_PV_PRETTY_LTGT       |
13074                   PERL_PV_PRETTY_NOCLEAR
13075                   );
13076     } else if (k == TRIE) {
13077         /* print the details of the trie in dumpuntil instead, as
13078          * progi->data isn't available here */
13079         const char op = OP(o);
13080         const U32 n = ARG(o);
13081         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
13082                (reg_ac_data *)progi->data->data[n] :
13083                NULL;
13084         const reg_trie_data * const trie
13085             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
13086         
13087         Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
13088         DEBUG_TRIE_COMPILE_r(
13089             Perl_sv_catpvf(aTHX_ sv,
13090                 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
13091                 (UV)trie->startstate,
13092                 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
13093                 (UV)trie->wordcount,
13094                 (UV)trie->minlen,
13095                 (UV)trie->maxlen,
13096                 (UV)TRIE_CHARCOUNT(trie),
13097                 (UV)trie->uniquecharcount
13098             )
13099         );
13100         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
13101             int i;
13102             int rangestart = -1;
13103             U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
13104             sv_catpvs(sv, "[");
13105             for (i = 0; i <= 256; i++) {
13106                 if (i < 256 && BITMAP_TEST(bitmap,i)) {
13107                     if (rangestart == -1)
13108                         rangestart = i;
13109                 } else if (rangestart != -1) {
13110                     if (i <= rangestart + 3)
13111                         for (; rangestart < i; rangestart++)
13112                             put_byte(sv, rangestart);
13113                     else {
13114                         put_byte(sv, rangestart);
13115                         sv_catpvs(sv, "-");
13116                         put_byte(sv, i - 1);
13117                     }
13118                     rangestart = -1;
13119                 }
13120             }
13121             sv_catpvs(sv, "]");
13122         } 
13123          
13124     } else if (k == CURLY) {
13125         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
13126             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
13127         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
13128     }
13129     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
13130         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
13131     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
13132         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
13133         if ( RXp_PAREN_NAMES(prog) ) {
13134             if ( k != REF || (OP(o) < NREF)) {
13135                 AV *list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
13136                 SV **name= av_fetch(list, ARG(o), 0 );
13137                 if (name)
13138                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
13139             }       
13140             else {
13141                 AV *list= MUTABLE_AV(progi->data->data[ progi->name_list_idx ]);
13142                 SV *sv_dat= MUTABLE_SV(progi->data->data[ ARG( o ) ]);
13143                 I32 *nums=(I32*)SvPVX(sv_dat);
13144                 SV **name= av_fetch(list, nums[0], 0 );
13145                 I32 n;
13146                 if (name) {
13147                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
13148                         Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
13149                                     (n ? "," : ""), (IV)nums[n]);
13150                     }
13151                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
13152                 }
13153             }
13154         }            
13155     } else if (k == GOSUB) 
13156         Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
13157     else if (k == VERB) {
13158         if (!o->flags) 
13159             Perl_sv_catpvf(aTHX_ sv, ":%"SVf, 
13160                            SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
13161     } else if (k == LOGICAL)
13162         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
13163     else if (k == ANYOF) {
13164         int i, rangestart = -1;
13165         const U8 flags = ANYOF_FLAGS(o);
13166         int do_sep = 0;
13167
13168         /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
13169         static const char * const anyofs[] = {
13170             "\\w",
13171             "\\W",
13172             "\\s",
13173             "\\S",
13174             "\\d",
13175             "\\D",
13176             "[:alnum:]",
13177             "[:^alnum:]",
13178             "[:alpha:]",
13179             "[:^alpha:]",
13180             "[:ascii:]",
13181             "[:^ascii:]",
13182             "[:cntrl:]",
13183             "[:^cntrl:]",
13184             "[:graph:]",
13185             "[:^graph:]",
13186             "[:lower:]",
13187             "[:^lower:]",
13188             "[:print:]",
13189             "[:^print:]",
13190             "[:punct:]",
13191             "[:^punct:]",
13192             "[:upper:]",
13193             "[:^upper:]",
13194             "[:xdigit:]",
13195             "[:^xdigit:]",
13196             "[:space:]",
13197             "[:^space:]",
13198             "[:blank:]",
13199             "[:^blank:]"
13200         };
13201
13202         if (flags & ANYOF_LOCALE)
13203             sv_catpvs(sv, "{loc}");
13204         if (flags & ANYOF_LOC_NONBITMAP_FOLD)
13205             sv_catpvs(sv, "{i}");
13206         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
13207         if (flags & ANYOF_INVERT)
13208             sv_catpvs(sv, "^");
13209
13210         /* output what the standard cp 0-255 bitmap matches */
13211         for (i = 0; i <= 256; i++) {
13212             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
13213                 if (rangestart == -1)
13214                     rangestart = i;
13215             } else if (rangestart != -1) {
13216                 if (i <= rangestart + 3)
13217                     for (; rangestart < i; rangestart++)
13218                         put_byte(sv, rangestart);
13219                 else {
13220                     put_byte(sv, rangestart);
13221                     sv_catpvs(sv, "-");
13222                     put_byte(sv, i - 1);
13223                 }
13224                 do_sep = 1;
13225                 rangestart = -1;
13226             }
13227         }
13228         
13229         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
13230         /* output any special charclass tests (used entirely under use locale) */
13231         if (ANYOF_CLASS_TEST_ANY_SET(o))
13232             for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
13233                 if (ANYOF_CLASS_TEST(o,i)) {
13234                     sv_catpv(sv, anyofs[i]);
13235                     do_sep = 1;
13236                 }
13237         
13238         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
13239         
13240         if (flags & ANYOF_NON_UTF8_LATIN1_ALL) {
13241             sv_catpvs(sv, "{non-utf8-latin1-all}");
13242         }
13243
13244         /* output information about the unicode matching */
13245         if (flags & ANYOF_UNICODE_ALL)
13246             sv_catpvs(sv, "{unicode_all}");
13247         else if (ANYOF_NONBITMAP(o))
13248             sv_catpvs(sv, "{unicode}");
13249         if (flags & ANYOF_NONBITMAP_NON_UTF8)
13250             sv_catpvs(sv, "{outside bitmap}");
13251
13252         if (ANYOF_NONBITMAP(o)) {
13253             SV *lv; /* Set if there is something outside the bit map */
13254             SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
13255             bool byte_output = FALSE;   /* If something in the bitmap has been
13256                                            output */
13257
13258             if (lv && lv != &PL_sv_undef) {
13259                 if (sw) {
13260                     U8 s[UTF8_MAXBYTES_CASE+1];
13261
13262                     for (i = 0; i <= 256; i++) { /* Look at chars in bitmap */
13263                         uvchr_to_utf8(s, i);
13264
13265                         if (i < 256
13266                             && ! ANYOF_BITMAP_TEST(o, i)    /* Don't duplicate
13267                                                                things already
13268                                                                output as part
13269                                                                of the bitmap */
13270                             && swash_fetch(sw, s, TRUE))
13271                         {
13272                             if (rangestart == -1)
13273                                 rangestart = i;
13274                         } else if (rangestart != -1) {
13275                             byte_output = TRUE;
13276                             if (i <= rangestart + 3)
13277                                 for (; rangestart < i; rangestart++) {
13278                                     put_byte(sv, rangestart);
13279                                 }
13280                             else {
13281                                 put_byte(sv, rangestart);
13282                                 sv_catpvs(sv, "-");
13283                                 put_byte(sv, i-1);
13284                             }
13285                             rangestart = -1;
13286                         }
13287                     }
13288                 }
13289
13290                 {
13291                     char *s = savesvpv(lv);
13292                     char * const origs = s;
13293
13294                     while (*s && *s != '\n')
13295                         s++;
13296
13297                     if (*s == '\n') {
13298                         const char * const t = ++s;
13299
13300                         if (byte_output) {
13301                             sv_catpvs(sv, " ");
13302                         }
13303
13304                         while (*s) {
13305                             if (*s == '\n') {
13306
13307                                 /* Truncate very long output */
13308                                 if (s - origs > 256) {
13309                                     Perl_sv_catpvf(aTHX_ sv,
13310                                                    "%.*s...",
13311                                                    (int) (s - origs - 1),
13312                                                    t);
13313                                     goto out_dump;
13314                                 }
13315                                 *s = ' ';
13316                             }
13317                             else if (*s == '\t') {
13318                                 *s = '-';
13319                             }
13320                             s++;
13321                         }
13322                         if (s[-1] == ' ')
13323                             s[-1] = 0;
13324
13325                         sv_catpv(sv, t);
13326                     }
13327
13328                 out_dump:
13329
13330                     Safefree(origs);
13331                 }
13332                 SvREFCNT_dec(lv);
13333             }
13334         }
13335
13336         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
13337     }
13338     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
13339         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
13340 #else
13341     PERL_UNUSED_CONTEXT;
13342     PERL_UNUSED_ARG(sv);
13343     PERL_UNUSED_ARG(o);
13344     PERL_UNUSED_ARG(prog);
13345 #endif  /* DEBUGGING */
13346 }
13347
13348 SV *
13349 Perl_re_intuit_string(pTHX_ REGEXP * const r)
13350 {                               /* Assume that RE_INTUIT is set */
13351     dVAR;
13352     struct regexp *const prog = (struct regexp *)SvANY(r);
13353     GET_RE_DEBUG_FLAGS_DECL;
13354
13355     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
13356     PERL_UNUSED_CONTEXT;
13357
13358     DEBUG_COMPILE_r(
13359         {
13360             const char * const s = SvPV_nolen_const(prog->check_substr
13361                       ? prog->check_substr : prog->check_utf8);
13362
13363             if (!PL_colorset) reginitcolors();
13364             PerlIO_printf(Perl_debug_log,
13365                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
13366                       PL_colors[4],
13367                       prog->check_substr ? "" : "utf8 ",
13368                       PL_colors[5],PL_colors[0],
13369                       s,
13370                       PL_colors[1],
13371                       (strlen(s) > 60 ? "..." : ""));
13372         } );
13373
13374     return prog->check_substr ? prog->check_substr : prog->check_utf8;
13375 }
13376
13377 /* 
13378    pregfree() 
13379    
13380    handles refcounting and freeing the perl core regexp structure. When 
13381    it is necessary to actually free the structure the first thing it 
13382    does is call the 'free' method of the regexp_engine associated to
13383    the regexp, allowing the handling of the void *pprivate; member 
13384    first. (This routine is not overridable by extensions, which is why 
13385    the extensions free is called first.)
13386    
13387    See regdupe and regdupe_internal if you change anything here. 
13388 */
13389 #ifndef PERL_IN_XSUB_RE
13390 void
13391 Perl_pregfree(pTHX_ REGEXP *r)
13392 {
13393     SvREFCNT_dec(r);
13394 }
13395
13396 void
13397 Perl_pregfree2(pTHX_ REGEXP *rx)
13398 {
13399     dVAR;
13400     struct regexp *const r = (struct regexp *)SvANY(rx);
13401     GET_RE_DEBUG_FLAGS_DECL;
13402
13403     PERL_ARGS_ASSERT_PREGFREE2;
13404
13405     if (r->mother_re) {
13406         ReREFCNT_dec(r->mother_re);
13407     } else {
13408         CALLREGFREE_PVT(rx); /* free the private data */
13409         SvREFCNT_dec(RXp_PAREN_NAMES(r));
13410     }        
13411     if (r->substrs) {
13412         SvREFCNT_dec(r->anchored_substr);
13413         SvREFCNT_dec(r->anchored_utf8);
13414         SvREFCNT_dec(r->float_substr);
13415         SvREFCNT_dec(r->float_utf8);
13416         Safefree(r->substrs);
13417     }
13418     RX_MATCH_COPY_FREE(rx);
13419 #ifdef PERL_OLD_COPY_ON_WRITE
13420     SvREFCNT_dec(r->saved_copy);
13421 #endif
13422     Safefree(r->offs);
13423     SvREFCNT_dec(r->qr_anoncv);
13424 }
13425
13426 /*  reg_temp_copy()
13427     
13428     This is a hacky workaround to the structural issue of match results
13429     being stored in the regexp structure which is in turn stored in
13430     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
13431     could be PL_curpm in multiple contexts, and could require multiple
13432     result sets being associated with the pattern simultaneously, such
13433     as when doing a recursive match with (??{$qr})
13434     
13435     The solution is to make a lightweight copy of the regexp structure 
13436     when a qr// is returned from the code executed by (??{$qr}) this
13437     lightweight copy doesn't actually own any of its data except for
13438     the starp/end and the actual regexp structure itself. 
13439     
13440 */    
13441     
13442     
13443 REGEXP *
13444 Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
13445 {
13446     struct regexp *ret;
13447     struct regexp *const r = (struct regexp *)SvANY(rx);
13448     register const I32 npar = r->nparens+1;
13449
13450     PERL_ARGS_ASSERT_REG_TEMP_COPY;
13451
13452     if (!ret_x)
13453         ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
13454     ret = (struct regexp *)SvANY(ret_x);
13455     
13456     (void)ReREFCNT_inc(rx);
13457     /* We can take advantage of the existing "copied buffer" mechanism in SVs
13458        by pointing directly at the buffer, but flagging that the allocated
13459        space in the copy is zero. As we've just done a struct copy, it's now
13460        a case of zero-ing that, rather than copying the current length.  */
13461     SvPV_set(ret_x, RX_WRAPPED(rx));
13462     SvFLAGS(ret_x) |= SvFLAGS(rx) & (SVf_POK|SVp_POK|SVf_UTF8);
13463     memcpy(&(ret->xpv_cur), &(r->xpv_cur),
13464            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
13465     SvLEN_set(ret_x, 0);
13466     SvSTASH_set(ret_x, NULL);
13467     SvMAGIC_set(ret_x, NULL);
13468     Newx(ret->offs, npar, regexp_paren_pair);
13469     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
13470     if (r->substrs) {
13471         Newx(ret->substrs, 1, struct reg_substr_data);
13472         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
13473
13474         SvREFCNT_inc_void(ret->anchored_substr);
13475         SvREFCNT_inc_void(ret->anchored_utf8);
13476         SvREFCNT_inc_void(ret->float_substr);
13477         SvREFCNT_inc_void(ret->float_utf8);
13478
13479         /* check_substr and check_utf8, if non-NULL, point to either their
13480            anchored or float namesakes, and don't hold a second reference.  */
13481     }
13482     RX_MATCH_COPIED_off(ret_x);
13483 #ifdef PERL_OLD_COPY_ON_WRITE
13484     ret->saved_copy = NULL;
13485 #endif
13486     ret->mother_re = rx;
13487     SvREFCNT_inc_void(ret->qr_anoncv);
13488     
13489     return ret_x;
13490 }
13491 #endif
13492
13493 /* regfree_internal() 
13494
13495    Free the private data in a regexp. This is overloadable by 
13496    extensions. Perl takes care of the regexp structure in pregfree(), 
13497    this covers the *pprivate pointer which technically perl doesn't 
13498    know about, however of course we have to handle the 
13499    regexp_internal structure when no extension is in use. 
13500    
13501    Note this is called before freeing anything in the regexp 
13502    structure. 
13503  */
13504  
13505 void
13506 Perl_regfree_internal(pTHX_ REGEXP * const rx)
13507 {
13508     dVAR;
13509     struct regexp *const r = (struct regexp *)SvANY(rx);
13510     RXi_GET_DECL(r,ri);
13511     GET_RE_DEBUG_FLAGS_DECL;
13512
13513     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
13514
13515     DEBUG_COMPILE_r({
13516         if (!PL_colorset)
13517             reginitcolors();
13518         {
13519             SV *dsv= sv_newmortal();
13520             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
13521                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
13522             PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n", 
13523                 PL_colors[4],PL_colors[5],s);
13524         }
13525     });
13526 #ifdef RE_TRACK_PATTERN_OFFSETS
13527     if (ri->u.offsets)
13528         Safefree(ri->u.offsets);             /* 20010421 MJD */
13529 #endif
13530     if (ri->code_blocks) {
13531         int n;
13532         for (n = 0; n < ri->num_code_blocks; n++)
13533             SvREFCNT_dec(ri->code_blocks[n].src_regex);
13534         Safefree(ri->code_blocks);
13535     }
13536
13537     if (ri->data) {
13538         int n = ri->data->count;
13539
13540         while (--n >= 0) {
13541           /* If you add a ->what type here, update the comment in regcomp.h */
13542             switch (ri->data->what[n]) {
13543             case 'a':
13544             case 'r':
13545             case 's':
13546             case 'S':
13547             case 'u':
13548                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
13549                 break;
13550             case 'f':
13551                 Safefree(ri->data->data[n]);
13552                 break;
13553             case 'l':
13554             case 'L':
13555                 break;
13556             case 'T':           
13557                 { /* Aho Corasick add-on structure for a trie node.
13558                      Used in stclass optimization only */
13559                     U32 refcount;
13560                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
13561                     OP_REFCNT_LOCK;
13562                     refcount = --aho->refcount;
13563                     OP_REFCNT_UNLOCK;
13564                     if ( !refcount ) {
13565                         PerlMemShared_free(aho->states);
13566                         PerlMemShared_free(aho->fail);
13567                          /* do this last!!!! */
13568                         PerlMemShared_free(ri->data->data[n]);
13569                         PerlMemShared_free(ri->regstclass);
13570                     }
13571                 }
13572                 break;
13573             case 't':
13574                 {
13575                     /* trie structure. */
13576                     U32 refcount;
13577                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
13578                     OP_REFCNT_LOCK;
13579                     refcount = --trie->refcount;
13580                     OP_REFCNT_UNLOCK;
13581                     if ( !refcount ) {
13582                         PerlMemShared_free(trie->charmap);
13583                         PerlMemShared_free(trie->states);
13584                         PerlMemShared_free(trie->trans);
13585                         if (trie->bitmap)
13586                             PerlMemShared_free(trie->bitmap);
13587                         if (trie->jump)
13588                             PerlMemShared_free(trie->jump);
13589                         PerlMemShared_free(trie->wordinfo);
13590                         /* do this last!!!! */
13591                         PerlMemShared_free(ri->data->data[n]);
13592                     }
13593                 }
13594                 break;
13595             default:
13596                 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
13597             }
13598         }
13599         Safefree(ri->data->what);
13600         Safefree(ri->data);
13601     }
13602
13603     Safefree(ri);
13604 }
13605
13606 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
13607 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
13608 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
13609
13610 /* 
13611    re_dup - duplicate a regexp. 
13612    
13613    This routine is expected to clone a given regexp structure. It is only
13614    compiled under USE_ITHREADS.
13615
13616    After all of the core data stored in struct regexp is duplicated
13617    the regexp_engine.dupe method is used to copy any private data
13618    stored in the *pprivate pointer. This allows extensions to handle
13619    any duplication it needs to do.
13620
13621    See pregfree() and regfree_internal() if you change anything here. 
13622 */
13623 #if defined(USE_ITHREADS)
13624 #ifndef PERL_IN_XSUB_RE
13625 void
13626 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
13627 {
13628     dVAR;
13629     I32 npar;
13630     const struct regexp *r = (const struct regexp *)SvANY(sstr);
13631     struct regexp *ret = (struct regexp *)SvANY(dstr);
13632     
13633     PERL_ARGS_ASSERT_RE_DUP_GUTS;
13634
13635     npar = r->nparens+1;
13636     Newx(ret->offs, npar, regexp_paren_pair);
13637     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
13638     if(ret->swap) {
13639         /* no need to copy these */
13640         Newx(ret->swap, npar, regexp_paren_pair);
13641     }
13642
13643     if (ret->substrs) {
13644         /* Do it this way to avoid reading from *r after the StructCopy().
13645            That way, if any of the sv_dup_inc()s dislodge *r from the L1
13646            cache, it doesn't matter.  */
13647         const bool anchored = r->check_substr
13648             ? r->check_substr == r->anchored_substr
13649             : r->check_utf8 == r->anchored_utf8;
13650         Newx(ret->substrs, 1, struct reg_substr_data);
13651         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
13652
13653         ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
13654         ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
13655         ret->float_substr = sv_dup_inc(ret->float_substr, param);
13656         ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
13657
13658         /* check_substr and check_utf8, if non-NULL, point to either their
13659            anchored or float namesakes, and don't hold a second reference.  */
13660
13661         if (ret->check_substr) {
13662             if (anchored) {
13663                 assert(r->check_utf8 == r->anchored_utf8);
13664                 ret->check_substr = ret->anchored_substr;
13665                 ret->check_utf8 = ret->anchored_utf8;
13666             } else {
13667                 assert(r->check_substr == r->float_substr);
13668                 assert(r->check_utf8 == r->float_utf8);
13669                 ret->check_substr = ret->float_substr;
13670                 ret->check_utf8 = ret->float_utf8;
13671             }
13672         } else if (ret->check_utf8) {
13673             if (anchored) {
13674                 ret->check_utf8 = ret->anchored_utf8;
13675             } else {
13676                 ret->check_utf8 = ret->float_utf8;
13677             }
13678         }
13679     }
13680
13681     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
13682     ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param));
13683
13684     if (ret->pprivate)
13685         RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
13686
13687     if (RX_MATCH_COPIED(dstr))
13688         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
13689     else
13690         ret->subbeg = NULL;
13691 #ifdef PERL_OLD_COPY_ON_WRITE
13692     ret->saved_copy = NULL;
13693 #endif
13694
13695     if (ret->mother_re) {
13696         if (SvPVX_const(dstr) == SvPVX_const(ret->mother_re)) {
13697             /* Our storage points directly to our mother regexp, but that's
13698                1: a buffer in a different thread
13699                2: something we no longer hold a reference on
13700                so we need to copy it locally.  */
13701             /* Note we need to use SvCUR(), rather than
13702                SvLEN(), on our mother_re, because it, in
13703                turn, may well be pointing to its own mother_re.  */
13704             SvPV_set(dstr, SAVEPVN(SvPVX_const(ret->mother_re),
13705                                    SvCUR(ret->mother_re)+1));
13706             SvLEN_set(dstr, SvCUR(ret->mother_re)+1);
13707         }
13708         ret->mother_re      = NULL;
13709     }
13710     ret->gofs = 0;
13711 }
13712 #endif /* PERL_IN_XSUB_RE */
13713
13714 /*
13715    regdupe_internal()
13716    
13717    This is the internal complement to regdupe() which is used to copy
13718    the structure pointed to by the *pprivate pointer in the regexp.
13719    This is the core version of the extension overridable cloning hook.
13720    The regexp structure being duplicated will be copied by perl prior
13721    to this and will be provided as the regexp *r argument, however 
13722    with the /old/ structures pprivate pointer value. Thus this routine
13723    may override any copying normally done by perl.
13724    
13725    It returns a pointer to the new regexp_internal structure.
13726 */
13727
13728 void *
13729 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
13730 {
13731     dVAR;
13732     struct regexp *const r = (struct regexp *)SvANY(rx);
13733     regexp_internal *reti;
13734     int len;
13735     RXi_GET_DECL(r,ri);
13736
13737     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
13738     
13739     len = ProgLen(ri);
13740     
13741     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal);
13742     Copy(ri->program, reti->program, len+1, regnode);
13743
13744     reti->num_code_blocks = ri->num_code_blocks;
13745     if (ri->code_blocks) {
13746         int n;
13747         Newxc(reti->code_blocks, ri->num_code_blocks, struct reg_code_block,
13748                 struct reg_code_block);
13749         Copy(ri->code_blocks, reti->code_blocks, ri->num_code_blocks,
13750                 struct reg_code_block);
13751         for (n = 0; n < ri->num_code_blocks; n++)
13752              reti->code_blocks[n].src_regex = (REGEXP*)
13753                     sv_dup_inc((SV*)(ri->code_blocks[n].src_regex), param);
13754     }
13755     else
13756         reti->code_blocks = NULL;
13757
13758     reti->regstclass = NULL;
13759
13760     if (ri->data) {
13761         struct reg_data *d;
13762         const int count = ri->data->count;
13763         int i;
13764
13765         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
13766                 char, struct reg_data);
13767         Newx(d->what, count, U8);
13768
13769         d->count = count;
13770         for (i = 0; i < count; i++) {
13771             d->what[i] = ri->data->what[i];
13772             switch (d->what[i]) {
13773                 /* see also regcomp.h and regfree_internal() */
13774             case 'a': /* actually an AV, but the dup function is identical.  */
13775             case 'r':
13776             case 's':
13777             case 'S':
13778             case 'u': /* actually an HV, but the dup function is identical.  */
13779                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
13780                 break;
13781             case 'f':
13782                 /* This is cheating. */
13783                 Newx(d->data[i], 1, struct regnode_charclass_class);
13784                 StructCopy(ri->data->data[i], d->data[i],
13785                             struct regnode_charclass_class);
13786                 reti->regstclass = (regnode*)d->data[i];
13787                 break;
13788             case 'T':
13789                 /* Trie stclasses are readonly and can thus be shared
13790                  * without duplication. We free the stclass in pregfree
13791                  * when the corresponding reg_ac_data struct is freed.
13792                  */
13793                 reti->regstclass= ri->regstclass;
13794                 /* Fall through */
13795             case 't':
13796                 OP_REFCNT_LOCK;
13797                 ((reg_trie_data*)ri->data->data[i])->refcount++;
13798                 OP_REFCNT_UNLOCK;
13799                 /* Fall through */
13800             case 'l':
13801             case 'L':
13802                 d->data[i] = ri->data->data[i];
13803                 break;
13804             default:
13805                 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
13806             }
13807         }
13808
13809         reti->data = d;
13810     }
13811     else
13812         reti->data = NULL;
13813
13814     reti->name_list_idx = ri->name_list_idx;
13815
13816 #ifdef RE_TRACK_PATTERN_OFFSETS
13817     if (ri->u.offsets) {
13818         Newx(reti->u.offsets, 2*len+1, U32);
13819         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
13820     }
13821 #else
13822     SetProgLen(reti,len);
13823 #endif
13824
13825     return (void*)reti;
13826 }
13827
13828 #endif    /* USE_ITHREADS */
13829
13830 #ifndef PERL_IN_XSUB_RE
13831
13832 /*
13833  - regnext - dig the "next" pointer out of a node
13834  */
13835 regnode *
13836 Perl_regnext(pTHX_ register regnode *p)
13837 {
13838     dVAR;
13839     register I32 offset;
13840
13841     if (!p)
13842         return(NULL);
13843
13844     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
13845         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(p), (int)REGNODE_MAX);
13846     }
13847
13848     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
13849     if (offset == 0)
13850         return(NULL);
13851
13852     return(p+offset);
13853 }
13854 #endif
13855
13856 STATIC void
13857 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
13858 {
13859     va_list args;
13860     STRLEN l1 = strlen(pat1);
13861     STRLEN l2 = strlen(pat2);
13862     char buf[512];
13863     SV *msv;
13864     const char *message;
13865
13866     PERL_ARGS_ASSERT_RE_CROAK2;
13867
13868     if (l1 > 510)
13869         l1 = 510;
13870     if (l1 + l2 > 510)
13871         l2 = 510 - l1;
13872     Copy(pat1, buf, l1 , char);
13873     Copy(pat2, buf + l1, l2 , char);
13874     buf[l1 + l2] = '\n';
13875     buf[l1 + l2 + 1] = '\0';
13876 #ifdef I_STDARG
13877     /* ANSI variant takes additional second argument */
13878     va_start(args, pat2);
13879 #else
13880     va_start(args);
13881 #endif
13882     msv = vmess(buf, &args);
13883     va_end(args);
13884     message = SvPV_const(msv,l1);
13885     if (l1 > 512)
13886         l1 = 512;
13887     Copy(message, buf, l1 , char);
13888     buf[l1-1] = '\0';                   /* Overwrite \n */
13889     Perl_croak(aTHX_ "%s", buf);
13890 }
13891
13892 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
13893
13894 #ifndef PERL_IN_XSUB_RE
13895 void
13896 Perl_save_re_context(pTHX)
13897 {
13898     dVAR;
13899
13900     struct re_save_state *state;
13901
13902     SAVEVPTR(PL_curcop);
13903     SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
13904
13905     state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
13906     PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
13907     SSPUSHUV(SAVEt_RE_STATE);
13908
13909     Copy(&PL_reg_state, state, 1, struct re_save_state);
13910
13911     PL_reg_oldsaved = NULL;
13912     PL_reg_oldsavedlen = 0;
13913     PL_reg_maxiter = 0;
13914     PL_reg_leftiter = 0;
13915     PL_reg_poscache = NULL;
13916     PL_reg_poscache_size = 0;
13917 #ifdef PERL_OLD_COPY_ON_WRITE
13918     PL_nrs = NULL;
13919 #endif
13920
13921     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
13922     if (PL_curpm) {
13923         const REGEXP * const rx = PM_GETRE(PL_curpm);
13924         if (rx) {
13925             U32 i;
13926             for (i = 1; i <= RX_NPARENS(rx); i++) {
13927                 char digits[TYPE_CHARS(long)];
13928                 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
13929                 GV *const *const gvp
13930                     = (GV**)hv_fetch(PL_defstash, digits, len, 0);
13931
13932                 if (gvp) {
13933                     GV * const gv = *gvp;
13934                     if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
13935                         save_scalar(gv);
13936                 }
13937             }
13938         }
13939     }
13940 }
13941 #endif
13942
13943 static void
13944 clear_re(pTHX_ void *r)
13945 {
13946     dVAR;
13947     ReREFCNT_dec((REGEXP *)r);
13948 }
13949
13950 #ifdef DEBUGGING
13951
13952 STATIC void
13953 S_put_byte(pTHX_ SV *sv, int c)
13954 {
13955     PERL_ARGS_ASSERT_PUT_BYTE;
13956
13957     /* Our definition of isPRINT() ignores locales, so only bytes that are
13958        not part of UTF-8 are considered printable. I assume that the same
13959        holds for UTF-EBCDIC.
13960        Also, code point 255 is not printable in either (it's E0 in EBCDIC,
13961        which Wikipedia says:
13962
13963        EO, or Eight Ones, is an 8-bit EBCDIC character code represented as all
13964        ones (binary 1111 1111, hexadecimal FF). It is similar, but not
13965        identical, to the ASCII delete (DEL) or rubout control character.
13966        ) So the old condition can be simplified to !isPRINT(c)  */
13967     if (!isPRINT(c)) {
13968         if (c < 256) {
13969             Perl_sv_catpvf(aTHX_ sv, "\\x%02x", c);
13970         }
13971         else {
13972             Perl_sv_catpvf(aTHX_ sv, "\\x{%x}", c);
13973         }
13974     }
13975     else {
13976         const char string = c;
13977         if (c == '-' || c == ']' || c == '\\' || c == '^')
13978             sv_catpvs(sv, "\\");
13979         sv_catpvn(sv, &string, 1);
13980     }
13981 }
13982
13983
13984 #define CLEAR_OPTSTART \
13985     if (optstart) STMT_START { \
13986             DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
13987             optstart=NULL; \
13988     } STMT_END
13989
13990 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
13991
13992 STATIC const regnode *
13993 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
13994             const regnode *last, const regnode *plast, 
13995             SV* sv, I32 indent, U32 depth)
13996 {
13997     dVAR;
13998     register U8 op = PSEUDO;    /* Arbitrary non-END op. */
13999     register const regnode *next;
14000     const regnode *optstart= NULL;
14001     
14002     RXi_GET_DECL(r,ri);
14003     GET_RE_DEBUG_FLAGS_DECL;
14004
14005     PERL_ARGS_ASSERT_DUMPUNTIL;
14006
14007 #ifdef DEBUG_DUMPUNTIL
14008     PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
14009         last ? last-start : 0,plast ? plast-start : 0);
14010 #endif
14011             
14012     if (plast && plast < last) 
14013         last= plast;
14014
14015     while (PL_regkind[op] != END && (!last || node < last)) {
14016         /* While that wasn't END last time... */
14017         NODE_ALIGN(node);
14018         op = OP(node);
14019         if (op == CLOSE || op == WHILEM)
14020             indent--;
14021         next = regnext((regnode *)node);
14022
14023         /* Where, what. */
14024         if (OP(node) == OPTIMIZED) {
14025             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
14026                 optstart = node;
14027             else
14028                 goto after_print;
14029         } else
14030             CLEAR_OPTSTART;
14031
14032         regprop(r, sv, node);
14033         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
14034                       (int)(2*indent + 1), "", SvPVX_const(sv));
14035         
14036         if (OP(node) != OPTIMIZED) {                  
14037             if (next == NULL)           /* Next ptr. */
14038                 PerlIO_printf(Perl_debug_log, " (0)");
14039             else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
14040                 PerlIO_printf(Perl_debug_log, " (FAIL)");
14041             else 
14042                 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
14043             (void)PerlIO_putc(Perl_debug_log, '\n'); 
14044         }
14045         
14046       after_print:
14047         if (PL_regkind[(U8)op] == BRANCHJ) {
14048             assert(next);
14049             {
14050                 register const regnode *nnode = (OP(next) == LONGJMP
14051                                              ? regnext((regnode *)next)
14052                                              : next);
14053                 if (last && nnode > last)
14054                     nnode = last;
14055                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
14056             }
14057         }
14058         else if (PL_regkind[(U8)op] == BRANCH) {
14059             assert(next);
14060             DUMPUNTIL(NEXTOPER(node), next);
14061         }
14062         else if ( PL_regkind[(U8)op]  == TRIE ) {
14063             const regnode *this_trie = node;
14064             const char op = OP(node);
14065             const U32 n = ARG(node);
14066             const reg_ac_data * const ac = op>=AHOCORASICK ?
14067                (reg_ac_data *)ri->data->data[n] :
14068                NULL;
14069             const reg_trie_data * const trie =
14070                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
14071 #ifdef DEBUGGING
14072             AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
14073 #endif
14074             const regnode *nextbranch= NULL;
14075             I32 word_idx;
14076             sv_setpvs(sv, "");
14077             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
14078                 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
14079
14080                 PerlIO_printf(Perl_debug_log, "%*s%s ",
14081                    (int)(2*(indent+3)), "",
14082                     elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
14083                             PL_colors[0], PL_colors[1],
14084                             (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
14085                             PERL_PV_PRETTY_ELLIPSES    |
14086                             PERL_PV_PRETTY_LTGT
14087                             )
14088                             : "???"
14089                 );
14090                 if (trie->jump) {
14091                     U16 dist= trie->jump[word_idx+1];
14092                     PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
14093                                   (UV)((dist ? this_trie + dist : next) - start));
14094                     if (dist) {
14095                         if (!nextbranch)
14096                             nextbranch= this_trie + trie->jump[0];    
14097                         DUMPUNTIL(this_trie + dist, nextbranch);
14098                     }
14099                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
14100                         nextbranch= regnext((regnode *)nextbranch);
14101                 } else {
14102                     PerlIO_printf(Perl_debug_log, "\n");
14103                 }
14104             }
14105             if (last && next > last)
14106                 node= last;
14107             else
14108                 node= next;
14109         }
14110         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
14111             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
14112                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
14113         }
14114         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
14115             assert(next);
14116             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
14117         }
14118         else if ( op == PLUS || op == STAR) {
14119             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
14120         }
14121         else if (PL_regkind[(U8)op] == ANYOF) {
14122             /* arglen 1 + class block */
14123             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_CLASS)
14124                     ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
14125             node = NEXTOPER(node);
14126         }
14127         else if (PL_regkind[(U8)op] == EXACT) {
14128             /* Literal string, where present. */
14129             node += NODE_SZ_STR(node) - 1;
14130             node = NEXTOPER(node);
14131         }
14132         else {
14133             node = NEXTOPER(node);
14134             node += regarglen[(U8)op];
14135         }
14136         if (op == CURLYX || op == OPEN)
14137             indent++;
14138     }
14139     CLEAR_OPTSTART;
14140 #ifdef DEBUG_DUMPUNTIL    
14141     PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
14142 #endif
14143     return node;
14144 }
14145
14146 #endif  /* DEBUGGING */
14147
14148 /*
14149  * Local variables:
14150  * c-indentation-style: bsd
14151  * c-basic-offset: 4
14152  * indent-tabs-mode: nil
14153  * End:
14154  *
14155  * ex: set ts=8 sts=4 sw=4 et:
14156  */